Giter VIP home page Giter VIP logo

box2d-wasm's Introduction

box2d-wasm

npm version

Box2D compiled to WebAssembly.

Showcase

Usage

Install the box2d-wasm npm package

npm i box2d-wasm

Then check out the documentation.

Alternative distributions

For additional functionality:

  • fluid simulation
  • particle simulation
  • soft-body collisions

You can install from the liquidfun branch like so:

npm i "box2d-wasm@npm:[email protected]"

License

Zlib-licensed.
Links against MIT-licensed code from Erin Catto's Box2D.
Compiles Zlib-licensed code from Alon Zakai's box2d.js.

Project

Compared to the existing box2d.js package: box2d-wasm aims to support Box2D v2.4.0+ and TypeScript.

Developing in this monorepo

See README.dev.md.

box2d-wasm's People

Contributors

birch-san avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

box2d-wasm's Issues

Node.js

Hello, thank you very much for porting the newer version of Box2d and supporting TypeScript.
Is it possible to make the package work also server-side on Node.js?

AABB Queries

I'm trying to implement AABB queries similar to the following example:
https://box2d.org/documentation/md__d_1__git_hub_box2d_docs_dynamics.html#autotoc_md118

That would be with something like:

class MyQueryCallback extends Box2D.b2QueryCallback {
  ReportFixture(fixture: Box2D.b2Fixture) {
    const body = fixture.GetBody()
    body.SetAwake(true)
    return true
  }
}

But then when I instantiate the class I get this error: 'cannot construct a b2QueryCallback, no constructor in IDL'

What am I doing wrong? Would appreciate any help... Thanks!

WASM streaming compile failed

I'm using this code to initialize Box2D similar to what @kripken did here in an example

<script language="javascript" type="text/javascript" src="node_modules/box2d-wasm/build/Box2D.js"></script>
    <script language="javascript" type="text/javascript">  
        if (!Box2D) Box2D = (typeof Box2D !== 'undefined' ? Box2D : null) || Module; 
        Box2D().then(function(r){
            Box2D = r;
            Module = Box2D;
            if(document.readyState === "complete"){
                afterDocumentLoaded()
            } else {
                window.onload = afterDocumentLoaded
            }
        });
        const afterDocumentLoaded = function(){
            using(Box2D, "b2.+");
        };
    </script>
    <script language="javascript" type="text/javascript" src="libs/box2d.js/helpers/embox2d-helpers.js"></script>

So I'm getting this

> Box2D.js:58 wasm streaming compile failed: TypeError: Failed to execute 'compile' on 'WebAssembly': Incorrect response MIME type. Expected 'application/wasm'.

> Box2D.js:58 falling back to ArrayBuffer instantiation

I'm not running this local web server with npm, because I still don't get npm that much...

Documentation?

Since the usage of the generated code is quite different from the original API of Box2D, some documentation would be helpfull.
I just noticed, you use the wiki and added a entry about collision helpers, maybe make a note on the main Readme to link there?
(I seldom see a project use wiki)

Anyway, I can probably help a bit with documentation, I don't have much time, though, but sharing bits of code with some explenation, I can do.

For example I just got raycast to work, like it should - and since this was not at all straight forward, I could save others the trouble.
So, would you like contributions in that regard?
If so, how?
I cannot edit the wiki, would this also work with pullrequests? (not really used to work with Github) Or just email you? Or open a issue, like this?

Anyway, heres the code about the raycast:

// preparing the callback
const _callback = new box2D.JSRayCastCallback();
 _callback.ReportFixture = function(fixture, point, normal, fraction) {
         // all the parameters come as pointers, but we want the real object
          const f = box.wrapPointer(fixture, box2D.b2Fixture);
          const p = box.wrapPointer(point, box2D.b2Vec2);
          const n = box.wrapPointer(normal, box2D.b2Vec2);
           console.log(f);

        }
// then later, do the raycast
world.RayCast(_callback,point1,point2)


Unable to use SetLength() with DistanceJoint

when i want to set length dynamicly , i find that either bodyA and bodyB transform have no changes.also the anchor and localanchor. the only change is length. I think there may something wrong or my code has bugs?

  setDistanceJoint(config: {
    jointId: string,
    length: number,
  }) {
    const joint = <Box2D.b2DistanceJoint>this.checkJoint(config.jointId)?.b2Joint
    if (joint) {
      joint.SetLength(config.length); 
      // console.log(joint.GetLength());
      // console.log(joint.GetStiffness());
      console.log(joint.GetAnchorA())
      console.log(joint.GetAnchorB())
      // console.log(joint.GetReactionForce(1));
      // console.log(joint.GetReactionTorque(1));
      // console.log(joint.SetMinLength(config.length));
    }
  }

Doesn't work on latest Node

it works with v14.8.0 with nvm, but with v18.5.0 or v19 (haven't tried others) it spits this out:

./node_modules/box2d-wasm/dist/umd/Box2D.simd.js:12

TypeError: Failed to parse URL from ./node_modules/box2d-wasm/dist/umd/Box2D.simd.wasm
    at Object.fetch (node:internal/deps/undici/undici:11413:11) {
  [cause]: TypeError [ERR_INVALID_URL]: Invalid URL

Convex shapes are not supported

Convex shapes are not supported

const square = new b2PolygonShape(); var vArray = [new b2Vec2(0,-20),new b2Vec2(25,0),new b2Vec2(15,30),new b2Vec2(-15,30),new b2Vec2(-25,0)] square.Set(vArray, 4);

GetUserData() can't get userdata 111

var bd_ground = new b2BodyDef(); bd_ground.set_userData(111); var ground = world.CreateBody(bd_ground); var shape = new b2EdgeShape(); shape.SetTwoSided(new b2Vec2(0, 38), new b2Vec2(800 / pixelsPerMeter, 38)); ground.CreateFixture(shape, 0); console.log(ground.GetUserData());

this check should be wrong.

image

it means i have to implement the JSDrawer like this?

  const myDrawer  = {
      DrawSegments(...) {}
  }

im doing this:
image
and then

this._drawer = new DebugDrawer(this);
world.SetDebugDraw(this._drawer);

the method is just right there:
image

btw, the current way to import methods, i feel inconvenient, because i have to pass the b2d instance everywhere....
i prefer just import { what i need } from 'box2d';

i'm doing test on this proj.

thank you.

Unable to deploy example with box2d-wasm on Node.js hosting.

I can show the example code if needed, but there is some problem with the library itself. I tried to deploy on render.com It can be an issue of render.com

Jul 14 01:31:02 AM  ==> Starting service with 'node src/server/app.js'
Jul 14 01:31:04 AM  Listening at port: 10000
Jul 14 01:33:54 AM  /opt/render/project/src/node_modules/box2d-wasm/dist/umd/Box2D.simd.js:12
Jul 14 01:33:54 AM  p){f?d(f):c(p.buffer)})},1<process.argv.length&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function(b){throw b;}),process.on("unhandledRejection",function(b){throw b;}),a.inspect=function(){return"[Emscripten Module object]"};else if(ea||fa)fa?ha=self.location.href:"undefined"!==typeof document&&document.currentScript&&(ha=document.currentScript.src),_scriptDir&&(ha=_scriptDir),ha=0!==ha.indexOf("blob:")?ha.substr(0,ha.replace(/[?#].*/,"").lastIndexOf("/")+
Jul 14 01:33:54 AM                                                                                                                                                      ^
Jul 14 01:33:54 AM  
Jul 14 01:33:54 AM  TypeError: Failed to parse URL from /opt/render/project/src/node_modules/box2d-wasm/dist/umd/Box2D.simd.wasm
Jul 14 01:33:54 AM      at Object.fetch (node:internal/deps/undici/undici:11576:11)
Jul 14 01:33:54 AM      at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
Jul 14 01:33:54 AM    [cause]: TypeError [ERR_INVALID_URL]: Invalid URL
Jul 14 01:33:54 AM        at new NodeError (node:internal/errors:405:5)
Jul 14 01:33:54 AM        at new URL (node:internal/url:778:13)
Jul 14 01:33:54 AM        at new Request (node:internal/deps/undici/undici:7132:25)
Jul 14 01:33:54 AM        at fetch2 (node:internal/deps/undici/undici:10715:25)
Jul 14 01:33:54 AM        at Object.fetch (node:internal/deps/undici/undici:11574:18)
Jul 14 01:33:54 AM        at fetch (node:internal/process/pre_execution:252:25)
Jul 14 01:33:54 AM        at /opt/render/project/src/node_modules/box2d-wasm/dist/umd/Box2D.simd.js:29:275
Jul 14 01:33:54 AM        at /opt/render/project/src/node_modules/box2d-wasm/dist/umd/Box2D.simd.js:29:499
Jul 14 01:33:54 AM        at /opt/render/project/src/node_modules/box2d-wasm/dist/umd/Box2D.simd.js:30:11
Jul 14 01:33:54 AM        at file:///opt/render/project/src/src/server/init-box2d.js:7:9 {
Jul 14 01:33:54 AM      input: '/opt/render/project/src/node_modules/box2d-wasm/dist/umd/Box2D.simd.wasm',
Jul 14 01:33:54 AM      code: 'ERR_INVALID_URL'
Jul 14 01:33:54 AM    }
Jul 14 01:33:54 AM  }

I try to use physics on the server side. My example just creates a physical world on the server side and sends the gravity value to the client, and the client shows it.

init-box2d.js

import Box2DLib from "box2d-wasm";

export let box2d = null;

export function initBox2D() {
    return new Promise(resolve => {
        Box2DLib().then((re) => {
            box2d = re;
            resolve();
        });
    });
}

app.js

import express from "express";
import http from "http";
import path from "path";
import { WebSocketServer } from "ws";
import { box2d, initBox2D } from "./init-box2d.js";
import { makeMessage, serverEvents } from "../share/events.js"

const app = express();
app.use(express.static(path.join(process.cwd(), "public")));

const httpServer = http.createServer(app);
const wss = new WebSocketServer({ server: httpServer });
const port = process.env.PORT || 3000;
httpServer.listen(port, () => console.log("Listening at port: " + port));

wss.on("connection", client => {
    async function init() {
        await initBox2D();
        const {
            b2Vec2,
            b2World
        } = box2d;

        const gravity = new b2Vec2(0, -3);
        const world = new b2World(gravity);
        const g = world.GetGravity();
        console.log(g.x, g.y);
        client.send(makeMessage(serverEvents.outgoing.GRAVITY, JSON.stringify({ x: g.x, y: g.y })));
    }

    init();
});

This is a full code of my example that is ready to deploy on render.com: https://github.com/8Observer8/send-gravity-from-server-to-client-box2d-wasm-js

To load wasm

I want to know how your demo loads 'box2d.wasm' because I noticed that the entry.js in the demo loads 'box2d.js' directly and does not directly load the wasm file. Perhaps it's loading the wasm through the JavaScript or it's not loading the wasm file at all? If it's the latter, how can I load the wasm file?

const asset = hasSIMD
  ? './Box2D.simd.js'
  : './Box2D.js';

The jsDelivr ESM link doesn't work for Box2D-WASM

Description

The main contributor for Plunker wrote in the next message that it can be an issue of jsDelivr or Box2D-WASM: plnkr/feedback#597 (comment) So I created the issue for jsDelivr too: jsdelivr/jsdelivr#18510

I try to use the [email protected] ESM link from here: https://www.jsdelivr.com/package/npm/box2d-wasm

It doesn't work on Plunker, and it doesn't work locally on my laptop (I have the same errors, see errors below):

But it works on PlayCode: https://playcode.io/1527756

I uploaded Box2D-WASM files on GitHub Pages:

image

So it works locally and on Plunker if I use the next link: https://8observer8.github.io/lib/box2d-wasm-7.0.0-box2d-2.4.1/box2d-wasm.min.js You can just replace the jsDelivr link with this one.

index.html

<!DOCTYPE html>

<html>

<head>
    <meta charset="utf-8">
    <title>Example</title>
</head>

<body>
    <!-- Since import maps are not yet supported by all browsers, its is
        necessary to add the polyfill es-module-shims.js -->
    <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>

    <script type="importmap">
        {
            "imports": {
                "box2d-wasm": "https://cdn.jsdelivr.net/npm/[email protected]/+esm",
                "gl-matrix": "https://cdn.jsdelivr.net/npm/[email protected]/+esm"
            }
        }
    </script>

    <script type="module" src="./js/index.js"></script>
</body>

</html>

index.js

import { box2d, initBox2D } from "./init-box2d.js";

async function init() {
    await initBox2D();

    const {
        b2Vec2
    } = box2d;

    const vec = new b2Vec2(1, 2);
    console.log(`vec = (x: ${vec.x}, y: ${vec.y})`);
}

init();

init-box2d.js

import Box2DLib from "box2d-wasm";

export let box2d = null;

export function initBox2D() {
    return new Promise(resolve => {
        Box2DLib().then((re) => {
            box2d = re;
            resolve();
        });
    });
}

But I have these errors:

image

Affected jsDelivr links

https://cdn.jsdelivr.net/npm/[email protected]/+esm

The simple "hello, world" example with ESM on box2d-wasm on sandboxes (PlayCode and Plunker)

This example works on PlayCode: https://playcode.io/1512368 but it doesn't work on Plunker: https://plnkr.co/edit/YQTyTFtudEFTq9tj

Issue for Plunker: plnkr/feedback#597

index.html

<!DOCTYPE html>

<html>

<head>
    <title>Example</title>
</head>

<body>
    <!-- Since import maps are not yet supported by all browsers, it is
        necessary to add the polyfill es-module-shims.js -->
    <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>

    <script type="importmap">
        {
            "imports": {
                "box2d-wasm": "https://cdn.jsdelivr.net/npm/[email protected]/+esm"
            }
        }
    </script>

    <script type="module" src="./js/index.js"></script>
</body>

</html>

js/index.js

import { box2d, initBox2D } from "./init-box2d.js";

let world;
const pixlesPerMeter = 30;

async function init() {
    await initBox2D();

    const {
        b2Vec2
    } = box2d;

    const gravity = new b2Vec2(0, -9.8);
    console.log(`gravity = (${gravity.x}, ${gravity.y})`);
}

init();

js/init-box2d.js

import Box2DLib from "box2d-wasm";

export let box2d = null;

export function initBox2D() {
    return new Promise(resolve => {
        Box2DLib().then((re) => {
            box2d = re;
            resolve();
        });
    });
}

Cannot construct a b2Draw, no constructor in IDL

I try to create an instance of b2Draw class:

import { box2d } from "./init-box2d.js";

export default class DebugDrawer {
    constructor() {
        this.debugDrawer = box2d.b2Draw();
    }
}

But I have this error: Uncaught (in promise) cannot construct a b2Draw, no constructor in IDL

My example on Playground: https://plnkr.co/edit/Y8seZUXNtgv6uTUS

Full code of the example:

index.html

<!DOCTYPE html>

<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <canvas id="renderCanvas" width="400" height="400"></canvas>

    <!-- Since import maps are not yet supported by all browsers, it is
        necessary to add the polyfill es-module-shims.js
        Source: https://threejs.org/docs/index.html#manual/en/introduction/Installation
    -->
    <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>

    <script type="importmap">
        {
            "imports": {
                "gl-matrix": "https://cdn.skypack.dev/[email protected]",
                "box2d": "https://8observer8.github.io/lib/box2d-wasm-2.4.1/box2d-wasm-2.4.1.min.js"
            }
        }
    </script>

    <script type="module" src="./js/main.js"></script>
</body>

</html>

js/debug-drawer.js

import { box2d } from "./init-box2d.js";

export default class DebugDrawer {
    constructor() {
        this.debugDrawer = box2d.b2Draw();
    }
}

js/init-box2d.js

import Box2DLib from "box2d";

export let box2d = null;

export function initBox2D() {
    return new Promise(resolve => {
        Box2DLib().then((re) => {
            box2d = re;
            resolve();
        });
    });
}

js/main.js

import { box2d, initBox2D } from "./init-box2d.js";
import DebugDrawer from "./debug-drawer.js";

async function init() {
    await initBox2D();

    const vec = new box2d.b2Vec2(1, 2);
    console.log(`vec = ${vec.x}, ${vec.y}`);

    const debugDrawer = new DebugDrawer();
}

init();

broken compatibility with web

Hello, I am trying to use box2d-wasm on web with webpack, but it does not compile because "Can't resolve 'fs'" I see https://stackoverflow.com/questions/59487224/webpack-throws-error-with-emscripten-cant-resolve-fs that the quicker solution is set -s ENVIRONMENT='web' and in you code I see "we used to use -s ENVIRONMENT=web for a slightly smaller build, until Node.js compatibility was requested in #8".
The problem is that ok, you fix the compatibility with node.js but broke the compatibility with web... maybe it is necessary make more than one distribution, for me the better solution is 4:

  • box2d-wasm-web
  • box2d-wasm-node
  • box2d-liquidfun-wasm-web
  • box2d-liquidfun-wasm-web

because not everybody needs liquid simulation, honestly I don't want compile box2d-wasm, because to do this I need to install a lot of tools that I don't need for anything else...

Ray casting from fixture doesn't work in my example

This code doesn't work:

        // Down ray
        raycaster.drawLine([playerPosition[0], playerPosition[1] - 5],
            [playerPosition[0], playerPosition[1] - 15], [1, 1, 1]);
        const point1 = new b2Vec2(playerPosition[0] / pixelsPerMeter,
            (playerPosition[1] - 5) / pixelsPerMeter);
        const point2 = new b2Vec2(playerPosition[0] / pixelsPerMeter,
            (playerPosition[1] - 15) / pixelsPerMeter);
        // world.RayCast(downRayCallback, point1, point2);

        const input = {
            p1: point1,
            p2: point2,
            maxFraction: 1
        };
        const output = {
            normal: new b2Vec2(0, 0),
            fraction: 1
        };

        grounded = false;
        for (let i = 0; i < fixtures.length; i++) {
            grounded = fixtures[i].RayCast(input, output);
            if (grounded)
                break;
        }
        console.log(`grounded = ${grounded}`);

It prints grounded = false:

Example in Sandboxes:

Run in browser

GitHub Repository with sandboxes and instruction for Rollup.

simple-can-jump-with-ray-box2dwasm-webgl-js

I made this gif-animation to show that point1 and point2 are correct in this example:

// Down ray
        raycaster.drawLine([playerPosition[0], playerPosition[1] - 5],
            [playerPosition[0], playerPosition[1] - 15], [1, 1, 1]);
        const point1 = new b2Vec2(playerPosition[0] / pixelsPerMeter,
            (playerPosition[1] - 5) / pixelsPerMeter);
        const point2 = new b2Vec2(playerPosition[0] / pixelsPerMeter,
            (playerPosition[1] - 15) / pixelsPerMeter);
        world.RayCast(downRayCallback, point1, point2);

world.RayCast works:

point1-and-point2-are-corrent

but fixtures[i].RayCast doesn't work.

b2_maxTranslation

Box2D has a max velocity setting. Which is also does not recommend to mess with, but I want to, but can't find the property in your port.

b2_maxTranslation and b2_maxTranslationSquared are the properties I am looking for to change them.
Maybe they got hardcoded into WASM?

Unable to load using imports

getting failed to compile

./node_modules/box2d-wasm/dist/es/Box2D.simd.js 2:25
Module parse failed: Unexpected token (2:25)
File was processed with these loaders:

  • ./node_modules/babel-loader/lib/index.js
    You may need an additional loader to handle the result of these loaders.
    | var Box2D = function () {

var _scriptDir = import.meta.url;
| return function (Box2D) {
| Box2D = Box2D || {};

GetFixtureList().Next() Never returns falsey

I am trying to port from a different TypeScript Box2D port, but I am finding that all code of this form has infinite loops:

// Set all fixtures to be sensors
for (let f = this.body.GetFixtureList(); f; f = f.GetNext()) {
    f.SetSensor(!true);
}

It seems that f.GetNext() never returns undefined, null, or false, and so the loop keeps running forever.

Contact

Would it be possible to get in contact regarding your work on Box2D web? I would like to propose something. Kind regards, Erik

how to Change the shape of body dynamically

const gravity = new b2Vec2(0, 10);

world = new b2World(gravity);

const bd_ground = new b2BodyDef();

const ground = world.CreateBody(bd_ground);
const shape = new b2EdgeShape();
var xx=new b2Vec2(3, 4)
shape.SetTwoSided(xx, new b2Vec2(6, 7));
ground.CreateFixture(shape, 0);

Thanks you for your Liquidfun rebase!

My best regards!

I want to thank you for having shared your work on the rebasing of the LiquidFun library with the latest Box2D version. I program in C++ (I'm a novice), and I was really interested in an effort along these lines.

I was able to compile it successfully in Visual Studio 2019 except for Testbed, which gave me errors. Fortunately it can be disabled with -D BOX2D_BUILD_TESTBED:BOOL=OFF. Anyway I leave you here the errors for reference. :-)

P:\Compilados\x32-x64\TRABAJO_MSVC2019_x64\box2d-liquidfun-rebase\testbed\draw.h(98): error C2259: 'DebugDraw': cannot instantiate abstract class
P:\Compilados\x32-x64\TRABAJO_MSVC2019_x64\box2d-liquidfun-rebase\testbed\draw.h(61): note: see declaration of 'DebugDraw'
P:\Compilados\x32-x64\TRABAJO_MSVC2019_x64\box2d-liquidfun-rebase\testbed\draw.h(98): note: due to following members:
P:\Compilados\x32-x64\TRABAJO_MSVC2019_x64\box2d-liquidfun-rebase\testbed\draw.h(98): note: 'void b2Draw::DrawParticles(const b2Vec2 *,float,const b2ParticleColor *,int32)': is abstract
P:\Compilados\x32-x64\TRABAJO_MSVC2019_x64\box2d-liquidfun-rebase\include\box2d\b2_draw.h(91): note: see declaration of 'b2Draw::DrawParticles'
P:\Compilados\x32-x64\TRABAJO_MSVC2019_x64\box2d-liquidfun-rebase\testbed\draw.cpp(32): error C2259: 'DebugDraw': cannot instantiate abstract class
P:\Compilados\x32-x64\TRABAJO_MSVC2019_x64\box2d-liquidfun-rebase\testbed\draw.h(61): note: see declaration of 'DebugDraw'
P:\Compilados\x32-x64\TRABAJO_MSVC2019_x64\box2d-liquidfun-rebase\testbed\draw.cpp(32): note: due to following members:
P:\Compilados\x32-x64\TRABAJO_MSVC2019_x64\box2d-liquidfun-rebase\testbed\draw.cpp(32): note: 'void b2Draw::DrawParticles(const b2Vec2 *,float,const b2ParticleColor *,int32)': is abstract
P:\Compilados\x32-x64\TRABAJO_MSVC2019_x64\box2d-liquidfun-rebase\include\box2d\b2_draw.h(91): note: see declaration of 'b2Draw::DrawParticles'
NMAKE : fatal error U1077: 'P:\Desarrollo\cmake\bin\cmake.exe' : return code '0x2'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.29.30133\bin\HostX64\x64\nmake.exe"' : return code '0x2'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.29.30133\bin\HostX64\x64\nmake.exe"' : return code '0x2'
Stop.

I would like to ask you about the experience with your rebase, does it work correctly, has it met your expectations, has it been stable?

I am surprised that this interesting contribution has not had more projection.

Thanks again!

DJuego

'box2d/b2_voronoi_diagram.h' file not found

Hello

First of all thanks for this amazing library!

I recently switched to node 18 (lts) and I've noticed that my jest tests (which are using box2d-wasm) are leaking memory (just by importing the module via the factory).

For that reason I thought to rebuild the library locally and re-test.

I'm able to build the "Box2D" version of it but when I switch to liquidfun branch I get this error when building it:
'box2d/b2_voronoi_diagram.h' file not found

Any ideas?

C++ Version of LiquidFun integration?

This seems to be the only attempt to re-merge LiquidFun into the latest box2d, but it seems to build a final wasm, rather than generating source files for inclusion in a project. Would you know if there is a way to get updated sources for integration in a C++ project?

Node errors

Hi!

Not sure this is an issue with your package or something wrong with my setup.

I'm using your package on the server, initialising it like so:

import Box2DFactory from 'box2d-wasm'

// then inside a singleton class:
this.b2 = await Box2DFactory()

This has an impact on how Node displays runtime errors. For example, here is the output I get if there's a type error (not related to box2d):

TypeError: Cannot read property 'graceTime' of undefined
/Users/gonipeles/Desktop/sc/game/scorecraft/node_modules/box2d-wasm/dist/umd/Box2D.js:12
q){e?d(e):c(q.buffer)})},1<process.argv.length&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function(b){throw b;}),process.on("unhandledRejection",oa),a.inspect=function(){return"[Emscripten Module object]"};else if(ea||ha)ha?ia=self.location.href:"undefined"!==typeof document&&document.currentScript&&(ia=document.currentScript.src),_scriptDir&&(ia=_scriptDir),ia=0!==ia.indexOf("blob:")?ia.substr(0,ia.lastIndexOf("/")+1):"",ja=function(b){var c=new XMLHttpRequest;
                                                                                                                                                    ^

RuntimeError: abort(TypeError: Cannot read property 'graceTime' of undefined). Build with -s ASSERTIONS=1 for more info.
    at process.oa (/Users/gonipeles/Desktop/sc/game/scorecraft/node_modules/box2d-wasm/dist/umd/Box2D.js:16:62)
    at process.emit (events.js:315:20)
    at processPromiseRejections (internal/process/promises.js:245:33)
    at processTicksAndRejections (internal/process/task_queues.js:94:32)

The issue is that the actual file name and line number are not displayed.

If I comment out this.b2 = await Box2DFactory(), then the output is the following:

(node:18501) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'graceTime' of undefined
    at new WhacGame (webpack://scorecraft/./src/server/games/inner/Whac/WhacGame.ts?:45:41)
    at StandaloneInnerGame.eval (webpack://scorecraft/./src/server/games/outer/StandaloneInner/StandaloneInnerGame.ts?:95:42)
    at step (webpack://scorecraft/./src/server/games/outer/StandaloneInner/StandaloneInnerGame.ts?:66:23)
    at Object.eval [as next] (webpack://scorecraft/./src/server/games/outer/StandaloneInner/StandaloneInnerGame.ts?:47:53)
    at fulfilled (webpack://scorecraft/./src/server/games/outer/StandaloneInner/StandaloneInnerGame.ts?:38:58)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:18501) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:18501) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Any ideas for how to solve this?

how to get bounds?

how to get bounds? Upper left and upper right coordinates calculate it yourself?

How to use b2ContactListener in box2d-wasm

I want to try to rewrite my Pong game from @box2d/core to box2d-wasm because I was stuck with the issue: Lusito/box2d.ts#42

These is no any examples in docs about b2ContactListener. How to rewrite the code below from @box2d/core to box2d-wasm:

contact-listener.js

import { b2ContactListener, b2Vec2 } from "@box2d/core";

export default class ContactListener extends b2ContactListener {

    constructor() {
        super();
    }

    BeginContact(contact) {
        console.log("ok");
    }
}

index.js

import ContactListener from "./contact-listener.js";

const contactListener = new ContactListener();
world.SetContactListener(contactListener);

Working Demo?

Hey, I am trying to get your version of Box2D running.

But I am not clear of the scope of the project and the included Demo does not seem to run out of the box (on a local apache webserver).

Basically, what I want, is to upgrade my old javascript port of box2d (box2dweb) to the more efficient Box2D libary in wasm, but I do not really want to dug deep into the compile chain (or rather touch it not at all at the moment).

I want to achieve setting up a simple box2d world, which I can manipulate with javascript live in the console. (And then I can port my old work step by step)

So can you clarify, whether I am at the right place, to achieve this with reasonable amount of time? (you seem to focus on ts?) Or should I rather go with https://github.com/kripken/box2d.js ?

DestroyBody / recycled bodies

I got very strange bugs, which I tracked down to the fact, that apparently Box2D in general or just this port via emscripten does recycle bodies. (but I never had this issue with the port from actionscript)

Meaning, unlike I thought

const bd = new b2BodyDef();
const body = world.CreateBody(bd);

does not necessarily gives you a fresh new body.
If you removed bodies before with

world.DestroyBody(body)

and those bodies had some custom set properties, those old properties are still there, when objects gets recycled!
(Which in my case led to bullets behaving like enemies for example)
This also means big memory leaks.

So the solution for me was to iterate through each ownproperty before destroying bodies and removing every custom property.

for (var i in body){
 // Su is the pointer, which we want to keep
 if(body.hasOwnProperty(i) && i != "Su"){
    delete body[i]
 }
}
world.DestroyBody(body)

I believe this should go to the docs ...

liquidfun's GetPositionBuffer() doesn't return a list

I try to use liquid fun. GetPositionBuffer doesn't return a list:

    const positions = particleSystem.GetPositionBuffer();
    console.log(positions[0]);

I prints undefined.

But it must return a list because C++ works like this:

    b2Vec2 *pos = m_particleSystem->GetPositionBuffer();
    qDebug() << pos[0].x  << pos[0].y;

Full example that includes the liquid fun lib library: get-position-buffer-box2dwasm-js.zip

index.js

import { box2d, initBox2D } from "./init-box2d.js";

async function init() {
    await initBox2D();

    const {
        b2CircleShape,
        b2ParticleGroupDef,
        b2ParticleSystemDef,
        b2Vec2,
        b2World
    } = box2d;

    const world = new b2World();
    const pixelsPerMeter = 50;

    const particleSystemDef = new b2ParticleSystemDef();
    particleSystemDef.radius = 5 / pixelsPerMeter;
    const particleSystem = world.CreateParticleSystem(particleSystemDef);
    const spawnArea = new b2CircleShape();
    spawnArea.m_radius = 20 / pixelsPerMeter;
    spawnArea.m_p.x = 100 / pixelsPerMeter;
    spawnArea.m_p.y = 30 / pixelsPerMeter;
    const particleGroupDefinition = new b2ParticleGroupDef();
    particleGroupDefinition.shape = spawnArea;
    particleSystem.CreateParticleGroup(particleGroupDefinition);

    const positions = particleSystem.GetPositionBuffer();
    console.log(positions[0].x);
}

init();

index.html

<!DOCTYPE html>

<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Liquid fun</title>
</head>

<body>
    <script type="importmap">
        {
            "imports": {
                "box2d-wasm": "/libs/[email protected]/es/entry.js"
            }
        }
    </script>

    <script type="module" src="./js/index.js"></script>
</body>

</html>

Liquidfun ParticleGroup shapes array

Hi. Thanks for amazing Box2D wasm port!
I'm curious if it possible to iterate through b2ParticleGroupDef.shapes array?
I think multiple shapes is important feature in Liquidfun when you need complex elastic shape for example.

I found this lines in Box2D.idl file :

// can't bind to const b2Shape* const* shapes;
// [Const] attribute b2Shape shapes;

For example we have b2PolygonShape#get_m_vertices(index?: number) and b2PolygonShape#set_m_vertices(index: number, m_vertices_elem: b2Vec2) to work with multiple polygon vertices.

vue2.0 run wrong

`Failed to compile.

./node_modules/box2d-wasm/dist/es/Box2D.simd.js
Module parse failed: Unexpected token (3:25)
You may need an appropriate loader to handle this file type.
|
| var Box2D = (function() {
| var _scriptDir = import.meta.url;
|
| return (
@ ./node_modules/box2d-wasm/dist/es/entry.js 25:8-33
@ ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/pages/index.vue
@ ./src/pages/index.vue
@ ./src/router/index.js
@ ./src/main.js
@ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/main.js`

How to instantiate b2RayCastInput class

Hello,

I need to create an instance of the b2RayCastInput class like in the tutorial: https://www.iforce2d.net/b2dtut/raycasting

      //set up input
      b2RayCastInput input;
      input.p1 = p1;
      input.p2 = p2;
      input.maxFraction = 1;

I try to do like this: https://plnkr.co/edit/vwQsOkQrbx8y8l5m

    const {
        b2_dynamicBody,
        b2BodyDef,
        b2PolygonShape,
        b2RayCastInput,
        b2Vec2,
        b2World
    } = box2d;

    const input = new b2RayCastInput();

But I have this error: cannot construct a b2RayCastInput, no constructor in IDL

Can't instantiate packages

I am trying to follow instructions from README.dev.md, but after running pnpm --filter=webidl-to-ts build, I get the error:

src/codegen.ts:994:13 - error TS2345: Argument of type 'NodeArray<ModifierLike>' is not assignable to parameter of type 'readonly Modifier[]'.
  The types returned by 'concat(...)' are incompatible between these types.
    Type 'ModifierLike[]' is not assignable to type 'Modifier[]'.
      Type 'ModifierLike' is not assignable to type 'Modifier'.
        Type 'Decorator' is not assignable to type 'Modifier'.
          Type 'Decorator' is not assignable to type 'StaticKeyword'.
            Types of property 'kind' are incompatible.
              Type 'SyntaxKind.Decorator' is not assignable to type 'SyntaxKind.StaticKeyword'.

994             node.modifiers,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.