Three.js skeletal animations not working unless source is modified - animation

Using Three.js r68+ I have been needing to very slightly modify the source to get my animations working correctly. Unmodified only one of each type of model are animated (there are multiple spawns of each type of model).
This is the modified source at line 29407 (posted code beginning at 29389):
THREE.AnimationHandler = {
LINEAR: 0,
CATMULLROM: 1,
CATMULLROM_FORWARD: 2,
//
add: function () { console.warn( 'THREE.AnimationHandler.add() has been deprecated.' ); },
get: function () { console.warn( 'THREE.AnimationHandler.get() has been deprecated.' ); },
remove: function () { console.warn( 'THREE.AnimationHandler.remove() has been deprecated.' ); },
//
animations: [],
init: function ( data ) {
// original -> if ( data.initialized === true ) return;
if ( data.initialized === true ) return data; //<-- modified
The function now returns the animation data if initialized. I'm assuming it doesn't do so because of caching. My question is what is the best practice for animating multiple models that have the same animation names? I tried naming them uniquely per model name ie: "Death_MaleWarrior" but this had no effect.
Currently my models and animations are handled like so:
var modelArray = [];
var geoCache = [];
var loader = new THREE.JSONLoader(true);
var _MODEL = function(data){
this.data = data;
this.mesh = null;
this.animations = {};
this.canAnimate = false;
this.parseAnimations = function () {
var len,i,anim;
if (this.mesh) {
if( this.mesh.geometry.animations ){
this.canAnimate = true;
len = this.mesh.geometry.animations.length;
if( len ){
for(i=0;i<len;i++){
anim = this.mesh.geometry.animations[i];
if( anim ){
this.animations[anim.name] = new THREE.Animation( this.mesh, anim );
}
}
}
}
}
};
this.playAnimation = function(label){
if (this.canAnimate) {
if( this.animations[label] ){
//if( this.animations[label].data ){
this.animations[label].play(0,1);
//}
}
}
return false;
};
this.load = function(geo){
var mat;
mat = new THREE.MeshPhongMaterial({color:somecolor, skinning:true})
this.mesh = new THREE.SkinnedMesh(geo,mat);
this.mesh.position.x = this.data.position[0];
this.mesh.position.y = this.data.position[1];
this.mesh.position.z = this.data.position[2];
this.parseAnimations();
scene.add(this.mesh);
this.playAnimation('Idle');
};
this.init = function(){
var geo;
if( geoCache[this.data.name] ){
geo = geoCache[this.data.name];
this.load(geo);
}else{
geo = loader.parse(JSON.parse(this.data.json)).geometry;
geoCache[this.data.name] = geo;
this.load(geo);
}
};
this.init();
};
var dataArray = [{name:'MaleWarrior',json:'json_data',position:[x,y,z]},{name:'FemaleWarrior',json:'json_data',position:[x,y,z]},{name:'MaleWarrior',json:'json_data',position:[x,y,z]}];
for(var i=0, len=objectArray.length; i<len; i++){
modelArray.push(new _MODEL(dataArray[i]) );
}
In this example the first MaleWarrior will animate but the second will not. If there was a second female she would not be animated either as the animation (even though it is a new THREE.Animation() ) will be considered initialized and will not return any data. If I do not check for the existence of animations.data in playAnimation I get the error ""Uncaught TypeError: Cannot read property 'name' of undefined " on line 29665".
Is what I'm doing bypassing animation caching and hurting performance? I feel like I'm missing something. How will an animation play without data?
All animation names are the same for every model "Idle", "Run", "Attack" etc.
Any help would be appreciated. If I'm not being clear enough please let me know. I have added additional detail.

This turned out to be an official three.js bug.
https://github.com/mrdoob/three.js/issues/5516

Related

Three.js - exporting scene with TextGeometry to OBJ/GLTF then load by OBJ/GLTF Loader

I have problem with import/export scenes in Three.js
I have few objects (models loaded with OBJLoader, Text generated with TextGeometry). Im able to export it to string definition using OBjExporter/GLTFExporter, but when Im trying to load it again, it loads text to BufferGeometry not TextGeometry.
Is it possible to load all scene meshes with proper geometries?
Or maybe its possible to parse geometries?
I know I can save scene without text (store text parametries in different definition then generate it again), but I would like to avoid it.
Im looking forward for Your help.
Thanks.
Code samples:
1. Function to export scene to OBJ
function CanvasToOBJ(callback) {
var exporter = new THREE.OBJExporter();
var options = {
trs: false,
onlyVisible: true,
truncateDrawRange: true,
binary: false,
forceIndices: false,
forcePowerOfTwoTextures: false,
embedImages: true
};
var result = exporter.parse(scene);
callback(result);
exporter.parse(scene, function (result) {
if (result instanceof ArrayBuffer) {
callback(null);
} else {
var output = JSON.stringify(result, null, 2);
callback(output);
}
}, options);
}
Function to import from OBJ string
function LoadOBJ() {
var elem = document.getElementById("modelEditor");
if (elem != null && elem !== "undefined" && elem.value !== "undefined" && elem.value != null && elem.value != "") {
var gltfString = elem.value;
var loader = new THREE.OBJLoader();
loader.load = function load(url, localtext, onLoad, onProgress, onError) {
var scope = this;
var loader = new THREE.XHRLoader(scope.manager);
loader.setPath(this.path);
loader.load(url, function (text) {
if (url == "") {
text = localtext;
}
onLoad(scope.parse(text));
}, onProgress, onError);
},
loader.load('', gltfString, function (gltf) {
scene = new THREE.Scene();
scene.background = new THREE.Color(0xf0f0f0);
scene.add(new THREE.AmbientLight(0x505050));
var light = new THREE.SpotLight(0xffffff, 1.5);
light.position.set(0, 500, 2000);
light.angle = Math.PI / 9;
light.castShadow = true;
light.shadow.camera.near = 1000;
light.shadow.camera.far = 4000;
light.shadow.mapSize.width = 1024;
light.shadow.mapSize.height = 1024;
scene.add(light);
var elem = gltf.children[0];
scene.add(elem);
objects.push(elem);
renderer.setSize(renderer.domElement.width, renderer.domElement.height, false);
})
}
}
Answer: NO. Neither .obj nor .gltf support anything other than plain buffergeometry.
If you want to keep everything in its original format, for a example a sphere defined by a radius and number of subdivisions rather than just a bunch of triangles, you'll need to use three.js's custom format .json format used by the three.js editor which AFAICT is undocumented.
Unfortunately even it doesn't support any Geometry formats, only BufferGeometry formats like SphereBufferGeometry but it also doesn't currently support TextBufferGeometry though you could try to add support.
https://github.com/mrdoob/three.js/blob/513eceb0fedfd05089168bde81c5bb85ba0e6ec1/src/loaders/ObjectLoader.js#L200
One issue you'll need to deal with is loading and saving references to fonts.

How can do uniformly (same sized checker boxes) of custom checkered texture image which applied on all objects of Model which loaded in Three Js?

I have loaded one model (obj file) in three js and applied custom checker texture image on all objects. Texture is applied on Model. But, issue is that - checker are not like uniformly - some checker are look small and some are look larger.
Here is link of screenshot.
Is there any way to fix it ? I mean - any calculation on geometry or any in-built properties of texture etc. in three js.
Here is link of model file Model.obj
loaded this model in three js and applied texture image.
// Below some code which I have tried.
function loadModel() {
object.traverse( function ( child ) {
if (child.type.toLowerCase() == "mesh" && child.material) {
if (child.material.length) {
for (var i=0; i < child.material.length; i++) {
child.material[i].map = texture;
child.material[i].needsUpdate = true;
}
}
else {
child.material.map = texture;
child.material.needsUpdate = true;
}
}
} );
scene.add( object );
}
manager = new THREE.LoadingManager( loadModel );
manager.onProgress = function ( item, loaded, total ) {
console.log( item, loaded, total );
};
textureLoader = new THREE.TextureLoader( manager );
texture = textureLoader.load(currentTextureUrl); // texture checker image
texture.onUpdate = true;
function onProgress( xhr ) {
if ( xhr.lengthComputable ) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log( 'model ' + Math.round( percentComplete, 2 ) + '% downloaded' );
}
}
function onError() {}
var loader = new THREE.OBJLoader( manager );
loader.load(modals.currentModal.objectFile, function ( obj ) {
object = obj;
}, onProgress, onError );

three.js order of loading resources

I have a obj model that I'm loading via THREE.LoadingManager and a few textures. When I'm opening the page with clear cache - I'm always getting model without textures. I can see them after pressing F5. My code looks like this:
var manager = new THREE.LoadingManager();
var loader = new THREE.TextureLoader(manager);
var textures_loaded = 0;
var id;
for (id in materials) {
loader.load('images/' + materials[id].unique_id + '.jpg', function(t) {
t.magFilter = THREE.NearestFilter;
t.minFilter = THREE.LinearMipMapLinearFilter;
var re = /images\/(\d+)\.jpg/g;
var result = re.exec(t.image.currentSrc);
material = materials.filter(function(obj) {
return obj.unique_id == result[1];
}).shift();
material.setTexture(t);
textures_loaded += 1;
if (textures_loaded == materials.length) {
mainLoop();
}
});
}
var loader = new THREE.OBJLoader(manager);
loader.load('obj/' + model.model_name, function (object) {
object.traverse(function(child) {
if (child instanceof THREE.Mesh) {
var mesh = model.meshes.filter(function(mesh) {
return mesh.name == child.name;
}).shift();
child.material.map = mesh.material.texture;
child.geometry.buffersNeedUpdate;
child.geometry.uvsNeedUpdate;
}
});
scene.add(object);
}
);
I'm running mainLoop only after all textures are loaded. But sometimes model loads faster. How can I control order of loading objects using THREE.LoadingManager ?. How can I show model only after everything is loaded ?
I would do something like this. Have two functions responsible for loading each set of content inline. In this case the meshes will not be loaded until the materials are done loading.
var manager = new THREE.LoadingManager();
var loader = new THREE.TextureLoader(manager);
function loadMaterials(materials, callback){
var textures_loaded = 0;
for (var id in materials) {
loader.load('images/' + materials[id].unique_id + '.jpg', function(t) {
t.magFilter = THREE.NearestFilter;
t.minFilter = THREE.LinearMipMapLinearFilter;
var re = /images\/(\d+)\.jpg/g;
var result = re.exec(t.image.currentSrc);
material = materials.filter(function(obj) {
return obj.unique_id == result[1];
}).shift();
material.setTexture(t);
textures_loaded += 1;
if (textures_loaded == materials.length) {
callback("materialsLoaded");
//mainLoop();
}
});
}
}
var loadedMeshes = [];
function loadMeshes(meshes, callback){
var meshes_loaded = 0;
for(var i in meshes){
var loader = new THREE.OBJLoader(manager);
loader.load('obj/' + model.model_name, function (object) {
loadedMeshes.push(object);
object.traverse(function(child) {
if (child instanceof THREE.Mesh) {
//you'll need to map to the right material.
child.material.map = mesh.material.texture;
child.geometry.buffersNeedUpdate;
child.geometry.uvsNeedUpdate;
}
});
if(loadedMeshes.length == meshes.length){
callback("meshesLoaded");
}
};
}
}
var materials = ["material1", "material2"];
var meshes = ["mesh1.obj", "mesh2.obj"];
function onLoad(){
for(var i in loadedMeshes){
scene.add(loadedMeshes[i]);
}
mainLoop();
}
function init(){
loadMaterials(materials, function(t){
console.log(t);
loadMeshes(meshes, function(t){
console.log(t);
onLoad(t);
})
})
}
Maybe you can try to execute your mainLoop only when the document is ready, using some jQuery:
$('document').ready(function mainLoop(){});
"this event does not get triggered until all assets such as images have been completely received"
from jQuery .ready event

Load multiple OBJ-files together with multple textures

Using the many examples on ThreeJS, I'm able to load multiple OBJ files into my scene. I'm also able to load multiple images as textures. However, the textures get assigned to the objects in 'order of appearance' and therefore, sometimes the wrong image gets assigned to the OBJ files.
I retrieve a list of OBJ files and textures from a JavaScript array, let's say:
…
"arr_threejs": [{
"geometry": "my_first_object.obj",
"material_uvmap": "my_first_texture.jpg",
}, {
"geometry": "my_second_object.obj",
"material_uvmap": "my_second_object.obj",
}],…
Then, I use this 'loader' class to load the textures:
for (var i = 0; i < arr_threejs.length; i++) {
var loader = new THREE.ImageLoader(manager);
str_material_uvmap_url = arr_threejs[i].material_uvmap;
loader.load(str_material_uvmap_url, function (image) {
console.log(image);
var index = textures.push(new THREE.Texture()) - 1;
textures[index].image = image;
textures[index].needsUpdate = true;
});
}
And, simillary, the geometry:
var loader = new THREE.OBJLoader(manager);
for (var i = 0; i < arr_threejs.length; i++) {
str_model_url = arr_threejs[i].geometry;
loader.load(str_model_url, function (object, i) {
var index = get_index_by_url(str_model_url); //doesn't work
objects[index] = object;
objects[index].traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material.map = textures[index];
child.material.side = THREE.DoubleSide;
}
});
scene.add(objects[index]);
}, onProgress, onError);
}
It seems I have no way in the callback function to know what object or what texture I'm dealing with. var index = get_index_by_url(str_model_url); doesnt work, because str_model_url isn't passed as arguement.
So, my question is,
specifically:
Is there a way to know the index of the image or object that I'm trying to load?
or generally:
Is there a standard way to load multple OBJ-files with textures?
You can use anonymus functions. For example:
loader.load(str_model_url, (function (url,scale) { return function (object, i) {
console.log( url );
console.log( scale );
}}) (str_model_url, 0.5)
, onProgress
, onError
);
Here's #stdob answer implemented in my code:
// MODEL
// model - LOAD TEXTURE
for (var i = 0; i < arr_threejs.length; i++) {
var loader = new THREE.ImageLoader(manager);
str_material_uvmap_url = arr_threejs[i].material_uvmap;
loader.load(str_material_uvmap_url, (function (url, index) {
return function (image, i) {
textures[index] = new THREE.Texture();
textures[index].image = image;
textures[index].needsUpdate = true;
}
})(str_material_uvmap_url, i)
, onProgress
, onError
);
}
// model - LOAD OBJECT
var loader = new THREE.OBJLoader(manager);
for (var i = 0; i < arr_threejs.length; i++) {
str_model_url = arr_threejs[i].geometry;
loader.load(str_model_url, (function (url, index) {
return function (object, i) {
objects[index] = object;
objects[index].traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material.map = textures[index];
child.material.side = THREE.DoubleSide;
}
});
scene.add(objects[index]);
}
})(str_model_url, i)
, onProgress
, onError
);
}

three.js Materials are not working after exported using ObjectExporter

am exporting my models using ObjectExporter, my code is follows
exporter = new THREE.ObjectExporter;
var obj = exporter.parse(globalObject);
var json = JSON.stringify(obj);
console.log(json);
i can get the json exported data successfully, but after load it using ObjectLoader the Geometry only loading materials are not loading, am loading my saved model by following code
var loader = new THREE.ObjectLoader();
loader.load("savedjson.json",function ( obj ) {
scene.add( obj );
console.log(obj);
});
any clue to get materials work with the ObjectExporter?
I had the same problem. I have a first attempt at a workaround(but it needs to be improved for sure). What I do is, after loading the object, I traverse the model
loader.load("savedjson.json", function (obj){
obj.traverse(function(child){ initChild(child); });
scene.add(obj);
}
In initChild(child) I do this:
initChild(child)
{
if(child.material != null)
{
var childMaterialName = child.material.name;
child.material = new THREE.MeshPhongMaterial();
child.material.name = childMaterialName ;
AssignMap(child.material);
}
}
In AssignMap(material) I first load the textures, then assign them based on the material name:
AssignMap(material)
{
var texture_metal = new THREE.ImageUtils.loadTexture("media/texture_metal.jpg");
var texture_glass = new THREE.ImageUtils.loadTexture("media/texture_glass.jpg");
if(material.name == "metal texture")
{
material.map = texture_metal;
}
if(material.name == "glass texture")
{
material.map = texture_glass;
}
}

Resources