Code Monkey home page Code Monkey logo

three-to-cannon's Introduction

three-to-cannon

Latest NPM release npm bundle size License Build Status Coverage

Convert a THREE.Mesh or THREE.Object3D to a CANNON.Shape, with optimizations to simplified bounding shapes (AABB, sphere, etc.).

API

Installation:

npm install --save three-to-cannon

Use:

/****************************************
 * Import:
 */

// ES6
import { threeToCannon, ShapeType } from 'three-to-cannon';

// CommonJS
const { threeToCannon, ShapeType } = require('three-to-cannon');

/****************************************
 * Generate a CANNON.Shape:
 */

// Automatic (Usually an AABB, except obvious cases like THREE.SphereGeometry).
const result = threeToCannon(object3D);

// Bounding box (AABB).
const result = threeToCannon(object3D, {type: ShapeType.BOX});

// Bounding sphere.
const result = threeToCannon(object3D, {type: ShapeType.SPHERE});

// Cylinder.
const result = threeToCannon(object3D, {type: ShapeType.CYLINDER});

// Convex hull. 
const result = threeToCannon(object3D, {type: ShapeType.HULL});

// Mesh (Not recommended — limitations: https://github.com/pmndrs/cannon-es/issues/21).
const result = threeToCannon(object3D, {type: ShapeType.MESH});

/****************************************
 * Using the result:
 */

// Result object includes a CANNON.Shape instance, and (optional)
// an offset or quaternion for that shape.
const {shape, offset, orientation} = result;

// Add the shape to a CANNON.Body.
body.addShape(shape, offset, orientation);

See further documentation on the CANNON.Shape class.

three-to-cannon's People

Contributors

arpu avatar dependabot[bot] avatar donmccurdy avatar eriksom avatar isaac-mason avatar kschzt avatar mignonbelongie avatar mqp avatar ngokevin avatar renovate-bot avatar renovate[bot] 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  avatar  avatar  avatar  avatar  avatar

three-to-cannon's Issues

Remove dist/ folder

Including the dist/ folder in source control is a regular source of confusion for new contributors, because the files are modified when building or testing changes, but shouldn't be included in PRs. These files cannot be reviewed easily, and are meant to be rebuilt by an author when publishing a new release. To avoid this confusion, the dist/ folder should be added to .gitignore and explicitly added to the published files in package.json. Because it's published to NPM, it will still be available from CDNs like Unpkg.

Uncaught TypeError: shape.calculateWorldAABB is not a function

The project is throwing this error when attempting to use:

cannon-es.js:3679 Uncaught TypeError: shape.calculateWorldAABB is not a function
at Body.updateAABB (cannon-es.js:3679:13)
at Body.updateMassProperties (cannon-es.js:3856:10)
at Body.addShape (cannon-es.js:3602:10)
at new Body (cannon-es.js:3455:12)
at main.js?t=1649830614683:225:20

Here is the code:

let custom = await loadFile(".glb", "./models/custom-``collider.glb");
const customShape = threeToCannon(custom.scene);
scene.add(custom.scene);

const customBody = new CANNON.Body({
mass: 1,
position: new CANNON.Vec3(0, 0, 0),
shape: customShape,
material: defaultMaterial,
});

customBody.position.copy(custom.position);
world.addBody(customBody);

I've attempted a few things to no avail!

The createConvexPolyhedron function returns cannon shape without faces.

The shape returned has both vertices and facenormals but not the faces, and with the help of CannonDebugRenderer I can confirm that the shape itself is correct. However, whenever a collision occurs between the player(A cannon box) and the convexPolyhedron, an error occurs: "Cannot read property 'length' of undefined at ConvexPolyhedron.clipAgainstHull (cannon-es.js:2347)". After looking at the cannon-es code I can see that it is trying to access the length of the faces array, which is undefined!

I've tried many different solutions to this. Using the ConvexHull method I can get faces and vertices but they are of THREE.Face and THREE.Vector3 respectively and CANNON wants simple arrays of which vertices to use. Further, I've tried to convert the vertices to Vec3, which worked, but figuring out how to create the face arrays was very tricky. In the end it gave me a bunch of errors since the vertices were not ordered correctly, CCW right hand rule and all that.

Either way there might be a bug with the createConvexPolyhedron function or im simply not using it correctly. Would be glad to get some feedback!

Unhandled Promise Rejection: TypeError: i.calculateWorldAABB is not a function. (In 'i.calculateWorldAABB(o,n,l.lowerBound,l.upperBound)', 'i.calculateWorldAABB' is undefined)

let loader = new GLTFLoader();

// Load a glb model
loader.load('models/chernovan_nemesis.glb', function (gltf) {

  // Get the model and its animations
  let model = gltf.scene;
  let animations = gltf.animations;
  console.log(gltf, model);
  // Add the model to the scene
  scene.add(model);

  // Get the geometry of the model
  let object3D = gltf.scene.children[0];
  console.log(object3D);

  const shape = threeToCannon(object3D, { type: ShapeType.BOX });
  let body = new CANNON.Body({ mass: 1, shape: shape });

  // Add the body to the world
  world.addBody(body);

object3D is indeed a valid Object3D. What is the problem here? I am using the latest versions of Cannon-es and Three.js.
Why won't it work?
Screenshot 2023-10-28 at 9 39 12 PM

Physics simulation stops when generated convex hulls collide

It looks like there may be some issues with generated convex hulls. When two bodies with generated convex hull shapes collide, the physics simulation stops and the page becomes unresponsive.

I made a simple codesandbox demonstrating the issue: https://codesandbox.io/s/repro-three-to-cannon-hull-collision-issue-68jtcd?file=/src/index.ts

I haven't checked what versions have the issue, but it appears to at least be present in 4.0.2, predating the introduction of the getShapeParameters function. The issue may be somewhere in ConvexHull.js?

getVertices() has a bug that causes trimesh issue

The getVertices function is incorrectly accessing the geometry vertex positions.

Current function
export function getVertices (geometry: BufferGeometry): Float32Array {
const position = geometry.attributes.position;
const vertices = new Float32Array(position.count * 3);
for (let i = 0; i < position.count; i += 3) {
vertices[i] = position.getX(i);
vertices[i + 1] = position.getY(i);
vertices[i + 2] = position.getZ(i);
}
return vertices;
}

Easily fixed as follows:
export function getVertices (geometry: BufferGeometry): Float32Array {
const position = geometry.attributes.position;
const vertices = new Float32Array(position.count * 3);
for (let i = 0; i < position.count; i++) {
vertices[i3] = position.getX(i);
vertices[i
3 + 1] = position.getY(i);
vertices[i*3 + 2] = position.getZ(i);
}
return vertices;
}

Can't compile aframe-physics-system with three-to-cannon 3.0.2

I'm having trouble figuring out how to use the latest three-to-cannon in aframe-physics-system. There's some discussion in n5ro/aframe-physics-system#172, but that might be more than you want to read, so I'll summarize here.

When I ran

browserify index.js -o bundle.js

after updating three-to-cannon to 3.0.2, I got the following error:

Error: Cannot find module 'three' from 'D:\src\aframe-physics-system\node_modules\three-to-cannon\dist'

So I added three as a dependency. Then browserify succeeded, and everything worked when I loaded bundle.js in the browser, e.g. in examples/cannon.html. What I didn't notice at first was that all of three.js was included in bundle.js, which was therefore huge. If I exclude three, i.e.

browserify -x three index.js  -o bundle.js

then I get a small bundle, but I get an error in the browser:

Uncaught Error: Cannot find module 'three'
	at o (bundle.js:1)
	at bundle.js:1
	at Object.6.cannon-es (bundle.js:14226)
	at o (bundle.js:1)
	at bundle.js:1
	at Object.10.../../../lib/CANNON-shape2mesh (bundle.js:14980)
	at o (bundle.js:1)
	at bundle.js:1
	at Object.1../src/components/ammo-constraint (bundle.js:6)
	at o (bundle.js:1)

If I manually replace t=require("three") with t=THREE in bundle.js, then everything is great. To try to achieve that result, I tried using exposify or browserify-shim, which seem designed for this. Unfortunately, they seem to have no effect on require statements in required packages, specifically the require("three") in three-to-cannon.js.

I also tried making three a peer dependency instead of a regular dependency, but still no luck. For example, I tried the following in package.json:

"scripts": {
  ...
  "dist2": "browserify index.js -o bundle.js",
  ...
},
"browserify": {
  "transform": [
    "browserify-shim"
  ]
},
"browserify-shim": {
  "three": "global:THREE"
},
"dependencies": {
  "ammo-debug-drawer": "^0.1.0",
  "cannon-es": "^0.9.1",
  "three-to-ammo": "^0.1.0",
  "three-to-cannon": "^3.0.2",
  "webworkify": "^1.4.0"
},
"peerDependencies": {
  "aframe": ">=0.5.0",
  "three": "^0.115.0"
},

Can you help me figure out how to compile aframe-physics-system with three-to-cannon 3.0.2?

Hull has no vertices

Libs:
three-to-cannon: ^3.0.0
three: ^0.116.1

I had a question, whenever I create a Hull via the framework it returns a ConvexPolyhedron with 0 vertices.
I'm using the following code to generate a capsule object.

export const spawnCapsule = (target, _props)=>{
    if(!target) target = scene;
    const props = Object.assign({
        geometry:[5, 5, 5],
        material:{color:0xff0000, side: DoubleSide},
        position: [0, 0, 0],
        rotation: [0, 0, 0],
        collisionObject:true,
    }, (_props || {}))

    const segments = 32;

    const geometry = new CylinderGeometry( props.geometry[0], props.geometry[0], props.geometry[1], segments );
    const material = new MeshBasicMaterial( {color: 0xffff00} );

    [-1, 1].forEach(offset => {
        const sphereGeom = new SphereGeometry( props.geometry[0], segments, segments );
        const sphere = new Mesh( sphereGeom, material );
        sphere.position.set(0, (props.geometry[1]/2)*offset, 0);
        // sphere.updateMatrix();
        geometry.mergeMesh(sphere);
    });

    const mesh = new Mesh( geometry, material );

    mesh.position.copy(new Vector3(...props.position));
    mesh.rotation.setFromVector3(new Vector3(...props.rotation));
    if(props.collisionObject) collisionObjects.push(mesh);
    target.add( mesh );
    physics.addAutoConvertMesh( mesh, 1, physics.autoConvertType.HULL );
    return mesh;
}

The function physics.addAutoConvertMesh looks as follows:

    function addAutoConvertMesh(mesh, mass, type){
        const shape = threeToCannon(mesh, {type});
        handleMesh( mesh, mass, shape )
    }

Now it works perfectly if I use the type 'Mesh', but when i use Hull, the object falls through the floor and I can see that the ConvexPolyhedron has no vertices:

image

What am I missing here? Would be great if anyone could point me in the right direction.

Throws Uncaught error on usage.

I use the most up to date version of the package with up to date peer dependencies. During usage:

 const shape = threeToCannon(trackMesh, { type: threeToCannon.Type.BOX });

an error is thrown:

index.js:292 Uncaught (in promise) TypeError: _three.Geometry is not a constructor
    at B (index.js:292)
    at index.js:260
    at Object.E [as threeToCannon] (index.js:256)

The trackmesh variable is a glt loaded file. I cannot get around this issue except if I use the

{ type: threeToCannon.Type.BOX }

option.
Yet this box creates an unusable physics object for our purposes.

A mistake in the Readme ?

const {shape, offset, quaternion} = result; body.addShape(shape, offset, orientation);

quaternion and orientation ?

Missing dependency version

When installing (this package directly or aframe-extras), I get a:
No compatible version found: cannon@'github:donmccurdy/cannon.js#v0.6.2-dev1'

"points is not defined" HULL type error

Hi!
I get this error while trying to use the HULL type.

image

I can't pretty-print the file, and when I looked for ".points" in the error file, but couldn't find anything like that.

My code goes like this:

import { threeToCannon } from 'three-to-cannon';

const object = new THREE.Mesh(new THREE.BoxGeometry(10, 10, 10));
const shape = threeToCannon(object, {type: threeToCannon.Type.HULL});

I ran it on THREE r92 and r99 but the error is in both versions. Any idea what I've done wrong?
Thanks.

three-to-cannon v4

Proposed breaking changes for v4:

  • Port to TypeScript (not strictly a breaking change, but risky)
  • Use only BufferGeometry internally
  • Don't use .metadata
  • Lint pass on the codebase
  • Don't add .offset, and .quaternion properties to shapes; return them (breaking)
  • Support Geometry->BufferGeometry conversion internally if feasible
  • More unit tests
  • Update documentation

The usage will change a bit with the 4th point:

// Before
const shape = threeToCannon(object);
const {offset, quaternion} = shape;

// After
const { shape, offset, quaternion } = threeToCannon(object);

TypeScript support

Thanks for this very useful library! Would it be possible to export typescript definitions? Thank you!

npm install failed

(base) CN3114000452M:AframeThreeTs weihao$ npm install --save three-to-cannon
npm ERR! code 128
npm ERR! An unknown git error occurred
npm ERR! command git --no-replace-objects ls-remote ssh://[email protected]/donmccurdy/cannon.js.git
npm ERR! [email protected]: Permission denied (publickey).

What is the file that I have to import?

Hello, sorry for this newbie question, but, after installing the library I try to import it in my client.js (im using express and made sure that three-to-cannon folder was being served) as you showed in the readme.md and it gives me a 404 error not found, so, what is the file that I have to export exactly? Because apparently thats the only way imports work in my app.

Error creating box with a THREE.Audio in the tree

Unfortunately, it doesn't seem to be safe to call clone on an arbitrary three.js Object3D. As a result, creating a box shape fails if you try to create it on an object hierarchy that includes somewhere in it an Audio or PositionalAudio Object3D. For example, in a browser:

const listener = new THREE.AudioListener();
const object = new THREE.Mesh(new THREE.BoxGeometry(10, 10, 10));
object.children.push(new THREE.Audio(listener));

// fails
const box = mesh2shape(object, { type: mesh2shape.Type.BOX });

will result in

TypeError: listener is undefined three.js:39118
	Audio three.js:39118
	clone three.js:8636
	copy three.js:8674
	clone three.js:8636
	createBoundingBoxShape index.js:104
	mesh2shape index.js:25

This regressed recently with this commit: 0c7bc98

I don't know enough about three.js conventions to say whether three or this library is the one that is "wrong". One possible fix would be to write the bounding box creation code in question directly in terms of the matrices involved instead of calling clone, but it looks like that would be mostly duplicating a lot of code from Box3.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined

THREE is not defined

When I import the package as an ES6 module
import { threeToCannon } from 'three-to-cannon';

I get a THREE is not defined error

In source THREE is never imported - how is the library supposed to be linked?

Cannot read property 'x' of undefined

dice
Uncaught TypeError: Cannot read property 'x' of undefined at Vec3.copy (cannon-es.js:915) at ConvexPolyhedron.clipFaceAgainstHull (cannon-es.js:2593) at ConvexPolyhedron.clipAgainstHull (cannon-es.js:2335) at Narrowphase.convexConvex (cannon-es.js:11067) at Narrowphase.getContacts (cannon-es.js:10759) at World.internalStep (cannon-es.js:12774) at World.step (cannon-es.js:12650) at animate (index.js:149)

I've been getting this error when two bodies with the hull settings collide with each other. My knowledge about geometries is pretty low, so I don't really understand what is happening. I found this (schteppe/cannon.js#459) in the CannonJS issues tab, might be useful.

Any help would be greatly appreciated!

Dependency Dashboard

This issue provides visibility into Renovate updates and their statuses. Learn more

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.


  • Check this box to trigger a request for Renovate to run again on this repository

Use with common js (no node.js)?

How do I use this library if I do not want to use node.js?
I'm using Three.js and cannon-es as modules from my local directory

Sorry, I know this is the wrong place to ask this.

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.