diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml index b25e651f..32fb8cc8 100644 --- a/.github/workflows/deploy.yaml +++ b/.github/workflows/deploy.yaml @@ -3,20 +3,15 @@ name: Deploy to GitHub Pages on: push: branches: - - main + - main workflow_dispatch: permissions: - contents: write - pages: write - id-token: write + contents: write jobs: build-and-deploy: runs-on: ubuntu-latest - env: - MOONBIT_INSTALL_VERSION: latest - steps: - uses: actions/checkout@v4 @@ -25,24 +20,16 @@ jobs: curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash -s latest echo "$HOME/.moon/bin" >> $GITHUB_PATH - - name: Build project + - name: Build Pages run: | moon update moon build --target js --release --deny-warn - - - name: Collect Pages files - run: | - site="$RUNNER_TEMP/selene-pages" - mkdir -p "$site" - cp page/index.html "$site/index.html" - cp -R --parents \ - examples/index.html examples/preload-assets.js \ - examples/*/index.html examples/*/screenshot.png examples/*/assets \ - _build/js/release/build/Milky2018/selene-examples-web/*/web/web.js \ - "$site" + for game in cards pixeladventure survivors; do + cp "_build/js/release/build/Milky2018/selene-examples-web/$game/web/web.js" "page/examples/$game/web.js" + done - name: Deploy to GitHub Pages uses: peaceiris/actions-gh-pages@v4 with: github_token: ${{ secrets.GITHUB_TOKEN }} - publish_dir: ${{ runner.temp }}/selene-pages + publish_dir: page diff --git a/.gitignore b/.gitignore index a8a38758..91ed183a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,10 @@ .DS_Store __pycache__/ -page/examples/ -page/preload-assets.js -page/assets/ +/page/examples/*/web.js todo.md .mooncakes/ _build/ target + +examples/*/embedded_assets/*.g.mbt diff --git a/AGENTS.md b/AGENTS.md index dde4ea8c..8c9ae9fe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,7 @@ - Follow [CONTRIBUTING.md](CONTRIBUTING.md#release-process) for the release sequence. ## Pages -- Build examples from the repository root with `moon build --target js --release`. Serve the repository root to preview `examples/index.html`. +- Build examples from the repository root with `moon build --target js --release`, then copy the generated JavaScript as described in [page/README.md](page/README.md). Serve `page/` to preview the same directory published by Pages. ## Release Manifest Behavior - Stable publish flow rewrites each release module `moon.mod` version and internal Selene deps to `@x.y.z`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 08b620c0..ecfff743 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,10 +16,10 @@ To try a change in the browser: ```sh moon build --target js --release -python3 -m http.server 8000 ``` -Open . +Follow the [Pages preview instructions](page/README.md) to copy the generated +JavaScript and serve `page/`. See the [README](README.md) for package roles and tutorials. ## Changes and pull requests diff --git a/README-zh.md b/README-zh.md index 400f88b5..49aacf97 100644 --- a/README-zh.md +++ b/README-zh.md @@ -17,10 +17,9 @@ Selene 是一个面向 MoonBit 的 ECS 游戏引擎,提供浏览器 WebGPU 渲 ```bash moon update moon build --target js --release -python3 -m http.server 8000 ``` -打开 `http://localhost:8000/examples/index.html`。 +本地游玩示例请参阅 [Pages 预览说明](page/README.md)。 ## 文档 diff --git a/README.md b/README.md index 79032cef..5cb2771f 100644 --- a/README.md +++ b/README.md @@ -17,10 +17,9 @@ which may report syntax deprecation warnings until `latest` supports the replace ```bash moon update moon build --target js --release -python3 -m http.server 8000 ``` -Open `http://localhost:8000/examples/index.html`. +To play the examples locally, follow the [Pages preview instructions](page/README.md). ## Documentation diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 6a7361da..fcebe303 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -4,6 +4,17 @@ ### Added +- Add typed `Assets[T]` collections and `Handle[T]`, with independent resource + construction, registration, replacement, and removal. Embedded images, fonts, + and audio are used directly without hand-maintained path catalogues. +- Expose backend preparation states separately from file-loader completion. +- Share image resources and handles across Sprite, UI, autotile visuals, and + 3D materials; remove + the separate 3D image registry and image synchronization records. + +- Expose registered asset paths for Tiled world pattern discovery without host + directory scans. + - Add `Query::set(entity, row)` for World-bound point writes that preserve component layouts and iterator validity and reject non-matching rows. @@ -48,6 +59,12 @@ ### Changed +- Keep the complete Pages site in `page/`, with each example loading an + adjacent `web.js`. Build and copy the three game bundles, then deploy `page/` + directly without collecting a separate staging directory. +- Embed example game assets with `moonbit-community/embed` through `dev_build` + and route WebGPU image, font, and audio loading through the embedded data. + Remove the network preloader, asset manifests, and `moonbitlang/x` dependency. - Migrate ordinary gameplay, UI, camera, firing, collision-event, and animation helpers in Cards, Pixel Adventure, and Survivors to injected queries, resources, Commands, and clocks. Private named parameter views combine diff --git a/docs/tutorial-en.md b/docs/tutorial-en.md index d18d510a..a0a7077c 100644 --- a/docs/tutorial-en.md +++ b/docs/tutorial-en.md @@ -50,7 +50,7 @@ This chapter shows how to build a complete platformer-style game with Selene and The game we will build looks like this: -![](../examples/pixeladventure/screenshot.png) +![](../page/examples/pixeladventure/screenshot.png) In the following process, we will build: @@ -111,7 +111,6 @@ import { "Milky2018/selene/transform", "Milky2018/selene/ui", "moonbitlang/core/json", - "moonbitlang/x/fs", } ``` @@ -422,19 +421,20 @@ fn volume_button_input_system(_world : @ecs.World) -> Unit { Build command: ```shell -moon -C examples-web build ./pixeladventure/web --target js --release +moon build examples-web/pixeladventure/web --target js --release +cp _build/js/release/build/Milky2018/selene-examples-web/pixeladventure/web/web.js page/examples/pixeladventure/web.js ``` -Then use `examples/pixeladventure/index.html`, which references: +Then use `page/examples/pixeladventure/index.html`, which references: ```html - + ``` -Run the local server from the repository root: +Run the local server from the repository root, serving the Pages directory: ```shell -python3 -m http.server 8000 +python3 -m http.server --directory page 8000 ``` Open `http://localhost:8000/examples/pixeladventure/` to play. diff --git a/docs/tutorial-zh.md b/docs/tutorial-zh.md index cef33545..d69d26a0 100644 --- a/docs/tutorial-zh.md +++ b/docs/tutorial-zh.md @@ -50,7 +50,7 @@ python3 -m http.server 8000 我们将要制作的游戏如下: -![](../examples/pixeladventure/screenshot.png) +![](../page/examples/pixeladventure/screenshot.png) 我们会在流程中展示如何制作: @@ -111,7 +111,6 @@ import { "Milky2018/selene/transform", "Milky2018/selene/ui", "moonbitlang/core/json", - "moonbitlang/x/fs", } ``` @@ -418,19 +417,20 @@ fn volume_button_input_system(_world : @ecs.World) -> Unit { 构建命令: ```shell -moon -C examples-web build ./pixeladventure/web --target js --release +moon build examples-web/pixeladventure/web --target js --release +cp _build/js/release/build/Milky2018/selene-examples-web/pixeladventure/web/web.js page/examples/pixeladventure/web.js ``` -构建后可直接使用 `examples/pixeladventure/index.html`,其中脚本路径如下: +构建后可直接使用 `page/examples/pixeladventure/index.html`,其中脚本路径如下: ```html - + ``` -然后在仓库根目录启动本地 Web 服务: +然后在仓库根目录启动本地 Web 服务,以 `page/` 为站点目录: ```shell -python3 -m http.server 8000 +python3 -m http.server --directory page 8000 ``` 访问 `http://localhost:8000/examples/pixeladventure/` 即可游玩。 diff --git a/examples/cards/assets/cards/assets-manifest.json b/examples/cards/assets/cards/assets-manifest.json deleted file mode 100644 index 2af0f322..00000000 --- a/examples/cards/assets/cards/assets-manifest.json +++ /dev/null @@ -1,55 +0,0 @@ -[ - "10-C.png", - "10-D.png", - "10-H.png", - "10-S.png", - "2-C.png", - "2-D.png", - "2-H.png", - "2-S.png", - "3-C.png", - "3-D.png", - "3-H.png", - "3-S.png", - "4-C.png", - "4-D.png", - "4-H.png", - "4-S.png", - "5-C.png", - "5-D.png", - "5-H.png", - "5-S.png", - "6-C.png", - "6-D.png", - "6-H.png", - "6-S.png", - "7-C.png", - "7-D.png", - "7-H.png", - "7-S.png", - "8-C.png", - "8-D.png", - "8-H.png", - "8-S.png", - "9-C.png", - "9-D.png", - "9-H.png", - "9-S.png", - "A-C.png", - "A-D.png", - "A-H.png", - "A-S.png", - "J-C.png", - "J-D.png", - "J-H.png", - "J-S.png", - "K-C.png", - "K-D.png", - "K-H.png", - "K-S.png", - "Q-C.png", - "Q-D.png", - "Q-H.png", - "Q-S.png", - "ThaleahFat.ttf" -] diff --git a/examples/cards/embedded_assets/moon.pkg b/examples/cards/embedded_assets/moon.pkg new file mode 100644 index 00000000..875ba8a0 --- /dev/null +++ b/examples/cards/embedded_assets/moon.pkg @@ -0,0 +1,59 @@ +dev_build( + input: [ + "../assets/cards/10-C.png", + "../assets/cards/10-D.png", + "../assets/cards/10-H.png", + "../assets/cards/10-S.png", + "../assets/cards/2-C.png", + "../assets/cards/2-D.png", + "../assets/cards/2-H.png", + "../assets/cards/2-S.png", + "../assets/cards/3-C.png", + "../assets/cards/3-D.png", + "../assets/cards/3-H.png", + "../assets/cards/3-S.png", + "../assets/cards/4-C.png", + "../assets/cards/4-D.png", + "../assets/cards/4-H.png", + "../assets/cards/4-S.png", + "../assets/cards/5-C.png", + "../assets/cards/5-D.png", + "../assets/cards/5-H.png", + "../assets/cards/5-S.png", + "../assets/cards/6-C.png", + "../assets/cards/6-D.png", + "../assets/cards/6-H.png", + "../assets/cards/6-S.png", + "../assets/cards/7-C.png", + "../assets/cards/7-D.png", + "../assets/cards/7-H.png", + "../assets/cards/7-S.png", + "../assets/cards/8-C.png", + "../assets/cards/8-D.png", + "../assets/cards/8-H.png", + "../assets/cards/8-S.png", + "../assets/cards/9-C.png", + "../assets/cards/9-D.png", + "../assets/cards/9-H.png", + "../assets/cards/9-S.png", + "../assets/cards/A-C.png", + "../assets/cards/A-D.png", + "../assets/cards/A-H.png", + "../assets/cards/A-S.png", + "../assets/cards/J-C.png", + "../assets/cards/J-D.png", + "../assets/cards/J-H.png", + "../assets/cards/J-S.png", + "../assets/cards/K-C.png", + "../assets/cards/K-D.png", + "../assets/cards/K-H.png", + "../assets/cards/K-S.png", + "../assets/cards/Q-C.png", + "../assets/cards/Q-D.png", + "../assets/cards/Q-H.png", + "../assets/cards/Q-S.png", + "../assets/cards/ThaleahFat.ttf", + ], + output: "assets.g.mbt", + command: "moonx moonbit-community/embed@0.1.3 \"$pkg_dir/../assets\" -o \"$output\"", +) diff --git a/examples/cards/embedded_assets/pkg.generated.mbti b/examples/cards/embedded_assets/pkg.generated.mbti new file mode 100644 index 00000000..e3c56e87 --- /dev/null +++ b/examples/cards/embedded_assets/pkg.generated.mbti @@ -0,0 +1,72 @@ +// Generated using `moon info`, DON'T EDIT IT +package "Milky2018/selene-examples/cards/embedded_assets" + +// Values +pub let assets : AssetsFixture + +// Errors + +// Types and methods +pub struct AssetsFixture { + cards : CardsFixture +} + +pub struct CardsFixture { + v_2_c_png : Bytes + v_2_d_png : Bytes + v_2_h_png : Bytes + v_2_s_png : Bytes + v_3_c_png : Bytes + v_3_d_png : Bytes + v_3_h_png : Bytes + v_3_s_png : Bytes + v_4_c_png : Bytes + v_4_d_png : Bytes + v_4_h_png : Bytes + v_4_s_png : Bytes + v_5_c_png : Bytes + v_5_d_png : Bytes + v_5_h_png : Bytes + v_5_s_png : Bytes + v_6_c_png : Bytes + v_6_d_png : Bytes + v_6_h_png : Bytes + v_6_s_png : Bytes + v_7_c_png : Bytes + v_7_d_png : Bytes + v_7_h_png : Bytes + v_7_s_png : Bytes + v_8_c_png : Bytes + v_8_d_png : Bytes + v_8_h_png : Bytes + v_8_s_png : Bytes + v_9_c_png : Bytes + v_9_d_png : Bytes + v_9_h_png : Bytes + v_9_s_png : Bytes + a_c_png : Bytes + a_d_png : Bytes + a_h_png : Bytes + a_s_png : Bytes + j_c_png : Bytes + j_d_png : Bytes + j_h_png : Bytes + j_s_png : Bytes + k_c_png : Bytes + k_d_png : Bytes + k_h_png : Bytes + k_s_png : Bytes + q_c_png : Bytes + q_d_png : Bytes + q_h_png : Bytes + q_s_png : Bytes + v_10_c_png : Bytes + v_10_d_png : Bytes + v_10_h_png : Bytes + v_10_s_png : Bytes + thaleahfat_ttf : Bytes +} + +// Type aliases + +// Traits diff --git a/examples/cards/main.mbt b/examples/cards/main.mbt index ab9371b4..94ebb0f5 100644 --- a/examples/cards/main.mbt +++ b/examples/cards/main.mbt @@ -38,7 +38,6 @@ pub fn run() -> Unit { fn game_start(world : @ecs.World) -> Unit { reset_cards_runtime() // Load font - ignore(@asset.load_font("assets/cards/ThaleahFat.ttf", family="ThaleahFat")) @ui.set_ui_scale_mode(Viewport) ignore( spawn_cards_entity( diff --git a/examples/cards/moon.pkg b/examples/cards/moon.pkg index 2912c164..989b9472 100644 --- a/examples/cards/moon.pkg +++ b/examples/cards/moon.pkg @@ -1,4 +1,5 @@ import { + "Milky2018/selene-examples/cards/embedded_assets", "Milky2018/selene/window", "Milky2018/selene/render2d_types", "moonbitlang/core/debug", diff --git a/examples/cards/resources.mbt b/examples/cards/resources.mbt new file mode 100644 index 00000000..1266251a --- /dev/null +++ b/examples/cards/resources.mbt @@ -0,0 +1,11 @@ +///| +let game_font : @asset.FontHandle = @asset.fonts.add( + @asset.Font::from_bytes(@embedded_assets.assets.cards.thaleahfat_ttf), +) + +///| +fn game_text_font(css : String) -> @ui.TextFont { + let style = @ui.TextFont::from_css(css) + style.font_handle = Some(game_font) + style +} diff --git a/examples/cards/restart_wbtest.mbt b/examples/cards/restart_wbtest.mbt index 84152e72..7fcf42d3 100644 --- a/examples/cards/restart_wbtest.mbt +++ b/examples/cards/restart_wbtest.mbt @@ -1,7 +1,5 @@ ///| test "restarting Cards replaces only its entities in the current World" { - @asset.set_io(fn(_path) { Some(Bytes::from_array([1U.to_byte()])) }) - defer @asset.set_io(fn(_path) { None }) let first = @ecs.World() let second = @ecs.World() let other_world_card = Ref(None) @@ -43,8 +41,6 @@ test "restarting Cards replaces only its entities in the current World" { ///| test "injected Cards gameplay refreshes its resource after restart and across Worlds" { - @asset.set_io(fn(_path) { Some(Bytes::from_array([1U.to_byte()])) }) - defer @asset.set_io(fn(_path) { None }) let first = @ecs.World() let second = @ecs.World() let app = cards_app() diff --git a/examples/cards/sprite.mbt b/examples/cards/sprite.mbt index 7b5a12a5..57c24bbe 100644 --- a/examples/cards/sprite.mbt +++ b/examples/cards/sprite.mbt @@ -22,15 +22,17 @@ pub extend Card with Eq::{not_equal, equal} ///| pub extend Card with Hash::{hash, hash_combine} -///| -fn Card::to_path(self : Card) -> String { - "assets/cards/\{self.0.to_string()}-\{self.1.to_string()}.png" -} - ///| fn Card::to_sprite(self : Card) -> @sprite.Sprite { Sprite( - image=Some(@asset.load_image(self.to_path())), + image=Some( + card_images[self.0.to_int() - 2][match self.1 { + C => 0 + D => 1 + H => 2 + S => 3 + }], + ), custom_size=Some(Vec2(59.0, 84.0)), ) } @@ -59,25 +61,6 @@ pub extend CardNum with Eq::{not_equal, equal} ///| pub extend CardNum with Hash::{hash, hash_combine} -///| -fn CardNum::to_string(self : CardNum) -> String { - match self { - A => "A" - N2 => "2" - N3 => "3" - N4 => "4" - N5 => "5" - N6 => "6" - N7 => "7" - N8 => "8" - N9 => "9" - N10 => "10" - J => "J" - Q => "Q" - K => "K" - } -} - ///| fn CardNum::to_int(self : CardNum) -> Int32 { match self { @@ -113,11 +96,25 @@ pub extend CardSuit with Eq::{not_equal, equal} pub extend CardSuit with Hash::{hash, hash_combine} ///| -fn CardSuit::to_string(self : CardSuit) -> String { - match self { - H => "H" - D => "D" - C => "C" - S => "S" - } +// Rows follow numeric rank 2 through ace; columns are clubs, diamonds, hearts, spades. +let card_images : Array[Array[@asset.ImageHandle]] = { + let cards = @embedded_assets.assets.cards + let bytes = [ + [cards.v_2_c_png, cards.v_2_d_png, cards.v_2_h_png, cards.v_2_s_png], + [cards.v_3_c_png, cards.v_3_d_png, cards.v_3_h_png, cards.v_3_s_png], + [cards.v_4_c_png, cards.v_4_d_png, cards.v_4_h_png, cards.v_4_s_png], + [cards.v_5_c_png, cards.v_5_d_png, cards.v_5_h_png, cards.v_5_s_png], + [cards.v_6_c_png, cards.v_6_d_png, cards.v_6_h_png, cards.v_6_s_png], + [cards.v_7_c_png, cards.v_7_d_png, cards.v_7_h_png, cards.v_7_s_png], + [cards.v_8_c_png, cards.v_8_d_png, cards.v_8_h_png, cards.v_8_s_png], + [cards.v_9_c_png, cards.v_9_d_png, cards.v_9_h_png, cards.v_9_s_png], + [cards.v_10_c_png, cards.v_10_d_png, cards.v_10_h_png, cards.v_10_s_png], + [cards.j_c_png, cards.j_d_png, cards.j_h_png, cards.j_s_png], + [cards.q_c_png, cards.q_d_png, cards.q_h_png, cards.q_s_png], + [cards.k_c_png, cards.k_d_png, cards.k_h_png, cards.k_s_png], + [cards.a_c_png, cards.a_d_png, cards.a_h_png, cards.a_s_png], + ] + bytes.map(row => { + row.map(data => @asset.images.add(@asset.Image::from_bytes(data))) + }) } diff --git a/examples/cards/ui.mbt b/examples/cards/ui.mbt index 260203a8..f0f3fb28 100644 --- a/examples/cards/ui.mbt +++ b/examples/cards/ui.mbt @@ -62,7 +62,7 @@ fn spawn_text( @ui.Node::absolute(offset, size~), @ui.ZIndex(zindex), @ui.Text(content), - @ui.TextFont::from_css(font), + game_text_font(font), @ui.TextColor::from_css(color), @ui.TextLayout(align~, baseline~), ), diff --git a/examples/moon.mod b/examples/moon.mod index a521e113..6960e30e 100644 --- a/examples/moon.mod +++ b/examples/moon.mod @@ -4,7 +4,6 @@ version = "0.21.2" import { "Milky2018/selene@0.39.1", - "moonbitlang/x@0.5.7", } readme = "README.md" diff --git a/examples/pixeladventure/asset_io_support.mbt b/examples/pixeladventure/asset_io_support.mbt deleted file mode 100644 index 62ceb1a3..00000000 --- a/examples/pixeladventure/asset_io_support.mbt +++ /dev/null @@ -1,37 +0,0 @@ -///| -fn read_file_bytes_if_exists(path : String) -> Bytes? { - if !@fs.path_exists(path) { - return None - } - Some(@fs.read_file_to_bytes(path)) catch { - _ => None - } -} - -///| -let pixeladventure_test_asset_root : String = "pixeladventure" - -///| -fn pixeladventure_test_asset_path(path : String) -> String { - let normalized = path.replace(old="\\", new="/") - if normalized == "" { - pixeladventure_test_asset_root - } else { - pixeladventure_test_asset_root + "/" + normalized - } -} - -///| -fn pixeladventure_test_asset_reader(path : String) -> Bytes? { - read_file_bytes_if_exists(pixeladventure_test_asset_path(path)) -} - -///| -pub fn with_pixeladventure_test_asset_io( - action : () -> Unit raise, -) -> Unit raise { - @asset.set_io(pixeladventure_test_asset_reader) - errdefer @asset.set_io(fn(_path : String) { None }) - action() - @asset.set_io(fn(_path : String) { None }) -} diff --git a/examples/pixeladventure/assets/pixeladventure/assets-manifest.json b/examples/pixeladventure/assets/pixeladventure/assets-manifest.json deleted file mode 100644 index e9026da9..00000000 --- a/examples/pixeladventure/assets/pixeladventure/assets-manifest.json +++ /dev/null @@ -1,20 +0,0 @@ -[ - "Background/Gray.png", - "Enemies/BlueBird/Flying (32x32).png", - "Enemies/BlueBird/Hit (32x32).png", - "Fonts/ThaleahFat.ttf", - "Items/Checkpoints/Checkpoint/Checkpoint (Flag Idle)(64x64).png", - "Items/Fruits/Apple.png", - "Main Characters/Mask Dude/Fall (32x32).png", - "Main Characters/Mask Dude/Hit (32x32).png", - "Main Characters/Mask Dude/Idle (32x32).png", - "Main Characters/Mask Dude/Jump (32x32).png", - "Main Characters/Mask Dude/Run (32x32).png", - "Menu/Buttons/Volume.png", - "Menu/Buttons/VolumeOff.png", - "Terrain/Terrain (16x16).png", - "arrowkey.png", - "sounds/coin.wav", - "sounds/hurt.wav", - "sounds/jump.wav" -] diff --git a/examples/pixeladventure/embedded_assets/moon.pkg b/examples/pixeladventure/embedded_assets/moon.pkg new file mode 100644 index 00000000..117d2b6c --- /dev/null +++ b/examples/pixeladventure/embedded_assets/moon.pkg @@ -0,0 +1,23 @@ +dev_build( + input: [ + "../assets/pixeladventure/Background/Gray.png", + "../assets/pixeladventure/Enemies/BlueBird/Flying (32x32).png", + "../assets/pixeladventure/Enemies/BlueBird/Hit (32x32).png", + "../assets/pixeladventure/Fonts/ThaleahFat.ttf", + "../assets/pixeladventure/Items/Checkpoints/Checkpoint/Checkpoint (Flag Idle)(64x64).png", + "../assets/pixeladventure/Items/Fruits/Apple.png", + "../assets/pixeladventure/Main Characters/Mask Dude/Fall (32x32).png", + "../assets/pixeladventure/Main Characters/Mask Dude/Hit (32x32).png", + "../assets/pixeladventure/Main Characters/Mask Dude/Idle (32x32).png", + "../assets/pixeladventure/Main Characters/Mask Dude/Jump (32x32).png", + "../assets/pixeladventure/Main Characters/Mask Dude/Run (32x32).png", + "../assets/pixeladventure/Menu/Buttons/Volume.png", + "../assets/pixeladventure/Menu/Buttons/VolumeOff.png", + "../assets/pixeladventure/Terrain/Terrain (16x16).png", + "../assets/pixeladventure/sounds/coin.wav", + "../assets/pixeladventure/sounds/hurt.wav", + "../assets/pixeladventure/sounds/jump.wav", + ], + output: "assets.g.mbt", + command: "moonx moonbit-community/embed@0.1.3 \"$pkg_dir/../assets\" -o \"$output\"", +) diff --git a/examples/pixeladventure/embedded_assets/pkg.generated.mbti b/examples/pixeladventure/embedded_assets/pkg.generated.mbti new file mode 100644 index 00000000..87728553 --- /dev/null +++ b/examples/pixeladventure/embedded_assets/pkg.generated.mbti @@ -0,0 +1,92 @@ +// Generated using `moon info`, DON'T EDIT IT +package "Milky2018/selene-examples/pixeladventure/embedded_assets" + +// Values +pub let assets : AssetsFixture + +// Errors + +// Types and methods +pub struct AssetsFixture { + pixeladventure : PixeladventureFixture +} + +pub struct BackgroundFixture { + gray_png : Bytes +} + +pub struct BluebirdFixture { + hit_32x32_png : Bytes + flying_32x32_png : Bytes +} + +pub struct ButtonsFixture { + volume_png : Bytes + volumeoff_png : Bytes +} + +pub struct CheckpointFixture { + checkpoint_flag_idle_64x64_png : Bytes +} + +pub struct CheckpointsFixture { + checkpoint : CheckpointFixture +} + +pub struct EnemiesFixture { + bluebird : BluebirdFixture +} + +pub struct FontsFixture { + thaleahfat_ttf : Bytes +} + +pub struct FruitsFixture { + apple_png : Bytes +} + +pub struct ItemsFixture { + fruits : FruitsFixture + checkpoints : CheckpointsFixture +} + +pub struct MainCharactersFixture { + mask_dude : MaskDudeFixture +} + +pub struct MaskDudeFixture { + hit_32x32_png : Bytes + run_32x32_png : Bytes + fall_32x32_png : Bytes + idle_32x32_png : Bytes + jump_32x32_png : Bytes +} + +pub struct MenuFixture { + buttons : ButtonsFixture +} + +pub struct PixeladventureFixture { + menu : MenuFixture + fonts : FontsFixture + items : ItemsFixture + sounds : SoundsFixture + enemies : EnemiesFixture + terrain : TerrainFixture + background : BackgroundFixture + main_characters : MainCharactersFixture +} + +pub struct SoundsFixture { + coin_wav : Bytes + hurt_wav : Bytes + jump_wav : Bytes +} + +pub struct TerrainFixture { + terrain_16x16_png : Bytes +} + +// Type aliases + +// Traits diff --git a/examples/pixeladventure/frame_rate_wbtest.mbt b/examples/pixeladventure/frame_rate_wbtest.mbt index 12a6ed69..71073d37 100644 --- a/examples/pixeladventure/frame_rate_wbtest.mbt +++ b/examples/pixeladventure/frame_rate_wbtest.mbt @@ -43,47 +43,42 @@ fn player_motion_at_refresh_rate(refresh : Int32) -> Array[@math.Vec2] raise { ///| test "player movement follows identical fixed steps at 60 120 and 144 Hz" { - with_pixeladventure_test_asset_io(fn() raise { - let baseline = player_motion_at_refresh_rate(60) - assert_true(baseline.iter().any(position => position.y < 450.0)) - for refresh in [120, 144] { - assert_eq(player_motion_at_refresh_rate(refresh), baseline) - } - }) + let baseline = player_motion_at_refresh_rate(60) + assert_true(baseline.iter().any(position => position.y < 450.0)) + for refresh in [120, 144] { + assert_eq(player_motion_at_refresh_rate(refresh), baseline) + } } ///| test "a jump press survives render frames without a physics step" { - with_pixeladventure_test_asset_io(fn() raise { - with_pixeladventure_test_world(fn(world) raise { - @time.initialize(world) - game_start(world) - flush_test_commands(world) - let session : GameSession = world.resource() - let pressed = @inputs.InputSnapshot() - pressed.pressed_keys.add(ArrowUp) - @inputs.apply_input_snapshot(pressed) - @input_action.input_action_system() - @ecs.args2(player_input_system)(test_params(world)) - @inputs.apply_input_snapshot(InputSnapshot()) - @input_action.input_action_system() - @ecs.args2(player_input_system)(test_params(world)) - let controller = ( - world.query() : @ecs.Query[@ecs.Single[PlayerController]]) - .get(session.player) - .map(value => value.0) - .unwrap() - assert_true(controller.jump_requested) - @physics2d.grounded_entities().add(session.player) - @time.use_fixed_delta(1.0 / 60.0) - @ecs.args4(player_controller_system)(test_params(world)) - assert_false(controller.jump_requested) - let velocity = ( - world.query() : @ecs.Query[@ecs.Single[@physics2d.LinearVelocity]]) - .get(session.player) - .map(value => value.0) - .unwrap() - assert_true((velocity.0.y - (-JUMP_V + GRAVITY / 60.0)).abs() < 0.000001) - }) + with_pixeladventure_test_world(fn(world) raise { + @time.initialize(world) + game_start(world) + flush_test_commands(world) + let session : GameSession = world.resource() + let pressed = @inputs.InputSnapshot() + pressed.pressed_keys.add(ArrowUp) + @inputs.apply_input_snapshot(pressed) + @input_action.input_action_system() + @ecs.args2(player_input_system)(test_params(world)) + @inputs.apply_input_snapshot(InputSnapshot()) + @input_action.input_action_system() + @ecs.args2(player_input_system)(test_params(world)) + let controller = (world.query() : @ecs.Query[@ecs.Single[PlayerController]]) + .get(session.player) + .map(value => value.0) + .unwrap() + assert_true(controller.jump_requested) + @physics2d.grounded_entities().add(session.player) + @time.use_fixed_delta(1.0 / 60.0) + @ecs.args4(player_controller_system)(test_params(world)) + assert_false(controller.jump_requested) + let velocity = ( + world.query() : @ecs.Query[@ecs.Single[@physics2d.LinearVelocity]]) + .get(session.player) + .map(value => value.0) + .unwrap() + assert_true((velocity.0.y - (-JUMP_V + GRAVITY / 60.0)).abs() < 0.000001) }) } diff --git a/examples/pixeladventure/level.mbt b/examples/pixeladventure/level.mbt index e9646520..b925fef7 100644 --- a/examples/pixeladventure/level.mbt +++ b/examples/pixeladventure/level.mbt @@ -34,9 +34,6 @@ fn load_level_scene(world~ : @ecs.World) -> LoadedLevelScene { } spawn_bird_entity(world~, 240.0, 50.0) spawn_bird_entity(world~, 752.0, 210.0) - let terrain_image = @asset.load_image( - "assets/pixeladventure/Terrain/Terrain (16x16).png", - ) let rows : Map[Int32, Array[Int32]] = Map([]) let plan : @ecs.SpawnPlan[(@transform.Spatial, @sprite.Sprite)] = @ecs.commands( world, diff --git a/examples/pixeladventure/model.mbt b/examples/pixeladventure/model.mbt index aebe2584..bc8027c4 100644 --- a/examples/pixeladventure/model.mbt +++ b/examples/pixeladventure/model.mbt @@ -12,12 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -///| -const FONT_FAMILY : String = "ThaleahFat" - -///| -const FONT_PATH : String = "assets/pixeladventure/Fonts/ThaleahFat.ttf" - ///| const HUD_ZINDEX : Int32 = 100 @@ -27,9 +21,6 @@ const BUTTON_ZINDEX : Int32 = 110 ///| const PLAYFIELD_LEFT_INSET : Double = 48.0 -///| -const FLAG_IDLE_PATH : String = "assets/pixeladventure/Items/Checkpoints/Checkpoint/Checkpoint (Flag Idle)(64x64).png" - ///| const PLAYER_Z : Double = 10.0 @@ -133,7 +124,7 @@ priv struct BirdAnimationNodes { ///| priv struct SpriteAnimationDef { name : String - image_path : String + image : @asset.ImageHandle layout : @sprite.TextureAtlasLayoutHandle fps : Double loop_ : Bool @@ -232,7 +223,7 @@ fn ui_click_reader() -> @event.EventReader[@ui.UiClickEvent] { ///| fn SpriteAnimationDef::SpriteAnimationDef( - path : String, + image : @asset.ImageHandle, frame_count : Int32, loop_~ : Bool = true, fps~ : Double = 12.0, @@ -241,8 +232,8 @@ fn SpriteAnimationDef::SpriteAnimationDef( anchor~ : @sprite.Anchor = Anchor(Vec2(-0.5, 0.5)), ) -> SpriteAnimationDef { { - name: path, - image_path: path, + name: "sprite-\{image.id()}", + image, layout: @sprite.register_texture_atlas_layout( @sprite.TextureAtlasLayout::from_grid(size, frame_count, 1), ), @@ -258,7 +249,7 @@ fn SpriteAnimationDef::SpriteAnimationDef( ///| fn sprite_animation_sprite(animation : SpriteAnimationDef) -> @sprite.Sprite { Sprite( - image=Some(@asset.load_image(animation.image_path)), + image=Some(animation.image), texture_atlas=Some(TextureAtlas(animation.layout)), custom_size=Some(animation.size), anchor=animation.anchor, @@ -267,97 +258,74 @@ fn sprite_animation_sprite(animation : SpriteAnimationDef) -> @sprite.Sprite { ) } -///| -fn jump_sound() -> @audio.AudioHandle { - @asset.load_audio("assets/pixeladventure/sounds/jump.wav") -} - -///| -fn coin_sound() -> @audio.AudioHandle { - @asset.load_audio("assets/pixeladventure/sounds/coin.wav") -} - -///| -fn hurt_sound() -> @audio.AudioHandle { - @asset.load_audio("assets/pixeladventure/sounds/hurt.wav") -} - ///| fn volume_on_ui_image() -> @ui.UiImage { - UiImage( - Vec2(21.0, 22.0), - "assets/pixeladventure/Menu/Buttons/Volume.png", - fit=Contain, - ) + @ui.UiImage::from_image(Vec2(21.0, 22.0), volume_on_image, fit=Contain) } ///| fn volume_off_ui_image() -> @ui.UiImage { - UiImage( - Vec2(21.0, 22.0), - "assets/pixeladventure/Menu/Buttons/VolumeOff.png", - fit=Contain, - ) + @ui.UiImage::from_image(Vec2(21.0, 22.0), volumeoff_image, fit=Contain) } ///| let player_idle_right_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/pixeladventure/Main Characters/Mask Dude/Idle (32x32).png", 11, + player_idle_image, 11, ) ///| let player_idle_left_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/pixeladventure/Main Characters/Mask Dude/Idle (32x32).png", + player_idle_image, 11, flip_x=true, ) ///| let player_run_right_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/pixeladventure/Main Characters/Mask Dude/Run (32x32).png", 12, + player_run_image, 12, ) ///| let player_run_left_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/pixeladventure/Main Characters/Mask Dude/Run (32x32).png", + player_run_image, 12, flip_x=true, ) ///| let player_fall_right_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/pixeladventure/Main Characters/Mask Dude/Fall (32x32).png", 1, + player_fall_image, 1, ) ///| let player_fall_left_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/pixeladventure/Main Characters/Mask Dude/Fall (32x32).png", + player_fall_image, 1, flip_x=true, ) ///| let player_jump_right_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/pixeladventure/Main Characters/Mask Dude/Jump (32x32).png", 1, + player_jump_image, 1, ) ///| let player_jump_left_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/pixeladventure/Main Characters/Mask Dude/Jump (32x32).png", + player_jump_image, 1, flip_x=true, ) ///| let player_hit_right_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/pixeladventure/Main Characters/Mask Dude/Hit (32x32).png", + player_hit_image, 7, loop_=false, ) ///| let player_hit_left_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/pixeladventure/Main Characters/Mask Dude/Hit (32x32).png", + player_hit_image, 7, loop_=false, flip_x=true, @@ -365,19 +333,19 @@ let player_hit_left_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let bird_fly_right_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/pixeladventure/Enemies/BlueBird/Flying (32x32).png", + bird_flying_image, 9, flip_x=true, ) ///| let bird_fly_left_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/pixeladventure/Enemies/BlueBird/Flying (32x32).png", 9, + bird_flying_image, 9, ) ///| let bird_hit_right_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/pixeladventure/Enemies/BlueBird/Hit (32x32).png", + bird_hit_image, 5, loop_=false, flip_x=true, @@ -385,19 +353,19 @@ let bird_hit_right_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let bird_hit_left_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/pixeladventure/Enemies/BlueBird/Hit (32x32).png", + bird_hit_image, 5, loop_=false, ) ///| let apple_spin_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/pixeladventure/Items/Fruits/Apple.png", 17, + apple_image, 17, ) ///| let flag_idle_animation : SpriteAnimationDef = SpriteAnimationDef( - FLAG_IDLE_PATH, + flag_idle_image, 10, size=Vec2(64.0, 64.0), ) diff --git a/examples/pixeladventure/moon.pkg b/examples/pixeladventure/moon.pkg index 104fbef7..a06c1e7a 100644 --- a/examples/pixeladventure/moon.pkg +++ b/examples/pixeladventure/moon.pkg @@ -1,4 +1,5 @@ import { + "Milky2018/selene-examples/pixeladventure/embedded_assets", "Milky2018/selene/render2d_types", "Milky2018/selene/app", "Milky2018/selene/animation", @@ -17,7 +18,6 @@ import { "Milky2018/selene/event", "Milky2018/selene/inputs", "Milky2018/selene/touch_controls", - "moonbitlang/x/fs", } supported_targets = "all" diff --git a/examples/pixeladventure/pkg.generated.mbti b/examples/pixeladventure/pkg.generated.mbti index b0af75c4..5a8f886e 100644 --- a/examples/pixeladventure/pkg.generated.mbti +++ b/examples/pixeladventure/pkg.generated.mbti @@ -4,8 +4,6 @@ package "Milky2018/selene-examples/pixeladventure" // Values pub fn run() -> Unit -pub fn with_pixeladventure_test_asset_io(() -> Unit raise) -> Unit raise - // Errors // Types and methods diff --git a/examples/pixeladventure/resources.mbt b/examples/pixeladventure/resources.mbt new file mode 100644 index 00000000..a08048a8 --- /dev/null +++ b/examples/pixeladventure/resources.mbt @@ -0,0 +1,125 @@ +///| +let background_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.pixeladventure.background.gray_png, + ), +) + +///| +let bird_flying_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.pixeladventure.enemies.bluebird.flying_32x32_png, + ), +) + +///| +let bird_hit_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.pixeladventure.enemies.bluebird.hit_32x32_png, + ), +) + +///| +let flag_idle_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.pixeladventure.items.checkpoints.checkpoint.checkpoint_flag_idle_64x64_png, + ), +) + +///| +let apple_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.pixeladventure.items.fruits.apple_png, + ), +) + +///| +let player_fall_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.pixeladventure.main_characters.mask_dude.fall_32x32_png, + ), +) + +///| +let player_hit_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.pixeladventure.main_characters.mask_dude.hit_32x32_png, + ), +) + +///| +let player_idle_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.pixeladventure.main_characters.mask_dude.idle_32x32_png, + ), +) + +///| +let player_jump_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.pixeladventure.main_characters.mask_dude.jump_32x32_png, + ), +) + +///| +let player_run_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.pixeladventure.main_characters.mask_dude.run_32x32_png, + ), +) + +///| +let volume_on_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.pixeladventure.menu.buttons.volume_png, + ), +) + +///| +let volumeoff_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.pixeladventure.menu.buttons.volumeoff_png, + ), +) + +///| +let terrain_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.pixeladventure.terrain.terrain_16x16_png, + ), +) + +///| +let coin_sound : @asset.AudioHandle = @asset.audios.add( + @asset.Audio::from_bytes( + @embedded_assets.assets.pixeladventure.sounds.coin_wav, + ), +) + +///| +let hurt_sound : @asset.AudioHandle = @asset.audios.add( + @asset.Audio::from_bytes( + @embedded_assets.assets.pixeladventure.sounds.hurt_wav, + ), +) + +///| +let jump_sound : @asset.AudioHandle = @asset.audios.add( + @asset.Audio::from_bytes( + @embedded_assets.assets.pixeladventure.sounds.jump_wav, + ), +) + +///| +let game_font : @asset.FontHandle = @asset.fonts.add( + @asset.Font::from_bytes( + @embedded_assets.assets.pixeladventure.fonts.thaleahfat_ttf, + ), +) + +///| +fn game_text_font(css : String) -> @ui.TextFont { + let style = @ui.TextFont::from_css(css) + style.font_handle = Some(game_font) + style +} diff --git a/examples/pixeladventure/scene_runtime_wbtest.mbt b/examples/pixeladventure/scene_runtime_wbtest.mbt index 260a5854..ad84a19d 100644 --- a/examples/pixeladventure/scene_runtime_wbtest.mbt +++ b/examples/pixeladventure/scene_runtime_wbtest.mbt @@ -20,131 +20,119 @@ fn with_pixeladventure_test_world( ///| test "level loading preserves gameplay entities and terrain" { - with_pixeladventure_test_asset_io(fn() raise { - with_pixeladventure_test_world(fn(world) raise { - let loaded = load_level_scene(world~) - flush_test_commands(world) - inspect( - (world.query() : @ecs.Query[@ecs.Single[PlayerController]]).length(), - content="1", - ) - inspect( - (world.query() : @ecs.Query[@ecs.Single[BirdController]]).length(), - content="2", - ) - inspect( - (world.query() : @ecs.Query[@ecs.Single[AppleTag]]).length(), - content="7", - ) - inspect( - (world.query() : @ecs.Query[@ecs.Single[FlagTag]]).length(), - content="1", - ) - let player_transform = @transform.local_transform( - world~, - loaded.player_entity, - ).unwrap() - inspect(player_transform.translation.x, content="80") - inspect(player_transform.translation.y, content="496") - inspect(player_transform.translation.z == PLAYER_Z, content="true") - inspect(loaded.world_size == Vec2(928.0, 576.0), content="true") - inspect( - (world.query() : @ecs.Query[@ecs.Single[@camera.Camera2d]]).contains( - loaded.camera_entity, - ), - content="true", - ) - let mut terrain_count = 0 - for - _, Single(sprite) in ( - world.query() : @ecs.Query[@ecs.Single[@sprite.Sprite]]) { - if sprite.image.bind(@asset.image_path) == - Some("assets/pixeladventure/Terrain/Terrain (16x16).png") { - terrain_count += 1 - } + with_pixeladventure_test_world(fn(world) raise { + let loaded = load_level_scene(world~) + flush_test_commands(world) + inspect( + (world.query() : @ecs.Query[@ecs.Single[PlayerController]]).length(), + content="1", + ) + inspect( + (world.query() : @ecs.Query[@ecs.Single[BirdController]]).length(), + content="2", + ) + inspect( + (world.query() : @ecs.Query[@ecs.Single[AppleTag]]).length(), + content="7", + ) + inspect( + (world.query() : @ecs.Query[@ecs.Single[FlagTag]]).length(), + content="1", + ) + let player_transform = @transform.local_transform( + world~, + loaded.player_entity, + ).unwrap() + inspect(player_transform.translation.x, content="80") + inspect(player_transform.translation.y, content="496") + inspect(player_transform.translation.z == PLAYER_Z, content="true") + inspect(loaded.world_size == Vec2(928.0, 576.0), content="true") + inspect( + (world.query() : @ecs.Query[@ecs.Single[@camera.Camera2d]]).contains( + loaded.camera_entity, + ), + content="true", + ) + let mut terrain_count = 0 + for + _, Single(sprite) in ( + world.query() : @ecs.Query[@ecs.Single[@sprite.Sprite]]) { + if sprite.image == Some(terrain_image) { + terrain_count += 1 } - inspect(terrain_count, content="702") - }) + } + inspect(terrain_count, content="702") }) } ///| test "level flag retains its animated sprite" { - with_pixeladventure_test_asset_io(fn() raise { - with_pixeladventure_test_world(fn(world) raise { - ignore(load_level_scene(world~)) - flush_test_commands(world) - let flag_entity = (world.query() : @ecs.Query[@ecs.Single[FlagTag]]).to_array()[0].0 - let flag_sprite = (world.query() : @ecs.Query[@ecs.Single[@sprite.Sprite]]) - .get(flag_entity) - .map(value => value.0) - .unwrap() - inspect( - flag_sprite.image.bind(@asset.image_path) == Some(FLAG_IDLE_PATH), - content="true", - ) - let atlas = flag_sprite.texture_atlas.unwrap() - inspect( - @sprite.texture_atlas_layout(atlas.layout).unwrap().rects.length(), - content="10", - ) - inspect( - (world.query() : @ecs.Query[@ecs.Single[@animation.AnimationPlayer]]).contains( - flag_entity, - ), - content="true", - ) - }) + with_pixeladventure_test_world(fn(world) raise { + ignore(load_level_scene(world~)) + flush_test_commands(world) + let flag_entity = (world.query() : @ecs.Query[@ecs.Single[FlagTag]]).to_array()[0].0 + let flag_sprite = (world.query() : @ecs.Query[@ecs.Single[@sprite.Sprite]]) + .get(flag_entity) + .map(value => value.0) + .unwrap() + inspect(flag_sprite.image == Some(flag_idle_image), content="true") + let atlas = flag_sprite.texture_atlas.unwrap() + inspect( + @sprite.texture_atlas_layout(atlas.layout).unwrap().rects.length(), + content="10", + ) + inspect( + (world.query() : @ecs.Query[@ecs.Single[@animation.AnimationPlayer]]).contains( + flag_entity, + ), + content="true", + ) }) } ///| test "restarting Pixel Adventure replaces its session and game entities" { - with_pixeladventure_test_asset_io(fn() raise { - with_pixeladventure_test_world(fn(world) raise { - let other = @ecs.commands(@ecs.require_current_world()).spawn(()) - game_start(world) - flush_test_commands(world) - let previous_session : GameSession = world.resource() - previous_session.score = 100 - previous_session.health = 1 - previous_session.volume_on = false - previous_session.result = Some(Win) - let previous_entities = pixeladventure_world_state().entities.copy() - let entity_count = @ecs.alive_entity_count() - assert_false(previous_entities.is_empty()) + with_pixeladventure_test_world(fn(world) raise { + let other = @ecs.commands(@ecs.require_current_world()).spawn(()) + game_start(world) + flush_test_commands(world) + let previous_session : GameSession = world.resource() + previous_session.score = 100 + previous_session.health = 1 + previous_session.volume_on = false + previous_session.result = Some(Win) + let previous_entities = pixeladventure_world_state().entities.copy() + let entity_count = @ecs.alive_entity_count() + assert_false(previous_entities.is_empty()) - game_start(world) - flush_test_commands(world) + game_start(world) + flush_test_commands(world) - assert_eq(@ecs.alive_entity_count(), entity_count) - assert_true(other.is_alive()) - let session : GameSession = world.resource() - assert_true(session.player != previous_session.player) - assert_eq(session.score, 0) - assert_eq(session.health, 3) - assert_true(session.volume_on) - assert_true(session.result is None) - for entity in previous_entities { - assert_false(entity.is_valid_in(world)) - } - }) + assert_eq(@ecs.alive_entity_count(), entity_count) + assert_true(other.is_alive()) + let session : GameSession = world.resource() + assert_true(session.player != previous_session.player) + assert_eq(session.score, 0) + assert_eq(session.health, 3) + assert_true(session.volume_on) + assert_true(session.result is None) + for entity in previous_entities { + assert_false(entity.is_valid_in(world)) + } }) } ///| test "injected trigger queries collect an apple and delete it at schedule completion" { - with_pixeladventure_test_asset_io(fn() raise { - with_pixeladventure_test_world(fn(world) raise { - game_start(world) - flush_test_commands(world) - let session : GameSession = world.resource() - let apples : @ecs.Query[(AppleTag, @physics2d.Area)] = world.query() - let (entity, (_, area)) = apples.iter().next().unwrap() - area.contains.add(session.player) - @ecs.Schedule().add_system(@ecs.args4(trigger_system)).run(world) - assert_eq(session.score, 10) - assert_false(entity.is_valid_in(world)) - }) + with_pixeladventure_test_world(fn(world) raise { + game_start(world) + flush_test_commands(world) + let session : GameSession = world.resource() + let apples : @ecs.Query[(AppleTag, @physics2d.Area)] = world.query() + let (entity, (_, area)) = apples.iter().next().unwrap() + area.contains.add(session.player) + @ecs.Schedule().add_system(@ecs.args4(trigger_system)).run(world) + assert_eq(session.score, 10) + assert_false(entity.is_valid_in(world)) }) } diff --git a/examples/pixeladventure/spawn.mbt b/examples/pixeladventure/spawn.mbt index 64e11bef..337bf34c 100644 --- a/examples/pixeladventure/spawn.mbt +++ b/examples/pixeladventure/spawn.mbt @@ -14,7 +14,6 @@ ///| fn game_start(world : @ecs.World) -> Unit { - ignore(@asset.load_font(FONT_PATH, family=FONT_FAMILY)) @ui.set_ui_scale_mode(Viewport) configure_pixeladventure_input() reset_pixeladventure_world_store() @@ -90,7 +89,7 @@ fn spawn_text_box( @ui.Node::absolute(offset, size~), @ui.ZIndex(HUD_ZINDEX), @ui.Text(content), - @ui.TextFont::from_css(font), + game_text_font(font), @ui.TextColor::from_css(color), @ui.TextLayout(align~, baseline~), ), @@ -250,9 +249,7 @@ fn spawn_background(size : @math.Vec2) -> Unit { spawn_game_entity( ( @sprite.Sprite( - image=Some( - @asset.load_image("assets/pixeladventure/Background/Gray.png"), - ), + image=Some(background_image), custom_size=Some(size), anchor=Anchor(Vec2(-0.5, 0.5)), image_mode=Tiled(Repeat), diff --git a/examples/pixeladventure/systems.mbt b/examples/pixeladventure/systems.mbt index 5a7e6688..920ab5bc 100644 --- a/examples/pixeladventure/systems.mbt +++ b/examples/pixeladventure/systems.mbt @@ -397,7 +397,7 @@ fn hurt_player( if session.health <= 0 { session.result = Some(GameOver) } - play_sfx(hurt_sound(), session.volume_on) + play_sfx(hurt_sound, session.volume_on) Some(knockback) } @@ -501,7 +501,7 @@ fn player_controller_system( if grounded && jump_requested { new_velocity_y = -JUMP_V controller.state = Jump - play_sfx(jump_sound(), session.volume_on) + play_sfx(jump_sound, session.volume_on) } else if !grounded { controller.state = if velocity.y > 0.0 { Fall } else { Jump } } else if new_velocity_x != 0.0 { @@ -678,7 +678,7 @@ fn trigger_system( } if area.contains.contains(session.player) { session.score += 10 - play_sfx(coin_sound(), session.volume_on) + play_sfx(coin_sound, session.volume_on) commands.delete(apple_entity) } } diff --git a/examples/preload-assets.js b/examples/preload-assets.js deleted file mode 100644 index daf36b4f..00000000 --- a/examples/preload-assets.js +++ /dev/null @@ -1,90 +0,0 @@ -// Asset preloader for examples -(function () { - 'use strict'; - - const DEFAULT_PRELOAD_CONCURRENCY = 8; - - function detectGameName() { - const parts = window.location.pathname.split('/').filter(Boolean); - if (parts.length === 0) return ''; - const last = parts[parts.length - 1]; - if (last.endsWith('.html')) { - return parts.length >= 2 ? parts[parts.length - 2] : ''; - } - return last; - } - - const gameName = detectGameName(); - if (!gameName) return; - - const ASSETS_BASE_PATH = `assets/${gameName}/`; - const MANIFEST_PATH = ASSETS_BASE_PATH + 'assets-manifest.json'; - - function preferredConcurrency() { - const hardware = navigator.hardwareConcurrency || DEFAULT_PRELOAD_CONCURRENCY; - return Math.max(4, Math.min(DEFAULT_PRELOAD_CONCURRENCY, hardware)); - } - - function waitForIdle() { - return new Promise(resolve => { - if (typeof window.requestIdleCallback === 'function') { - window.requestIdleCallback(() => resolve(), { timeout: 200 }); - } else { - window.setTimeout(resolve, 0); - } - }); - } - - async function preloadWithConcurrency(assetPaths, limit) { - let index = 0; - - async function worker() { - while (index < assetPaths.length) { - const currentIndex = index; - index += 1; - const path = assetPaths[currentIndex]; - try { - await fetch(ASSETS_BASE_PATH + path); - } catch (error) { - console.warn('Failed to preload asset:', path, error); - } - } - } - - const workers = Array.from( - { length: Math.min(limit, assetPaths.length) }, - () => worker(), - ); - await Promise.all(workers); - } - - // Fetch and preload all assets - async function preloadAssets() { - try { - // Fetch the manifest - const response = await fetch(MANIFEST_PATH); - if (!response.ok) { - console.warn('Failed to load asset manifest:', response.statusText); - return; - } - - const assetPaths = await response.json(); - console.log(`Found ${assetPaths.length} assets to preload`); - - // Yield one frame before starting network-heavy background work. - await waitForIdle(); - await preloadWithConcurrency(assetPaths, preferredConcurrency()); - console.log('All assets preloaded successfully'); - - } catch (error) { - console.error('Error preloading assets:', error); - } - } - - // Start preloading when DOM is ready - if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', preloadAssets); - } else { - preloadAssets(); - } -})(); diff --git a/examples/survivors/assets/survivors/assets-manifest.json b/examples/survivors/assets/survivors/assets-manifest.json deleted file mode 100644 index 16714190..00000000 --- a/examples/survivors/assets/survivors/assets-manifest.json +++ /dev/null @@ -1,28 +0,0 @@ -[ - "enemy/Creeper.png", - "enemy/Devil.png", - "enemy/Icecream.png", - "enemy/Orc.png", - "enemy/Pirate.png", - "enemy/Skull.png", - "enemy/Teleman.png", - "fonts/ThaleahFat.ttf", - "icon/bullet.png", - "icon/icon.png", - "icon/powerup_attack.png", - "icon/powerup_bandana.png", - "icon/powerup_cooldown.png", - "icon/powerup_range.png", - "icon/powerup_speed.png", - "icon/weapon_minigun.png", - "icon/weapon_pistol.png", - "icon/weapon_sniperrifle.png", - "icon/weapon_sword.png", - "tilesets/decor_16x16.png", - "tilesets/grass.png", - "whiteboy/death.png", - "whiteboy/hurt.png", - "whiteboy/idle.png", - "whiteboy/run.png", - "whiteboy/walk.png" -] diff --git a/examples/survivors/embedded_assets/moon.pkg b/examples/survivors/embedded_assets/moon.pkg new file mode 100644 index 00000000..49e8a141 --- /dev/null +++ b/examples/survivors/embedded_assets/moon.pkg @@ -0,0 +1,31 @@ +dev_build( + input: [ + "../assets/survivors/enemy/Creeper.png", + "../assets/survivors/enemy/Devil.png", + "../assets/survivors/enemy/Icecream.png", + "../assets/survivors/enemy/Orc.png", + "../assets/survivors/enemy/Pirate.png", + "../assets/survivors/enemy/Skull.png", + "../assets/survivors/enemy/Teleman.png", + "../assets/survivors/fonts/ThaleahFat.ttf", + "../assets/survivors/icon/bullet.png", + "../assets/survivors/icon/powerup_attack.png", + "../assets/survivors/icon/powerup_bandana.png", + "../assets/survivors/icon/powerup_cooldown.png", + "../assets/survivors/icon/powerup_range.png", + "../assets/survivors/icon/powerup_speed.png", + "../assets/survivors/icon/weapon_minigun.png", + "../assets/survivors/icon/weapon_pistol.png", + "../assets/survivors/icon/weapon_sniperrifle.png", + "../assets/survivors/icon/weapon_sword.png", + "../assets/survivors/tilesets/decor_16x16.png", + "../assets/survivors/tilesets/grass.png", + "../assets/survivors/whiteboy/death.png", + "../assets/survivors/whiteboy/hurt.png", + "../assets/survivors/whiteboy/idle.png", + "../assets/survivors/whiteboy/run.png", + "../assets/survivors/whiteboy/walk.png", + ], + output: "assets.g.mbt", + command: "moonx moonbit-community/embed@0.1.3 \"$pkg_dir/../assets\" -o \"$output\" --prune survivors/icon/icon.png", +) diff --git a/examples/survivors/embedded_assets/pkg.generated.mbti b/examples/survivors/embedded_assets/pkg.generated.mbti new file mode 100644 index 00000000..6eeb3046 --- /dev/null +++ b/examples/survivors/embedded_assets/pkg.generated.mbti @@ -0,0 +1,64 @@ +// Generated using `moon info`, DON'T EDIT IT +package "Milky2018/selene-examples/survivors/embedded_assets" + +// Values +pub let assets : AssetsFixture + +// Errors + +// Types and methods +pub struct AssetsFixture { + survivors : SurvivorsFixture +} + +pub struct EnemyFixture { + orc_png : Bytes + devil_png : Bytes + skull_png : Bytes + pirate_png : Bytes + creeper_png : Bytes + teleman_png : Bytes + icecream_png : Bytes +} + +pub struct FontsFixture { + thaleahfat_ttf : Bytes +} + +pub struct IconFixture { + bullet_png : Bytes + weapon_sword_png : Bytes + powerup_range_png : Bytes + powerup_speed_png : Bytes + weapon_pistol_png : Bytes + powerup_attack_png : Bytes + weapon_minigun_png : Bytes + powerup_bandana_png : Bytes + powerup_cooldown_png : Bytes + weapon_sniperrifle_png : Bytes +} + +pub struct SurvivorsFixture { + icon : IconFixture + enemy : EnemyFixture + fonts : FontsFixture + tilesets : TilesetsFixture + whiteboy : WhiteboyFixture +} + +pub struct TilesetsFixture { + grass_png : Bytes + decor_16x16_png : Bytes +} + +pub struct WhiteboyFixture { + run_png : Bytes + hurt_png : Bytes + idle_png : Bytes + walk_png : Bytes + death_png : Bytes +} + +// Type aliases + +// Traits diff --git a/examples/survivors/levelup_wbtest.mbt b/examples/survivors/levelup_wbtest.mbt index fc3940ea..626eb9ac 100644 --- a/examples/survivors/levelup_wbtest.mbt +++ b/examples/survivors/levelup_wbtest.mbt @@ -1,6 +1,5 @@ ///| test "level up shows panel and buttons" { - use_survivors_test_assets() let world = @ecs.World() @ecs.set_current_world(world) @time.initialize(@ecs.require_current_world()) @@ -74,7 +73,6 @@ test "level up shows panel and buttons" { ///| test "level up click resumes game" { - use_survivors_test_assets() let world = @ecs.World() @ecs.set_current_world(world) @time.initialize(@ecs.require_current_world()) diff --git a/examples/survivors/main.mbt b/examples/survivors/main.mbt index 3c2520bc..0164f671 100644 --- a/examples/survivors/main.mbt +++ b/examples/survivors/main.mbt @@ -591,12 +591,6 @@ fn game_start(world : @ecs.World) -> Unit { reset_survivors_runtime() @time.initialize(@ecs.require_current_world()) @time.set_scale(1.0) - ignore( - @asset.load_font( - "assets/survivors/fonts/ThaleahFat.ttf", - family="ThaleahFat", - ), - ) @ui.set_ui_scale_mode(Viewport) configure_survivors_input() ignore(game_state(world~)) diff --git a/examples/survivors/map.mbt b/examples/survivors/map.mbt index 78c9c141..41650689 100644 --- a/examples/survivors/map.mbt +++ b/examples/survivors/map.mbt @@ -15,7 +15,7 @@ ///| fn add_background(size : @math.Vec2) -> Unit { let background_sprite = @sprite.Sprite( - image=Some(@asset.load_image(background_picture)), + image=Some(background_image), custom_size=Some(size), anchor=Anchor(Vec2(-0.5, 0.5)), image_mode=Tiled(Repeat), diff --git a/examples/survivors/moon.pkg b/examples/survivors/moon.pkg index 123c040a..edadd8a7 100644 --- a/examples/survivors/moon.pkg +++ b/examples/survivors/moon.pkg @@ -1,4 +1,5 @@ import { + "Milky2018/selene-examples/survivors/embedded_assets", "Milky2018/selene/state", "Milky2018/selene/render2d_types", "Milky2018/selene/app", diff --git a/examples/survivors/player_animation_wbtest.mbt b/examples/survivors/player_animation_wbtest.mbt index 271bdcea..03b4653b 100644 --- a/examples/survivors/player_animation_wbtest.mbt +++ b/examples/survivors/player_animation_wbtest.mbt @@ -1,6 +1,5 @@ ///| test "player animation controller remembers current node" { - use_survivors_test_assets() let world = @ecs.World() @ecs.set_current_world(world) @time.initialize(@ecs.require_current_world()) @@ -32,7 +31,6 @@ test "player animation controller remembers current node" { ///| test "replaying same player animation state does not reset atlas index" { - use_survivors_test_assets() let world = @ecs.World() @ecs.set_current_world(world) @time.initialize(@ecs.require_current_world()) @@ -78,7 +76,6 @@ test "replaying same player animation state does not reset atlas index" { ///| test "player run animation advances atlas indices in order" { - use_survivors_test_assets() let world = @ecs.World() @ecs.set_current_world(world) @time.initialize(@ecs.require_current_world()) diff --git a/examples/survivors/resources.mbt b/examples/survivors/resources.mbt new file mode 100644 index 00000000..23274927 --- /dev/null +++ b/examples/survivors/resources.mbt @@ -0,0 +1,138 @@ +///| +let creeper_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes(@embedded_assets.assets.survivors.enemy.creeper_png), +) + +///| +let devil_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes(@embedded_assets.assets.survivors.enemy.devil_png), +) + +///| +let icecream_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes(@embedded_assets.assets.survivors.enemy.icecream_png), +) + +///| +let orc_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes(@embedded_assets.assets.survivors.enemy.orc_png), +) + +///| +let pirate_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes(@embedded_assets.assets.survivors.enemy.pirate_png), +) + +///| +let skull_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes(@embedded_assets.assets.survivors.enemy.skull_png), +) + +///| +let teleman_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes(@embedded_assets.assets.survivors.enemy.teleman_png), +) + +///| +let bullet_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes(@embedded_assets.assets.survivors.icon.bullet_png), +) + +///| +let powerup_attack_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.survivors.icon.powerup_attack_png, + ), +) + +///| +let powerup_bandana_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.survivors.icon.powerup_bandana_png, + ), +) + +///| +let powerup_cooldown_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.survivors.icon.powerup_cooldown_png, + ), +) + +///| +let powerup_range_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.survivors.icon.powerup_range_png, + ), +) + +///| +let powerup_speed_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.survivors.icon.powerup_speed_png, + ), +) + +///| +let weapon_minigun_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.survivors.icon.weapon_minigun_png, + ), +) + +///| +let weapon_pistol_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.survivors.icon.weapon_pistol_png, + ), +) + +///| +let weapon_sniperrifle_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.survivors.icon.weapon_sniperrifle_png, + ), +) + +///| +let weapon_sword_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.survivors.icon.weapon_sword_png, + ), +) + +///| +let decor_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes( + @embedded_assets.assets.survivors.tilesets.decor_16x16_png, + ), +) + +///| +let background_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes(@embedded_assets.assets.survivors.tilesets.grass_png), +) + +///| +let player_idle_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes(@embedded_assets.assets.survivors.whiteboy.idle_png), +) + +///| +let player_run_image : @asset.ImageHandle = @asset.images.add( + @asset.Image::from_bytes(@embedded_assets.assets.survivors.whiteboy.run_png), +) + +///| +let game_font : @asset.FontHandle = @asset.fonts.add( + @asset.Font::from_bytes( + @embedded_assets.assets.survivors.fonts.thaleahfat_ttf, + ), +) + +///| +fn game_text_font(css : String) -> @ui.TextFont { + let style = @ui.TextFont::from_css(css) + style.font_handle = Some(game_font) + style +} diff --git a/examples/survivors/restart_wbtest.mbt b/examples/survivors/restart_wbtest.mbt index 58308fc9..29c3ba31 100644 --- a/examples/survivors/restart_wbtest.mbt +++ b/examples/survivors/restart_wbtest.mbt @@ -1,7 +1,5 @@ ///| test "state-driven Survivors restart replaces entities and cancels old timers" { - use_survivors_test_assets() - defer @asset.set_io(fn(_path) { None }) let world = @ecs.World() let other_entity = @ecs.commands(world).spawn(()) let old_callback_ran = Ref(false) @@ -41,8 +39,6 @@ test "state-driven Survivors restart replaces entities and cancels old timers" { ///| test "injected Survivors gameplay fires and refreshes its parameters after a state restart" { - use_survivors_test_assets() - defer @asset.set_io(fn(_path) { None }) let world = @ecs.World() let app = survivors_app().with_world(world).init_state(GamePhase::Playing) app.run_frames(1) diff --git a/examples/survivors/sprites.mbt b/examples/survivors/sprites.mbt index 0f172056..a6631d93 100644 --- a/examples/survivors/sprites.mbt +++ b/examples/survivors/sprites.mbt @@ -15,7 +15,7 @@ ///| priv struct SpriteAnimationDef { name : String - image_path : String + image : @asset.ImageHandle layout : @sprite.TextureAtlasLayoutHandle fps : Double loop_ : Bool @@ -27,7 +27,7 @@ priv struct SpriteAnimationDef { ///| fn SpriteAnimationDef::SpriteAnimationDef( - path : String, + image : @asset.ImageHandle, frame_count : Int32, size : @math.Vec2, offset~ : @math.Vec2 = @math.Vec2::zero(), @@ -39,8 +39,8 @@ fn SpriteAnimationDef::SpriteAnimationDef( flip_y~ : Bool = false, ) -> SpriteAnimationDef { { - name: path, - image_path: path, + name: "sprite-\{image.id()}", + image, layout: @sprite.register_texture_atlas_layout( @sprite.TextureAtlasLayout::from_grid( size, @@ -62,7 +62,7 @@ fn SpriteAnimationDef::SpriteAnimationDef( ///| fn sprite_animation_sprite(animation : SpriteAnimationDef) -> @sprite.Sprite { Sprite( - image=Some(@asset.load_image(animation.image_path)), + image=Some(animation.image), texture_atlas=Some(TextureAtlas(animation.layout)), custom_size=Some(animation.size), anchor=animation.anchor, @@ -73,22 +73,17 @@ fn sprite_animation_sprite(animation : SpriteAnimationDef) -> @sprite.Sprite { ///| fn static_region_sprite( - path : String, + image : @asset.ImageHandle, size : @math.Vec2, rect~ : @math.Rect? = None, anchor~ : @sprite.Anchor = Anchor(Vec2(0.0, 0.0)), ) -> @sprite.Sprite { - Sprite( - image=Some(@asset.load_image(path)), - rect~, - custom_size=Some(size), - anchor~, - ) + Sprite(image=Some(image), rect~, custom_size=Some(size), anchor~) } ///| let player_idle_right_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/whiteboy/idle.png", + player_idle_image, 4, Vec2(PLAYER_SIZE, PLAYER_SIZE), offset=Vec2(32.0, 32.0), @@ -97,7 +92,7 @@ let player_idle_right_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let player_idle_left_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/whiteboy/idle.png", + player_idle_image, 4, Vec2(PLAYER_SIZE, PLAYER_SIZE), offset=Vec2(32.0, 32.0), @@ -107,7 +102,7 @@ let player_idle_left_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let player_idle_up_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/whiteboy/idle.png", + player_idle_image, 4, Vec2(PLAYER_SIZE, PLAYER_SIZE), offset=Vec2(32.0, 192.0), @@ -116,7 +111,7 @@ let player_idle_up_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let player_idle_down_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/whiteboy/idle.png", + player_idle_image, 4, Vec2(PLAYER_SIZE, PLAYER_SIZE), offset=Vec2(32.0, 112.0), @@ -125,7 +120,7 @@ let player_idle_down_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let player_run_right_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/whiteboy/run.png", + player_run_image, 8, Vec2(PLAYER_SIZE, PLAYER_SIZE), offset=Vec2(32.0, 32.0), @@ -134,7 +129,7 @@ let player_run_right_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let player_run_left_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/whiteboy/run.png", + player_run_image, 8, Vec2(PLAYER_SIZE, PLAYER_SIZE), offset=Vec2(32.0, 32.0), @@ -144,7 +139,7 @@ let player_run_left_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let player_run_down_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/whiteboy/run.png", + player_run_image, 8, Vec2(PLAYER_SIZE, PLAYER_SIZE), offset=Vec2(32.0, 112.0), @@ -153,7 +148,7 @@ let player_run_down_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let player_run_up_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/whiteboy/run.png", + player_run_image, 8, Vec2(PLAYER_SIZE, PLAYER_SIZE), offset=Vec2(32.0, 192.0), @@ -163,19 +158,16 @@ let player_run_up_animation : SpriteAnimationDef = SpriteAnimationDef( ///| fn grass_sprite() -> @sprite.Sprite { static_region_sprite( - "assets/survivors/tilesets/decor_16x16.png", + decor_image, Vec2(16.0, 16.0), rect=Some({ position: Vec2(0.0, 0.0), size: Vec2(16.0, 16.0), }), anchor=Anchor(Vec2(-0.5, 0.5)), ) } -///| -let background_picture = "assets/survivors/tilesets/grass.png" - ///| let creeper_right_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/enemy/Creeper.png", + creeper_image, 4, Vec2(16.0, 24.0), offset=Vec2(0.0, 48.0), @@ -183,7 +175,7 @@ let creeper_right_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let creeper_left_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/enemy/Creeper.png", + creeper_image, 4, Vec2(16.0, 24.0), offset=Vec2(0.0, 48.0), @@ -192,7 +184,7 @@ let creeper_left_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let icecream_right_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/enemy/Icecream.png", + icecream_image, 4, Vec2(16.0, 24.0), offset=Vec2(0.0, 48.0), @@ -200,7 +192,7 @@ let icecream_right_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let icecream_left_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/enemy/Icecream.png", + icecream_image, 4, Vec2(16.0, 24.0), offset=Vec2(0.0, 48.0), @@ -209,7 +201,7 @@ let icecream_left_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let orc_right_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/enemy/Orc.png", + orc_image, 4, Vec2(16.0, 24.0), offset=Vec2(0.0, 48.0), @@ -217,7 +209,7 @@ let orc_right_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let orc_left_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/enemy/Orc.png", + orc_image, 4, Vec2(16.0, 24.0), offset=Vec2(0.0, 48.0), @@ -226,7 +218,7 @@ let orc_left_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let skull_right_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/enemy/Skull.png", + skull_image, 4, Vec2(16.0, 24.0), offset=Vec2(0.0, 48.0), @@ -234,7 +226,7 @@ let skull_right_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let skull_left_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/enemy/Skull.png", + skull_image, 4, Vec2(16.0, 24.0), offset=Vec2(0.0, 48.0), @@ -243,7 +235,7 @@ let skull_left_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let devil_right_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/enemy/Devil.png", + devil_image, 4, Vec2(16.0, 24.0), offset=Vec2(0.0, 48.0), @@ -251,7 +243,7 @@ let devil_right_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let devil_left_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/enemy/Devil.png", + devil_image, 4, Vec2(16.0, 24.0), offset=Vec2(0.0, 48.0), @@ -260,7 +252,7 @@ let devil_left_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let pirate_right_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/enemy/Pirate.png", + pirate_image, 4, Vec2(16.0, 24.0), offset=Vec2(0.0, 48.0), @@ -268,7 +260,7 @@ let pirate_right_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let pirate_left_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/enemy/Pirate.png", + pirate_image, 4, Vec2(16.0, 24.0), offset=Vec2(0.0, 48.0), @@ -277,7 +269,7 @@ let pirate_left_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let teleman_right_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/enemy/Teleman.png", + teleman_image, 4, Vec2(16.0, 24.0), offset=Vec2(0.0, 0.0), @@ -285,7 +277,7 @@ let teleman_right_animation : SpriteAnimationDef = SpriteAnimationDef( ///| let teleman_left_animation : SpriteAnimationDef = SpriteAnimationDef( - "assets/survivors/enemy/Teleman.png", + teleman_image, 4, Vec2(16.0, 24.0), offset=Vec2(0.0, 0.0), diff --git a/examples/survivors/test_assets_wbtest.mbt b/examples/survivors/test_assets_wbtest.mbt deleted file mode 100644 index 58c0c64b..00000000 --- a/examples/survivors/test_assets_wbtest.mbt +++ /dev/null @@ -1,4 +0,0 @@ -///| -fn use_survivors_test_assets() -> Unit { - @asset.set_io(fn(_path) { Some(Bytes::from_array([1U.to_byte()])) }) -} diff --git a/examples/survivors/ui.mbt b/examples/survivors/ui.mbt index 12c88967..efc4d747 100644 --- a/examples/survivors/ui.mbt +++ b/examples/survivors/ui.mbt @@ -39,33 +39,6 @@ const LEVELUP_BUTTON_ICON_OFFSET_X = 8.0 ///| const LEVELUP_BUTTON_ICON_OFFSET_Y = 6.0 -///| -const POWERUP_ATTACK_ICON_PATH = "assets/survivors/icon/powerup_attack.png" - -///| -const POWERUP_RANGE_ICON_PATH = "assets/survivors/icon/powerup_range.png" - -///| -const POWERUP_SPEED_ICON_PATH = "assets/survivors/icon/powerup_speed.png" - -///| -const POWERUP_COOLDOWN_ICON_PATH = "assets/survivors/icon/powerup_cooldown.png" - -///| -const POWERUP_BANDANA_ICON_PATH = "assets/survivors/icon/powerup_bandana.png" - -///| -const WEAPON_PISTOL_ICON_PATH = "assets/survivors/icon/weapon_pistol.png" - -///| -const WEAPON_MINIGUN_ICON_PATH = "assets/survivors/icon/weapon_minigun.png" - -///| -const WEAPON_SNIPERRIFLE_ICON_PATH = "assets/survivors/icon/weapon_sniperrifle.png" - -///| -const WEAPON_SWORD_ICON_PATH = "assets/survivors/icon/weapon_sword.png" - ///| fn set_ui_text( texts~ : @ecs.Query[@ecs.Single[@ui.Text]], @@ -101,7 +74,7 @@ fn spawn_text_entity( @ui.Node::absolute(offset, size~, border=@ui.UiRectValues::all(1.0)), @ui.ZIndex(zindex), @ui.Text(content), - @ui.TextFont::from_css(font), + game_text_font(font), @ui.TextColor::from_css(color), @ui.TextLayout(align~, baseline~), ), @@ -154,7 +127,7 @@ fn spawn_panel_button( ), ( @ui.Text(label), - @ui.TextFont::from_css(font), + game_text_font(font), @ui.TextColor::from_css("white"), @ui.TextLayout(align=Center, baseline=Center), ), @@ -200,14 +173,14 @@ fn set_button_enabled( fn set_icon_image( ui~ : SurvivorsUi, entity : @ecs.Entity, - path : String, + image : @asset.ImageHandle, ) -> Unit { ui.images.set( entity, Single( - UiImage( + @ui.UiImage::from_image( Vec2(LEVELUP_BUTTON_ICON_SIZE, LEVELUP_BUTTON_ICON_SIZE), - path, + image, fit=Contain, ), ), @@ -215,23 +188,23 @@ fn set_icon_image( } ///| -fn powerup_icon_path(powerup_type : PowerupType) -> String { +fn powerup_icon(powerup_type : PowerupType) -> @asset.ImageHandle { match powerup_type { - AttackLv1 | AttackLv2 | AttackLv3 => POWERUP_ATTACK_ICON_PATH - RangeLv1 | RangeLv2 => POWERUP_RANGE_ICON_PATH - SpeedLv1 | SpeedLv2 => POWERUP_SPEED_ICON_PATH - CooldownLv1 | CooldownLv2 => POWERUP_COOLDOWN_ICON_PATH - Bandana => POWERUP_BANDANA_ICON_PATH + AttackLv1 | AttackLv2 | AttackLv3 => powerup_attack_image + RangeLv1 | RangeLv2 => powerup_range_image + SpeedLv1 | SpeedLv2 => powerup_speed_image + CooldownLv1 | CooldownLv2 => powerup_cooldown_image + Bandana => powerup_bandana_image } } ///| -fn weapon_icon_path(weapon_type : WeaponType) -> String { +fn weapon_icon(weapon_type : WeaponType) -> @asset.ImageHandle { match weapon_type { - Pistol => WEAPON_PISTOL_ICON_PATH - Minigun => WEAPON_MINIGUN_ICON_PATH - SniperRifle => WEAPON_SNIPERRIFLE_ICON_PATH - Sword => WEAPON_SWORD_ICON_PATH + Pistol => weapon_pistol_image + Minigun => weapon_minigun_image + SniperRifle => weapon_sniperrifle_image + Sword => weapon_sword_image } } @@ -334,9 +307,9 @@ fn setup_level_up_ui(ui~ : SurvivorsUi) -> Unit { size=Vec2(LEVELUP_BUTTON_ICON_SIZE, LEVELUP_BUTTON_ICON_SIZE), ), @ui.ZIndex(PANEL_TEXT_ZINDEX), - @ui.UiImage( + @ui.UiImage::from_image( Vec2(LEVELUP_BUTTON_ICON_SIZE, LEVELUP_BUTTON_ICON_SIZE), - POWERUP_RANGE_ICON_PATH, + powerup_range_image, fit=Contain, ), ), @@ -381,7 +354,7 @@ fn update_selection_display( Single(@ui.BackgroundColor::from_css("rgba(13, 167, 170, 1)")), ) set_ui_text(texts=ui.texts, button_entity, powerup.name) - set_icon_image(ui~, icon_entity, powerup_icon_path(powerup.powerup_type)) + set_icon_image(ui~, icon_entity, powerup_icon(powerup.powerup_type)) } WeaponSelection(weapon_type) => { ui.backgrounds.set( @@ -389,7 +362,7 @@ fn update_selection_display( Single(@ui.BackgroundColor::from_css("rgba(255, 140, 0, 1)")), ) set_ui_text(texts=ui.texts, button_entity, get_weapon_name(weapon_type)) - set_icon_image(ui~, icon_entity, weapon_icon_path(weapon_type)) + set_icon_image(ui~, icon_entity, weapon_icon(weapon_type)) } } } diff --git a/examples/survivors/weapon.mbt b/examples/survivors/weapon.mbt index 1e299eb4..66d84520 100644 --- a/examples/survivors/weapon.mbt +++ b/examples/survivors/weapon.mbt @@ -156,10 +156,7 @@ type PlayerBulletSpawnPlan = @ecs.SpawnPlan[ ///| fn player_bullet_visual() -> @sprite.Sprite { - Sprite( - image=Some(@asset.load_image("assets/survivors/icon/bullet.png")), - custom_size=Some(Vec2(12.0, 12.0)), - ) + Sprite(image=Some(bullet_image), custom_size=Some(Vec2(12.0, 12.0))) } ///| diff --git a/page/README.md b/page/README.md index 5a1a5988..4140dead 100644 --- a/page/README.md +++ b/page/README.md @@ -1,7 +1,8 @@ # Selene Pages -This directory contains the site's landing page. Example pages and assets live -in `examples/`. +This directory is the complete GitHub Pages site. Example pages, screenshots, +and other static images live in `examples/`; game assets are embedded in the +compiled JavaScript. ## Build @@ -10,8 +11,13 @@ Run these commands from the repository root: ```bash moon update moon build --target js --release -python3 -m http.server 8000 +for game in cards pixeladventure survivors; do + cp "_build/js/release/build/Milky2018/selene-examples-web/$game/web/web.js" "page/examples/$game/web.js" +done +python3 -m http.server --directory page 8000 ``` -Open `http://localhost:8000/examples/index.html`. The Pages workflow copies the -landing page, examples, and compiled JavaScript into the deployment directory. +Open `http://localhost:8000/` or `http://localhost:8000/examples/`. +Each game page loads its adjacent `web.js`, which is ignored by Git. +The Pages workflow uses the same build and copy commands, then publishes this +directory directly. diff --git a/examples/cards/index.html b/page/examples/cards/index.html similarity index 96% rename from examples/cards/index.html rename to page/examples/cards/index.html index ac5f8839..ac7f7f99 100644 --- a/examples/cards/index.html +++ b/page/examples/cards/index.html @@ -139,7 +139,6 @@ } } - - + diff --git a/examples/cards/screenshot.png b/page/examples/cards/screenshot.png similarity index 100% rename from examples/cards/screenshot.png rename to page/examples/cards/screenshot.png diff --git a/examples/index.html b/page/examples/index.html similarity index 100% rename from examples/index.html rename to page/examples/index.html diff --git a/examples/pixeladventure/assets/pixeladventure/arrowkey.png b/page/examples/pixeladventure/arrowkey.png similarity index 100% rename from examples/pixeladventure/assets/pixeladventure/arrowkey.png rename to page/examples/pixeladventure/arrowkey.png diff --git a/examples/pixeladventure/index.html b/page/examples/pixeladventure/index.html similarity index 94% rename from examples/pixeladventure/index.html rename to page/examples/pixeladventure/index.html index 777bede1..0b8bc569 100644 --- a/examples/pixeladventure/index.html +++ b/page/examples/pixeladventure/index.html @@ -147,7 +147,7 @@ } }); - + @@ -161,7 +161,7 @@

Pixel Adventure

- Arrow Keys + Arrow Keys
← Back to Games diff --git a/examples/pixeladventure/screenshot.png b/page/examples/pixeladventure/screenshot.png similarity index 100% rename from examples/pixeladventure/screenshot.png rename to page/examples/pixeladventure/screenshot.png diff --git a/examples/survivors/index.html b/page/examples/survivors/index.html similarity index 96% rename from examples/survivors/index.html rename to page/examples/survivors/index.html index 4156d6eb..fe45a7e4 100644 --- a/examples/survivors/index.html +++ b/page/examples/survivors/index.html @@ -139,7 +139,6 @@ } } - - + diff --git a/examples/survivors/screenshot.png b/page/examples/survivors/screenshot.png similarity index 100% rename from examples/survivors/screenshot.png rename to page/examples/survivors/screenshot.png diff --git a/selene-core/moon.mod b/selene-core/moon.mod index f48451dd..d5723c39 100644 --- a/selene-core/moon.mod +++ b/selene-core/moon.mod @@ -8,7 +8,6 @@ import { "Milky2018/xml@0.6.1", "moonbit-community/flate@0.10.0", "gmlewis/base64@0.16.14", - "moonbitlang/x@0.5.7", "Milky2018/zstd@0.1.4", "Milky2018/chicle@0.6.3", } diff --git a/selene-core/src/asset/audio.mbt b/selene-core/src/asset/audio.mbt index a7a6439f..24c80786 100644 --- a/selene-core/src/asset/audio.mbt +++ b/selene-core/src/asset/audio.mbt @@ -1,9 +1,6 @@ ///| pub type AudioHandle = @asset_types.AudioHandle -///| -let next_audio_id : Ref[UInt32] = Ref(0) - ///| let audios_by_path : Map[String, AudioHandle] = Map([]) @@ -18,11 +15,10 @@ pub let audio_asset_events : @event.Events[AssetEvent[AudioHandle]] = Events() ///| fn ensure_audio_handle(path : String) -> AudioHandle { - if audios_by_path.get(path) is Some(handle) { + if audios_by_path.get(path) is Some(handle) && handle.is_alive() { return handle } - let handle = @asset_types.AudioHandle(next_audio_id.val) - next_audio_id.val += 1 + let handle = audios.reserve() audios_by_path.set(path, handle) audio_path_by_handle.set(handle, path) handle @@ -39,8 +35,9 @@ pub fn load_audio(path : String) -> AudioHandle { audio_asset_events.send({ handle, kind: Added, }) } audio_states.set(handle, Loading) - if read_bytes(path) is Some(_) { - @platform_audio.preload(path) + if read_bytes(path) is Some(bytes) { + ignore(audios.insert(handle, Audio::from_bytes(bytes))) + @platform_audio.preload(handle) audio_states.set(handle, Loaded) audio_asset_events.send({ handle, kind: Loaded, }) } else { @@ -58,16 +55,24 @@ pub fn audio_path(handle : AudioHandle) -> String? { ///| pub fn audio_load_state(handle : AudioHandle) -> LoadState { - audio_states.get(handle).unwrap_or(NotLoaded) + if !handle.is_alive() { + NotLoaded + } else { + audio_states + .get(handle) + .unwrap_or(if handle.get() is Some(_) { Loaded } else { NotLoaded }) + } } ///| pub fn reload_audio(handle : AudioHandle) -> Unit { + guard handle.is_alive() else { return } match audio_path(handle) { Some(path) => { audio_states.set(handle, Loading) - if read_bytes(path) is Some(_) { - @platform_audio.preload(path) + if read_bytes(path) is Some(bytes) { + ignore(audios.insert(handle, Audio::from_bytes(bytes))) + @platform_audio.preload(handle) audio_states.set(handle, Loaded) audio_asset_events.send({ handle, kind: Modified, }) } else { @@ -82,6 +87,7 @@ pub fn reload_audio(handle : AudioHandle) -> Unit { ///| pub fn remove_audio(handle : AudioHandle) -> Unit { + ignore(audios.remove(handle)) if audio_states.get(handle) is Some(_) { audio_states.remove(handle) audio_asset_events.send({ handle, kind: Removed, }) diff --git a/selene-core/src/asset/font.mbt b/selene-core/src/asset/font.mbt index 0aa3433a..cbdb0732 100644 --- a/selene-core/src/asset/font.mbt +++ b/selene-core/src/asset/font.mbt @@ -1,9 +1,6 @@ ///| pub type FontHandle = @asset_types.FontHandle -///| -let next_font_id : Ref[UInt32] = Ref(0) - ///| let fonts_by_path : Map[String, FontHandle] = Map([]) @@ -35,16 +32,14 @@ fn normalize_font_family(path : String) -> String { ///| fn ensure_font_handle(path : String, family : String) -> FontHandle { - if fonts_by_path.get(path) is Some(handle) { + if fonts_by_path.get(path) is Some(handle) && handle.is_alive() { return handle } - let handle = @asset_types.FontHandle(next_font_id.val) - next_font_id.val += 1 + let handle = fonts.reserve() fonts_by_path.set(path, handle) font_family_by_handle.set(handle, family) font_handle_by_family.set(family, handle) font_path_by_handle.set(handle, path) - @platform_render.register_font(family, path) handle } @@ -60,7 +55,8 @@ pub fn load_font(path : String, family? : String) -> FontHandle { font_asset_events.send({ handle, kind: Added, }) } font_states.set(handle, Loading) - if read_bytes(path) is Some(_) { + if read_bytes(path) is Some(bytes) { + ignore(fonts.insert(handle, Font::from_bytes(bytes))) font_states.set(handle, Loaded) font_asset_events.send({ handle, kind: Loaded, }) } else { @@ -78,25 +74,37 @@ pub fn font_path(handle : FontHandle) -> String? { ///| pub fn font_family(handle : FontHandle) -> String? { - font_family_by_handle.get(handle) + if handle.is_alive() { + font_family_by_handle.get(handle) + } else { + None + } } ///| pub fn font_by_family(family : String) -> FontHandle? { - font_handle_by_family.get(family) + font_handle_by_family.get(family).filter(handle => handle.is_alive()) } ///| pub fn font_load_state(handle : FontHandle) -> LoadState { - font_states.get(handle).unwrap_or(NotLoaded) + if !handle.is_alive() { + NotLoaded + } else { + font_states + .get(handle) + .unwrap_or(if handle.get() is Some(_) { Loaded } else { NotLoaded }) + } } ///| pub fn reload_font(handle : FontHandle) -> Unit { + guard handle.is_alive() else { return } match font_path(handle) { Some(path) => { font_states.set(handle, Loading) - if read_bytes(path) is Some(_) { + if read_bytes(path) is Some(bytes) { + ignore(fonts.insert(handle, Font::from_bytes(bytes))) font_states.set(handle, Loaded) font_asset_events.send({ handle, kind: Modified, }) } else { @@ -111,6 +119,7 @@ pub fn reload_font(handle : FontHandle) -> Unit { ///| pub fn remove_font(handle : FontHandle) -> Unit { + ignore(fonts.remove(handle)) if font_states.get(handle) is Some(_) { font_states.remove(handle) font_asset_events.send({ handle, kind: Removed, }) diff --git a/selene-core/src/asset/image.mbt b/selene-core/src/asset/image.mbt index ba750ca9..d4a7da34 100644 --- a/selene-core/src/asset/image.mbt +++ b/selene-core/src/asset/image.mbt @@ -1,9 +1,6 @@ ///| pub type ImageHandle = @asset_types.ImageHandle -///| -let next_image_id : Ref[UInt32] = Ref(0) - ///| let images_by_path : Map[String, ImageHandle] = Map([]) @@ -18,11 +15,10 @@ pub let image_asset_events : @event.Events[AssetEvent[ImageHandle]] = Events() ///| fn ensure_image_handle(path : String) -> ImageHandle { - if images_by_path.get(path) is Some(handle) { + if images_by_path.get(path) is Some(handle) && handle.is_alive() { return handle } - let handle = @asset_types.ImageHandle(next_image_id.val) - next_image_id.val += 1 + let handle = images.reserve() images_by_path.set(path, handle) image_path_by_handle.set(handle, path) handle @@ -39,7 +35,8 @@ pub fn load_image(path : String) -> ImageHandle { image_asset_events.send({ handle, kind: Added, }) } image_states.set(handle, Loading) - if read_bytes(path) is Some(_) { + if read_bytes(path) is Some(bytes) { + ignore(images.insert(handle, Image::from_bytes(bytes))) image_states.set(handle, Loaded) image_asset_events.send({ handle, kind: Loaded, }) } else { @@ -57,15 +54,23 @@ pub fn image_path(handle : ImageHandle) -> String? { ///| pub fn image_load_state(handle : ImageHandle) -> LoadState { - image_states.get(handle).unwrap_or(NotLoaded) + if !handle.is_alive() { + NotLoaded + } else { + image_states + .get(handle) + .unwrap_or(if handle.get() is Some(_) { Loaded } else { NotLoaded }) + } } ///| pub fn reload_image(handle : ImageHandle) -> Unit { + guard handle.is_alive() else { return } match image_path(handle) { Some(path) => { image_states.set(handle, Loading) - if read_bytes(path) is Some(_) { + if read_bytes(path) is Some(bytes) { + ignore(images.insert(handle, Image::from_bytes(bytes))) image_states.set(handle, Loaded) image_asset_events.send({ handle, kind: Modified, }) } else { @@ -80,6 +85,7 @@ pub fn reload_image(handle : ImageHandle) -> Unit { ///| pub fn remove_image(handle : ImageHandle) -> Unit { + ignore(images.remove(handle)) if image_states.get(handle) is Some(_) { image_states.remove(handle) image_asset_events.send({ handle, kind: Removed, }) diff --git a/selene-core/src/asset/io.mbt b/selene-core/src/asset/io.mbt index 53f13986..43b27cb2 100644 --- a/selene-core/src/asset/io.mbt +++ b/selene-core/src/asset/io.mbt @@ -1,9 +1,18 @@ ///| -pub fn set_io(reader : (String) -> Bytes?) -> Unit { - @platform_asset_io.set_reader(reader) +/// Registers an asset reader and the paths available from that reader. +/// Replacing the reader also replaces its catalogue; the array is copied. +/// Registered resource values and active playback are unaffected. +pub fn set_io(reader : (String) -> Bytes?, paths~ : Array[String] = []) -> Unit { + @platform_asset_io.set_reader(reader, paths~) } ///| pub fn read_bytes(path : String) -> Bytes? { @platform_asset_io.read_bytes(path) } + +///| +/// Returns a snapshot of the registered asset paths. +pub fn paths() -> Array[String] { + @platform_asset_io.paths() +} diff --git a/selene-core/src/asset/io_test.mbt b/selene-core/src/asset/io_test.mbt new file mode 100644 index 00000000..7b1c8a63 --- /dev/null +++ b/selene-core/src/asset/io_test.mbt @@ -0,0 +1,39 @@ +///| +test "asset catalogue is a snapshot and reader replacement clears it" { + let catalogue = ["maps/a.tmj", "maps/b.tmj"] + @asset.set_io( + fn(path) { if path == "maps/a.tmj" { Some(b"map") } else { None } }, + paths=catalogue, + ) + defer @asset.set_io(fn(_) { None }) + catalogue.push("maps/not-registered.tmj") + let snapshot = @asset.paths() + assert_eq(snapshot.length(), 2) + snapshot.clear() + assert_eq(@asset.paths().length(), 2) + assert_eq(@asset.read_bytes("maps/a.tmj"), Some(b"map")) + @asset.set_io(fn(_) { None }) + assert_eq(@asset.paths().length(), 0) +} + +///| +test "registering byte assets does not invoke path IO or prepare backend resources" { + @asset.set_io(fn(_) { abort("byte registration must not read paths") }) + defer @asset.set_io(fn(_) { None }) + let images : @asset.Assets[@asset.Image] = Assets() + let image = images.add(@asset.Image::from_bytes(b"image")) + defer ignore(images.remove(image)) + assert_eq(@asset.image_path(image), None) + assert_true(@asset.image_preparation_state(image) is Unprepared) + let audios : @asset.Assets[@asset.Audio] = Assets() + let audio = audios.add(@asset.Audio::from_bytes(b"audio")) + defer ignore(audios.remove(audio)) + assert_eq(@asset.audio_path(audio), None) + assert_true(@asset.audio_preparation_state(audio) is Unprepared) + let fonts : @asset.Assets[@asset.Font] = Assets() + let font = fonts.add(@asset.Font::from_bytes(b"font")) + defer ignore(fonts.remove(font)) + assert_eq(@asset.font_path(font), None) + assert_eq(@asset.font_family(font), None) + assert_true(@asset.font_preparation_state(font) is Unprepared) +} diff --git a/selene-core/src/asset/moon.pkg b/selene-core/src/asset/moon.pkg index 8b4e92f9..ba8be6fe 100644 --- a/selene-core/src/asset/moon.pkg +++ b/selene-core/src/asset/moon.pkg @@ -1,8 +1,8 @@ import { + "Milky2018/selene/platform_render", "moonbitlang/core/debug", "Milky2018/selene/asset_types", "Milky2018/selene/event", "Milky2018/selene/platform_audio", "Milky2018/selene/platform_asset_io", - "Milky2018/selene/platform_render", } diff --git a/selene-core/src/asset/pkg.generated.mbti b/selene-core/src/asset/pkg.generated.mbti index b19b310f..ab01a70f 100644 --- a/selene-core/src/asset/pkg.generated.mbti +++ b/selene-core/src/asset/pkg.generated.mbti @@ -8,49 +8,63 @@ import { } // Values -pub let audio_asset_events : @event.Events[AssetEvent[@asset_types.AudioHandle]] +pub let audio_asset_events : @event.Events[AssetEvent[@asset_types.Handle[@asset_types.Audio]]] -pub fn audio_load_state(@asset_types.AudioHandle) -> LoadState +pub fn audio_load_state(@asset_types.Handle[@asset_types.Audio]) -> LoadState -pub fn audio_path(@asset_types.AudioHandle) -> String? +pub fn audio_path(@asset_types.Handle[@asset_types.Audio]) -> String? -pub let font_asset_events : @event.Events[AssetEvent[@asset_types.FontHandle]] +pub fn audio_preparation_state(@asset_types.Handle[@asset_types.Audio]) -> @asset_types.PreparationState -pub fn font_by_family(String) -> @asset_types.FontHandle? +pub let audios : @asset_types.Assets[@asset_types.Audio] -pub fn font_family(@asset_types.FontHandle) -> String? +pub let font_asset_events : @event.Events[AssetEvent[@asset_types.Handle[@asset_types.Font]]] -pub fn font_load_state(@asset_types.FontHandle) -> LoadState +pub fn font_by_family(String) -> @asset_types.Handle[@asset_types.Font]? -pub fn font_path(@asset_types.FontHandle) -> String? +pub fn font_family(@asset_types.Handle[@asset_types.Font]) -> String? -pub let image_asset_events : @event.Events[AssetEvent[@asset_types.ImageHandle]] +pub fn font_load_state(@asset_types.Handle[@asset_types.Font]) -> LoadState -pub fn image_load_state(@asset_types.ImageHandle) -> LoadState +pub fn font_path(@asset_types.Handle[@asset_types.Font]) -> String? -pub fn image_path(@asset_types.ImageHandle) -> String? +pub fn font_preparation_state(@asset_types.Handle[@asset_types.Font]) -> @asset_types.PreparationState -pub fn load_audio(String) -> @asset_types.AudioHandle +pub let fonts : @asset_types.Assets[@asset_types.Font] -pub fn load_font(String, family? : String) -> @asset_types.FontHandle +pub let image_asset_events : @event.Events[AssetEvent[@asset_types.Handle[@asset_types.Image]]] -pub fn load_image(String) -> @asset_types.ImageHandle +pub fn image_load_state(@asset_types.Handle[@asset_types.Image]) -> LoadState + +pub fn image_path(@asset_types.Handle[@asset_types.Image]) -> String? + +pub fn image_preparation_state(@asset_types.Handle[@asset_types.Image]) -> @asset_types.PreparationState + +pub let images : @asset_types.Assets[@asset_types.Image] + +pub fn load_audio(String) -> @asset_types.Handle[@asset_types.Audio] + +pub fn load_font(String, family? : String) -> @asset_types.Handle[@asset_types.Font] + +pub fn load_image(String) -> @asset_types.Handle[@asset_types.Image] + +pub fn paths() -> Array[String] pub fn read_bytes(String) -> Bytes? -pub fn reload_audio(@asset_types.AudioHandle) -> Unit +pub fn reload_audio(@asset_types.Handle[@asset_types.Audio]) -> Unit -pub fn reload_font(@asset_types.FontHandle) -> Unit +pub fn reload_font(@asset_types.Handle[@asset_types.Font]) -> Unit -pub fn reload_image(@asset_types.ImageHandle) -> Unit +pub fn reload_image(@asset_types.Handle[@asset_types.Image]) -> Unit -pub fn remove_audio(@asset_types.AudioHandle) -> Unit +pub fn remove_audio(@asset_types.Handle[@asset_types.Audio]) -> Unit -pub fn remove_font(@asset_types.FontHandle) -> Unit +pub fn remove_font(@asset_types.Handle[@asset_types.Font]) -> Unit -pub fn remove_image(@asset_types.ImageHandle) -> Unit +pub fn remove_image(@asset_types.Handle[@asset_types.Image]) -> Unit -pub fn set_io((String) -> Bytes?) -> Unit +pub fn set_io((String) -> Bytes?, paths? : Array[String]) -> Unit // Errors @@ -88,10 +102,22 @@ pub fn LoadState::not_equal(Self, Self) -> Bool pub fn LoadState::to_repr(Self) -> @debug.Repr // Type aliases -pub using @asset_types {type AudioHandle} +pub using @asset_types {type Assets} + +pub using @asset_types {type Audio} + +pub type AudioHandle = @asset_types.Handle[@asset_types.Audio] + +pub using @asset_types {type Font} + +pub type FontHandle = @asset_types.Handle[@asset_types.Font] + +pub using @asset_types {type Handle} + +pub using @asset_types {type Image} -pub using @asset_types {type FontHandle} +pub type ImageHandle = @asset_types.Handle[@asset_types.Image] -pub using @asset_types {type ImageHandle} +pub using @asset_types {type PreparationState} // Traits diff --git a/selene-core/src/asset/types.mbt b/selene-core/src/asset/types.mbt new file mode 100644 index 00000000..e940f20a --- /dev/null +++ b/selene-core/src/asset/types.mbt @@ -0,0 +1,33 @@ +///| +pub using @asset_types { + type Assets, + type Handle, + type Image, + type Audio, + type Font, + type PreparationState, +} + +///| +pub let images : Assets[Image] = Assets() + +///| +pub let audios : Assets[Audio] = Assets() + +///| +pub let fonts : Assets[Font] = Assets() + +///| +pub fn image_preparation_state(handle : ImageHandle) -> PreparationState { + @platform_render.image_preparation_state(handle) +} + +///| +pub fn font_preparation_state(handle : FontHandle) -> PreparationState { + @platform_render.font_preparation_state(handle) +} + +///| +pub fn audio_preparation_state(handle : AudioHandle) -> PreparationState { + @platform_audio.preparation_state(handle) +} diff --git a/selene-core/src/asset_types/assets.mbt b/selene-core/src/asset_types/assets.mbt new file mode 100644 index 00000000..b24cf172 --- /dev/null +++ b/selene-core/src/asset_types/assets.mbt @@ -0,0 +1,91 @@ +///| +let next_identity : Ref[UInt32] = Ref(0U) + +///| +fn allocate_identity() -> UInt32 { + guard next_identity.val < 0xFFFFFFFFU else { + abort("Asset identity exhausted") + } + next_identity.val += 1U + next_identity.val +} + +///| +/// A collection of resource values. Registration does not decode or upload data. +struct Assets[T] { + id : UInt32 + entries : Map[UInt32, Handle[T]] +} + +///| +pub fn[T] Assets::Assets() -> Assets[T] { + { id: allocate_identity(), entries: Map([]), } +} + +///| +/// Reserves an identity for an asset which has not finished loading. +pub fn[T] Assets::reserve(self : Assets[T]) -> Handle[T] { + let handle = { + id: allocate_identity(), + owner: self.id, + entry: { value: None, alive: true, invalidations: [], }, + } + self.entries[handle.id] = handle + handle +} + +///| +pub fn[T] Assets::add(self : Assets[T], value : T) -> Handle[T] { + let handle = self.reserve() + handle.entry.value = Some(value) + handle +} + +///| +pub fn[T] Assets::get(self : Assets[T], handle : Handle[T]) -> T? { + if handle.owner == self.id { + handle.get() + } else { + None + } +} + +///| +fn[T] invalidate(entry : AssetEntry[T]) -> Unit { + let callbacks = entry.invalidations.copy() + entry.invalidations.clear() + for callback in callbacks { + callback() + } +} + +///| +/// Replaces an owned entry, including an identity reserved by the loader. +/// Removed entries and handles from another collection are rejected. +pub fn[T] Assets::insert( + self : Assets[T], + handle : Handle[T], + value : T, +) -> Bool { + guard handle.owner == self.id && handle.entry.alive else { return false } + handle.entry.value = Some(value) + invalidate(handle.entry) + true +} + +///| +pub fn[T] Assets::remove(self : Assets[T], handle : Handle[T]) -> T? { + guard handle.owner == self.id && handle.entry.alive else { return None } + let value = handle.entry.value + handle.entry.value = None + handle.entry.alive = false + self.entries.remove(handle.id) + invalidate(handle.entry) + value +} + +///| +/// Includes reserved entries whose loading has not completed. +pub fn[T] Assets::length(self : Assets[T]) -> Int32 { + self.entries.length() +} diff --git a/selene-core/src/asset_types/assets_test.mbt b/selene-core/src/asset_types/assets_test.mbt new file mode 100644 index 00000000..24b0c7b3 --- /dev/null +++ b/selene-core/src/asset_types/assets_test.mbt @@ -0,0 +1,58 @@ +///| +test "collections own handles and asset identity is independent of value" { + let first : @asset_types.Assets[Int32] = Assets() + let second : @asset_types.Assets[Int32] = Assets() + let a = first.add(42) + let b = first.add(42) + let c = second.add(42) + assert_true(a != b && a != c) + assert_eq(first.get(a), Some(42)) + assert_eq(second.get(a), None) + assert_false(second.insert(a, 7)) + assert_eq(second.remove(a), None) + let handles = Map([(a, "a"), (b, "b"), (c, "c")]) + assert_true(first.insert(a, 99)) + assert_eq(handles.get(a), Some("a")) + assert_eq(first.get(a), Some(99)) +} + +///| +test "removal invalidates all copies and cannot resurrect a stale handle" { + let assets : @asset_types.Assets[String] = Assets() + let handle = assets.add("old") + let copy = handle + assert_eq(assets.remove(handle), Some("old")) + assert_eq(copy.get(), None) + assert_false(copy.is_alive()) + assert_false(assets.insert(copy, "new")) + assert_eq(assets.remove(copy), None) + let next = assets.add("new") + assert_true(next != copy) + assert_eq(assets.length(), 1) +} + +///| +test "reserved identities can be fulfilled and invalidation callbacks run once" { + let assets : @asset_types.Assets[Int32] = Assets() + let handle = assets.reserve() + assert_true(handle.is_alive()) + assert_eq(handle.get(), None) + let invalidations = Ref(0) + handle.on_invalidate(fn() { invalidations.val += 1 }) + assert_true(assets.insert(handle, 1)) + assert_true(assets.insert(handle, 2)) + assert_eq(invalidations.val, 1) + handle.on_invalidate(fn() { invalidations.val += 1 }) + assert_eq(assets.remove(handle), Some(2)) + assert_eq(invalidations.val, 2) +} + +///| +test "resource constructors preserve encoded data without backend preparation" { + let images : @asset_types.Assets[@asset_types.Image] = Assets() + let image = images.add(@asset_types.Image::from_bytes(b"encoded image")) + assert_eq(images.get(image).unwrap().bytes, b"encoded image") + let fonts : @asset_types.Assets[@asset_types.Font] = Assets() + let font = fonts.add(@asset_types.Font::from_bytes(b"encoded font")) + assert_eq(font.get().unwrap().bytes, b"encoded font") +} diff --git a/selene-core/src/asset_types/handles.mbt b/selene-core/src/asset_types/handles.mbt index d740cd8c..1bb882e9 100644 --- a/selene-core/src/asset_types/handles.mbt +++ b/selene-core/src/asset_types/handles.mbt @@ -1,38 +1,84 @@ ///| -#derive(Eq, Debug, Hash) -pub(all) struct ImageHandle(UInt32) +priv struct AssetEntry[T] { + mut value : T? + mut alive : Bool + invalidations : Array[() -> Unit] +} ///| -pub extend ImageHandle with @moonbitlang/core/debug.Debug::{to_repr} +/// A typed identity. Copies refer to the same entry; removing it invalidates all copies. +struct Handle[T] { + id : UInt32 + owner : UInt32 + entry : AssetEntry[T] +} ///| -pub extend ImageHandle with Eq::{not_equal, equal} +pub fn[T] Handle::id(self : Handle[T]) -> UInt32 { + self.id +} ///| -pub extend ImageHandle with Hash::{hash, hash_combine} +/// Reads the current asset without retaining its owning collection. +pub fn[T] Handle::get(self : Handle[T]) -> T? { + self.entry.value +} ///| -#derive(Eq, Debug, Hash) -pub(all) struct AudioHandle(UInt32) +pub fn[T] Handle::is_alive(self : Handle[T]) -> Bool { + self.entry.alive +} ///| -pub extend AudioHandle with @moonbitlang/core/debug.Debug::{to_repr} +/// Runs once when the entry is replaced or removed. Used to invalidate prepared resources. +pub fn[T] Handle::on_invalidate( + self : Handle[T], + callback : () -> Unit, +) -> Unit { + if self.entry.alive { + self.entry.invalidations.push(callback) + } else { + callback() + } +} ///| -pub extend AudioHandle with Eq::{not_equal, equal} +pub impl[T] Eq for Handle[T] with fn equal(self, other) { + self.id == other.id +} ///| -pub extend AudioHandle with Hash::{hash, hash_combine} +pub extend Handle with Eq::{equal, not_equal} ///| -#derive(Eq, Debug, Hash) -pub(all) struct FontHandle(UInt32) +pub impl[T] Hash for Handle[T] with fn hash_combine(self, hasher) { + Hash::hash_combine(self.id, hasher) +} ///| -pub extend FontHandle with @moonbitlang/core/debug.Debug::{to_repr} +pub extend Handle with Hash::{hash, hash_combine} ///| -pub extend FontHandle with Eq::{not_equal, equal} +pub impl[T] @debug.Debug for Handle[T] with fn to_repr(self) { + @debug.Repr::literal("Handle(\{self.id})") +} ///| -pub extend FontHandle with Hash::{hash, hash_combine} +pub extend Handle with @debug.Debug::{to_repr} + +///| +pub type ImageHandle = Handle[Image] + +///| +pub type AudioHandle = Handle[Audio] + +///| +pub type FontHandle = Handle[Font] + +///| +pub impl[T] ToJson for Handle[T] with fn to_json(self) { + ToJson::to_json(self.id) +} + +///| +pub extend Handle with ToJson::{to_json} diff --git a/selene-core/src/asset_types/pkg.generated.mbti b/selene-core/src/asset_types/pkg.generated.mbti index ab060f64..21899b2f 100644 --- a/selene-core/src/asset_types/pkg.generated.mbti +++ b/selene-core/src/asset_types/pkg.generated.mbti @@ -3,6 +3,7 @@ package "Milky2018/selene/asset_types" import { "moonbitlang/core/debug", + "moonbitlang/core/json", } // Values @@ -10,30 +11,68 @@ import { // Errors // Types and methods -#derive(Eq, Hash, @debug.Debug) -pub(all) struct AudioHandle(UInt32) -pub fn AudioHandle::equal(Self, Self) -> Bool -pub fn AudioHandle::hash(Self) -> Int32 -pub fn AudioHandle::hash_combine(Self, Hasher) -> Unit -pub fn AudioHandle::not_equal(Self, Self) -> Bool -pub fn AudioHandle::to_repr(Self) -> @debug.Repr - -#derive(Eq, Hash, @debug.Debug) -pub(all) struct FontHandle(UInt32) -pub fn FontHandle::equal(Self, Self) -> Bool -pub fn FontHandle::hash(Self) -> Int32 -pub fn FontHandle::hash_combine(Self, Hasher) -> Unit -pub fn FontHandle::not_equal(Self, Self) -> Bool -pub fn FontHandle::to_repr(Self) -> @debug.Repr - -#derive(Eq, Hash, @debug.Debug) -pub(all) struct ImageHandle(UInt32) -pub fn ImageHandle::equal(Self, Self) -> Bool -pub fn ImageHandle::hash(Self) -> Int32 -pub fn ImageHandle::hash_combine(Self, Hasher) -> Unit -pub fn ImageHandle::not_equal(Self, Self) -> Bool -pub fn ImageHandle::to_repr(Self) -> @debug.Repr +type Assets[T] +pub fn[T] Assets::Assets() -> Self[T] +pub fn[T] Assets::add(Self[T], T) -> Handle[T] +pub fn[T] Assets::get(Self[T], Handle[T]) -> T? +pub fn[T] Assets::insert(Self[T], Handle[T], T) -> Bool +pub fn[T] Assets::length(Self[T]) -> Int32 +pub fn[T] Assets::remove(Self[T], Handle[T]) -> T? +pub fn[T] Assets::reserve(Self[T]) -> Handle[T] + +pub struct Audio { + bytes : Bytes +} +pub fn Audio::from_bytes(Bytes) -> Self +pub fn Audio::to_repr(Self) -> @debug.Repr +pub impl @debug.Debug for Audio + +pub struct Font { + bytes : Bytes +} +pub fn Font::from_bytes(Bytes) -> Self +pub fn Font::to_repr(Self) -> @debug.Repr +pub impl @debug.Debug for Font + +type Handle[T] +pub fn[T] Handle::equal(Self[T], Self[T]) -> Bool +pub fn[T] Handle::get(Self[T]) -> T? +pub fn[T] Handle::hash(Self[T]) -> Int32 +pub fn[T] Handle::hash_combine(Self[T], Hasher) -> Unit +pub fn[T] Handle::id(Self[T]) -> UInt32 +pub fn[T] Handle::is_alive(Self[T]) -> Bool +pub fn[T] Handle::not_equal(Self[T], Self[T]) -> Bool +pub fn[T] Handle::on_invalidate(Self[T], () -> Unit) -> Unit +pub fn[T] Handle::to_json(Self[T]) -> @json.Json +pub fn[T] Handle::to_repr(Self[T]) -> @debug.Repr +pub impl[T] Eq for Handle[T] +pub impl[T] Hash for Handle[T] +pub impl[T] @debug.Debug for Handle[T] +pub impl[T] @json.ToJson for Handle[T] + +pub struct Image { + bytes : Bytes +} +pub fn Image::from_bytes(Bytes) -> Self +pub fn Image::to_repr(Self) -> @debug.Repr +pub impl @debug.Debug for Image + +#derive(Eq, @debug.Debug) +pub(all) enum PreparationState { + Unprepared + Preparing + Ready + Failed(String) +} +pub fn PreparationState::equal(Self, Self) -> Bool +pub fn PreparationState::not_equal(Self, Self) -> Bool +pub fn PreparationState::to_repr(Self) -> @debug.Repr // Type aliases +pub type AudioHandle = Handle[Audio] + +pub type FontHandle = Handle[Font] + +pub type ImageHandle = Handle[Image] // Traits diff --git a/selene-core/src/asset_types/preparation.mbt b/selene-core/src/asset_types/preparation.mbt new file mode 100644 index 00000000..12601060 --- /dev/null +++ b/selene-core/src/asset_types/preparation.mbt @@ -0,0 +1,15 @@ +///| +/// Backend readiness, independent of registration and file-read completion. +#derive(Eq, Debug) +pub(all) enum PreparationState { + Unprepared + Preparing + Ready + Failed(String) +} + +///| +pub extend PreparationState with Eq::{equal, not_equal} + +///| +pub extend PreparationState with @debug.Debug::{to_repr} diff --git a/selene-core/src/asset_types/resources.mbt b/selene-core/src/asset_types/resources.mbt new file mode 100644 index 00000000..ad1d4a1c --- /dev/null +++ b/selene-core/src/asset_types/resources.mbt @@ -0,0 +1,56 @@ +///| +/// Encoded file contents. Construction does not imply successful backend decoding. +pub struct Image { + bytes : Bytes +} + +///| +pub fn Image::from_bytes(bytes : Bytes) -> Image { + { bytes, } +} + +///| +pub impl @debug.Debug for Image with fn to_repr(self) { + @debug.Repr::literal("Image(\{self.bytes.length()} bytes)") +} + +///| +pub extend Image with @debug.Debug::{to_repr} + +///| +/// Encoded file contents. Construction does not imply successful backend decoding. +pub struct Audio { + bytes : Bytes +} + +///| +pub fn Audio::from_bytes(bytes : Bytes) -> Audio { + { bytes, } +} + +///| +pub impl @debug.Debug for Audio with fn to_repr(self) { + @debug.Repr::literal("Audio(\{self.bytes.length()} bytes)") +} + +///| +pub extend Audio with @debug.Debug::{to_repr} + +///| +/// Encoded file contents. Construction does not imply successful backend decoding. +pub struct Font { + bytes : Bytes +} + +///| +pub fn Font::from_bytes(bytes : Bytes) -> Font { + { bytes, } +} + +///| +pub impl @debug.Debug for Font with fn to_repr(self) { + @debug.Repr::literal("Font(\{self.bytes.length()} bytes)") +} + +///| +pub extend Font with @debug.Debug::{to_repr} diff --git a/selene-core/src/audio/deletion_wbtest.mbt b/selene-core/src/audio/deletion_wbtest.mbt index 59e18664..70f88f47 100644 --- a/selene-core/src/audio/deletion_wbtest.mbt +++ b/selene-core/src/audio/deletion_wbtest.mbt @@ -5,7 +5,7 @@ test "audio cleanup stops deleted loops only in the active World" { Some(world) => @ecs.set_current_world(world) None => @ecs.clear_current_world() }) - let clip = @asset.load_audio("audio-deletion-test.ogg") + let clip = @asset.audios.add(@asset.Audio::from_bytes(b"test audio")) let settings = PlaybackSettings::looped() let first = @ecs.World() @ecs.set_current_world(first) @@ -54,7 +54,7 @@ test "audio cleanup retains old loop handles when the entity slot is reused" { }) let world = @ecs.World() @ecs.set_current_world(world) - let clip = @asset.load_audio("audio-slot-reuse-test.ogg") + let clip = @asset.audios.add(@asset.Audio::from_bytes(b"test audio")) let old = spawn_audio(clip, settings=PlaybackSettings::looped()) try! @ecs.Schedule().run(@ecs.require_current_world()) audio_playback_system(world.query(), world.query()) @@ -80,7 +80,7 @@ test "finished despawn audio queues deletion until query traversal completes" { None => @ecs.clear_current_world() }) @ecs.set_current_world(world) - let clip = @asset.load_audio("audio-deferred-delete-test.ogg") + let clip = @asset.audios.add(@asset.Audio::from_bytes(b"test audio")) let first = spawn_audio(clip, settings=PlaybackSettings::despawn()) let second = spawn_audio(clip, settings=PlaybackSettings::despawn()) try! @ecs.Schedule().run(@ecs.require_current_world()) diff --git a/selene-core/src/audio/pkg.generated.mbti b/selene-core/src/audio/pkg.generated.mbti index 9d729485..ee6a4592 100644 --- a/selene-core/src/audio/pkg.generated.mbti +++ b/selene-core/src/audio/pkg.generated.mbti @@ -21,15 +21,15 @@ pub fn audio_sink(@ecs.Entity) -> AudioSink? pub fn global_volume() -> Double -pub fn play_one_shot(@asset_types.AudioHandle, volume? : Double) -> Unit +pub fn play_one_shot(@asset_types.Handle[@asset_types.Audio], volume? : Double) -> Unit pub fn restart_audio(@ecs.Entity) -> Unit -pub fn send_audio_event(@asset_types.AudioHandle, settings? : PlaybackSettings, target? : @ecs.Entity) -> Unit +pub fn send_audio_event(@asset_types.Handle[@asset_types.Audio], settings? : PlaybackSettings, target? : @ecs.Entity) -> Unit pub fn set_global_volume(Double) -> Unit -pub fn spawn_audio(@asset_types.AudioHandle, settings? : PlaybackSettings) -> @ecs.Entity +pub fn spawn_audio(@asset_types.Handle[@asset_types.Audio], settings? : PlaybackSettings) -> @ecs.Entity pub fn stop_audio(@ecs.Entity) -> Unit @@ -38,7 +38,7 @@ pub fn stop_audio(@ecs.Entity) -> Unit // Types and methods #derive(Eq, @debug.Debug) pub(all) struct AudioEvent { - source : @asset_types.AudioHandle + source : @asset_types.Handle[@asset_types.Audio] settings : PlaybackSettings target : @ecs.Entity? } @@ -48,9 +48,9 @@ pub fn AudioEvent::to_repr(Self) -> @debug.Repr #derive(Eq, @debug.Debug) pub(all) struct AudioPlayer { - source : @asset_types.AudioHandle + source : @asset_types.Handle[@asset_types.Audio] } -pub fn AudioPlayer::AudioPlayer(@asset_types.AudioHandle) -> Self +pub fn AudioPlayer::AudioPlayer(@asset_types.Handle[@asset_types.Audio]) -> Self pub fn AudioPlayer::equal(Self, Self) -> Bool pub fn AudioPlayer::from_path(String) -> Self pub fn AudioPlayer::not_equal(Self, Self) -> Bool @@ -107,6 +107,6 @@ pub fn PlaybackSettings::with_volume(Self, Double) -> Self pub impl @ecs.Component for PlaybackSettings // Type aliases -pub using @asset_types {type AudioHandle} +pub type AudioHandle = @asset_types.Handle[@asset_types.Audio] // Traits diff --git a/selene-core/src/audio/playback.mbt b/selene-core/src/audio/playback.mbt index 82d88850..16946541 100644 --- a/selene-core/src/audio/playback.mbt +++ b/selene-core/src/audio/playback.mbt @@ -107,10 +107,10 @@ fn start_audio_sink( player : AudioPlayer, settings : PlaybackSettings, ) -> Unit { - guard @asset.audio_path(player.source) is Some(path) else { return } + guard player.source.get() is Some(_) else { return } let sink = { instance: @platform_audio.play_audio( - audio_path=path, + source=player.source, volume=if settings.muted { 0.0 } else { diff --git a/selene-core/src/audio/runtime_access_test.mbt b/selene-core/src/audio/runtime_access_test.mbt index 4baafe36..ed96c715 100644 --- a/selene-core/src/audio/runtime_access_test.mbt +++ b/selene-core/src/audio/runtime_access_test.mbt @@ -8,7 +8,9 @@ test "audio control handles are read per entity without exposing sink storage" { let first = @ecs.World() let second = @ecs.World() @ecs.set_current_world(first) - let entity = @audio.spawn_audio(@asset.load_audio("audio-access-test.ogg")) + let entity = @audio.spawn_audio( + @asset.audios.add(@asset.Audio::from_bytes(b"test audio")), + ) assert_true(@audio.audio_sink(entity) is None) try! @ecs.Schedule().run(@ecs.require_current_world()) @audio.audio_playback_system(first.query(), first.query()) diff --git a/selene-core/src/autotile2d/autotile2d_wbtest.mbt b/selene-core/src/autotile2d/autotile2d_wbtest.mbt index 55f1f026..caf90ce1 100644 --- a/selene-core/src/autotile2d/autotile2d_wbtest.mbt +++ b/selene-core/src/autotile2d/autotile2d_wbtest.mbt @@ -265,3 +265,33 @@ test "runtime layer cell updates keep source state in sync" { inspect(source_after_remove.cells.length(), content="1") @ecs_test.destroy(layer) } + +///| +test "runtime tile visuals reuse registered images without path IO" { + @asset.set_io(fn(_) { abort("tile visuals must use their image handle") }) + defer @asset.set_io(fn(_) { None }) + let images : @asset.Assets[@asset.Image] = Assets() + let image = images.add(@asset.Image::from_bytes(b"tile image")) + defer ignore(images.remove(image)) + let world = @ecs.require_current_world() + let source = test_source( + Bitmask4, + [AutoTilePaletteEntry(1, "base", bitmask4_rules=[mask_rule(0, "m0")])], + [AutoTileCell(0, 0, 1)], + ) + let layer = @ecs_test.spawn(world, ()) + defer @ecs_test.destroy(layer) + register_runtime_layer( + layer, + source, + context=AutoTileRuntimeContext( + visual_resolver=Some(fn(_, _) { Some(AutoTileVisual(image=Some(image))) }), + ), + ) + try! @ecs.Schedule().run(world) + let tile = runtime_layers().get(layer).unwrap().tile_entities + .get({ x: 0, y: 0, }) + .unwrap() + let sprites : @ecs.Query[@ecs.Single[@sprite.Sprite]] = world.query1() + assert_eq(sprites.get(tile).unwrap().0.image, Some(image)) +} diff --git a/selene-core/src/autotile2d/pkg.generated.mbti b/selene-core/src/autotile2d/pkg.generated.mbti index 1c491c1d..f08c6ec9 100644 --- a/selene-core/src/autotile2d/pkg.generated.mbti +++ b/selene-core/src/autotile2d/pkg.generated.mbti @@ -2,6 +2,7 @@ package "Milky2018/selene/autotile2d" import { + "Milky2018/selene/asset_types", "Milky2018/selene/ecs", "Milky2018/selene/math", "Milky2018/selene/sprite", @@ -153,12 +154,12 @@ pub fn AutoTileSolvedTile::to_json(Self) -> @json.Json pub fn AutoTileSolvedTile::to_repr(Self) -> @debug.Repr pub struct AutoTileVisual { - image_path : String? + image : @asset_types.Handle[@asset_types.Image]? rect : @math.Rect? custom_size : @math.Vec2? anchor : @sprite.Anchor } -pub fn AutoTileVisual::AutoTileVisual(image_path? : String?, rect? : @math.Rect?, custom_size? : @math.Vec2?, anchor? : @sprite.Anchor) -> Self +pub fn AutoTileVisual::AutoTileVisual(image? : @asset_types.Handle[@asset_types.Image]?, rect? : @math.Rect?, custom_size? : @math.Vec2?, anchor? : @sprite.Anchor) -> Self #derive(Eq, @debug.Debug, @json.FromJson, @json.ToJson) pub struct AutoTileWangRule { diff --git a/selene-core/src/autotile2d/runtime.mbt b/selene-core/src/autotile2d/runtime.mbt index 78e3d334..85f5732c 100644 --- a/selene-core/src/autotile2d/runtime.mbt +++ b/selene-core/src/autotile2d/runtime.mbt @@ -1,6 +1,6 @@ ///| pub struct AutoTileVisual { - image_path : String? + image : @asset.ImageHandle? rect : @math.Rect? custom_size : @math.Vec2? anchor : @sprite.Anchor @@ -8,12 +8,12 @@ pub struct AutoTileVisual { ///| pub fn AutoTileVisual::AutoTileVisual( - image_path~ : String? = None, + image~ : @asset.ImageHandle? = None, rect~ : @math.Rect? = None, custom_size~ : @math.Vec2? = None, anchor~ : @sprite.Anchor = @sprite.default_anchor(), ) -> AutoTileVisual { - { image_path, rect, custom_size, anchor, } + { image, rect, custom_size, anchor, } } ///| @@ -80,7 +80,7 @@ fn apply_tile_visual( ( Spatial(@transform.Transform::from_xyz(position.x, position.y, context.z)), Sprite( - image=visual.image_path.map(fn(path) { @asset.load_image(path) }), + image=visual.image, rect=visual.rect, custom_size=visual.custom_size, anchor=visual.anchor, diff --git a/selene-core/src/material2d/pkg.generated.mbti b/selene-core/src/material2d/pkg.generated.mbti index c24242fe..0ea1c80c 100644 --- a/selene-core/src/material2d/pkg.generated.mbti +++ b/selene-core/src/material2d/pkg.generated.mbti @@ -23,12 +23,12 @@ pub fn update_color_material(ColorMaterialHandle, ColorMaterial) -> Unit // Types and methods pub(all) struct ColorMaterial { color : @render.Color - texture : @asset_types.ImageHandle? + texture : @asset_types.Handle[@asset_types.Image]? uv_transform : @math.Affine2 alpha_mode : @render.AlphaMode2D blend_mode : @render.BlendMode2D } -pub fn ColorMaterial::ColorMaterial(color? : @render.Color, texture? : @asset_types.ImageHandle?, uv_transform? : @math.Affine2, alpha_mode? : @render.AlphaMode2D, blend_mode? : @render.BlendMode2D) -> Self +pub fn ColorMaterial::ColorMaterial(color? : @render.Color, texture? : @asset_types.Handle[@asset_types.Image]?, uv_transform? : @math.Affine2, alpha_mode? : @render.AlphaMode2D, blend_mode? : @render.BlendMode2D) -> Self pub fn ColorMaterial::from_color(@render.Color) -> Self #derive(Eq, Hash, @debug.Debug) diff --git a/selene-core/src/platform_asset_io/default.mbt b/selene-core/src/platform_asset_io/default.mbt index cb4e64e3..2056b15b 100644 --- a/selene-core/src/platform_asset_io/default.mbt +++ b/selene-core/src/platform_asset_io/default.mbt @@ -2,11 +2,23 @@ let reader : Ref[(String) -> Bytes?] = Ref(fn(_path : String) { None }) ///| -pub fn set_reader(callback : (String) -> Bytes?) -> Unit { +pub fn set_reader( + callback : (String) -> Bytes?, + paths~ : Array[String] = [], +) -> Unit { reader.val = callback + catalogue.val = paths.copy() } ///| pub fn read_bytes(path : String) -> Bytes? { (reader.val)(path) } + +///| +let catalogue : Ref[Array[String]] = Ref([]) + +///| +pub fn paths() -> Array[String] { + catalogue.val.copy() +} diff --git a/selene-core/src/platform_asset_io/pkg.mbti b/selene-core/src/platform_asset_io/pkg.mbti index 37906e55..c300a4ac 100644 --- a/selene-core/src/platform_asset_io/pkg.mbti +++ b/selene-core/src/platform_asset_io/pkg.mbti @@ -1,5 +1,7 @@ package "Milky2018/selene/platform_asset_io" -fn set_reader((String) -> Bytes?) -> Unit +fn set_reader((String) -> Bytes?, paths? : Array[String]) -> Unit fn read_bytes(String) -> Bytes? + +fn paths() -> Array[String] diff --git a/selene-core/src/platform_audio/default.mbt b/selene-core/src/platform_audio/default.mbt index 5213034b..0d213b7a 100644 --- a/selene-core/src/platform_audio/default.mbt +++ b/selene-core/src/platform_audio/default.mbt @@ -13,13 +13,13 @@ pub extend AudioInstance with Hash::{hash, hash_combine} ///| pub fn play_audio( - audio_path~ : String, + source~ : @asset_types.AudioHandle, volume~ : Double, speed~ : Double, loop_~ : Bool, paused~ : Bool, ) -> AudioInstance { - ignore(audio_path) + ignore(source) ignore(volume) ignore(speed) ignore(loop_) @@ -28,8 +28,8 @@ pub fn play_audio( } ///| -pub fn preload(path : String) -> Unit { - ignore(path) +pub fn preload(source : @asset_types.AudioHandle) -> Unit { + ignore(source) } ///| @@ -71,3 +71,11 @@ pub fn is_finished(instance~ : AudioInstance) -> Bool { pub fn tick() -> Unit { } + +///| +pub fn preparation_state( + handle : @asset_types.AudioHandle, +) -> @asset_types.PreparationState { + ignore(handle) + Unprepared +} diff --git a/selene-core/src/platform_audio/moon.pkg b/selene-core/src/platform_audio/moon.pkg index 34ac4a91..b14b0807 100644 --- a/selene-core/src/platform_audio/moon.pkg +++ b/selene-core/src/platform_audio/moon.pkg @@ -1,4 +1,5 @@ import { + "Milky2018/selene/asset_types", "moonbitlang/core/debug", } diff --git a/selene-core/src/platform_audio/pkg.mbti b/selene-core/src/platform_audio/pkg.mbti index 0196ea75..16c226d2 100644 --- a/selene-core/src/platform_audio/pkg.mbti +++ b/selene-core/src/platform_audio/pkg.mbti @@ -1,16 +1,18 @@ package "Milky2018/selene/platform_audio" +import { "Milky2018/selene/asset_types" } + type AudioInstance fn play_audio( - audio_path~ : String, + source~ : @asset_types.AudioHandle, volume~ : Double, speed~ : Double, loop_~ : Bool, paused~ : Bool ) -> AudioInstance -fn preload(String) -> Unit +fn preload(@asset_types.AudioHandle) -> Unit fn set_volume(instance~ : AudioInstance, volume~ : Double) -> Unit @@ -25,3 +27,5 @@ fn stop(instance~ : AudioInstance) -> Unit fn is_finished(instance~ : AudioInstance) -> Bool fn tick() -> Unit + +fn preparation_state(@asset_types.AudioHandle) -> @asset_types.PreparationState diff --git a/selene-core/src/platform_render/default.mbt b/selene-core/src/platform_render/default.mbt index 8f7cdb44..4292d313 100644 --- a/selene-core/src/platform_render/default.mbt +++ b/selene-core/src/platform_render/default.mbt @@ -4,16 +4,26 @@ pub fn submit_frame(frame : @render_pipeline.RenderFrame) -> Unit { } ///| -pub fn register_font(family : String, path : String) -> Unit { - ignore(family) - ignore(path) +pub fn image_preparation_state( + handle : @asset_types.ImageHandle, +) -> @asset_types.PreparationState { + ignore(handle) + Unprepared +} + +///| +pub fn font_preparation_state( + handle : @asset_types.FontHandle, +) -> @asset_types.PreparationState { + ignore(handle) + Unprepared } ///| /// Returns a monotonically increasing revision whenever the backend's /// measurable glyph metrics for `family` change. -pub fn font_metrics_revision(family : String) -> UInt32 { - ignore(family) +pub fn font_metrics_revision(style : @render2d_types.TextStyle2D) -> UInt32 { + ignore(style) 0U } @@ -75,21 +85,21 @@ pub fn render_offscreen_png( ///| pub fn image_region_is_fully_transparent( - path : String, + image : @asset_types.ImageHandle, rect : @math.Rect, ) -> Bool? { - ignore(path) + ignore(image) ignore(rect) None } ///| pub fn export_texture_region_png( - image_path : String, + image : @asset_types.ImageHandle, rect : @math.Rect, out_path : String, ) -> Bool { - ignore(image_path) + ignore(image) ignore(rect) ignore(out_path) false diff --git a/selene-core/src/platform_render/moon.pkg b/selene-core/src/platform_render/moon.pkg index 6103e33c..5da62f21 100644 --- a/selene-core/src/platform_render/moon.pkg +++ b/selene-core/src/platform_render/moon.pkg @@ -1,4 +1,5 @@ import { + "Milky2018/selene/asset_types", "Milky2018/selene/math", "Milky2018/selene/render2d_types", "Milky2018/selene/render_pipeline", diff --git a/selene-core/src/platform_render/pkg.mbti b/selene-core/src/platform_render/pkg.mbti index eda31e70..d68d6924 100644 --- a/selene-core/src/platform_render/pkg.mbti +++ b/selene-core/src/platform_render/pkg.mbti @@ -1,6 +1,7 @@ package "Milky2018/selene/platform_render" import { + "Milky2018/selene/asset_types", "Milky2018/selene/math", "Milky2018/selene/render2d_types", "Milky2018/selene/render_pipeline", @@ -8,9 +9,11 @@ import { fn submit_frame(@render_pipeline.RenderFrame) -> Unit -fn register_font(String, String) -> Unit +fn image_preparation_state(@asset_types.ImageHandle) -> @asset_types.PreparationState -fn font_metrics_revision(String) -> UInt +fn font_preparation_state(@asset_types.FontHandle) -> @asset_types.PreparationState + +fn font_metrics_revision(@render2d_types.TextStyle2D) -> UInt fn measure_text(@render2d_types.TextStyle2D, String) -> @math.Vec2 @@ -28,6 +31,6 @@ fn capture_frame_png_to_file(String) -> Bool fn render_offscreen_png(@render_pipeline.RenderFrame, Int, Int) -> Bytes? -fn image_region_is_fully_transparent(String, @math.Rect) -> Bool? +fn image_region_is_fully_transparent(@asset_types.ImageHandle, @math.Rect) -> Bool? -fn export_texture_region_png(String, @math.Rect, String) -> Bool +fn export_texture_region_png(@asset_types.ImageHandle, @math.Rect, String) -> Bool diff --git a/selene-core/src/render2d_types/pkg.generated.mbti b/selene-core/src/render2d_types/pkg.generated.mbti index b3d50df8..899df91f 100644 --- a/selene-core/src/render2d_types/pkg.generated.mbti +++ b/selene-core/src/render2d_types/pkg.generated.mbti @@ -53,7 +53,7 @@ pub(all) enum HAlign { } pub(all) struct ImageDrawCommand2D { - image : @asset_types.ImageHandle + image : @asset_types.Handle[@asset_types.Image] destination : @math.Rect source : ImageRegion2D? transform : @math.Affine2 @@ -132,7 +132,7 @@ pub(all) struct TextDrawCommand2D { } pub(all) struct TextStyle2D { - font : @asset_types.FontHandle? + font : @asset_types.Handle[@asset_types.Font]? family : String size : Double color : @render.Color diff --git a/selene-core/src/render3d/assets.mbt b/selene-core/src/render3d/assets.mbt index 8712b70a..47148c0b 100644 --- a/selene-core/src/render3d/assets.mbt +++ b/selene-core/src/render3d/assets.mbt @@ -18,9 +18,6 @@ let meshes : Map[MeshHandle, MeshAsset] = Map([]) ///| let materials : Map[MaterialHandle, StandardMaterial3D] = Map([]) -///| -let images : Map[ImageHandle, ImageAsset] = Map([]) - ///| let cubemaps : Map[CubemapHandle, CubemapAsset3D] = Map([]) @@ -33,9 +30,6 @@ let next_mesh_id : Ref[UInt32] = Ref(0) ///| let next_material_id : Ref[UInt32] = Ref(0) -///| -let next_image_id : Ref[UInt32] = Ref(0) - ///| let next_cubemap_id : Ref[UInt32] = Ref(0) @@ -48,9 +42,6 @@ let dirty_mesh_assets : Map[MeshHandle, MeshAsset] = Map([]) ///| let dirty_material_assets : Map[MaterialHandle, StandardMaterial3D] = Map([]) -///| -let dirty_image_assets : Map[ImageHandle, ImageAsset] = Map([]) - ///| let dirty_cubemap_assets : Map[CubemapHandle, CubemapAsset3D] = Map([]) @@ -60,9 +51,6 @@ let released_mesh_assets : Array[MeshHandle] = [] ///| let released_material_assets : Array[MaterialHandle] = [] -///| -let released_image_assets : Array[ImageHandle] = [] - ///| let released_cubemap_assets : Array[CubemapHandle] = [] @@ -89,15 +77,6 @@ pub fn register_material_asset(material : StandardMaterial3D) -> MaterialHandle handle } -///| -pub fn register_image_asset(image : ImageAsset) -> ImageHandle { - let handle = @render3d_types.ImageHandle(next_image_id.val) - next_image_id.val += 1 - images.set(handle, image) - dirty_image_assets.set(handle, image) - handle -} - ///| pub fn register_cubemap_asset(cubemap : CubemapAsset3D) -> CubemapHandle { let handle = @render3d_types.CubemapHandle(next_cubemap_id.val) @@ -127,12 +106,6 @@ pub fn update_material_asset( dirty_material_assets.set(handle, material) } -///| -pub fn update_image_asset(handle : ImageHandle, image : ImageAsset) -> Unit { - images.set(handle, image) - dirty_image_assets.set(handle, image) -} - ///| pub fn update_cubemap_asset( handle : CubemapHandle, @@ -156,13 +129,6 @@ pub fn release_material_asset(handle : MaterialHandle) -> Unit { released_material_assets.push(handle) } -///| -pub fn release_image_asset(handle : ImageHandle) -> Unit { - images.remove(handle) - dirty_image_assets.remove(handle) - released_image_assets.push(handle) -} - ///| pub fn release_cubemap_asset(handle : CubemapHandle) -> Unit { cubemaps.remove(handle) @@ -199,13 +165,6 @@ pub fn take_dirty_material_assets() -> Array[ values } -///| -pub fn take_dirty_image_assets() -> Array[(ImageHandle, ImageAsset)] { - let values = dirty_image_assets.to_array() - dirty_image_assets.clear() - values -} - ///| pub fn take_dirty_cubemap_assets() -> Array[(CubemapHandle, CubemapAsset3D)] { let values = dirty_cubemap_assets.to_array() @@ -227,13 +186,6 @@ pub fn take_released_material_assets() -> Array[MaterialHandle] { values } -///| -pub fn take_released_image_assets() -> Array[ImageHandle] { - let values = released_image_assets.copy() - released_image_assets.clear() - values -} - ///| pub fn take_released_cubemap_assets() -> Array[CubemapHandle] { let values = released_cubemap_assets.copy() diff --git a/selene-core/src/render3d/moon.pkg b/selene-core/src/render3d/moon.pkg index 98b34900..db77b492 100644 --- a/selene-core/src/render3d/moon.pkg +++ b/selene-core/src/render3d/moon.pkg @@ -16,3 +16,7 @@ formatter(ignore: [ "mesh_renderer.g.mbt" ]) import { "Milky2018/selene/internal/ecs_test", } for "wbtest" + +import { + "Milky2018/selene/asset", +} for "wbtest" diff --git a/selene-core/src/render3d/pkg.generated.mbti b/selene-core/src/render3d/pkg.generated.mbti index 533c68db..de061f14 100644 --- a/selene-core/src/render3d/pkg.generated.mbti +++ b/selene-core/src/render3d/pkg.generated.mbti @@ -2,6 +2,7 @@ package "Milky2018/selene/render3d" import { + "Milky2018/selene/asset_types", "Milky2018/selene/ecs", "Milky2018/selene/math", "Milky2018/selene/render", @@ -40,8 +41,6 @@ pub fn push_line3d(@render3d_types.RenderLine3D) -> Unit pub fn register_cubemap_asset(@render3d_types.CubemapAsset3D) -> @render3d_types.CubemapHandle -pub fn register_image_asset(@render3d_types.ImageAsset) -> @render3d_types.ImageHandle - pub fn register_material_asset(@render3d_types.StandardMaterial3D) -> @render3d_types.MaterialHandle pub fn register_mesh_asset(@render3d_types.MeshAsset) -> @render3d_types.MeshHandle @@ -50,8 +49,6 @@ pub fn register_scene_path(String) -> @render3d_types.SceneHandle pub fn release_cubemap_asset(@render3d_types.CubemapHandle) -> Unit -pub fn release_image_asset(@render3d_types.ImageHandle) -> Unit - pub fn release_material_asset(@render3d_types.MaterialHandle) -> Unit pub fn release_mesh_asset(@render3d_types.MeshHandle) -> Unit @@ -68,16 +65,12 @@ pub fn sphere_mesh(Double) -> @render3d_types.MeshAsset pub fn take_dirty_cubemap_assets() -> Array[(@render3d_types.CubemapHandle, @render3d_types.CubemapAsset3D)] -pub fn take_dirty_image_assets() -> Array[(@render3d_types.ImageHandle, @render3d_types.ImageAsset)] - pub fn take_dirty_material_assets() -> Array[(@render3d_types.MaterialHandle, @render3d_types.StandardMaterial3D)] pub fn take_dirty_mesh_assets() -> Array[(@render3d_types.MeshHandle, @render3d_types.MeshAsset)] pub fn take_released_cubemap_assets() -> Array[@render3d_types.CubemapHandle] -pub fn take_released_image_assets() -> Array[@render3d_types.ImageHandle] - pub fn take_released_material_assets() -> Array[@render3d_types.MaterialHandle] pub fn take_released_mesh_assets() -> Array[@render3d_types.MeshHandle] @@ -86,8 +79,6 @@ pub fn triangle_mesh(Array[@math.Vec3], uvs? : Array[@math.Vec2]?, normals? : Ar pub fn update_cubemap_asset(@render3d_types.CubemapHandle, @render3d_types.CubemapAsset3D) -> Unit -pub fn update_image_asset(@render3d_types.ImageHandle, @render3d_types.ImageAsset) -> Unit - pub fn update_material_asset(@render3d_types.MaterialHandle, @render3d_types.StandardMaterial3D) -> Unit pub fn update_mesh_asset(@render3d_types.MeshHandle, @render3d_types.MeshAsset) -> Unit @@ -131,9 +122,7 @@ pub using @render3d_types {type FramePointLight3D} pub using @render3d_types {type FrameSpotLight3D} -pub using @render3d_types {type ImageAsset} - -pub using @render3d_types {type ImageHandle} +pub type ImageHandle = @asset_types.Handle[@asset_types.Image] pub using @render3d_types {type MaterialHandle} diff --git a/selene-core/src/render3d/render3d_wbtest.mbt b/selene-core/src/render3d/render3d_wbtest.mbt index a3d17dae..68a2bb7f 100644 --- a/selene-core/src/render3d/render3d_wbtest.mbt +++ b/selene-core/src/render3d/render3d_wbtest.mbt @@ -145,13 +145,12 @@ test "render3d extract preserves shadow map size resources" { ///| test "render3d cubemap assets participate in dirty and release sync" { - let px = register_image_asset({ path: "sky/px.png", }) - let nx = register_image_asset({ path: "sky/nx.png", }) - let py = register_image_asset({ path: "sky/py.png", }) - let ny = register_image_asset({ path: "sky/ny.png", }) - let pz = register_image_asset({ path: "sky/pz.png", }) - let nz = register_image_asset({ path: "sky/nz.png", }) - ignore(take_dirty_image_assets()) + let px = @asset.images.add(@asset.Image::from_bytes(b"sky/px.png")) + let nx = @asset.images.add(@asset.Image::from_bytes(b"sky/nx.png")) + let py = @asset.images.add(@asset.Image::from_bytes(b"sky/py.png")) + let ny = @asset.images.add(@asset.Image::from_bytes(b"sky/ny.png")) + let pz = @asset.images.add(@asset.Image::from_bytes(b"sky/pz.png")) + let nz = @asset.images.add(@asset.Image::from_bytes(b"sky/nz.png")) let cubemap = register_cubemap_asset( cubemap_asset_six_faces(CubemapFaces3D(px, nx, py, ny, pz, nz)), @@ -169,24 +168,23 @@ test "render3d cubemap assets participate in dirty and release sync" { release_cubemap_asset(cubemap) inspect(take_released_cubemap_assets().length(), content="1") inspect(cubemap_asset(cubemap) is None, content="true") - release_image_asset(px) - release_image_asset(nx) - release_image_asset(py) - release_image_asset(ny) - release_image_asset(pz) - release_image_asset(nz) - ignore(take_released_image_assets()) + ignore(@asset.images.remove(px)) + ignore(@asset.images.remove(nx)) + ignore(@asset.images.remove(py)) + ignore(@asset.images.remove(ny)) + ignore(@asset.images.remove(pz)) + ignore(@asset.images.remove(nz)) } ///| test "render3d extracts skybox from active camera" { let world = @ecs.require_current_world() - let px = register_image_asset({ path: "sky/px.png", }) - let nx = register_image_asset({ path: "sky/nx.png", }) - let py = register_image_asset({ path: "sky/py.png", }) - let ny = register_image_asset({ path: "sky/ny.png", }) - let pz = register_image_asset({ path: "sky/pz.png", }) - let nz = register_image_asset({ path: "sky/nz.png", }) + let px = @asset.images.add(@asset.Image::from_bytes(b"sky/px.png")) + let nx = @asset.images.add(@asset.Image::from_bytes(b"sky/nx.png")) + let py = @asset.images.add(@asset.Image::from_bytes(b"sky/py.png")) + let ny = @asset.images.add(@asset.Image::from_bytes(b"sky/ny.png")) + let pz = @asset.images.add(@asset.Image::from_bytes(b"sky/pz.png")) + let nz = @asset.images.add(@asset.Image::from_bytes(b"sky/nz.png")) let cubemap = register_cubemap_asset( cubemap_asset_six_faces(CubemapFaces3D(px, nx, py, ny, pz, nz)), ) @@ -224,15 +222,13 @@ test "render3d extracts skybox from active camera" { @camera3d.set_active_camera3d(None) render3d_world_state().extracted_frame = RenderFrame3D() release_cubemap_asset(cubemap) - release_image_asset(px) - release_image_asset(nx) - release_image_asset(py) - release_image_asset(ny) - release_image_asset(pz) - release_image_asset(nz) - ignore(take_dirty_image_assets()) + ignore(@asset.images.remove(px)) + ignore(@asset.images.remove(nx)) + ignore(@asset.images.remove(py)) + ignore(@asset.images.remove(ny)) + ignore(@asset.images.remove(pz)) + ignore(@asset.images.remove(nz)) ignore(take_dirty_cubemap_assets()) - ignore(take_released_image_assets()) ignore(take_released_cubemap_assets()) ignore(@ecs_test.delete(camera_entity)) } diff --git a/selene-core/src/render3d/types.mbt b/selene-core/src/render3d/types.mbt index f898bfc3..c78bb5cf 100644 --- a/selene-core/src/render3d/types.mbt +++ b/selene-core/src/render3d/types.mbt @@ -57,9 +57,6 @@ pub type MeshPrimitive3D = @render3d_types.MeshPrimitive3D ///| pub type MeshAsset = @render3d_types.MeshAsset -///| -pub type ImageAsset = @render3d_types.ImageAsset - ///| pub using @render3d_types {type CubemapFaces3D} diff --git a/selene-core/src/render3d_types/handles.mbt b/selene-core/src/render3d_types/handles.mbt index 730647d7..fc2840ca 100644 --- a/selene-core/src/render3d_types/handles.mbt +++ b/selene-core/src/render3d_types/handles.mbt @@ -39,17 +39,7 @@ pub extend MaterialHandle with Eq::{not_equal, equal} pub extend MaterialHandle with Hash::{hash, hash_combine} ///| -#derive(Eq, Debug, Hash) -pub(all) struct ImageHandle(UInt32) - -///| -pub extend ImageHandle with @moonbitlang/core/debug.Debug::{to_repr} - -///| -pub extend ImageHandle with Eq::{not_equal, equal} - -///| -pub extend ImageHandle with Hash::{hash, hash_combine} +pub type ImageHandle = @asset_types.ImageHandle ///| #derive(Eq, Debug, Hash) diff --git a/selene-core/src/render3d_types/moon.pkg b/selene-core/src/render3d_types/moon.pkg index e079a50f..b1155ef5 100644 --- a/selene-core/src/render3d_types/moon.pkg +++ b/selene-core/src/render3d_types/moon.pkg @@ -1,4 +1,5 @@ import { + "Milky2018/selene/asset_types", "Milky2018/selene/ecs", "moonbitlang/core/debug", "Milky2018/selene/math", diff --git a/selene-core/src/render3d_types/pkg.generated.mbti b/selene-core/src/render3d_types/pkg.generated.mbti index 655a52f0..fb394c5b 100644 --- a/selene-core/src/render3d_types/pkg.generated.mbti +++ b/selene-core/src/render3d_types/pkg.generated.mbti @@ -2,6 +2,7 @@ package "Milky2018/selene/render3d_types" import { + "Milky2018/selene/asset_types", "Milky2018/selene/ecs", "Milky2018/selene/math", "Milky2018/selene/render", @@ -74,14 +75,14 @@ pub fn CubemapAsset3D::to_repr(Self) -> @debug.Repr #derive(Eq, @debug.Debug) pub(all) struct CubemapFaces3D { - positive_x : ImageHandle - negative_x : ImageHandle - positive_y : ImageHandle - negative_y : ImageHandle - positive_z : ImageHandle - negative_z : ImageHandle -} -pub fn CubemapFaces3D::CubemapFaces3D(ImageHandle, ImageHandle, ImageHandle, ImageHandle, ImageHandle, ImageHandle) -> Self + positive_x : @asset_types.Handle[@asset_types.Image] + negative_x : @asset_types.Handle[@asset_types.Image] + positive_y : @asset_types.Handle[@asset_types.Image] + negative_y : @asset_types.Handle[@asset_types.Image] + positive_z : @asset_types.Handle[@asset_types.Image] + negative_z : @asset_types.Handle[@asset_types.Image] +} +pub fn CubemapFaces3D::CubemapFaces3D(@asset_types.Handle[@asset_types.Image], @asset_types.Handle[@asset_types.Image], @asset_types.Handle[@asset_types.Image], @asset_types.Handle[@asset_types.Image], @asset_types.Handle[@asset_types.Image], @asset_types.Handle[@asset_types.Image]) -> Self pub fn CubemapFaces3D::equal(Self, Self) -> Bool pub fn CubemapFaces3D::not_equal(Self, Self) -> Bool pub fn CubemapFaces3D::to_repr(Self) -> @debug.Repr @@ -152,22 +153,6 @@ pub(all) struct FrameSpotLight3D { outer_angle : Double } -#derive(Eq, @debug.Debug) -pub(all) struct ImageAsset { - path : String -} -pub fn ImageAsset::equal(Self, Self) -> Bool -pub fn ImageAsset::not_equal(Self, Self) -> Bool -pub fn ImageAsset::to_repr(Self) -> @debug.Repr - -#derive(Eq, Hash, @debug.Debug) -pub(all) struct ImageHandle(UInt32) -pub fn ImageHandle::equal(Self, Self) -> Bool -pub fn ImageHandle::hash(Self) -> Int32 -pub fn ImageHandle::hash_combine(Self, Hasher) -> Unit -pub fn ImageHandle::not_equal(Self, Self) -> Bool -pub fn ImageHandle::to_repr(Self) -> @debug.Repr - #derive(Eq, Hash, @debug.Debug) pub(all) struct MaterialHandle(UInt32) pub fn MaterialHandle::equal(Self, Self) -> Bool @@ -327,12 +312,12 @@ pub fn Tangent3D::to_repr(Self) -> @debug.Repr #derive(Eq, @debug.Debug) pub(all) struct TextureBinding3D { - image : ImageHandle + image : @asset_types.Handle[@asset_types.Image] sampler : TextureSampler3D texcoord_set : Int32 transform : TextureTransform3D } -pub fn TextureBinding3D::TextureBinding3D(ImageHandle, texcoord_set? : Int32, sampler? : TextureSampler3D, transform? : TextureTransform3D) -> Self +pub fn TextureBinding3D::TextureBinding3D(@asset_types.Handle[@asset_types.Image], texcoord_set? : Int32, sampler? : TextureSampler3D, transform? : TextureTransform3D) -> Self pub fn TextureBinding3D::equal(Self, Self) -> Bool pub fn TextureBinding3D::not_equal(Self, Self) -> Bool pub fn TextureBinding3D::to_repr(Self) -> @debug.Repr @@ -405,5 +390,6 @@ pub fn TriangleTopology3D::not_equal(Self, Self) -> Bool pub fn TriangleTopology3D::to_repr(Self) -> @debug.Repr // Type aliases +pub type ImageHandle = @asset_types.Handle[@asset_types.Image] // Traits diff --git a/selene-core/src/render3d_types/texture.mbt b/selene-core/src/render3d_types/texture.mbt index efc9ce46..06a1434e 100644 --- a/selene-core/src/render3d_types/texture.mbt +++ b/selene-core/src/render3d_types/texture.mbt @@ -84,18 +84,6 @@ pub extend TextureBinding3D with @moonbitlang/core/debug.Debug::{to_repr} ///| pub extend TextureBinding3D with Eq::{not_equal, equal} -///| -#derive(Eq, Debug) -pub(all) struct ImageAsset { - path : String -} - -///| -pub extend ImageAsset with @moonbitlang/core/debug.Debug::{to_repr} - -///| -pub extend ImageAsset with Eq::{not_equal, equal} - ///| pub fn TextureSampler3D::TextureSampler3D() -> TextureSampler3D { { diff --git a/selene-core/src/render_pipeline/frame.mbt b/selene-core/src/render_pipeline/frame.mbt index 4d8b556f..05c4e689 100644 --- a/selene-core/src/render_pipeline/frame.mbt +++ b/selene-core/src/render_pipeline/frame.mbt @@ -4,15 +4,11 @@ pub(all) struct RenderAssetSync3D { material_upserts : Array[ (@render3d_types.MaterialHandle, @render3d_types.StandardMaterial3D), ] - image_upserts : Array[ - (@render3d_types.ImageHandle, @render3d_types.ImageAsset), - ] cubemap_upserts : Array[ (@render3d_types.CubemapHandle, @render3d_types.CubemapAsset3D), ] mesh_releases : Array[@render3d_types.MeshHandle] material_releases : Array[@render3d_types.MaterialHandle] - image_releases : Array[@render3d_types.ImageHandle] cubemap_releases : Array[@render3d_types.CubemapHandle] } @@ -28,11 +24,9 @@ pub fn RenderAssetSync3D::RenderAssetSync3D() -> RenderAssetSync3D { { mesh_upserts: [], material_upserts: [], - image_upserts: [], cubemap_upserts: [], mesh_releases: [], material_releases: [], - image_releases: [], cubemap_releases: [], } } diff --git a/selene-core/src/render_pipeline/pkg.generated.mbti b/selene-core/src/render_pipeline/pkg.generated.mbti index bcedded3..c02623b0 100644 --- a/selene-core/src/render_pipeline/pkg.generated.mbti +++ b/selene-core/src/render_pipeline/pkg.generated.mbti @@ -14,11 +14,9 @@ import { pub(all) struct RenderAssetSync3D { mesh_upserts : Array[(@render3d_types.MeshHandle, @render3d_types.MeshAsset)] material_upserts : Array[(@render3d_types.MaterialHandle, @render3d_types.StandardMaterial3D)] - image_upserts : Array[(@render3d_types.ImageHandle, @render3d_types.ImageAsset)] cubemap_upserts : Array[(@render3d_types.CubemapHandle, @render3d_types.CubemapAsset3D)] mesh_releases : Array[@render3d_types.MeshHandle] material_releases : Array[@render3d_types.MaterialHandle] - image_releases : Array[@render3d_types.ImageHandle] cubemap_releases : Array[@render3d_types.CubemapHandle] } pub fn RenderAssetSync3D::RenderAssetSync3D() -> Self diff --git a/selene-core/src/render_submit/submit.mbt b/selene-core/src/render_submit/submit.mbt index 54f3e0b8..8bce731a 100644 --- a/selene-core/src/render_submit/submit.mbt +++ b/selene-core/src/render_submit/submit.mbt @@ -126,11 +126,9 @@ pub fn render_submit_system(world~ : @ecs.World, _delta : Double) -> Unit { let assets3d : @render_pipeline.RenderAssetSync3D = { mesh_upserts: @render3d.take_dirty_mesh_assets(), material_upserts: @render3d.take_dirty_material_assets(), - image_upserts: @render3d.take_dirty_image_assets(), cubemap_upserts: @render3d.take_dirty_cubemap_assets(), mesh_releases: @render3d.take_released_mesh_assets(), material_releases: @render3d.take_released_material_assets(), - image_releases: @render3d.take_released_image_assets(), cubemap_releases: @render3d.take_released_cubemap_assets(), } let frame : @render_pipeline.RenderFrame = { diff --git a/selene-core/src/runtime_debug/atlas_validation.mbt b/selene-core/src/runtime_debug/atlas_validation.mbt index ac971fbe..49b7630d 100644 --- a/selene-core/src/runtime_debug/atlas_validation.mbt +++ b/selene-core/src/runtime_debug/atlas_validation.mbt @@ -48,22 +48,22 @@ fn rect_overlap(lhs : @math.Rect, rhs : @math.Rect) -> Bool { ///| fn validate_atlas_transparency( - image_path : String?, + image : @asset.ImageHandle?, rects : Array[@math.Rect], issues : Array[AtlasValidationIssue], ) -> Unit { - guard image_path is Some(path) else { + guard image is Some(handle) else { issues.push({ kind: TransparencyCheckUnavailable, rect_index: None, other_rect_index: None, - message: "Transparency checks require an atlas image path", + message: "Transparency checks require an atlas image", }) return } let mut backend_supported = false for index, rect in rects { - match @platform_render.image_region_is_fully_transparent(path, rect) { + match @platform_render.image_region_is_fully_transparent(handle, rect) { Some(true) => { backend_supported = true issues.push({ @@ -97,7 +97,7 @@ pub fn validate_texture_atlas_layout( ///| pub fn validate_texture_atlas_layout_for_image( layout : @sprite.TextureAtlasLayout, - image_path : String?, + image : @asset.ImageHandle?, ) -> AtlasValidationReport { let atlas_size = @sprite.texture_atlas_layout_size(layout) let rects = @sprite.texture_atlas_layout_rects(layout) @@ -154,7 +154,7 @@ pub fn validate_texture_atlas_layout_for_image( } } } - validate_atlas_transparency(image_path, rects, issues) + validate_atlas_transparency(image, rects, issues) { total_rects: rects.length(), issues, } } @@ -163,13 +163,13 @@ pub fn validate_registered_texture_atlases( world~ : @ecs.World, ) -> Array[(@sprite.TextureAtlasLayoutHandle, AtlasValidationReport)] { let query_sprite : @ecs.Query[@ecs.Single[@sprite.Sprite]] = world.query() - let atlas_image_paths : Map[@sprite.TextureAtlasLayoutHandle, String] = Map([]) + let atlas_images : Map[@sprite.TextureAtlasLayoutHandle, @asset.ImageHandle] = Map([], + ) for _entity, Single(sprite) in query_sprite { guard sprite.texture_atlas is Some(atlas) else { continue } guard sprite.image is Some(image_handle) else { continue } - guard @asset.image_path(image_handle) is Some(path) else { continue } - if !atlas_image_paths.contains(atlas.layout) { - atlas_image_paths.set(atlas.layout, path) + if !atlas_images.contains(atlas.layout) { + atlas_images.set(atlas.layout, image_handle) } } let reports : Array[(@sprite.TextureAtlasLayoutHandle, AtlasValidationReport)] = [] @@ -179,7 +179,7 @@ pub fn validate_registered_texture_atlases( handle, validate_texture_atlas_layout_for_image( layout, - atlas_image_paths.get(handle), + atlas_images.get(handle), ), ), ) diff --git a/selene-core/src/runtime_debug/pkg.generated.mbti b/selene-core/src/runtime_debug/pkg.generated.mbti index 3edb5298..8988e9ab 100644 --- a/selene-core/src/runtime_debug/pkg.generated.mbti +++ b/selene-core/src/runtime_debug/pkg.generated.mbti @@ -2,6 +2,7 @@ package "Milky2018/selene/runtime_debug" import { + "Milky2018/selene/asset_types", "Milky2018/selene/collision", "Milky2018/selene/ecs", "Milky2018/selene/inputs", @@ -49,7 +50,7 @@ pub fn deterministic_ordering_enabled() -> Bool pub fn export_sprite_inspector_regions(Array[SpriteInspectorEntry], String, file_naming? : (SpriteInspectorEntry, Int32) -> String) -> Int32 -pub fn export_texture_region_png(String, @math.Rect, String) -> Bool +pub fn export_texture_region_png(@asset_types.Handle[@asset_types.Image], @math.Rect, String) -> Bool pub fn fixed_delta_override() -> Double? @@ -101,7 +102,7 @@ pub fn validate_registered_texture_atlases(world~ : @ecs.World) -> Array[(@sprit pub fn validate_texture_atlas_layout(@sprite.TextureAtlasLayout) -> AtlasValidationReport -pub fn validate_texture_atlas_layout_for_image(@sprite.TextureAtlasLayout, String?) -> AtlasValidationReport +pub fn validate_texture_atlas_layout_for_image(@sprite.TextureAtlasLayout, @asset_types.Handle[@asset_types.Image]?) -> AtlasValidationReport pub fn world_snapshot(world~ : @ecs.World) -> WorldSnapshot @@ -112,7 +113,8 @@ pub fn world_snapshot(world~ : @ecs.World) -> WorldSnapshot pub(all) struct AtlasOverlayEntry { entity_id : UInt32? layer : String - texture_path : String + image : @asset_types.Handle[@asset_types.Image] + texture_path : String? source_rect : DebugRect destination_rect : DebugRect? } @@ -198,6 +200,7 @@ pub(all) struct DrawSubmission2DInfo { layer : String kind : String depth : Double? + image : @asset_types.Handle[@asset_types.Image]? texture_path : String? uv_rect : @math.Rect? destination_rect : @math.Rect? @@ -211,6 +214,7 @@ pub(all) struct DrawSubmission2DMetadataEntry { layer : String kind : String depth : Double? + image : @asset_types.Handle[@asset_types.Image]? texture_path : String? source_rect : DebugRect? destination_rect : DebugRect? @@ -319,7 +323,9 @@ pub(all) struct SpriteInspectorEntry { entity_id : UInt32 entity_name : String? visible : Bool + image : @asset_types.Handle[@asset_types.Image]? image_path : String? + image_byte_length : Int32? source_rect : DebugRect? destination_size : DebugVec2? anchor : DebugVec2 diff --git a/selene-core/src/runtime_debug/region_export.mbt b/selene-core/src/runtime_debug/region_export.mbt index 12b24557..4b786ff9 100644 --- a/selene-core/src/runtime_debug/region_export.mbt +++ b/selene-core/src/runtime_debug/region_export.mbt @@ -26,11 +26,11 @@ fn join_output_path(output_dir : String, file_name : String) -> String { ///| pub fn export_texture_region_png( - image_path : String, + image : @asset.ImageHandle, rect : @math.Rect, out_path : String, ) -> Bool { - @platform_render.export_texture_region_png(image_path, rect, out_path) + @platform_render.export_texture_region_png(image, rect, out_path) } ///| @@ -41,11 +41,11 @@ pub fn export_sprite_inspector_regions( ) -> Int32 { let mut exported = 0 for index, entry in entries { - guard entry.image_path is Some(image_path) else { continue } + guard entry.image is Some(image) else { continue } guard entry.source_rect is Some(source_rect) else { continue } let out_path = join_output_path(output_dir, file_naming(entry, index)) if export_texture_region_png( - image_path, + image, debug_rect_to_math_rect(source_rect), out_path, ) { diff --git a/selene-core/src/runtime_debug/render_capture.mbt b/selene-core/src/runtime_debug/render_capture.mbt index 36ee9dfe..1d347637 100644 --- a/selene-core/src/runtime_debug/render_capture.mbt +++ b/selene-core/src/runtime_debug/render_capture.mbt @@ -4,6 +4,7 @@ pub(all) struct DrawSubmission2DInfo { layer : String kind : String depth : Double? + image : @asset.ImageHandle? texture_path : String? uv_rect : @math.Rect? destination_rect : @math.Rect? @@ -36,6 +37,7 @@ pub(all) struct DrawSubmission2DMetadataEntry { layer : String kind : String depth : Double? + image : @asset.ImageHandle? texture_path : String? source_rect : DebugRect? destination_rect : DebugRect? @@ -130,6 +132,7 @@ fn draw2d_info( layer, kind: "Image", depth, + image: Some(image.image), texture_path: @asset.image_path(image.image), uv_rect, destination_rect: Some(image.destination), @@ -147,6 +150,7 @@ fn draw2d_info( layer, kind: "Text", depth, + image: None, texture_path: None, uv_rect: None, destination_rect: Some(destination), @@ -160,6 +164,7 @@ fn draw2d_info( layer, kind: "Rect", depth, + image: None, texture_path: None, uv_rect: None, destination_rect: Some(rect.rect), @@ -176,6 +181,7 @@ fn draw2d_info( layer, kind: "Circle", depth, + image: None, texture_path: None, uv_rect: None, destination_rect: Some(destination), @@ -189,6 +195,7 @@ fn draw2d_info( layer, kind: "GradientRect", depth, + image: None, texture_path: None, uv_rect: None, destination_rect: Some(gradient.rect), @@ -201,6 +208,7 @@ fn draw2d_info( layer, kind: "PushClip", depth, + image: None, texture_path: None, uv_rect: None, destination_rect: Some(clip.rect), @@ -213,6 +221,7 @@ fn draw2d_info( layer, kind: "PopClip", depth, + image: None, texture_path: None, uv_rect: None, destination_rect: None, @@ -278,6 +287,7 @@ fn draw2d_metadata_entry( layer: item.layer, kind: item.kind, depth: item.depth, + image: item.image, texture_path: item.texture_path, source_rect: item.uv_rect.map(debug_rect), destination_rect: item.destination_rect.map(debug_rect), diff --git a/selene-core/src/runtime_debug/runtime_debug_wbtest.mbt b/selene-core/src/runtime_debug/runtime_debug_wbtest.mbt index 00249b8a..9a103634 100644 --- a/selene-core/src/runtime_debug/runtime_debug_wbtest.mbt +++ b/selene-core/src/runtime_debug/runtime_debug_wbtest.mbt @@ -205,7 +205,8 @@ test "atlas overlay decoration appends highlight rects when enabled" { ///| test "frame metadata export includes draw commands and atlas overlay entries" { with_runtime_debug_world(fn(world) raise { - let image = @asset.load_image("assets/debug/metadata.png") + let image = @asset.images.add(@asset.Image::from_bytes(b"debug image")) + defer ignore(@asset.images.remove(image)) let draw_image : @render2d_types.ImageDrawCommand2D = { image, destination: { position: Vec2(0.0, 0.0), size: Vec2(16.0, 16.0), }, @@ -237,6 +238,9 @@ test "frame metadata export includes draw commands and atlas overlay entries" { let metadata = capture_last_frame_metadata(world~).unwrap() inspect(metadata.draw2d.length(), content="1") inspect(metadata.atlas_overlay.length(), content="1") + assert_eq(metadata.draw2d[0].image, Some(image)) + assert_eq(metadata.draw2d[0].texture_path, None) + assert_eq(metadata.atlas_overlay[0].image, image) let json_text = capture_last_frame_metadata_json(world~).unwrap() inspect(json_text.contains("\"frame_index\""), content="true") inspect(json_text.contains("\"atlas_overlay\""), content="true") @@ -258,7 +262,9 @@ test "export sprite inspector regions only processes entries with image and sour entity_id: 1U, entity_name: Some("No Image"), visible: true, + image: None, image_path: None, + image_byte_length: None, source_rect: Some({ x: 0.0, y: 0.0, width: 8.0, height: 8.0, }), destination_size: None, anchor: { x: 0.0, y: 0.0, }, @@ -271,7 +277,9 @@ test "export sprite inspector regions only processes entries with image and sour entity_id: 2U, entity_name: Some("No Rect"), visible: true, + image: Some(@asset.images.add(@asset.Image::from_bytes(b"debug image"))), image_path: Some("assets/debug/export.png"), + image_byte_length: Some(11), source_rect: None, destination_size: None, anchor: { x: 0.0, y: 0.0, }, @@ -284,7 +292,9 @@ test "export sprite inspector regions only processes entries with image and sour entity_id: 3U, entity_name: Some("Valid"), visible: true, + image: Some(@asset.images.add(@asset.Image::from_bytes(b"debug image"))), image_path: Some("assets/debug/export.png"), + image_byte_length: Some(11), source_rect: Some({ x: 1.0, y: 2.0, width: 4.0, height: 5.0, }), destination_size: None, anchor: { x: 0.0, y: 0.0, }, @@ -311,7 +321,7 @@ test "export texture region png returns false for missing image path" { with_runtime_debug_world(fn(_world) raise { inspect( export_texture_region_png( - "/tmp/selene_runtime_debug_missing.png", + @asset.load_image("/tmp/selene_runtime_debug_missing.png"), { position: Vec2(0.0, 0.0), size: Vec2(1.0, 1.0), }, "/tmp/selene_runtime_debug_missing_out.png", ), diff --git a/selene-core/src/runtime_debug/snapshot_inspector_overlay.mbt b/selene-core/src/runtime_debug/snapshot_inspector_overlay.mbt index 2c94fd30..11cb9ec8 100644 --- a/selene-core/src/runtime_debug/snapshot_inspector_overlay.mbt +++ b/selene-core/src/runtime_debug/snapshot_inspector_overlay.mbt @@ -94,7 +94,9 @@ pub(all) struct SpriteInspectorEntry { entity_id : UInt32 entity_name : String? visible : Bool + image : @asset.ImageHandle? image_path : String? + image_byte_length : Int32? source_rect : DebugRect? destination_size : DebugVec2? anchor : DebugVec2 @@ -115,7 +117,8 @@ pub extend SpriteInspectorEntry with ToJson::{to_json} pub(all) struct AtlasOverlayEntry { entity_id : UInt32? layer : String - texture_path : String + image : @asset.ImageHandle + texture_path : String? source_rect : DebugRect destination_rect : DebugRect? } @@ -274,7 +277,11 @@ pub fn sprite_inspector_entries( entity_id: entity.id(), entity_name: @name.name_of(world~, entity), visible: @visibility.is_visible(entity), + image: sprite.image, image_path, + image_byte_length: sprite.image.bind(handle => { + handle.get().map(image => image.bytes.length()) + }), source_rect, destination_size, anchor, @@ -301,12 +308,13 @@ pub fn atlas_overlay_entries() -> Array[AtlasOverlayEntry] { let entries : Array[AtlasOverlayEntry] = [] guard latest_render_submission() is Some(submission) else { return entries } for item in submission.draw2d { - guard item.texture_path is Some(texture_path) else { continue } + guard item.image is Some(image) else { continue } guard item.uv_rect is Some(source_rect) else { continue } entries.push({ entity_id: item.entity_id, layer: item.layer, - texture_path, + image, + texture_path: item.texture_path, source_rect: debug_rect(source_rect), destination_rect: item.destination_rect.map(debug_rect), }) diff --git a/selene-core/src/scene3d/gltf_parse_entry.mbt b/selene-core/src/scene3d/gltf_parse_entry.mbt index cafaf24f..2c3afb4d 100644 --- a/selene-core/src/scene3d/gltf_parse_entry.mbt +++ b/selene-core/src/scene3d/gltf_parse_entry.mbt @@ -278,23 +278,27 @@ fn parse_image_handles( continue } let resolved = resolve_relative_asset_path(scene_path, uri) - handles.push(Some(@render3d.register_image_asset({ path: resolved, }))) + if uri.to_lower().has_prefix("data:") { + handles.push( + decode_data_uri_base64(uri).map(bytes => { + @asset.images.add(@asset.Image::from_bytes(bytes)) + }), + ) + } else { + handles.push(Some(@asset.load_image(resolved))) + } continue } guard field_int(image_object, "bufferView") is Some(buffer_view_index) else { handles.push(None) continue } - let mime_type = field_string(image_object, "mimeType").unwrap_or( - "image/png", - ) guard resolve_buffer_view_bytes(buffer_view_index, buffers, buffer_views) is Some(image_bytes) else { handles.push(None) continue } - let data_uri = "data:\{mime_type};base64,\{@base64.encode(image_bytes[:])}" - handles.push(Some(@render3d.register_image_asset({ path: data_uri, }))) + handles.push(Some(@asset.images.add(@asset.Image::from_bytes(image_bytes)))) } handles } diff --git a/selene-core/src/scene3d/scene3d_wbtest.mbt b/selene-core/src/scene3d/scene3d_wbtest.mbt index 426b6f66..5575982c 100644 --- a/selene-core/src/scene3d/scene3d_wbtest.mbt +++ b/selene-core/src/scene3d/scene3d_wbtest.mbt @@ -78,11 +78,11 @@ fn scene3d_test_texture_sources() -> ( ) { let sampler = @render3d.TextureSampler3D() let handles = [ - @render3d.register_image_asset({ path: "wbtest://image0", }), - @render3d.register_image_asset({ path: "wbtest://image1", }), - @render3d.register_image_asset({ path: "wbtest://image2", }), - @render3d.register_image_asset({ path: "wbtest://image3", }), - @render3d.register_image_asset({ path: "wbtest://image4", }), + @asset.images.add(@asset.Image::from_bytes(b"wbtest://image0")), + @asset.images.add(@asset.Image::from_bytes(b"wbtest://image1")), + @asset.images.add(@asset.Image::from_bytes(b"wbtest://image2")), + @asset.images.add(@asset.Image::from_bytes(b"wbtest://image3")), + @asset.images.add(@asset.Image::from_bytes(b"wbtest://image4")), ] ( [ @@ -627,3 +627,29 @@ test "canceled scene subtrees release their cloned meshes" { scene_templates.remove(scene) } } + +///| +test "glTF data URIs and buffer-view images register their original bytes" { + @asset.set_io(fn(_) { abort("embedded glTF images must not read files") }) + defer @asset.set_io(fn(_) { None }) + let document : Json = { + "images": [ + { "uri": "data:image/png;base64,aW1hZ2U=" }, + { "bufferView": 0, "mimeType": "image/png" }, + ], + } + let handles = parse_image_handles( + "scene.gltf", + json_object(document).unwrap(), + [Some(b"image")], + [Some(sparse_test_buffer_view(0, 5))], + ) + assert_eq(handles.length(), 2) + let first = handles[0].unwrap() + let second = handles[1].unwrap() + defer ignore(@asset.images.remove(first)) + defer ignore(@asset.images.remove(second)) + assert_eq(first.get().unwrap().bytes, b"image") + assert_eq(second.get().unwrap().bytes, b"image") + assert_true(first != second) +} diff --git a/selene-core/src/sprite/pkg.generated.mbti b/selene-core/src/sprite/pkg.generated.mbti index b78d3d08..f29c61de 100644 --- a/selene-core/src/sprite/pkg.generated.mbti +++ b/selene-core/src/sprite/pkg.generated.mbti @@ -52,7 +52,7 @@ pub fn Anchor::to_repr(Self) -> @debug.Repr pub impl @ecs.Component for Anchor pub(all) struct Sprite { - image : @asset_types.ImageHandle? + image : @asset_types.Handle[@asset_types.Image]? mut texture_atlas : TextureAtlas? mut rect : @math.Rect? mut color : @render.Color @@ -63,10 +63,10 @@ pub(all) struct Sprite { mut image_mode : SpriteImageMode mut blend_mode : @render.BlendMode2D } -pub fn Sprite::Sprite(image? : @asset_types.ImageHandle?, texture_atlas? : TextureAtlas?, rect? : @math.Rect?, color? : @render.Color, custom_size? : @math.Vec2?, anchor? : Anchor, flip_x? : Bool, flip_y? : Bool, image_mode? : SpriteImageMode, blend_mode? : @render.BlendMode2D) -> Self -pub fn Sprite::from_atlas_image(@asset_types.ImageHandle, TextureAtlas) -> Self +pub fn Sprite::Sprite(image? : @asset_types.Handle[@asset_types.Image]?, texture_atlas? : TextureAtlas?, rect? : @math.Rect?, color? : @render.Color, custom_size? : @math.Vec2?, anchor? : Anchor, flip_x? : Bool, flip_y? : Bool, image_mode? : SpriteImageMode, blend_mode? : @render.BlendMode2D) -> Self +pub fn Sprite::from_atlas_image(@asset_types.Handle[@asset_types.Image], TextureAtlas) -> Self pub fn Sprite::from_color(@render.Color, @math.Vec2) -> Self -pub fn Sprite::from_image(@asset_types.ImageHandle, custom_size? : @math.Vec2?) -> Self +pub fn Sprite::from_image(@asset_types.Handle[@asset_types.Image], custom_size? : @math.Vec2?) -> Self pub impl @ecs.Component for Sprite pub(all) enum SpriteImageMode { diff --git a/selene-core/src/text2d/layout.mbt b/selene-core/src/text2d/layout.mbt index e4153c19..682e57e3 100644 --- a/selene-core/src/text2d/layout.mbt +++ b/selene-core/src/text2d/layout.mbt @@ -196,7 +196,7 @@ fn text_layout_cache_key( font: style.font, family: style.family, size: style.size, - font_metrics_revision: @platform_render.font_metrics_revision(style.family), + font_metrics_revision: @platform_render.font_metrics_revision(style), line_height: layout.line_height, wrap: layout.wrap, overflow: layout.overflow, diff --git a/selene-core/src/tiled/moon.pkg b/selene-core/src/tiled/moon.pkg index d70d9f72..e9aab1e3 100644 --- a/selene-core/src/tiled/moon.pkg +++ b/selene-core/src/tiled/moon.pkg @@ -23,7 +23,6 @@ import { "moonbitlang/core/encoding/utf8" @encoding/utf8, "moonbitlang/core/math" @cmath, "moonbitlang/core/string", - "moonbitlang/x/fs", } formatter(ignore: [ "ecs.g.mbt", "physics.g.mbt", "world.g.mbt" ]) diff --git a/selene-core/src/tiled/tiled_wbtest.mbt b/selene-core/src/tiled/tiled_wbtest.mbt index b150ffd4..3a5d6ea8 100644 --- a/selene-core/src/tiled/tiled_wbtest.mbt +++ b/selene-core/src/tiled/tiled_wbtest.mbt @@ -13,9 +13,9 @@ fn with_fake_asset_io( files : Map[String, Bytes], body : () -> Unit raise, ) -> Unit raise { - @asset.set_io(fn(path) { files.get(path) }) + @asset.set_io(fn(path) { files.get(path) }, paths=files.keys().collect()) + defer @asset.set_io(fn(_path) { None }) body() - @asset.set_io(fn(_path) { None }) } ///| @@ -1635,3 +1635,42 @@ test "tiled diagonal flip swaps the tile axes before later flips" { content="0,32|16,0", ) } + +///| +test "world patterns discover sorted direct children from the asset catalogue" { + @asset.set_io(fn(_) { None }, paths=[ + "maps/a2b3.tmj", "maps/nested/a9b9.tmj", "other/a8b8.tmj", "maps/a1b1.tmj", "maps/a2b3.tmj", + "maps/readme.txt", + ]) + defer @asset.set_io(fn(_) { None }) + let source_world : TiledWorld = { + ..TiledWorld(), + source_path: Some("maps/demo.world"), + maps: [{ file_name: "a1b1.tmj", x: 7, y: 9, width: None, height: None, }], + patterns: [ + { + regexp: "a(\\d+)b(\\d+)\\.tmj", + multiplier_x: 16, + multiplier_y: 32, + offset_x: 0, + offset_y: 0, + map_width: 16, + map_height: 32, + }, + ], + } + let maps = tiled_world_collect_maps(source_world) + assert_eq(maps.length(), 2) + assert_eq(maps[0].file_name, "a1b1.tmj") + assert_eq(maps[0].x, 7) + assert_eq(maps[1].file_name, "a2b3.tmj") + assert_eq(maps[1].x, 32) + assert_eq(maps[1].y, 96) + assert_eq( + tiled_world_asset_file_names({ + ..TiledWorld(), + source_path: Some("local.world"), + }).length(), + 0, + ) +} diff --git a/selene-core/src/tiled/world.mbt b/selene-core/src/tiled/world.mbt index 4d8d7841..28a88194 100644 --- a/selene-core/src/tiled/world.mbt +++ b/selene-core/src/tiled/world.mbt @@ -464,7 +464,7 @@ fn tiled_world_expand_patterns( if source_world.patterns.length() == 0 { return [] } - let file_names = tiled_world_scan_directory_files(source_world) + let file_names = tiled_world_asset_file_names(source_world) if file_names.length() == 0 { return [] } @@ -502,15 +502,26 @@ fn tiled_world_expand_pattern( } ///| -fn tiled_world_scan_directory_files(source_world : TiledWorld) -> Array[String] { +fn tiled_world_asset_file_names(source_world : TiledWorld) -> Array[String] { guard source_world.source_path is Some(source_path) else { return [] } - let directory = tiled_world_directory_path(source_path) - let entries = @fs.read_dir(directory) catch { _ => return [] } + let directory = tiled_world_directory_path( + source_path.replace_all(old="\\", new="/"), + ) let file_names : Array[String] = [] - for entry in entries { - let resolved = source_world.resolve_map_path(entry) - if (@fs.is_file(resolved) catch { _ => false }) { - file_names.push(entry) + let seen : @set.Set[String] = Set([]) + for path in @asset.paths() { + let normalized = path.replace_all(old="\\", new="/") + if tiled_world_directory_path(normalized) != directory { + continue + } + let name = match normalized.rev_find("/") { + Some(index) => + normalized.unsafe_substring(start=index + 1, end=normalized.length()) + None => normalized + } + if !seen.contains(name) { + seen.add(name) + file_names.push(name) } } file_names.sort() diff --git a/selene-core/src/ui/layout_runtime.mbt b/selene-core/src/ui/layout_runtime.mbt index 3556ed00..64e34441 100644 --- a/selene-core/src/ui/layout_runtime.mbt +++ b/selene-core/src/ui/layout_runtime.mbt @@ -221,7 +221,7 @@ fn ui_measure_snapshot( font_handle, font_state: font_handle.map(@asset.font_load_state), font_metrics_revision: style - .map(fn(value) { @platform_render.font_metrics_revision(value.family) }) + .map(fn(value) { @platform_render.font_metrics_revision(value) }) .unwrap_or(0U), font_family: style.map(fn(value) { value.family }), font_size: style.map(fn(value) { value.size }), diff --git a/selene-core/src/ui/pkg.generated.mbti b/selene-core/src/ui/pkg.generated.mbti index e1f44b77..711332ff 100644 --- a/selene-core/src/ui/pkg.generated.mbti +++ b/selene-core/src/ui/pkg.generated.mbti @@ -626,11 +626,11 @@ pub impl @ecs.Component for TextColor pub(all) struct TextFont { mut family : String mut size : Double - mut font_handle : @asset_types.FontHandle? + mut font_handle : @asset_types.Handle[@asset_types.Font]? } pub fn TextFont::TextFont(family? : String, size? : Double) -> Self pub fn TextFont::from_css(String) -> Self -pub fn TextFont::from_font(@asset_types.FontHandle, size? : Double) -> Self +pub fn TextFont::from_font(@asset_types.Handle[@asset_types.Font], size? : Double) -> Self pub impl @ecs.Component for TextFont pub(all) struct TextLayout { @@ -687,13 +687,13 @@ pub fn UiGradient::to_repr(Self) -> @debug.Repr #derive(Eq, @debug.Debug) pub(all) struct UiImage { size : @math.Vec2 - image : @asset_types.ImageHandle + image : @asset_types.Handle[@asset_types.Image] tint : @render.Color fit : ImageFit } pub fn UiImage::UiImage(@math.Vec2, String, tint? : @render.Color, fit? : ImageFit) -> Self pub fn UiImage::equal(Self, Self) -> Bool -pub fn UiImage::from_image(@math.Vec2, @asset_types.ImageHandle, tint? : @render.Color, fit? : ImageFit) -> Self +pub fn UiImage::from_image(@math.Vec2, @asset_types.Handle[@asset_types.Image], tint? : @render.Color, fit? : ImageFit) -> Self pub fn UiImage::not_equal(Self, Self) -> Bool pub fn UiImage::to_repr(Self) -> @debug.Repr pub impl @ecs.Component for UiImage @@ -721,7 +721,7 @@ pub(all) struct UiMaterialAsset { } pub fn UiMaterialAsset::UiMaterialAsset(@math.Vec2, String, tint? : @render.Color, fit? : ImageFit) -> Self pub fn UiMaterialAsset::from_draw((UiMaterialContext) -> Unit) -> Self -pub fn UiMaterialAsset::from_image(@math.Vec2, @asset_types.ImageHandle, tint? : @render.Color, fit? : ImageFit) -> Self +pub fn UiMaterialAsset::from_image(@math.Vec2, @asset_types.Handle[@asset_types.Image], tint? : @render.Color, fit? : ImageFit) -> Self pub fn UiMaterialAsset::from_ui_image(UiImage) -> Self pub fn UiMaterialAsset::gradient(@render.Color, @render.Color) -> Self pub fn UiMaterialAsset::solid(@render.Color) -> Self diff --git a/selene-webgpu/README.md b/selene-webgpu/README.md index 8d5b244d..2f78501b 100644 --- a/selene-webgpu/README.md +++ b/selene-webgpu/README.md @@ -32,3 +32,48 @@ python3 -m http.server 8000 ``` Open `http://localhost:8000`. + +## Embedded Assets + +Embed resource files with `moonbit-community/embed@0.1.3` in a `dev_build` +rule. The example games demonstrate the generated structured resource fields. +Construct a resource value and register it once: + +```moonbit +let image = @asset.images.add( + @asset.Image::from_bytes(@embedded_assets.assets.cards.a_c_png), +) +let sprite = @sprite.Sprite(image=Some(image)) +``` + +`Assets[T]` stores values and returns `Handle[T]`. `asset.images`, `asset.audios`, +and `asset.fonts` are the default collections; applications may also create +independent `Assets[T]` collections. Images, audio, and fonts are encoded resource +values constructed with `Image::from_bytes`, `Audio::from_bytes`, and +`Font::from_bytes`. Construction and registration do +not perform file IO, decode media, or require an active World or browser device. +Reuse the returned handles across sprites, UI nodes, 3D material textures, and +playback requests. 2D and 3D image handles refer to the same resource type. + +Backends prepare resources when they are used. `image_preparation_state`, +`audio_preparation_state`, and `font_preparation_state` distinguish unprepared, +preparing, ready, and failed resources. File-loader `LoadState::Loaded` means the +encoded data was read; it does not imply successful decoding or GPU readiness. + +Use `collection.get(handle)` to read a resource, `insert(handle, value)` to +replace it while retaining its identity, and `remove(handle)` to invalidate it. +Collection operations reject foreign and removed handles. Backend caches are +invalidated on replacement and removal. Existing audio instances retain their +Blob source until they finish or are stopped. + +The example games require no path catalogue. Their generated `assets.g.mbt` +files are ignored by Git. `moon build` and `moon test` regenerate them using the +input files declared in each asset package's `moon.pkg`. + +## Path-Based Resources + +The existing file loaders remain available. Register a reader with +`@asset.set_io(read_asset, paths=asset_paths)` when assets are supplied by a +custom source. The path catalogue is optional and used for Tiled `.world` +patterns; relative references in maps use the reader. These path loaders populate +the same resource collections as direct registration. diff --git a/selene-webgpu/src/audio.mbt b/selene-webgpu/src/audio.mbt index 9de2715d..b2f23209 100644 --- a/selene-webgpu/src/audio.mbt +++ b/selene-webgpu/src/audio.mbt @@ -21,15 +21,10 @@ const AUDIO_PLAY_STATE_BLOCKED = 2 ///| const AUDIO_PLAY_STATE_FAILED = 3 -///| -priv struct CachedAudioSource { - src : String - blob_owned : Bool -} - ///| priv struct AudioPlayback { audio : Audio + source_url : String mut requested_paused : Bool mut last_play_attempt_activation_epoch : Int32 } @@ -44,13 +39,13 @@ let next_audio_instance : Ref[Int32] = Ref(1) let audio_user_activation_epoch : Ref[Int32] = Ref(0) ///| -let cached_audio_sources : Map[String, CachedAudioSource] = Map([]) +let cached_audio_sources : Map[@asset_types.AudioHandle, String] = Map([]) ///| let retired_blob_audio_sources : Array[String] = [] ///| -let preloaded_audio_templates : Map[String, Audio] = Map([]) +let preloaded_audio_templates : Map[@asset_types.AudioHandle, Audio] = Map([]) ///| fn clamp_playback_speed(speed : Double) -> Double { @@ -71,37 +66,6 @@ fn current_audio_activation_epoch() -> Int32 { audio_user_activation_epoch.val } -///| -fn audio_prefers_byte_backed_source(path : String) -> Bool { - if path.has_prefix("http://") || path.has_prefix("https://") { - return false - } - if path.has_prefix("data:") || path.has_prefix("blob:") { - return false - } - path.has_prefix("assets/") -} - -///| -fn browser_audio_mime_type(path : String) -> String { - if path.has_suffix(".ogg") || path.has_suffix(".oga") { - return "audio/ogg" - } - if path.has_suffix(".mp3") { - return "audio/mpeg" - } - if path.has_suffix(".wav") { - return "audio/wav" - } - if path.has_suffix(".flac") { - return "audio/flac" - } - if path.has_suffix(".aac") { - return "audio/aac" - } - "application/octet-stream" -} - ///| fn should_retry_blocked_audio_playback( play_state : Int32, @@ -115,80 +79,44 @@ fn should_retry_blocked_audio_playback( } ///| -fn retire_cached_audio_source(entry : CachedAudioSource) -> Unit { - if entry.blob_owned { - retired_blob_audio_sources.push(entry.src) - } -} - -///| -fn clear_cached_audio_source(path : String, retire~ : Bool = true) -> Unit { - if cached_audio_sources.get(path) is Some(entry) { - if retire { - retire_cached_audio_source(entry) - } else if entry.blob_owned { - revoke_object_url(entry.src) - } - cached_audio_sources.remove(path) +fn clear_cached_audio_source(source : @asset_types.AudioHandle) -> Unit { + if cached_audio_sources.get(source) is Some(url) { + retired_blob_audio_sources.push(url) + cached_audio_sources.remove(source) } } ///| -fn resolved_audio_source(path : String, refresh~ : Bool = false) -> String { - if !refresh { - if cached_audio_sources.get(path) is Some(entry) { - return entry.src - } - } else { - clear_cached_audio_source(path) - } - let src = if audio_prefers_byte_backed_source(path) { - match get_asset_bytes(path) { - Some(bytes) => { - let blob_url = create_audio_object_url( - bytes, - browser_audio_mime_type(path), - ) - cached_audio_sources.set(path, { src: blob_url, blob_owned: true, }) - blob_url - } - None => { - let resolved = resolve_asset_path(path) - cached_audio_sources.set(path, { src: resolved, blob_owned: false, }) - resolved - } - } - } else { - let resolved = resolve_asset_path(path) - cached_audio_sources.set(path, { src: resolved, blob_owned: false, }) - resolved +fn resolved_audio_source(source : @asset_types.AudioHandle) -> String { + if cached_audio_sources.get(source) is Some(url) { + return url } + guard source.get() is Some(asset) else { abort("Audio asset is unavailable") } + let src = create_object_url(asset.bytes, "application/octet-stream") + cached_audio_sources[source] = src + source.on_invalidate(fn() { + clear_preloaded_audio_template(source) + clear_cached_audio_source(source) + }) src } ///| -fn clear_preloaded_audio_template(path : String) -> Unit { - if preloaded_audio_templates.get(path) is Some(audio) { +fn clear_preloaded_audio_template(source : @asset_types.AudioHandle) -> Unit { + if preloaded_audio_templates.get(source) is Some(audio) { audio.pause() - preloaded_audio_templates.remove(path) + preloaded_audio_templates.remove(source) } } ///| -fn ensure_preloaded_audio_template( - path : String, - refresh~ : Bool = false, -) -> Audio { - if !refresh { - if preloaded_audio_templates.get(path) is Some(audio) { - return audio - } - } else { - clear_preloaded_audio_template(path) +fn ensure_preloaded_audio_template(source : @asset_types.AudioHandle) -> Audio { + if preloaded_audio_templates.get(source) is Some(audio) { + return audio } - let audio = Audio(resolved_audio_source(path, refresh~)) + let audio = Audio(resolved_audio_source(source)) audio.load() - preloaded_audio_templates.set(path, audio) + preloaded_audio_templates.set(source, audio) audio } @@ -200,14 +128,22 @@ fn request_audio_playback(playback : AudioPlayback) -> Unit { } ///| -fn create_audio_instance(path : String) -> (AudioInstance, AudioPlayback) { +fn create_audio_instance( + source : @asset_types.AudioHandle, +) -> (AudioInstance, AudioPlayback) { let id = next_audio_instance.val next_audio_instance.val += 1 - let template = ensure_preloaded_audio_template(path) + let template = ensure_preloaded_audio_template(source) let audio = template.clone_audio() ( id, - { audio, requested_paused: false, last_play_attempt_activation_epoch: -1, }, + { + audio, + source_url: ( + @js.Value::cast_from(template).get_with_string("src") : String), + requested_paused: false, + last_play_attempt_activation_epoch: -1, + }, ) } @@ -223,10 +159,8 @@ fn reset_audio_runtime() -> Unit { template.set_current_time(0.0) } preloaded_audio_templates.clear() - for entry in cached_audio_sources.values() { - if entry.blob_owned { - revoke_object_url(entry.src) - } + for url in cached_audio_sources.values() { + revoke_object_url(url) } cached_audio_sources.clear() for src in retired_blob_audio_sources { @@ -237,13 +171,13 @@ fn reset_audio_runtime() -> Unit { ///| pub fn play_audio( - audio_path~ : String, + source~ : @asset_types.AudioHandle, volume~ : Double, speed~ : Double, loop_~ : Bool, paused~ : Bool, ) -> AudioInstance { - let (instance, playback) = create_audio_instance(audio_path) + let (instance, playback) = create_audio_instance(source) playback.audio.set_volume(volume) playback.audio.set_loop(loop_) playback.audio.set_playback_rate(clamp_playback_speed(speed)) @@ -301,6 +235,7 @@ pub fn stop(instance~ : AudioInstance) -> Unit { playback.audio.set_current_time(0.0) } audio_instances.remove(instance) + collect_retired_audio_sources() } ///| @@ -315,6 +250,7 @@ pub fn is_finished(instance~ : AudioInstance) -> Bool { ///| pub fn tick_audio() -> Unit { + defer collect_retired_audio_sources() let activation_epoch = current_audio_activation_epoch() audio_instances.retain((_instance, playback) => { let play_state = audio_play_state(playback.audio) @@ -334,6 +270,38 @@ pub fn tick_audio() -> Unit { } ///| -pub fn preload_audio(audio_path : String) -> Unit { - ignore(ensure_preloaded_audio_template(audio_path, refresh=true)) +pub fn preload_audio(source : @asset_types.AudioHandle) -> Unit { + ignore(ensure_preloaded_audio_template(source)) +} + +///| +pub fn audio_preparation_state( + handle : @asset_types.AudioHandle, +) -> @asset_types.PreparationState { + guard preloaded_audio_templates.get(handle) is Some(audio) else { + return Unprepared + } + let value = @js.Value::cast_from(audio) + let error : @js.Value = value.get_with_string("error") + if is_js_object(error) { + return Failed(error.get_with_string("message")) + } + let state : Int32 = value.get_with_string("readyState") + if state >= 2 { + Ready + } else { + Preparing + } +} + +///| +fn collect_retired_audio_sources() -> Unit { + retired_blob_audio_sources.retain(url => { + if audio_instances.values().any(playback => playback.source_url == url) { + true + } else { + revoke_object_url(url) + false + } + }) } diff --git a/selene-webgpu/src/audio_wbtest.mbt b/selene-webgpu/src/audio_wbtest.mbt index 51ec30af..d27c19ec 100644 --- a/selene-webgpu/src/audio_wbtest.mbt +++ b/selene-webgpu/src/audio_wbtest.mbt @@ -1,42 +1,3 @@ -///| -test "web audio uses byte-backed sources only for local asset paths" { - inspect( - audio_prefers_byte_backed_source("assets/music/bgm.ogg"), - content="true", - ) - inspect( - audio_prefers_byte_backed_source("https://cdn.test/bgm.ogg"), - content="false", - ) - inspect( - audio_prefers_byte_backed_source("data:audio/ogg;base64,AAAA"), - content="false", - ) - inspect( - audio_prefers_byte_backed_source("blob:https://test/123"), - content="false", - ) - inspect(audio_prefers_byte_backed_source("sounds/bgm.ogg"), content="false") -} - -///| -test "web audio infers browser mime types for common formats" { - inspect(browser_audio_mime_type("assets/music/loop.ogg"), content="audio/ogg") - inspect( - browser_audio_mime_type("assets/music/loop.mp3"), - content="audio/mpeg", - ) - inspect(browser_audio_mime_type("assets/music/loop.wav"), content="audio/wav") - inspect( - browser_audio_mime_type("assets/music/loop.flac"), - content="audio/flac", - ) - inspect( - browser_audio_mime_type("assets/music/loop.bin"), - content="application/octet-stream", - ) -} - ///| test "web audio retries blocked playback only after a new activation epoch" { inspect( diff --git a/selene-webgpu/src/canvas.mbt b/selene-webgpu/src/canvas.mbt index 01dd3073..8675c9d8 100644 --- a/selene-webgpu/src/canvas.mbt +++ b/selene-webgpu/src/canvas.mbt @@ -425,6 +425,7 @@ extern "js" fn webgpu_initialize_ffi( #| img.src = path; #| await img.decode(); #| const bitmap = await createImageBitmap(img); + #| if (rec.state === 'cancelled') { bitmap.close(); return; } #| rec.width = Math.max(1, bitmap.width); #| rec.height = Math.max(1, bitmap.height); #| rec.texture = rt.createImageTexture(bitmap, rec.width, rec.height); diff --git a/selene-webgpu/src/draw.mbt b/selene-webgpu/src/draw.mbt index e077c45e..728400e5 100644 --- a/selene-webgpu/src/draw.mbt +++ b/selene-webgpu/src/draw.mbt @@ -113,12 +113,6 @@ let synced_material_assets : Map[ @render3d_types.StandardMaterial3D, ] = Map([]) -///| -let synced_image_assets : Map[ - @render3d_types.ImageHandle, - @render3d_types.ImageAsset, -] = Map([]) - ///| let synced_cubemap_assets : Map[ @render3d_types.CubemapHandle, @@ -319,8 +313,10 @@ priv struct ResolvedMaterialTextureInput3D { } ///| -pub fn preload_img(path : String) -> Unit { - webgpu_preload_img(resolve_asset_path(path)) +pub fn prepare_image(handle : @asset_types.ImageHandle) -> Unit { + if image_url(handle) is Some(url) { + webgpu_preload_img(url) + } } ///| @@ -433,11 +429,8 @@ pub fn reset_clip_stack() -> Unit { } ///| -pub fn draw_image( - command : @render2d_types.ImageDrawCommand2D, - image_path : String, -) -> Unit { - let path = resolve_asset_path(image_path) +pub fn draw_image(command : @render2d_types.ImageDrawCommand2D) -> Unit { + guard image_url(command.image) is Some(path) else { return } let dimensions = webgpu_image_dimensions(path) if dimensions.length() < 3 || dimensions[0] < 0.5 || @@ -669,14 +662,6 @@ pub fn sync_material_asset( synced_material_assets.set(handle, material) } -///| -pub fn sync_image_asset( - handle : @render3d_types.ImageHandle, - image : @render3d_types.ImageAsset, -) -> Unit { - synced_image_assets.set(handle, image) -} - ///| pub fn sync_cubemap_asset( handle : @render3d_types.CubemapHandle, @@ -695,11 +680,6 @@ pub fn release_material_asset(handle : @render3d_types.MaterialHandle) -> Unit { synced_material_assets.remove(handle) } -///| -pub fn release_image_asset(handle : @render3d_types.ImageHandle) -> Unit { - synced_image_assets.remove(handle) -} - ///| pub fn release_cubemap_asset(handle : @render3d_types.CubemapHandle) -> Unit { synced_cubemap_assets.remove(handle) @@ -824,8 +804,7 @@ fn draw_skybox_face( p2 : @smath.Vec3, p3 : @smath.Vec3, ) -> Unit { - guard synced_image_assets.get(image) is Some(image_asset) else { return } - let path = resolve_asset_path(image_asset.path) + guard image_url(image) is Some(path) else { return } let vertices : Array[Double] = [] push_skybox_vertex( vertices, camera_position, rotation, half_size, p0, 0.0, 1.0, brightness, @@ -2984,10 +2963,10 @@ fn texture_sampler_code(sampler : @render3d_types.TextureSampler3D) -> Int32 { fn resolve_texture_source( binding : @render3d_types.TextureBinding3D, ) -> MaterialTextureSource3D? { - match synced_image_assets.get(binding.image) { - Some(image_asset) => + match image_url(binding.image) { + Some(path) => Some({ - path: resolve_asset_path(image_asset.path), + path, texcoord_set: binding.texcoord_set, sampler_code: texture_sampler_code(binding.sampler), }) diff --git a/selene-webgpu/src/draw_wbtest.mbt b/selene-webgpu/src/draw_wbtest.mbt index 12beb164..4cd02beb 100644 --- a/selene-webgpu/src/draw_wbtest.mbt +++ b/selene-webgpu/src/draw_wbtest.mbt @@ -1,6 +1,9 @@ ///| -fn webgpu_test_handle(id : Int32) -> @render3d_types.ImageHandle { - ImageHandle(id.reinterpret_as_uint()) +let test_images : @asset_types.Assets[@asset_types.Image] = Assets() + +///| +fn webgpu_test_image() -> @render3d_types.ImageHandle { + test_images.reserve() } ///| @@ -18,7 +21,12 @@ fn webgpu_test_sync_image( handle : @render3d_types.ImageHandle, path : String, ) -> Unit { - synced_image_assets.set(handle, { path, }) + ignore( + test_images.insert( + handle, + @asset_types.Image::from_bytes(@utf8.encode(path)), + ), + ) } ///| @@ -379,7 +387,7 @@ test "render3d submission stats reuse retained static primitive instances" { ///| test "render3d submission stats keep textured primitives unbatched" { - let image = webgpu_test_handle(9110) + let image = webgpu_test_image() let mesh = webgpu_test_mesh_handle(9111) let material = webgpu_test_material_handle(9112) webgpu_test_sync_image(image, "wbtest://base") @@ -401,7 +409,7 @@ test "render3d submission stats keep textured primitives unbatched" { inspect(stats.textured_triangle_commands, content="2") inspect(stats.uploaded_vertex_bytes, content="10080") inspect(stats.render_bind_group_creations, content="2") - release_image_asset(image) + ignore(test_images.remove(image)) release_mesh_asset(mesh) release_material_asset(material) } @@ -782,9 +790,9 @@ test "pack_light_uniform_data owns shader light layout in MoonBit" { ///| test "resolve_material_texture_bundle keeps independent UV channels when samplers match" { let sampler = @render3d_types.TextureSampler3D() - let base_handle = webgpu_test_handle(9000) - let emissive_handle = webgpu_test_handle(9001) - let occlusion_handle = webgpu_test_handle(9002) + let base_handle = webgpu_test_image() + let emissive_handle = webgpu_test_image() + let occlusion_handle = webgpu_test_image() webgpu_test_sync_image(base_handle, "wbtest://base") webgpu_test_sync_image(emissive_handle, "wbtest://emissive") webgpu_test_sync_image(occlusion_handle, "wbtest://occlusion") @@ -818,8 +826,8 @@ test "resolve_material_texture_bundle keeps textures with independent sampler co wrap_u: ClampToEdge, wrap_v: ClampToEdge, } - let base_handle = webgpu_test_handle(9010) - let emissive_handle = webgpu_test_handle(9011) + let base_handle = webgpu_test_image() + let emissive_handle = webgpu_test_image() webgpu_test_sync_image(base_handle, "wbtest://base-repeat") webgpu_test_sync_image(emissive_handle, "wbtest://emissive-clamp") let material = { @@ -858,7 +866,7 @@ test "resolve_material_texture_input applies bound texture transforms and falls Some({ path: "wbtest://emissive", texcoord_set: 1, sampler_code: 3, }), fallback_uvs, transform_binding=Some({ - ..TextureBinding3D(webgpu_test_handle(9020), texcoord_set=1), + ..TextureBinding3D(webgpu_test_image(), texcoord_set=1), transform: { offset: webgpu_test_uv(0.25, 0.5), scale: webgpu_test_uv(2.0, 1.0), diff --git a/selene-webgpu/src/embedded_assets.mbt b/selene-webgpu/src/embedded_assets.mbt new file mode 100644 index 00000000..693f4c82 --- /dev/null +++ b/selene-webgpu/src/embedded_assets.mbt @@ -0,0 +1,7 @@ +///| +let embedded_paths : Ref[Array[String]] = Ref([]) + +///| +pub fn embedded_asset_paths() -> Array[String] { + embedded_paths.val.copy() +} diff --git a/selene-webgpu/src/embedded_assets_wbtest.mbt b/selene-webgpu/src/embedded_assets_wbtest.mbt new file mode 100644 index 00000000..4f2afad9 --- /dev/null +++ b/selene-webgpu/src/embedded_assets_wbtest.mbt @@ -0,0 +1,27 @@ +///| +test "path reader caches and catalogue snapshots are replaced together" { + let reads = Ref(0) + let catalogue = ["assets/test.png", "assets/test.ttf"] + set_embedded_assets( + fn(_) { + reads.val += 1 + Some(b"first") + }, + paths=catalogue, + ) + defer set_embedded_assets(fn(_) { None }) + catalogue.clear() + assert_eq(embedded_asset_paths().length(), 2) + embedded_asset_paths().clear() + assert_eq(embedded_asset_paths().length(), 2) + assert_eq(get_asset_bytes("assets/test.png"), Some(b"first")) + assert_eq(get_asset_bytes("assets/test.png"), Some(b"first")) + assert_eq(reads.val, 1) + set_embedded_assets(fn(_) { Some(b"second") }) + assert_eq(embedded_asset_paths().length(), 0) + assert_eq(get_asset_bytes("assets/test.png"), Some(b"second")) + assert_eq( + resolve_asset_path("https://example.test/image.png"), + "https://example.test/image.png", + ) +} diff --git a/selene-webgpu/src/font_runtime.mbt b/selene-webgpu/src/font_runtime.mbt index 41b4f020..151ba08c 100644 --- a/selene-webgpu/src/font_runtime.mbt +++ b/selene-webgpu/src/font_runtime.mbt @@ -1,5 +1,6 @@ ///| priv struct WebFontRuntime { + mut error : String? mut generation : UInt32 mut metrics_revision : UInt32 mut dom_ready_generation : UInt32? @@ -12,6 +13,7 @@ let web_font_runtimes : Map[String, WebFontRuntime] = Map([]) ///| fn web_font_runtime(family : String) -> WebFontRuntime { web_font_runtimes.get_or_init(family, () => { + error: None, generation: 0U, metrics_revision: 0U, dom_ready_generation: None, @@ -22,6 +24,7 @@ fn web_font_runtime(family : String) -> WebFontRuntime { ///| fn begin_web_font_load(family : String) -> UInt32 { let runtime = web_font_runtime(family) + runtime.error = None runtime.generation += 1U runtime.dom_ready_generation = None runtime.bytes_ready_generation = None @@ -30,7 +33,10 @@ fn begin_web_font_load(family : String) -> UInt32 { ///| fn web_font_load_is_current(family : String, generation : UInt32) -> Bool { - web_font_runtime(family).generation == generation + web_font_runtimes + .get(family) + .map(runtime => runtime.generation == generation) + .unwrap_or(false) } ///| @@ -72,21 +78,20 @@ pub fn font_metrics_revision(family : String) -> UInt32 { } ///| -pub fn load_font(family : String, path : String) -> Unit { - let resolved_path = resolve_asset_path(path) +fn load_font(family : String, bytes : Bytes, url : String) -> Unit { let generation = begin_web_font_load(family) + if prepare_cosmic_font(family, bytes) { + mark_web_font_bytes_ready(family, generation) + } load_font_async( family, - resolved_path, + url, fn() { web_font_load_is_current(family, generation) }, fn() { mark_web_font_dom_ready(family, generation) }, - fn(_message) { () }, - ) - webgpu_preload_font_bytes( - family, - resolved_path, - fn() { web_font_load_is_current(family, generation) }, - fn() { mark_web_font_bytes_ready(family, generation) }, - fn(_message) { () }, + fn(message) { + if web_font_load_is_current(family, generation) { + web_font_runtime(family).error = Some(message) + } + }, ) } diff --git a/selene-webgpu/src/js_audio.mbt b/selene-webgpu/src/js_audio.mbt index 59a7c886..afb5f110 100644 --- a/selene-webgpu/src/js_audio.mbt +++ b/selene-webgpu/src/js_audio.mbt @@ -1,5 +1,5 @@ ///| -extern "js" fn create_audio_object_url(bytes : Bytes, mime : String) -> String = +extern "js" fn create_object_url(bytes : Bytes, mime : String) -> String = #| (bytes, mime) => { #| return URL.createObjectURL(new Blob([bytes], { type: mime })); #| } diff --git a/selene-webgpu/src/js_canvas_api.mbt b/selene-webgpu/src/js_canvas_api.mbt index 3d89d4ec..d3c4afb2 100644 --- a/selene-webgpu/src/js_canvas_api.mbt +++ b/selene-webgpu/src/js_canvas_api.mbt @@ -115,11 +115,14 @@ pub fn set_time_scale(time_scale : Double) -> Unit { } ///| -pub fn set_embedded_assets(lookup : (String) -> Bytes?) -> Unit { +pub fn set_embedded_assets( + lookup : (String) -> Bytes?, + paths~ : Array[String] = [], +) -> Unit { embedded_asset_lookup.val = lookup + embedded_paths.val = paths.copy() embedded_asset_cache.clear() reported_asset_io_failures.clear() - reset_audio_runtime() } ///| diff --git a/selene-webgpu/src/js_platform_io.mbt b/selene-webgpu/src/js_platform_io.mbt index fe8fc40e..3ebdd1bf 100644 --- a/selene-webgpu/src/js_platform_io.mbt +++ b/selene-webgpu/src/js_platform_io.mbt @@ -1,56 +1,3 @@ -///| -extern "js" fn webgpu_preload_font_bytes( - font : String, - path : String, - accept : () -> Bool, - loaded : () -> Unit, - failed : (String) -> Unit, -) -> Unit = - #| (font, path, accept, loaded, failed) => { - #| const g = globalThis; - #| if (!g.__selene_font_bytes_states) { - #| g.__selene_font_bytes_states = new Map(); - #| } - #| const states = g.__selene_font_bytes_states; - #| states.set(font, { status: 0, bytes: [] }); - #| fetch(path) - #| .then((res) => { - #| if (!res.ok) throw new Error('failed to fetch font'); - #| return res.arrayBuffer(); - #| }) - #| .then((buf) => { - #| if (!accept()) return; - #| states.set(font, { status: 1, bytes: Array.from(new Uint8Array(buf)) }); - #| loaded(); - #| }) - #| .catch((error) => { - #| if (!accept()) return; - #| states.set(font, { status: 2, bytes: [] }); - #| failed(error && error.message ? String(error.message) : String(error)); - #| }); - #| } - -///| -extern "js" fn webgpu_font_bytes_status(font : String) -> Int32 = - #| (font) => { - #| const states = globalThis.__selene_font_bytes_states; - #| if (!states) return -1; - #| const rec = states.get(font); - #| if (!rec) return -1; - #| return rec.status | 0; - #| } - -///| -extern "js" fn webgpu_take_font_bytes_ffi(font : String) -> FixedArray[Int32] = - #| (font) => { - #| const states = globalThis.__selene_font_bytes_states; - #| if (!states) return []; - #| const rec = states.get(font); - #| if (!rec || rec.status !== 1) return []; - #| states.set(font, { status: 3, bytes: [] }); - #| return rec.bytes || []; - #| } - ///| extern "js" fn resolve_asset_path(path : String) -> String = #| (path) => { @@ -169,11 +116,6 @@ extern "js" fn webgpu_gamepad_axis_value(index : Int32, axis : Int32) -> Double #| return v; #| } -///| -fn webgpu_take_font_bytes(font : String) -> Array[Int32] { - Array::from_fixed_array(webgpu_take_font_bytes_ffi(font)) -} - ///| fn webgpu_load_file_bytes_sync(path : String) -> Array[Int32] { Array::from_fixed_array(webgpu_load_file_bytes_sync_ffi(path)) diff --git a/selene-webgpu/src/moon.pkg b/selene-webgpu/src/moon.pkg index e268502f..202f6de5 100644 --- a/selene-webgpu/src/moon.pkg +++ b/selene-webgpu/src/moon.pkg @@ -1,4 +1,5 @@ import { + "Milky2018/selene/asset_types", "moonbitlang/core/set", "moonbitlang/core/cmp", "moonbitlang/core/debug", @@ -14,3 +15,7 @@ import { } supported_targets = "js" + +import { + "moonbitlang/core/encoding/utf8", +} for "wbtest" diff --git a/selene-webgpu/src/pkg.generated.mbti b/selene-webgpu/src/pkg.generated.mbti index 7673bf29..d761a57b 100644 --- a/selene-webgpu/src/pkg.generated.mbti +++ b/selene-webgpu/src/pkg.generated.mbti @@ -2,6 +2,7 @@ package "Milky2018/selene_webgpu" import { + "Milky2018/selene/asset_types", "Milky2018/selene/inputs", "Milky2018/selene/math", "Milky2018/selene/platform_runtime", @@ -14,6 +15,8 @@ import { } // Values +pub fn audio_preparation_state(@asset_types.Handle[@asset_types.Audio]) -> @asset_types.PreparationState + pub fn capture_frame_png() -> Bytes? pub fn capture_frame_png_to_file(String) -> Bool @@ -22,14 +25,18 @@ pub fn draw_circle(@render2d_types.CircleDrawCommand2D) -> Unit pub fn draw_gradient_rect(@render2d_types.GradientRectDrawCommand2D) -> Unit -pub fn draw_image(@render2d_types.ImageDrawCommand2D, String) -> Unit +pub fn draw_image(@render2d_types.ImageDrawCommand2D) -> Unit pub fn draw_rect(@render2d_types.RectDrawCommand2D) -> Unit pub fn draw_text(@render2d_types.TextDrawCommand2D) -> Unit +pub fn embedded_asset_paths() -> Array[String] + pub fn font_metrics_revision(String) -> UInt32 +pub fn font_preparation_state(@asset_types.Handle[@asset_types.Font]) -> @asset_types.PreparationState + pub fn frame_begin(@render.Color) -> Unit pub fn frame_end() -> Unit @@ -40,23 +47,25 @@ pub fn get_realtime_delta() -> Double pub fn get_time_scale() -> Double +pub fn image_preparation_state(@asset_types.Handle[@asset_types.Image]) -> @asset_types.PreparationState + pub fn initialize(@platform_runtime.WindowConfig, @platform_runtime.RunnerCallbacks) -> () -> Unit pub fn is_finished(instance~ : Int32) -> Bool -pub fn load_font(String, String) -> Unit - pub fn lock_mouse(@ref.Ref[Bool]) -> Unit pub fn measure_text(@render2d_types.TextStyle2D, String) -> @math.Vec2 -pub fn play_audio(audio_path~ : String, volume~ : Double, speed~ : Double, loop_~ : Bool, paused~ : Bool) -> Int32 +pub fn play_audio(source~ : @asset_types.Handle[@asset_types.Audio], volume~ : Double, speed~ : Double, loop_~ : Bool, paused~ : Bool) -> Int32 pub fn pop_clip_rect() -> Unit -pub fn preload_audio(String) -> Unit +pub fn preload_audio(@asset_types.Handle[@asset_types.Audio]) -> Unit + +pub fn prepare_font(@asset_types.Handle[@asset_types.Font]) -> String? -pub fn preload_img(String) -> Unit +pub fn prepare_image(@asset_types.Handle[@asset_types.Image]) -> Unit pub fn push_clip_rect(@math.Rect) -> Unit @@ -70,8 +79,6 @@ pub fn register_touch_events(Map[@inputs.TouchId, @inputs.TouchPoint], Array[@in pub fn release_cubemap_asset(@render3d_types.CubemapHandle) -> Unit -pub fn release_image_asset(@render3d_types.ImageHandle) -> Unit - pub fn release_material_asset(@render3d_types.MaterialHandle) -> Unit pub fn release_mesh_asset(@render3d_types.MeshHandle) -> Unit @@ -88,7 +95,7 @@ pub fn request_close() -> Unit pub fn reset_clip_stack() -> Unit -pub fn set_embedded_assets((String) -> Bytes?) -> Unit +pub fn set_embedded_assets((String) -> Bytes?, paths? : Array[String]) -> Unit pub fn set_loop(instance~ : Int32, loop_~ : Bool) -> Unit @@ -106,8 +113,6 @@ pub fn stop(instance~ : Int32) -> Unit pub fn sync_cubemap_asset(@render3d_types.CubemapHandle, @render3d_types.CubemapAsset3D) -> Unit -pub fn sync_image_asset(@render3d_types.ImageHandle, @render3d_types.ImageAsset) -> Unit - pub fn sync_material_asset(@render3d_types.MaterialHandle, @render3d_types.StandardMaterial3D) -> Unit pub fn sync_mesh_asset(@render3d_types.MeshHandle, @render3d_types.MeshAsset) -> Unit diff --git a/selene-webgpu/src/platform_asset_io/asset_io.mbt b/selene-webgpu/src/platform_asset_io/asset_io.mbt index add0e87a..5b54a141 100644 --- a/selene-webgpu/src/platform_asset_io/asset_io.mbt +++ b/selene-webgpu/src/platform_asset_io/asset_io.mbt @@ -1,9 +1,17 @@ ///| -pub fn set_reader(reader : (String) -> Bytes?) -> Unit { - @impl.set_embedded_assets(reader) +pub fn set_reader( + reader : (String) -> Bytes?, + paths~ : Array[String] = [], +) -> Unit { + @impl.set_embedded_assets(reader, paths~) } ///| pub fn read_bytes(path : String) -> Bytes? { @impl.get_asset_bytes(path) } + +///| +pub fn paths() -> Array[String] { + @impl.embedded_asset_paths() +} diff --git a/selene-webgpu/src/platform_audio/audio.mbt b/selene-webgpu/src/platform_audio/audio.mbt index 3d03f5e0..4fdb738f 100644 --- a/selene-webgpu/src/platform_audio/audio.mbt +++ b/selene-webgpu/src/platform_audio/audio.mbt @@ -23,20 +23,20 @@ fn from_impl_instance(instance : @impl.AudioInstance) -> AudioInstance { ///| pub fn play_audio( - audio_path~ : String, + source~ : @asset_types.AudioHandle, volume~ : Double, speed~ : Double, loop_~ : Bool, paused~ : Bool, ) -> AudioInstance { from_impl_instance( - @impl.play_audio(audio_path~, volume~, speed~, loop_~, paused~), + @impl.play_audio(source~, volume~, speed~, loop_~, paused~), ) } ///| -pub fn preload(path : String) -> Unit { - @impl.preload_audio(path) +pub fn preload(source : @asset_types.AudioHandle) -> Unit { + @impl.preload_audio(source) } ///| @@ -73,3 +73,10 @@ pub fn is_finished(instance~ : AudioInstance) -> Bool { pub fn tick() -> Unit { @impl.tick_audio() } + +///| +pub fn preparation_state( + handle : @asset_types.AudioHandle, +) -> @asset_types.PreparationState { + @impl.audio_preparation_state(handle) +} diff --git a/selene-webgpu/src/platform_audio/moon.pkg b/selene-webgpu/src/platform_audio/moon.pkg index 2c8628e7..687ca066 100644 --- a/selene-webgpu/src/platform_audio/moon.pkg +++ b/selene-webgpu/src/platform_audio/moon.pkg @@ -1,4 +1,5 @@ import { + "Milky2018/selene/asset_types", "moonbitlang/core/debug", "Milky2018/selene_webgpu" @impl, } diff --git a/selene-webgpu/src/platform_render/moon.pkg b/selene-webgpu/src/platform_render/moon.pkg index 1f9b5b2d..6d2cb72d 100644 --- a/selene-webgpu/src/platform_render/moon.pkg +++ b/selene-webgpu/src/platform_render/moon.pkg @@ -1,4 +1,5 @@ import { + "Milky2018/selene/asset_types", "Milky2018/selene/asset", "Milky2018/selene/math", "Milky2018/selene/render2d_types", diff --git a/selene-webgpu/src/platform_render/render.mbt b/selene-webgpu/src/platform_render/render.mbt index e99aee1f..ebe0ed48 100644 --- a/selene-webgpu/src/platform_render/render.mbt +++ b/selene-webgpu/src/platform_render/render.mbt @@ -1,8 +1,12 @@ ///| fn resolve_font_family(style : @render2d_types.TextStyle2D) -> String { match style.font { - Some(handle) => @asset.font_family(handle).unwrap_or(style.family) - None => style.family + Some(handle) => @impl.prepare_font(handle).unwrap_or(style.family) + None => + match @asset.font_by_family(style.family) { + Some(handle) => @impl.prepare_font(handle).unwrap_or(style.family) + None => style.family + } } } @@ -23,10 +27,7 @@ fn resolve_text_command( ///| fn submit_draw_command(command : @render2d_types.DrawCommand2D) -> Unit { match command { - Image(image) => - if @asset.image_path(image.image) is Some(path) { - @impl.draw_image(image, path) - } + Image(image) => @impl.draw_image(image) Text(text) => @impl.draw_text(resolve_text_command(text)) Rect(rect) => @impl.draw_rect(rect) Circle(circle) => @impl.draw_circle(circle) @@ -83,9 +84,6 @@ pub fn submit_frame(frame : @render_pipeline.RenderFrame) -> Unit { for (handle, asset) in frame.assets3d.material_upserts { @impl.sync_material_asset(handle, asset) } - for (handle, asset) in frame.assets3d.image_upserts { - @impl.sync_image_asset(handle, asset) - } for (handle, asset) in frame.assets3d.cubemap_upserts { @impl.sync_cubemap_asset(handle, asset) } @@ -95,9 +93,6 @@ pub fn submit_frame(frame : @render_pipeline.RenderFrame) -> Unit { for handle in frame.assets3d.material_releases { @impl.release_material_asset(handle) } - for handle in frame.assets3d.image_releases { - @impl.release_image_asset(handle) - } for handle in frame.assets3d.cubemap_releases { @impl.release_cubemap_asset(handle) } @@ -137,14 +132,23 @@ pub fn submit_frame(frame : @render_pipeline.RenderFrame) -> Unit { } ///| -pub fn register_font(family : String, path : String) -> Unit { - @impl.load_font(family, path) +pub fn image_preparation_state( + handle : @asset_types.ImageHandle, +) -> @asset_types.PreparationState { + @impl.image_preparation_state(handle) +} + +///| +pub fn font_preparation_state( + handle : @asset_types.FontHandle, +) -> @asset_types.PreparationState { + @impl.font_preparation_state(handle) } ///| /// Exposes backend font readiness transitions to retained layout caches. -pub fn font_metrics_revision(family : String) -> UInt32 { - @impl.font_metrics_revision(family) +pub fn font_metrics_revision(style : @render2d_types.TextStyle2D) -> UInt32 { + @impl.font_metrics_revision(resolve_font_family(style)) } ///| @@ -199,21 +203,21 @@ pub fn render_offscreen_png( ///| pub fn image_region_is_fully_transparent( - path : String, + image : @asset_types.ImageHandle, rect : @math.Rect, ) -> Bool? { - ignore(path) + ignore(image) ignore(rect) None } ///| pub fn export_texture_region_png( - image_path : String, + image : @asset_types.ImageHandle, rect : @math.Rect, out_path : String, ) -> Bool { - ignore(image_path) + ignore(image) ignore(rect) ignore(out_path) false diff --git a/selene-webgpu/src/resource_preparation.mbt b/selene-webgpu/src/resource_preparation.mbt new file mode 100644 index 00000000..c32baf77 --- /dev/null +++ b/selene-webgpu/src/resource_preparation.mbt @@ -0,0 +1,139 @@ +///| +// js-ffi 0.4.3 passes Array directly to JS spread. FixedArray is the native JS array. +fn[Arg, Result] call_browser_method( + object : @js.Value, + name : String, + args : FixedArray[Arg], +) -> Result { + let reflect : @js.Value = @js.globalThis.get_with_string("Reflect") + let apply : (@js.Value, @js.Value, FixedArray[Arg]) -> Result = reflect.get_with_string( + "apply", + ) + let callable : @js.Value = object.get_with_string(name) + apply(callable, object, args) +} + +///| +fn is_js_object(value : @js.Value) -> Bool { + value.is_object() && !value.is_null() +} + +///| +let prepared_images : Map[@asset_types.ImageHandle, String] = Map([]) + +///| +let prepared_fonts : Map[@asset_types.FontHandle, String] = Map([]) + +///| +fn browser_runtime() -> @js.Value { + @js.globalThis.get_with_string("__selene_webgpu_runtime") +} + +///| +fn release_prepared_image(url : String) -> Unit { + let runtime = browser_runtime() + guard is_js_object(runtime) else { return } + let cache : @js.Value = runtime.get_with_string("imageCache") + let record : @js.Value = call_browser_method(cache, "get", [url]) + if is_js_object(record) { + record.set_with_string("state", "cancelled") + let texture : @js.Value = record.get_with_string("texture") + if is_js_object(texture) { + let result : @js.Value = call_browser_method( + texture, + "destroy", + ([] : FixedArray[@js.Value]), + ) + ignore(result) + } + } + let removed : Bool = call_browser_method(cache, "delete", [url]) + ignore(removed) +} + +///| +fn image_url(handle : @asset_types.ImageHandle) -> String? { + guard handle.get() is Some(image) else { return None } + if prepared_images.get(handle) is Some(url) { + return Some(url) + } + let url = create_object_url(image.bytes, "application/octet-stream") + prepared_images[handle] = url + handle.on_invalidate(fn() { + prepared_images.remove(handle) + release_prepared_image(url) + revoke_object_url(url) + }) + Some(url) +} + +///| +pub fn image_preparation_state( + handle : @asset_types.ImageHandle, +) -> @asset_types.PreparationState { + guard prepared_images.get(handle) is Some(url) else { return Unprepared } + let runtime = browser_runtime() + guard is_js_object(runtime) else { return Preparing } + let cache : @js.Value = runtime.get_with_string("imageCache") + let record : @js.Value = call_browser_method(cache, "get", [url]) + guard is_js_object(record) else { return Preparing } + let state : String = record.get_with_string("state") + match state { + "ready" => Ready + "error" => Failed("Image decoding or texture preparation failed") + _ => Preparing + } +} + +///| +pub fn prepare_font(handle : @asset_types.FontHandle) -> String? { + guard handle.get() is Some(font) else { return None } + if prepared_fonts.get(handle) is Some(family) { + return Some(family) + } + let family = "selene-font-\{handle.id()}" + prepared_fonts[handle] = family + let url = create_object_url(font.bytes, "application/octet-stream") + load_font(family, font.bytes, url) + handle.on_invalidate(fn() { + prepared_fonts.remove(handle) + revoke_object_url(url) + cosmic_fonts.remove(family) + if handle.is_alive() { + ignore(begin_web_font_load(family)) + } else { + web_font_runtimes.remove(family) + } + invalidate_web_font_metrics() + let faces : @js.Value = @js.globalThis.get_with_string( + "__selene_font_faces", + ) + if is_js_object(faces) { + let face : @js.Value = call_browser_method(faces, "get", [family]) + if is_js_object(face) { + let document : @js.Value = @js.globalThis.get_with_string("document") + let fonts : @js.Value = document.get_with_string("fonts") + let removed : Bool = call_browser_method(fonts, "delete", [face]) + ignore(removed) + } + let removed : Bool = call_browser_method(faces, "delete", [family]) + ignore(removed) + } + }) + Some(family) +} + +///| +pub fn font_preparation_state( + handle : @asset_types.FontHandle, +) -> @asset_types.PreparationState { + guard prepared_fonts.get(handle) is Some(family) else { return Unprepared } + let runtime = web_font_runtime(family) + if runtime.error is Some(message) { + Failed(message) + } else if runtime.dom_ready_generation == Some(runtime.generation) { + Ready + } else { + Preparing + } +} diff --git a/selene-webgpu/src/resource_preparation_wbtest.mbt b/selene-webgpu/src/resource_preparation_wbtest.mbt new file mode 100644 index 00000000..543cac32 --- /dev/null +++ b/selene-webgpu/src/resource_preparation_wbtest.mbt @@ -0,0 +1,90 @@ +///| +test "image resources with equal bytes retain independent backend lifetimes" { + let images : @asset_types.Assets[@asset_types.Image] = Assets() + let first = images.add(@asset_types.Image::from_bytes(b"same")) + let second = images.add(@asset_types.Image::from_bytes(b"same")) + let first_url = image_url(first).unwrap() + let second_url = image_url(second).unwrap() + assert_true(first_url.has_prefix("blob:")) + assert_true(first_url != second_url) + assert_eq(image_url(first), Some(first_url)) + ignore(images.remove(first)) + assert_eq(image_url(first), None) + assert_eq(image_url(second), Some(second_url)) + ignore(images.remove(second)) +} + +///| +test "ordinary collection updates invalidate prepared image sources" { + let images : @asset_types.Assets[@asset_types.Image] = Assets() + let image = images.add(@asset_types.Image::from_bytes(b"first")) + assert_true(image_preparation_state(image) is Unprepared) + let first = image_url(image) + assert_true(images.insert(image, @asset_types.Image::from_bytes(b"second"))) + assert_true(image_preparation_state(image) is Unprepared) + assert_true(image_url(image) != first) + ignore(images.remove(image)) + assert_eq(image_url(image), None) + assert_true(image_preparation_state(image) is Unprepared) +} + +///| +test "3D materials use the same image resources as 2D rendering" { + let images : @asset_types.Assets[@asset_types.Image] = Assets() + let image = images.add(@asset_types.Image::from_bytes(b"shared image")) + let binding = @render3d_types.TextureBinding3D(image) + assert_eq(image_url(binding.image), image_url(image)) + ignore(images.remove(image)) +} + +///| +test "replacing path IO does not discard registered audio sources" { + let audios : @asset_types.Assets[@asset_types.Audio] = Assets() + let audio = audios.add(@asset_types.Audio::from_bytes(b"registered audio")) + let url = create_object_url(b"registered audio", "application/octet-stream") + cached_audio_sources[audio] = url + defer { + clear_cached_audio_source(audio) + collect_retired_audio_sources() + } + defer ignore(audios.remove(audio)) + set_embedded_assets(fn(_) { None }) + assert_eq(cached_audio_sources.get(audio).unwrap(), url) +} + +///| +test "invalid font bytes do not create a prepared Cosmic font" { + assert_false(prepare_cosmic_font("__invalid_font__", b"not a font")) + assert_false(cosmic_fonts.contains("__invalid_font__")) +} + +///| +test "browser method calls use native argument arrays and preserve their receiver" { + let values : FixedArray[String] = ["first"] + let receiver = @js.Value::cast_from(values) + let length : Int32 = call_browser_method(receiver, "push", ["second"]) + let joined : String = call_browser_method(receiver, "join", [","]) + assert_eq(length, 2) + assert_eq(joined, "first,second") + let last : String = call_browser_method( + receiver, + "pop", + ([] : FixedArray[String]), + ) + assert_eq(last, "second") + let null : @js.Nullable[@js.Value] = @js.Nullable::null() + assert_false(is_js_object(@js.Value::cast_from(null))) +} + +///| +test "audio source preparation is idempotent until its asset is replaced" { + let audios : @asset_types.Assets[@asset_types.Audio] = Assets() + let audio = audios.add(@asset_types.Audio::from_bytes(b"first")) + let first = resolved_audio_source(audio) + assert_eq(resolved_audio_source(audio), first) + assert_true(audios.insert(audio, @asset_types.Audio::from_bytes(b"second"))) + assert_true(resolved_audio_source(audio) != first) + ignore(audios.remove(audio)) + assert_true(audio_preparation_state(audio) is Unprepared) + collect_retired_audio_sources() +} diff --git a/selene-webgpu/src/text_cosmic.mbt b/selene-webgpu/src/text_cosmic.mbt index 97c2c207..ff55583e 100644 --- a/selene-webgpu/src/text_cosmic.mbt +++ b/selene-webgpu/src/text_cosmic.mbt @@ -26,17 +26,15 @@ priv struct CosmicTextCacheEntry { } ///| -let cosmic_font_system : Ref[@cosmic.FontSystem] = Ref( - @cosmic.FontSystem::new(), -) - -///| -let cosmic_swash_cache : Ref[@cosmic.SwashCache] = Ref( - @cosmic.SwashCache::new(), -) +priv struct CosmicFontRuntime { + system : @cosmic.FontSystem + mut swash : @cosmic.SwashCache + family : String +} ///| -let cosmic_loaded_families : @set.Set[String] = Set([]) +// Face ids and glyph cache keys are local to each resource's font system. +let cosmic_fonts : Map[String, CosmicFontRuntime] = Map([]) ///| let cosmic_text_cache : Map[String, CosmicTextCacheEntry] = Map([]) @@ -110,22 +108,15 @@ fn text_cache_key(command : @render2d_types.TextDrawCommand2D) -> String { } ///| -fn ensure_font_loaded(family : String) -> Bool { - if cosmic_loaded_families.contains(family) { - return true +fn prepare_cosmic_font(family : String, bytes : Bytes) -> Bool { + let system = @cosmic.FontSystem::new().load_font_data(bytes) + let entries = system.fonts() + guard entries.length() > 0 else { return false } + cosmic_fonts[family] = { + system, + swash: @cosmic.SwashCache::new(), + family: entries[0].family_name(), } - if webgpu_font_bytes_status(family) != 1 { - return false - } - let raw_bytes = webgpu_take_font_bytes(family) - if raw_bytes.is_empty() { - return false - } - let bytes = Bytes::from_iter( - raw_bytes.iter().map(fn(value) { saturating_byte(value) }), - ) - cosmic_font_system.val = cosmic_font_system.val.load_font_data(bytes) - cosmic_loaded_families.add(family) cosmic_text_cache.clear() true } @@ -135,7 +126,7 @@ fn measure_text_with_cosmic( style : @render2d_types.TextStyle2D, text : String, ) -> @smath.Vec2? { - guard ensure_font_loaded(style.family) else { return None } + guard cosmic_fonts.get(style.family) is Some(font) else { return None } let font_size = if style.size < 1.0 { 1.0 } else { style.size } if text == "" { return Some(Vec2(0.0, font_size)) @@ -144,13 +135,13 @@ fn measure_text_with_cosmic( Float::from_double(font_size), Float::from_double(font_size * 1.25), ) - let attrs = @cosmic.Attrs::new().family(Name(style.family)) + let attrs = @cosmic.Attrs::new().family(Name(font.family)) let attrs_list = @cosmic.AttrsList::new(attrs) let buffer = @cosmic.Buffer::new(metrics) .set_wrap(None) .set_text(text, attrs_list, Advanced) .set_size(None, None) - .layout_all_with_font_system(cosmic_font_system.val) + .layout_all_with_font_system(font.system) let mut width = 0.0 let mut height = 0.0 for run in buffer.layout_runs() { @@ -173,9 +164,10 @@ fn rasterize_with_cosmic( command : @render2d_types.TextDrawCommand2D, ) -> CosmicRasterImage? { let family = command.style.family - if !cosmic_loaded_families.contains(family) { + if !cosmic_fonts.contains(family) { return None } + let font = cosmic_fonts[family] let font_size = if command.style.size < 1.0 { 1.0 } else { @@ -185,7 +177,7 @@ fn rasterize_with_cosmic( Float::from_double(font_size), Float::from_double(font_size * 1.25), ) - let attrs = @cosmic.Attrs::new().family(Name(family)) + let attrs = @cosmic.Attrs::new().family(Name(font.family)) let attrs_list = @cosmic.AttrsList::new(attrs) let buffer = @cosmic.Buffer::new(metrics) .set_wrap(None) @@ -197,8 +189,8 @@ fn rasterize_with_cosmic( let mut max_y = -1 let points : Array[(Int32, Int32, Int32)] = [] let (drawn_buffer, swash_cache) = buffer.draw( - cosmic_font_system.val, - cosmic_swash_cache.val, + font.system, + font.swash, to_cosmic_color(command.style.color), fn(x, y, _w, _h, color) { let (_, _, _, a) = color.as_rgba() @@ -225,7 +217,7 @@ fn rasterize_with_cosmic( }, ) ignore(drawn_buffer) - cosmic_swash_cache.val = swash_cache + font.swash = swash_cache if points.is_empty() { return None } @@ -250,8 +242,7 @@ fn draw_text_with_cosmic(command : @render2d_types.TextDrawCommand2D) -> Bool { if command.text == "" { return true } - if !ensure_font_loaded(command.style.family) && - !cosmic_loaded_families.contains(command.style.family) { + if !cosmic_fonts.contains(command.style.family) { return false } let key = text_cache_key(command)