ThreeJS - multiple meshes from a .json 3D file - javascript

I exported a .json from the online 3D editor and I'm trying to load it and instantiate 20 versions of it, like this example. My code is flawed bc all 20 versions are actually acting like the same object. Not sure why they're not being added to the scene as separate objects in their given x,z coordinates.
var serverObject;
var allBrains = []
var xCenter;
var zCenter;
var spacing = .2;
var newServ;
var objectLoader = new THREE.ObjectLoader();
objectLoader.load("asset_src/model.json", function(obj) {
//give it a global name, so I can access it later?
serverObject = obj
//see what's inside of it
obj.traverse(function(child) {
if (child instanceof THREE.Mesh) {
console.log(child)
}
})
//was trying to add transparency this way, but ended up
//going through the online editor to apply it
// var cubeMaterial1 = new THREE.MeshBasicMaterial({
// color: 0xb7b7b7,
// refractionRatio: 0.98
// });
//Do i need to instantiate my mesh like this, if so, how do I make sure that it gets the materials from the json? The json has 6 children each with a different material
// serverObject = new THREE.Mesh( obj, cubeMaterial1 );
//make 20 versions of the file
for (var i = 0; i < 20; i++) {
xCenter = Math.cos(toRadians(i * spacing))
zCenter = Math.sin(toRadians(i * spacing))
serverObject.scale.set(.09, .09, .09)
//this amount of offset is correct for the scale of my world
//i was going to use my xCenter, zCenter but tried to simplify it till it works
serverObject.position.set((i * .1), controls.userHeight - 1, i * .1);
allBrains.push(serverObject)
//I've attempted a number of ways of adding the obj to the scene, this was just one
scene.add(allBrains[i]);
}
// see that there are 20 meshes
console.log(allBrains)
});
The return of my last console log looks like this:

At the moment, you have a single object (serverObject) which you manipulate and add multiple times, but each iteration of the loop just modifies the same object, overriding previous parameters.
You need to clone your mesh, using the... clone() method. You'll then be able to modify the settings of that object (the copy), and each of the meshes will remain independent.
Alternatively, you could run the objectLoader.load method inside the loop to create the object multiple times from the JSON file, but it's probably a waste of resources.

Thanks to #jcaor for the clone() idea, here is the working code:
var objectLoader = new THREE.ObjectLoader();
objectLoader.load("asset_src/model.json", function(obj) {
//give it a global name, so I can access it later
serverObject = obj
//see what's inside of it
obj.traverse(function(child) {
if (child instanceof THREE.Mesh) {
console.log(child)
}
})
for (var i = 0; i < 20; i++) {
var tempNew = serverObject.clone()
xCenter = Math.cos(toRadians(i * spacing))
zCenter = Math.sin(toRadians(i * spacing))
tempNew.scale.set(.05, .05, .05)
tempNew.position.set(xCenter, controls.userHeight - 1, zCenter);
allBrains.push(tempNew)
scene.add(allBrains[i]);
}
console.log(allBrains)
});

This looks like a pointer issue to me.
In JavaScript you can think of variables like pointers that is why you don't have to assign types to variables and how functions can be variables and still work in normal computer science.
In this case you are assigning the same pointer to each slot in the array.
This is a super simple version of the problem. obj2.foo was never changed but because we changed obj.foo obj2.foo changed because of the var simply pointing to the same object.
var obj = {
foo : 1
}
var obj2 = obj;
obj.foo = 2;
console.log(obj2.foo);
What I would do is create a new object and popluate it with the information of the master object in you case "serverObject"
allBrains.push(serverObject)

Related

using stagger animation in three.js

I want to animate array of meshes but properties are not recognized
tl.staggerFrom(array,2,{"position.y":-100})
position.y doesnt change
when I use console.log(array[0].position.y) it gives the the inital value of position.y
how can I use stagger animation in threejs meshes
It looks like you're using GSAP (TweenMax), and that library requires you to use shallow objects as its animation parameter. This means you can't animate a variable that's 2+ levels deep; you can't ask it to animate array[0].position.y, but you can ask it to animate position.y. With this in mind, consider the following:
// Save reference to all positions into a new array
var allPositions = [];
for (var i = 0; i < array.length; i++) {
allPositions.push(array[i].position);
}
// Now use the shallower objects to animate the y attribute
tl.staggerFrom(allPositions,2,{y: -100});
I solved it with using proxy
I create a new proxy instance for every mesh and in its set property I just do what I want to do with it and add the proxy to an array and use that array in stagger
for ex:
for(let i=0;i<5;i++){
let mesh = new THREE.Mesh(geometry,material);
let proxy = new Proxy({positionY:null},{
set(target,key,value){
target[key] = value;
if(target[key] !== null){
mesh.position.y = target.positionY
}
return true;
},
get(target,key){
return target[key];
}
})
proxy.positionY = 0
aarray.push(proxy)
}
tl.staggerFrom(aarray,5,{positionY:-100})

three.js selecting children of Object3D using raycaster.intersectObject

I am trying to make a series of cubes that can be clicked to highlight them. This will enable me to change their color or add a texture or manipulate them in some way. I have looked through the source code of all the interactive examples at https://threejs.org/examples/ and it appears that each example uses a slightly different way of creating and selecting objects in the scene. I am not used to using javascript though, so maybe I'm missing something simple.
I create an Object3D class named blocks to store all of the cubes
blocks = new THREE.Object3D()
I am using a for loop to create a 9 x 9 array of cubes starting at (0,0,0) coordinates with a slight gap between them, and add() them to blocks and add() blocks to the scene. example: (cube size 2,2,2)
function stack(mx,my,mz){
for (var i = 0; i < 9; i++){
line(mx,my,mz);
mz += 3;
}
}
function line(mx,my,mz){
for (var i = 0;i<9;i++){
var block = new THREE.Mesh( Geometry, Material);
block.position.x = mx;
block.position.y = my;
block.position.z = mz;
blocks.add(block);
mx+=3;
}
}
stack(mx,my,mz)
scene.add(blocks)
When I run this code, I can see them rendered. I use raycaster to .intersectObjects() which requires an array of objects. This is where I run into the problem of selecting just one object.
function onDocumentMouseDown(event) {
var vector = new THREE.Vector3(( event.clientX / window.innerWidth ) * 2 - 1, -( event.clientY / window.innerHeight ) * 2 + 1, 0.5);
projector.unprojectVector(vector, camera);
var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
**var intersects = raycaster.intersectObjects(blocks.children, true);**
if (intersects.length > 0) {
intersects[0].object.material.transparent = true;
other code stuff blah blah blah
{
This will make all children clickable but they have the same .id as the first object created. so if I try to .getObjectById() in order to change something, it doesn't work.
I have tried to generate each element and add them to the scene iteratively instead of creating an object array to hold them and it still has a similar effect. I've tried storing them in a regular array and then using true parameter to recursively search the .intersectObject() array but it selects all of the objects when I click on it.
var intersects = raycaster.intersectObjects(blocks, true);
I have considered creating 81 unique variables to hold each element and statically typing an array of 81 variables (desperate option) but I can't find a secure way to dynamically create variable names in the for loop to hold the objects. This way was posted on stackoverflow as a solution to creating different named variables but it doesn't seem to create variables at all.
for (var i=0, i<9, i++){
var window["cube" + i] = new THREE.Mesh( Geometry, Material)
{
Main Question: How can I iteratively create multiple Mesh's (enough that statically typing each variable would be ill-advised) in a controllable way that I can select them and manipulate them individually and not as a group?
I think the reason why you met this problem is you reference same Material to build your Mesh, you did intersect a single object in blocks.children, but when you change some properties of the material others mesh who use the material would change too.
function line(mx,my,mz){
for (var i = 0;i<9;i++){
material = new THREE.MeshLambertMaterial({color: 0xffffff});
var block = new THREE.Mesh( Geometry, material);
block.position.x = mx;
block.position.y = my;
block.position.z = mz;
blocks.add(block);
mx+=3;
}
}
it works for me.

How to update the topology of a geometry efficiently in ThreeJS?

I want to avoid creating new typed arrays and the consequent gc().
I made my geometry using BufferedGeometry. Upon receiving events, my vertex and the faces indices are updated. I can update the coordinates by setting verticesNeedUpdate but it does not update the faces. The update is called ~20-50 times per second, which can be heavy on the browser. How can I do this by avoiding creating heavy garbage for the JavaScript Garbage Collector? (See method update() below).
function WGeometry77(verts, faces) {
THREE.Geometry.call( this );
this.type = 'WGeometry77';
this.parameters = {};
// Initially create the mesh the easy way, by copying from a BufferGeometry
this.fromBufferGeometry( new MyBufferGeometry77( verts, faces ) );
};
WGeometry77.prototype = Object.create( THREE.Geometry.prototype );
WGeometry77.prototype.constructor = WGeometry77;
WGeometry77.prototype.update = function(verts, faces) {
var geom = this;
var nl = Math.min(geom.vertices.length, verts.length/3);
for ( var vi = 0; vi < nl; vi ++ ) {
geom.vertices[ vi ].x = verts[vi*3+0];
geom.vertices[ vi ].y = verts[vi*3+1];
geom.vertices[ vi ].z = verts[vi*3+2];
}
var nf = Math.min(geom.faces.length, faces.length/3);
for ( var fi = 0; fi < nf; fi ++ ) {
geom.faces[ fi ].a = faces[fi*3+0];
geom.faces[ fi ].b = faces[fi*3+1];
geom.faces[ fi ].c = faces[fi*3+2];
}
geom.verticesNeedUpdate = true; // Does not update the geom.faces
}
PS. My code is written in Emscripten, which does something like this:
var verts = Module.HEAPF32.subarray(verts_address/_FLOAT_SIZE, verts_address/_FLOAT_SIZE + 3*nverts);
What I want to do is almost animating, or a dynamic geometry (calculated using Marching Cubes). But my topology (the graph of the mesh) is also updated. Which ThreeJS class I should use? If there exists no such class, should I create we create a new class like UpdatableBufferedGeometry?
To update THREE.BufferGeometry after it has rendered, you can use this pattern:
geometry.attributes.position.setXYZ( index, x, y, z );
geometry.attributes.position.needsUpdate = true;
For indexed BufferGeometry, you can change the index array like so:
geometry.index.array[ index ] = value;
geometry.index.needsUpdate = true;
You cannot resize buffers -- only change their contents. You can pre-allocate larger arrays and use
geometry.setDrawRange( 0, numVertices );
three.js r.78
If you want efficiency, you should create a BufferGeometry instead of a Geometry.
You can use the source code of this example as reference:
http://threejs.org/examples/#webgl_buffergeometry_uint

Constructor methods in javascript affect all instances of object

I'm working on an implementation of tetris to teach myself javascript and I've run into a problem. First, the background: I have a class for each type of tetris block that inherits from a basic block template with methods like moving and returning coordinates. For instance,
function BlockTemplate(w, h, c){
var height = h;
var width = w;
var x = 0;
var y = 0;
var color = c;
this.getHeight = function(){return height;};
this.getWidth = function(){return width;};
this.getX = function(){return x;};
this.getY = function(){return y;};
this.getColor = function(){return color;};
this.moveTo = function(newX, newY){
x = newX;
y = newY;
};
this.translate = function(dx, dy){
x += dx;
y += dy;
};
}
function StraightBlock(){
this.draw = function(){
ctx.fillStyle = this.getColor();
ctx.fillRect(this.getX(), this.getY(), 20, 100);
};
}
StraightBlock.prototype = new BlockTemplate(20, 100, "#00FFE5");
All blocks currently on the screen are stored in an array, blockArr, except for the currently falling block, which is stored in curBlock.
I use a function called createRandomBlock() to create a block and put it in curBlock:
var blockTypeArr = [LBlock, SquareBlock, StraightBlock, SquigBlock];
var createRandomBlock = function(){
var block = blockTypeArr[Math.floor(Math.random()*blockTypeArr.length)];
var randomBlock = new block();
return randomBlock;
};
curBlock = createRandomBlock();
Once it's done falling I put it in the array and create a new block:
blockArr[blockArr.length] = curBlock;
curBlock = createRandomBlock();
If the newly created block hasn't yet been on screen then there's no problem. However, using the moveTo and translate methods of the new instance affect all instances of that class (I added an id property to make sure they were in fact distinct instances).
For example, using the JavaScript console,
>curBlock
SquigBlock
>blockArr
[SquareBlock, SquigBlock, SquigBlock]
As you can see, 3 SquigBlocks have fallen so far (2 in blockArr, 1 presently falling). Yet the only one I see is the one currently falling (curBlock), and checking the parameters, curBlock.getY(), blockArr[1].getY() and blockArr[2].getY() all return the same value. In other words, they're all being drawn in the same location.
How can I change it so that old blocks, no matter what the class, stay at the bottom of the screen, while the newly created block falls from the top without causing all other blocks of that class to move with it?
Thank you!
StraightBlock.prototype = new BlockTemplate(20, 100, "#00FFE5");
Well, that is only one BlockTemplate that is shared amongst with StraightBlock instances. You can see that new StraightBlock().moveTo == new StraightBlock().moveTo, ie two instances have the very same method which does affect the same x variable. Do not use new for creating the prototype, but Correct javascript inheritance:
function StraightBlock(){
BlockTemplate.call(this, 20, 100, "#00FFE5");
this.draw = function(){
ctx.fillStyle = this.getColor();
ctx.fillRect(this.getX(), this.getY(), 20, 100);
};
}
StraightBlock.prototype = Object.create(BlockTemplate.prototype);
StraightBlock.prototype = new BlockTemplate(20, 100, "#00FFE5");
Since this is called once, there is one var x that is closed over by the single getHeight that is shared among all instances of StraightBlock.
You should make two changes:
1 Use instance fields stored on this
function BlockTemplate(w, h, c){
this.height = h;
...
}
BlockTemplate.prototype.getHeight = function(){return this.height;};
...
2 Chain constructors
Have StraightBlock invoke its super-class constructor to add new versions of the methods to each instance created.
function StraightBlock(){
BlockTemplate.apply(this, arguments);
...
}
You could also just do constructor chaining, but that would mean that you are creating a new copy of each method for each instance. This can be expensive if you have a lot of short-lived instances of a "class".
The drawback of storing fields on this is that they can be unintentionally mutated by naive code. JavaScript does not have strong information hiding except via closed-over local variables, so if you want the robustness that you get via private fields in other languages, then your current design via local variables might be best.

How to set a dynamically generated pseudoclass name in JavaScript to work with the instanceof operator?

I'd like to set the name of a JavaScript pseudoclass stored in an array with a specific name, for example, the non-array version works flawlessly:
var Working = new Array();
Working = new Function('arg', 'this.Arg = arg;');
Working.prototype.constructor = Working;
var instw = new Working('test');
document.write(instw.Arg);
document.write('<BR />');
document.write((instw instanceof Working).toString());
Output:
test
true
However this format does not function:
// desired name of pseudoclass
var oname = 'Obj';
var objs = new Array();
objs.push(new Function('arg', 'this.Arg = arg;'));
// set objs[0] name - DOESN'T WORK
objs[0].prototype.constructor = oname;
// create new instance of objs[0] - works
var inst = new objs[0]('test');
document.write(inst.Arg);
document.write('<BR />Redundant: ');
// check inst name - this one doesn't need to work
try { document.write((inst instanceof objs[0]).toString()); } catch (ex) { document.write('false'); }
document.write('<BR />Required: ');
// check inst name - this is the desired use of instanceof
try { document.write((inst instanceof Obj).toString()); } catch (ex) { document.write('false'); }
Output:
test
Redundant: true
Required: false
Link to JSFiddle.
You've got a couple of things going on here that are a little bit off-kilter in terms of JS fluency (that's okay, my C# is pretty hackneyed as soon as I leave the base language features of 4.0).
First, might I suggest avoiding document.write at all costs?
There are technical reasons for it, and browsers try hard to circumvent them these days, but it's still about as bad an idea as to put alert() everywhere (including iterations).
And we all know how annoying Windows system-message pop-ups can be.
If you're in Chrome, hit CTRL+Shift+J and you'll get a handy console, which you can console.log() results into (even objects/arrays/functions), which will return traversable nodes for data-set/DOM objects and strings for other types (like functions).
One of the best features of JS these days is the fact that your IDE is sitting in your browser.
Writing from scratch and saving .js files isn't particularly simple from the console, but testing/debugging couldn't be any easier.
Now, onto the real issues.
Look at what you're doing with example #1.
The rewriting of .prototype.constructor should be wholly unnecessary, unless there are some edge-case browsers/engines out there.
Inside of any function used as a constructor (ie: called with new), the function is basically creating a new object {}, assigning it to this, setting this.__proto__ = arguments.callee.prototype, and setting this.__proto__.constructor = arguments.callee, where arguments.callee === function.
var Working = function () {};
var working = new Working();
console.log(working instanceof Working); // [log:] true
Working isn't a string: you've make it a function.
Actually, in JS, it's also a property of window (in the browser, that is).
window.Working === Working; // true
window["Working"] === Working; // true
That last one is really the key to solving the dilemma in example #2.
Just before looking at #2, though, a caveat:
If you're doing heavy pseud-subclassing,
var Shape = function () {
this.get_area = function () { };
},
Square = function (w) {
this.w = w;
Shape.call(this);
};
If you want your instanceof to work with both Square and Shape, then you have to start playing with prototypes and/or constructors, depending on what, exactly, you'd like to inherit and how.
var Shape = function () {};
Shape.prototype.getArea = function () { return this.length * this.width; };
var Square = function (l) { this.length = l; this.width = l; };
Square.prototype = new Shape();
var Circle = function (r) { this.radius = r; };
Circle.prototype = new Shape();
Circle.prototype.getArea = function () { return 2 * Math.PI * this.radius; };
var circle = new Circle(4),
square = new Square(4);
circle instanceof Shape; // true
square instanceof Shape; // true
This is simply because we're setting the prototype object (reused by every single instance) to a brand-new instance of the parent-class. We could even share that single-instance among all child-classes.
var shape = new Shape();
Circle.prototype = shape;
Square.prototype = shape;
...just don't override .getArea, because prototypical-inheritance is like inheriting public-static methods.
shape, of course, has shape.__proto__.constructor === Shape, much as square.__proto__.constructor === Square. Doing an instanceof just recurses up through the __proto__ links, checking to see if the functions match the one given.
And if you're building functions in the fashion listed above (Circle.prototype = new Shape(); Circle.prototype.getArea = function () { /* overriding Shape().getArea() */};, then circle instanceof Circle && circle instanceof Shape will take care of itself.
Mix-in inheritance, or pseudo-constructors (which return objects which aren't this, etc) require constructor mangling, to get those checks to work.
...anyway... On to #2:
Knowing all of the above, this should be pretty quick to fix.
You're creating a string for the desired name of a function, rather than creating a function, itself, and there is no Obj variable defined, so you're getting a "Reference Error": instead, make your "desired-name" a property of an object.
var classes = {},
class_name = "Circle",
constructors = [];
classes[class_name] = function (r) { this.radius = r; };
constructors.push(classes.Circle);
var circle = new constructors[0](8);
circle instanceof classes.Circle;
Now everything is nicely defined, you're not overwriting anything you don't need to overwrite, you can still subclass and override members of the .prototype, and you can still do instanceof in a procedural way (assigning data.name as a property of an object, and setting its value to new Function(data.args, data.constructor), and using that object-property for lookups).
Hope any/all of this helps.

Categories