Distorted mesh when rotating group in Three.JS - javascript

Bit of context, I have two skinned meshes with the same bone structure that over lap each other. The difference between these two meshes is what they have attached to them and where. For the purpose of this question I will be referring to the body and hand skinned meshes.
I am trying to rotate both the body forearm and hand forearm at the same time and in the same direction. I have added both to the group leftforearmgroup which is a child group. The group structure present is bodygroup > leftclaviclegroup > leftarmgroup > leftforearmgroup.
The issue I am running into is when I attempt to rotate the leftforearmgroup it distorts as shown in the image below. The other image shows how it should behave, this is achieved by attaching the control directly to the body forearm which won't control the hand forearm sadly. Every other group when rotated via TransformControl behaves as expected.
distorted mesh when rotating
correct mesh behavior
So my question is how do I fix the mesh from being distorted when rotating?
Code:
const headaccgroup = new THREE.Group();
headaccgroup.position.set(0, -15, 0);
headaccgroup.rotateY(THREE.Math.degToRad(180));
const headgroup = new THREE.Group();
headgroup.scale.set(1, 1, 1);
headgroup.position.set(0, 0.38, 0.028);
headgroup.rotateY(THREE.Math.degToRad(0));
const bodygroup = new THREE.Group();
bodygroup.rotateY(THREE.Math.degToRad(180));
const leftclavgroup = new THREE.Group();
leftclavgroup.scale.set(1, 1, 1);
leftclavgroup.position.set(-0.055, -0.055, 40);
leftclavgroup.rotateY(THREE.Math.degToRad(0));
const leftarmgroup = new THREE.Group();
leftarmgroup.scale.set(1, 1, 1);
leftarmgroup.position.set(-0.055, -0.055, 0);
leftarmgroup.rotateY(THREE.Math.degToRad(180));
const leftforearmgroup = new THREE.Group();
leftforearmgroup.scale.set(1, 1, 1);
leftforearmgroup.position.set(0,0,0);
function loadBody(modelPath, x = 0.1, y = 0.1, z = 0.1) {
gltf_loader.load(modelPath, function (gltf) {
scene.remove(body);
body = gltf.scene;
gltf.scene.traverse(function(object) {
if(object.isMesh) object.frustumCulled = false;
});
gltf.scene.scale.set(x, y, z);
body.position.set( 0, -2, 20);
leftforearmgroup.add( body.getObjectByName('bip02_l_forearm'));
controlleftforearm.attach(leftforearmgroup);
controlleftforearm.setMode('rotate');
scene.add(controlleftforearm);
leftarmgroup.add(body.getObjectByName('bip02_l_upperarm'));
leftclavgroup.add(body.getObjectByName('bip02_l_clavicle'));
leftarmgroup.add(leftforearmgroup);
leftclavgroup.add(leftarmgroup);
bodygroup.add(leftclavgroup);
headgroup.add(body.getObjectByName('bip02_head'));
bodygroup.scale.set( 10, 10, 10);
bodygroup.add(body.getObjectByName('bip02_spine1'));
bodygroup.add(headgroup);
scene.add(body);
controlspine1.attach(bodygroup);
controlspine1.setMode('rotate');
scene.add(controlspine1);
});
}

Related

Creating three plane geometry perpendicular to x, y and z axis?

I am supposed to create three plane geometries to the scene (one perpendicular to x axis, one perpendicular to y axis and one perpendicular to z axis) that would somewhat look like this.
So, herein is my code below for the same:
public showPlaneGeometry() {
console.log(this.hScene)
const geometryx = new th.PlaneGeometry(1, 1);
const geometryy = new th.PlaneGeometry(1, 1);
const geometryz = new th.PlaneGeometry(1, 1);
const material = new th.MeshBasicMaterial({
color: 0xa6cfe2,
side: th.DoubleSide,
transparent: true,
opacity: 0.5,
depthWrite: false,
});
const planex = new th.Mesh(geometryx, material);
const planey = new th.Mesh(geometryy, material);
const planez = new th.Mesh(geometryz, material);
planex.position.set(1, 0, 0);
planey.position.set(0, 1, 0)
planez.position.set(0, 0, 1)
material.transparent = true
this.hScene.add(planex, planey, planez);
}
The output for the same is just appearing this way disappointingly:
I was wondering how do I make it look like the image I posted above? That they intersect at the centre that way and the surface meshes when added to the scene would appear at the centre intersecting point? Thank you so much for your help in advance.
You don't need to change their position, since they all should go through 0, 0, 0. However, you need to change their rotation if you want them to align along different axes.
const planeGeom = new THREE.PlaneGeometry(1, 1);
const planeMat = new THREE.MeshBasicMaterial({
color: 0xa6cfe2,
side: THREE.DoubleSide,
transparent: true,
opacity: 0.5,
depthWrite: false,
});
const planeXY = new THREE.Mesh(planeGeom, planeMat);
const planeXZ = new THREE.Mesh(planeGeom, planeMat);
const planeYZ = new THREE.Mesh(planeGeom, planeMat);
// Default plane already occupies XY plane
planeXY.rotation.set(0, 0, 0);
// Rotate around x-axis to occupy XZ plane
planeXZ.rotation.set(Math.PI / 2, 0, 0);
// Rotate around y-axis to occupy YZ plane
planeYZ.rotation.set(0, Math.PI / 2, 0);
There's also no need to create 3 different plane geometries. You can just re-use the same one 3 times.

How to raycast onto a pointcloud in ThreeJs R71

I am working in autodesk forge which includes Threejs r71 and I want to use a raycaster to detect clicks on different elements within a pointcloud.
Sample code for how to do this with ThreeJs r71 be appreciated.
Right now, I register an extension with the forge api and run the code below within it. It creates creates a pointcloud and positions the points at predetermined locations (saved within the cameraInfo array).
let geometry = new THREE.Geometry();
this.cameraInfo.forEach( function(e) {
geometry.vertices.push(e.position);
}
)
const material = new THREE.PointCloudMaterial( { size: 150, color: 0Xff0000, sizeAttenuation: true } );
this.points = new THREE.PointCloud( geometry, material );
this.scene.add(this.points);
/* Set up event listeners */
document.addEventListener('mousemove', event => {
// console.log('mouse move!');
let mouse = {
x: ( event.clientX / window.innerWidth ) * 2 - 1,
y: - ( event.clientY / window.innerHeight ) * 2 + 1
};
let raycaster = new THREE.Raycaster();
raycaster.params.PointCloud.threshold = 15;
let vector = new THREE.Vector3(mouse.x, mouse.y, 0.5).unproject(this.camera);
raycaster.ray.set(this.camera.position, vector.sub(this.camera.position).normalize());
this.scene.updateMatrixWorld();
let intersects = raycaster.intersectObject(this.points);
if (intersects.length > 0) {
const hitIndex = intersects[0].index;
const hitPoint = this.points.geometry.vertices[ hitIndex ];
console.log(hitIndex);
console.log(hitPoint);
}
}, false);
The output seems to be illogical. At certain camera positions, it will constantly tell me that it is intersecting an item in the pointcloud (regardless of where the mouse is). And at certain camera positions, it won't detect an intersection at all.
TLDR: it doesn't actually detect an intersection b/w my pointcloud and the mouse.
I've simplified the code a bit, using some of the viewer APIs (using a couple of sample points in the point cloud):
const viewer = NOP_VIEWER;
const geometry = new THREE.Geometry();
for (let i = -100; i <= 100; i += 10) {
geometry.vertices.push(new THREE.Vector3(i, i, i));
}
const material = new THREE.PointCloudMaterial({ size: 50, color: 0Xff0000, sizeAttenuation: true });
const points = new THREE.PointCloud(geometry, material);
viewer.impl.scene.add(points);
const raycaster = new THREE.Raycaster();
raycaster.params.PointCloud.threshold = 50;
document.addEventListener('mousemove', function(event) {
const ray = viewer.impl.viewportToRay(viewer.impl.clientToViewport(event.clientX, event.clientY));
raycaster.ray.set(ray.origin, ray.direction);
let intersects = raycaster.intersectObject(viewer.impl.scene, true);
if (intersects.length > 0) {
console.log(intersects[0]);
}
});
I believe you'll need to tweak the raycaster.params.PointCloud.threshold value. The ray casting logic in three.js doesn't actually intersect the point "boxes" that you see rendered on the screen. It only computes distance between the ray and the point (in the world coordinate system), and only outputs an intersection when the distance is under the threshold value. In my example I tried setting the threshold to 50, and the intersection results were somewhat better.
As a side note, if you don't necessarily need point clouds inside the scene, consider overlaying HTML elements over the 3D view instead. We're using the approach in the https://forge-digital-twin.autodesk.io demo (source) to show rich annotations attached to specific positions in the 3D space. With this approach, you don't have to worry about custom intersections - the browser handles everything for you.

Three JS Cylinder Texture Distortion

Applying a texture to a cylinder geometry in THREE JS causes some weird distortion of the texture as can be seen in this image:
The shape is created like so:
var cylinderGeo = new THREE.CylinderGeometry(0.1, 1, 1, 4, 1, false, Math.PI / 4);
cylinderGeo.computeFlatVertexNormals();
var mesh = new THREE.Mesh(cylinderGeo);
mesh.position.x = 10;
mesh.scale.set(10, 5, 10);
mesh.material = new THREE.MeshLambertMaterial();
// LOAD TEXTURE:
textureLoader.load("/textures/" + src + ".png", function (texture) {
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(2,2);
texture.needsUpdate = true;
mesh.material.map = texture;
mesh.material.needsUpdate = true;
});
The texture seems to be applied per polygon and not per face? How can i make it wrap around the cylinder without any such artifacts?
EDIT: The texture is 256x256
Each side of your pyramid is composed of two triangles. You can see this quite clearly in the example on the CylinderGeometry documentation page.
Each triangle has UVs which are created based on the assumption that both triangles will be the same scale, like they are in the example. By making one end of your cylinder smaller, you're changing the scale of the triangles, but your UVs are remaining the same.
You can either edit the UVs to make up for the difference, or (and I recommend) create your own geometry with proper UVs defined.

Calculating individual spheres position to create a sphere made of spheres

I'm trying to re-create an atom with THREE.js, and I'm running into my first issue - since every type of atom has a different amount of Protons/Neutrons, I'm trying to find a way to position them automatically so that there is no collisions, and so the final result of them all together will make something as close to a sphere as possible - see this image for an example
(source: alternativephysics.org)
.
Is there a way to calculate this and assign each Neutron/Protons position easily with a formula? Or will I have to get a physics engine involved to just squeeze the spheres together and hope for the best result with each run?
I don't have any code on this yet, since I'm just trying to figure out where to start with this part.
EDIT
I should also note, that I want the spheres to be squished together within the space of the larger sphere. I am NOT trying to just make all the spheres go on the radius of the larger sphere.
EDIT 2
I looked into using a physics engine to squish them all into a small area, but I can't find an engine that will allow me to move all of the objects in my scene to position (0,0,0) with a gravitational force. All of the engines just make gravity push down on an object. I'd still rather use a formula for positioning the spheres, rather than include an entire physics engine into my project.
EDIT 3, 04/06/06
I've done a bit of experimenting, but I still can't get it right. Here's what it looks like now:
But as you can see, looks really off. This is what happens when I make a Uranium atom instead of a Carbon one (more protons/neutrons/electrons)
It might just be me, but that's looking more like some fancy ratatouille than a Uranium atom.
How I got here:
I was attempting to make what I was looking for up above, and here's the premise:
(particleObject is the parent of particle, the particle will move relative to this object)
I added all protons and neutrons lengths together, so that I could
loop through them all.
If the added number % 2 == 0, (which it is for my testing) I would set the rotate to (pi * 2) / 2 <- last two being there to represent the two above.
Every iteration I would increment l variable. (hopefully) whenever i would equal the loopcount variable, it would mean that I've placed sphere's around in a sphere shape. I'd then multiply loopcount by 3 to find out how many sphere's would be needed for the next run. I'd set l to 0 so that the sphere's positioning would be reset, and the loop would be incremented, causing the next row of sphere's to be placed 1 unit out on the x axis.
(Sorry for the terminology here, it's very hard to explain. See code.)
var PNamount = atomTypes[type].protons + atomTypes[type].neutrons;
var loopcount = 1;
if(PNamount % 2 == 0) {
var rotate = (PI * 2) / 2;
loopcount = 2;
}
var neutrons = 0,
protons = 0,
loop = 1,
l = 0;
for(var i = 0; i < PNamount; i++) {
if(i == loopcount){
loopcount = loopcount * 3;
loop++;
rotate = (PI * 2) / loopcount;
l = 0;
} else {
l++;
}
particleObject.rotation.x = rotate * l;
particleObject.rotation.y = rotate * l;
particleObject.rotation.z = rotate * l;
particle.position.x = loop;
}
Honestly, I'm not that great at all with 3D math. So any help would be really helpful. Plus, it's very possible that my method of positioning them is absolutely wrong in every way. Thanks!
You can see the code live here.
I would definitely say that this is a perfect use case of a physics engine. Making this simulation without a physics engine sounds like a real hassle, so "including an entire physics engine" doesn't seam like such a big cost to me. Most of the JavaScript physics engines that i've found are leight weight anyway. It will however demand some extra CPU power for the physics calculations!
I sat down and tried to create something similar to what you describe with the physics engine CANNON.js. It was quite easy to get a basic simulation working, but to get the parameters just right took is what seems a bit tricky, and will need more adjusting.
You mentioned that you tried this already but couldn't get the particles to gravitate towards a point, with CANNON.js (and probably most other physic engines) this can be achieved be applying a force to the object in the negative position direction:
function pullOrigin(body){
body.force.set(
-body.position.x,
-body.position.y,
-body.position.z
);
}
It is also easy to achieve behaviours where bodies are pulled towards a certain parent object, which in its turn is pull towards the average position of all other parent objects. This way you can create whole molecules.
One tricky thing was to let the electrons circulate the protons and neutrons at a distance. To achieve this I give them a slight force towards the origin, and then a slight force away from all the protons and neutrons at the same time. On top of that I also give them a small push sideways in the beginning of the simulation so that they start circulating the center.
Please let me know if you want me to clarify any particular part.
let scene = new THREE.Scene();
let world = new CANNON.World();
world.broadphase = new CANNON.NaiveBroadphase();
world.solver.iterations = 5;
let camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
let renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
function Proton(){
let radius = 1;
return {
// Cannon
body: new CANNON.Body({
mass: 1, // kg
position: randomPosition(6),
shape: new CANNON.Sphere(radius)
}),
// THREE
mesh: new THREE.Mesh(
new THREE.SphereGeometry( radius, 32, 32 ),
new THREE.MeshPhongMaterial( { color: 0xdd5555, specular: 0x999999, shininess: 13} )
)
}
}
function Neutron(){
let radius = 1;
return {
// Cannon
body: new CANNON.Body({
mass: 1, // kg
position: randomPosition(6),
shape: new CANNON.Sphere(radius)
}),
// THREE
mesh: new THREE.Mesh(
new THREE.SphereGeometry( radius, 32, 32 ),
new THREE.MeshPhongMaterial( { color: 0x55dddd, specular: 0x999999, shininess: 13} )
)
}
}
function Electron(){
let radius = 0.2;
return {
// Cannon
body: new CANNON.Body({
mass: 0.5, // kg
position: randomPosition(10),
shape: new CANNON.Sphere(radius)
}),
// THREE
mesh: new THREE.Mesh(
new THREE.SphereGeometry( radius, 32, 32 ),
new THREE.MeshPhongMaterial( { color: 0xdddd55, specular: 0x999999, shininess: 13} )
)
}
}
function randomPosition(outerRadius){
let x = (2 * Math.random() - 1 ) * outerRadius,
y = (2 * Math.random() - 1 ) * outerRadius,
z = (2 * Math.random() - 1 ) * outerRadius
return new CANNON.Vec3(x, y, z);
}
function addToWorld(object){
world.add(object.body);
scene.add(object.mesh);
}
// create our Atom
let protons = Array(5).fill(0).map( () => Proton() );
let neutrons = Array(5).fill(0).map( () => Neutron() );
let electrons = Array(15).fill(0).map( () => Electron() );
protons.forEach(addToWorld);
neutrons.forEach(addToWorld);
electrons.forEach(addToWorld);
let light = new THREE.AmbientLight( 0x202020 ); // soft white light
scene.add( light );
let directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
directionalLight.position.set( -1, 1, 1 );
scene.add( directionalLight );
camera.position.z = 18;
const timeStep = 1/60;
//Small impulse on the electrons to get them moving in the start
electrons.forEach((electron) => {
let centerDir = electron.body.position.vsub(new CANNON.Vec3(0, 0, 0));
centerDir.normalize();
let impulse = centerDir.cross(new CANNON.Vec3(0, 0, 1));
impulse.scale(2, impulse);
electron.body.applyLocalImpulse(impulse, new CANNON.Vec3(0, 0, 0));
});
function render () {
requestAnimationFrame( render );
// all particles pull towards the center
protons.forEach(pullOrigin);
neutrons.forEach(pullOrigin);
electrons.forEach(pullOrigin);
// electrons should also be pushed by protons and neutrons
electrons.forEach( (electron) => {
let pushForce = new CANNON.Vec3(0, 0, 0 );
protons.forEach((proton) => {
let f = electron.body.position.vsub(proton.body.position);
pushForce.vadd(f, pushForce);
});
neutrons.forEach((neutron) => {
let f = electron.body.position.vsub(neutron.body.position);
pushForce.vadd(f, pushForce);
});
pushForce.scale(0.07, pushForce);
electron.body.force.vadd(pushForce, electron.body.force);
})
// protons and neutrons slows down (like wind resistance)
neutrons.forEach((neutron) => resistance(neutron, 0.95));
protons.forEach((proton) => resistance(proton, 0.95));
// Electrons have a max velocity
electrons.forEach((electron) => {maxVelocity(electron, 5)});
// Step the physics world
world.step(timeStep);
// Copy coordinates from Cannon.js to Three.js
protons.forEach(updateMeshState);
neutrons.forEach(updateMeshState);
electrons.forEach(updateMeshState);
renderer.render(scene, camera);
};
function updateMeshState(object){
object.mesh.position.copy(object.body.position);
object.mesh.quaternion.copy(object.body.quaternion);
}
function pullOrigin(object){
object.body.force.set(
-object.body.position.x,
-object.body.position.y,
-object.body.position.z
);
}
function maxVelocity(object, vel){
if(object.body.velocity.length() > vel)
object.body.force.set(0, 0, 0);
}
function resistance(object, val) {
if(object.body.velocity.length() > 0)
object.body.velocity.scale(val, object.body.velocity);
}
render();
<script src="https://cdnjs.cloudflare.com/ajax/libs/cannon.js/0.6.2/cannon.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r75/three.min.js"></script>
EDIT
I have modularized the particles into a Atom object that can be retrieved from the Atom function. Also added some more comments in the code if your unsure about anything. I would advise you to really study the code, and check the CANNON.js documentation (it is really thourogh). The force related stuff is in the Body class of Cannon.js. All i've done is to combine a THREE.Mesh and a CANNON.Body into a single object (for each particle). Then I simulate all movements on the CANNON.Body, and right before I render the THREE.Mesh, I copy the positions and rotations from CANNON.Body to THREE.Mesh.
This is the Atom function (changed some of the electron physics aswell):
function Atom(nProtons, nNeutrons, nElectrons, pos = new CANNON.Vec3(0, 0, 0)){
//variable to move the atom, which att the particles will pull towards
let position = pos;
// create our Atom
let protons = Array(nProtons).fill(0).map( () => Proton() );
let neutrons = Array(nNeutrons).fill(0).map( () => Neutron() );
let electrons = Array(nElectrons).fill(0).map( () => Electron() );
// Public Functions
//=================
// add to a three.js and CANNON scene/world
function addToWorld(world, scene) {
protons.forEach((proton) => {
world.add(proton.body);
scene.add(proton.mesh);
});
neutrons.forEach((neutron) => {
world.add(neutron.body);
scene.add(neutron.mesh);
});
electrons.forEach((electron) => {
world.add(electron.body);
scene.add(electron.mesh);
});
}
function simulate() {
protons.forEach(pullParticle);
neutrons.forEach(pullParticle);
//pull electrons if they are further than 5 away
electrons.forEach((electron) => { pullParticle(electron, 5) });
//push electrons if they are closer than 6 away
electrons.forEach((electron) => { pushParticle(electron, 6) });
// give the particles some friction/wind resistance
//electrons.forEach((electron) => resistance(electron, 0.95));
neutrons.forEach((neutron) => resistance(neutron, 0.95));
protons.forEach((proton) => resistance(proton, 0.95));
}
function electronStartingVelocity(vel) {
electrons.forEach((electron) => {
let centerDir = electron.body.position.vsub(position);
centerDir.normalize();
let impulse = centerDir.cross(new CANNON.Vec3(0, 0, 1));
impulse.scale(vel, impulse);
electron.body.applyLocalImpulse(impulse, new CANNON.Vec3(0, 0, 0));
});
}
// Should be called after CANNON has simulated a frame and before THREE renders.
function updateAtomMeshState(){
protons.forEach(updateMeshState);
neutrons.forEach(updateMeshState);
electrons.forEach(updateMeshState);
}
// Private Functions
// =================
// pull a particale towards the atom position (if it is more than distance away)
function pullParticle(particle, distance = 0){
// if particle is close enough, dont pull more
if(particle.body.position.distanceTo(position) < distance)
return false;
//create vector pointing from particle to atom position
let pullForce = position.vsub(particle.body.position);
// same as: particle.body.force = particle.body.force.vadd(pullForce)
particle.body.force.vadd( // add particle force
pullForce, // to pullForce
particle.body.force); // and put it in particle force
}
// Push a particle from the atom position (if it is less than distance away)
function pushParticle(particle, distance = 0){
// if particle is far enough, dont push more
if(particle.body.position.distanceTo(position) > distance)
return false;
//create vector pointing from particle to atom position
let pushForce = particle.body.position.vsub(position);
particle.body.force.vadd( // add particle force
pushForce, // to pushForce
particle.body.force); // and put it in particle force
}
// give a partile some friction
function resistance(particle, val) {
if(particle.body.velocity.length() > 0)
particle.body.velocity.scale(val, particle.body.velocity);
}
// Call this on a particle if you want to limit its velocity
function limitVelocity(particle, vel){
if(particle.body.velocity.length() > vel)
particle.body.force.set(0, 0, 0);
}
// copy ratation and position from CANNON to THREE
function updateMeshState(particle){
particle.mesh.position.copy(particle.body.position);
particle.mesh.quaternion.copy(particle.body.quaternion);
}
// public API
return {
"simulate": simulate,
"electrons": electrons,
"neutrons": neutrons,
"protons": protons,
"position": position,
"updateAtomMeshState": updateAtomMeshState,
"electronStartingVelocity": electronStartingVelocity,
"addToWorld": addToWorld
}
}
function Proton(){
let radius = 1;
return {
// Cannon
body: new CANNON.Body({
mass: 1, // kg
position: randomPosition(0, 6), // random pos from radius 0-6
shape: new CANNON.Sphere(radius)
}),
// THREE
mesh: new THREE.Mesh(
new THREE.SphereGeometry( radius, 32, 32 ),
new THREE.MeshPhongMaterial( { color: 0xdd5555, specular: 0x999999, shininess: 13} )
)
}
}
function Neutron(){
let radius = 1;
return {
// Cannon
body: new CANNON.Body({
mass: 1, // kg
position: randomPosition(0, 6), // random pos from radius 0-6
shape: new CANNON.Sphere(radius)
}),
// THREE
mesh: new THREE.Mesh(
new THREE.SphereGeometry( radius, 32, 32 ),
new THREE.MeshPhongMaterial( { color: 0x55dddd, specular: 0x999999, shininess: 13} )
)
}
}
function Electron(){
let radius = 0.2;
return {
// Cannon
body: new CANNON.Body({
mass: 0.5, // kg
position: randomPosition(3, 7), // random pos from radius 3-8
shape: new CANNON.Sphere(radius)
}),
// THREE
mesh: new THREE.Mesh(
new THREE.SphereGeometry( radius, 32, 32 ),
new THREE.MeshPhongMaterial( { color: 0xdddd55, specular: 0x999999, shininess: 13} )
)
}
}
function randomPosition(innerRadius, outerRadius){
// get random direction
let x = (2 * Math.random() - 1 ),
y = (2 * Math.random() - 1 ),
z = (2 * Math.random() - 1 )
// create vector
let randVec = new CANNON.Vec3(x, y, z);
// normalize
randVec.normalize();
// scale it to the right radius
randVec = randVec.scale( Math.random() * (outerRadius - innerRadius) + innerRadius); //from inner to outer
return randVec;
}
And to use it:
let scene = new THREE.Scene();
let world = new CANNON.World();
world.broadphase = new CANNON.NaiveBroadphase();
world.solver.iterations = 5;
let camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
let renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
// create a Atom with 3 protons and neutrons, and 5 electrons
// all circulating position (-4, 0, 0)
let atom = Atom(3, 3, 5, new CANNON.Vec3(-4, 0, 0));
// move atom (will not be instant)
//atom.position.x = -2;
// add to THREE scene and CANNON world
atom.addToWorld(world, scene);
let light = new THREE.AmbientLight( 0x202020 ); // soft white light
scene.add( light );
let directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
directionalLight.position.set( -1, 1, 1 );
scene.add( directionalLight );
camera.position.z = 18;
const timeStep = 1/60;
// give the atoms electrons some starting velocity
atom.electronStartingVelocity(2);
function render () {
requestAnimationFrame( render );
// calculate all the particles positions
atom.simulate();
// Step the physics world
world.step(timeStep);
//update the THREE mesh
atom.updateAtomMeshState();
renderer.render(scene, camera);
};
render();
I have been facing the same problem, and also made a solution using Cannon.js. However, when rendering heavier elements this might cause a considerable load, especially on mobile.
I came up with an idea to capture the final position of the nucleons after they have settled and save that in a json file for all the elements.
Then the nucleons can be made to orbit the nucleus linearly without physics.
one solution would be to use the icosphere algorithm to calculate the position of a Neutrons/Protons using the vertex point of generated sphere.
You can find ad usefoul algorithm here
the distance between the points remains equal over the entire surface

babylonjs: multi-shadows for multi-elements not working

Im trying to get the shadows right using Babylonjs. Without any joy :p
Here is the resources on shadows I have found
Babylonjs wiki: Shadows
framework for building 3D games with HTML5 and WebGL
but I can't find anything on "element on element" shadows. :(
here is my attempt at it:
my sources loosely based on Babylonjs wiki: 17-Shadows
I have 2 lights and 3 objects
I get a shadow behind the sphere but then I also get an artefact on the front face of the sphere.
► Live code:
jsfiddle.net/codemeasandwich/z64Ba
I appreciate your help as I've been struggling with this for a while.
function createSceneTuto(engine) {
var scene = new BABYLON.Scene(engine);
//freeCamera is a FPS like camera where you control the camera with the cursors keys and the mouse
//touchCamera is a camera controlled with touch events (it requireshand.jsto work)
//arcRotateCamera is a camera that rotates around a given pivot. It can be controlled with the mouse or touch events (and it also requires hand.js to work)
// ArcRotateCamera >> Camera turning around a 3D point (here Vector zero)
// Parameters : name, alpha, beta, radius, target, scene
var camera = new BABYLON.ArcRotateCamera("Camera", 0, 0, 90, BABYLON.Vector3.Zero(), scene);
camera.setPosition(new BABYLON.Vector3(30, 30, 30));
// pointLight (like the sun for instance) which emits lights in every direction from a specific position
// directionalLight which emits lights from the infinite towards a specific direction
var light = new BABYLON.DirectionalLight("Dir0", new BABYLON.Vector3( -1,0, 0), scene);
var light0 = new BABYLON.PointLight("Omni0", new BABYLON.Vector3(1, 10, 100), scene);
light0.diffuse = new BABYLON.Color3( 0,1, 0);
light0.specular = new BABYLON.Color3(1, 1, 1);
var box = BABYLON.Mesh.CreateBox("Box", 3, scene);
var torus = BABYLON.Mesh.CreateTorus("torus", 5, 1, 20, scene);
// var plan = BABYLON.Mesh.CreatePlane("Plane", 50.0, scene);
// plan.position.z = -40
var sphere = BABYLON.Mesh.CreateSphere("Sphere", 15, 20, scene);
// Shadows
var shadowGenerator = new BABYLON.ShadowGenerator(1024, light);
var shadowGenerator0 = new BABYLON.ShadowGenerator(1024, light0);
shadowGenerator.getShadowMap().renderList.push(box);
shadowGenerator.getShadowMap().renderList.push(torus);
shadowGenerator.getShadowMap().renderList.push(sphere);
shadowGenerator0.getShadowMap().renderList.push(box);
shadowGenerator0.getShadowMap().renderList.push(torus);
shadowGenerator0.getShadowMap().renderList.push(sphere);
box.receiveShadows = true;
torus.receiveShadows = true;
sphere.receiveShadows = true;
var alphaTorus = 0, alphaBox =0;
scene.registerBeforeRender(function () {
torus.rotation.x += 0.02;
torus.position = new BABYLON.Vector3(Math.cos(alphaTorus) * 15, 0, Math.sin(alphaTorus) * 15);
alphaTorus += 0.003;
box.position = new BABYLON.Vector3(Math.cos(alphaBox) * 15, 0, Math.sin(alphaBox) * 15);
alphaBox += 0.01;
});
return scene;
}
► The above lights as directional lights
var light = new BABYLON.DirectionalLight("Dir0", new BABYLON.Vector3( -1,0, 0), scene);
light.position = new BABYLON.Vector3(0, 0, 20);
light.intensity = 0.5;
var light0 = new BABYLON.DirectionalLight("Omni0", new BABYLON.Vector3(0,0,-1), scene);
light0.position = new BABYLON.Vector3(25, 0, 0);
light.intensity = 0.5;
Only directional lights can cast shadows and they also need a position to define from where the shadows come
I update the wiki to add this IMPORTANT information :)
Only directional ligths can cast shadows:
var light = new BABYLON.DirectionalLight("dir01", new BABYLON.Vector3(-1, -2, -1), scene);
You must also define a position for your light (because Babylon.js must define a point of view to > create the shadow map):
light.position = new BABYLON.Vector3(20, 40, 20);
Please note that you should have to move the position to define the area where the shadows are seen.

Categories