jakobhellermann / bevy_mod_js_scripting

Other
83 stars 6 forks source link

`World.spawn()`, Non-primitive Assignments, and Patching #28

Closed zicklag closed 1 year ago

zicklag commented 1 year ago

This PR

  1. Adds a simple world.spawn() method.
  2. Allows you to assign non-primitives to value refs, allowing, in my use case, me to set the id of a Handle<T> in Bevy even though HandleId is not a JS primitive.
  3. Fixes a bug I introduced with the Value.patch() PR where non-primitive assignments stopped throwing an error when they failed.

It's worth noting that non-primitive patching doesn't work yet. That will require a kind of recursive value ref unwrapping helper, which I haven't implemented yet.

zicklag commented 1 year ago

Just pushed an update that adds non-primitive patching.

This let me load ( weak ) asset handles in my game quite ergonomically:

type AnimatedSprite = {
  start: usize;
  end: usize;
  atlas: HandleTextureAtlas;
  flip_x: boolean;
  flip_y: boolean;
  repeat: boolean;
  fps: f32;
};
const AnimatedSprite: BevyType<AnimatedSprite> = {
  typeName: "jumpy::animation::AnimatedSprite",
};

export default {
  preUpdate() {
    for (const entity of MapElement.getSpawnedEntities()) {
      let animated_sprite = Value.create(AnimatedSprite, {
        start: 0,
        end: 4,
        repeat: true,
        fps: 6,
        atlas: {
          id: Assets.getHandleId(
            "../../../resources/default_decoration.atlas.yaml"
          ),
        },
      });

      world.insert(entity, animated_sprite);
    }
  },
};
zicklag commented 1 year ago

If https://github.com/bevyengine/bevy/pull/6187 is merged, I think we'll be able to spawn sprites from scripts, with the nuance that the script can only create weak handles, so the game needs to provide a way for scripts to somehow register assets to load with strong handles.

In my game I have YAML files with a preload_assets field for that, because I preload all the assets in my game anyway.

jakobhellermann commented 1 year ago

Have you seen https://github.com/bevyengine/bevy/pull/5923? It would let you insert new assets and get back a handle.

zicklag commented 1 year ago

No I haven't, that's awesome! 🎉

I think that pretty much fixes the bulk of the things I was worried about for asset handling in scripts.

jakobhellermann commented 1 year ago

Can you rebase this? Otherwise it looks good. Sorry for leaving these PRs uncommented for so long.

zicklag commented 1 year ago

Yep, I'll rebase this today, and no problem about the delay. I was totally fine working off my fork.

zicklag commented 1 year ago

Pushed the rebase.

jakobhellermann commented 1 year ago

Thanks a ton for the PR and the patience for having this unmerged for so long. I rebased the PR on main and merged it in https://github.com/jakobhellermann/bevy_mod_js_scripting/pull/36.

zicklag commented 1 year ago

No problem! :D