WebGLRenderingContext ERROR loading texture maps - three.js

First of all, thank you for this wonderfull work, i'm having a lot of fun working with three.js.
I tried to find answer about a recurent issue, .WebGLRenderingContext: GL ERROR :GL_INVALID_OPERATION : glDrawElements: attempt to access out of range vertices in attribute 2
I'm making a website in webgl, i spend few week understanding all about three.js but i can't fix this issue.
I get this message on Chrome and firefox (latest) each time i try to load a canvas into a map, bumpmap and specmap.
All my mesh are loaded from obj files, by the way i rewrote OBJMTLLoader.js to be able to load more parameters from obj files and more.
here the code used to load image.
THREE.MTLLoader.loadTexture = function ( url, mapping, onLoad, onError ) {
var isCompressed = url.toLowerCase().endsWith( ".dds" );
var texture = null;
if ( isCompressed ) {
texture = THREE.ImageUtils.loadCompressedTexture( url, mapping, onLoad, onError );
} else {
var image = new Image();
texture = new THREE.Texture( image, mapping );
var loader = new THREE.ImageLoader();
loader.addEventListener( 'load', function ( event ) {
texture.image = THREE.MTLLoader.ensurePowerOfTwo_( event.content );
texture.needsUpdate = true;
if ( onLoad )
onLoad( texture );
} );
loader.addEventListener( 'error', function ( event ) {
if ( onError ) onError( event.message );
} );
loader.crossOrigin = this.crossOrigin;
loader.load( url, image );
}
return texture;
};
I'm pretty sure it is from this, because when i disable this function, no more warning.
Is it because the mesh has a texture with an empty image while loading datas ?
Is there any restriction on the dimensions of image ?
For now everything works fines, but i feel strange having those message in console.
Thanks

This error become because the Three.js buffers are outdated. When your add some textures (map,bumpMap ...) to a Mesh, you must recompose the buffers like this :
ob is THREE.Mesh, mt is a Material, tex is a texture.
tex.needsUpdate = true;
mt.map = tex;
ob.material = mt;
ob.geometry.buffersNeedUpdate = true;
ob.geometry.uvsNeedUpdate = true;
mt.needsUpdate = true;
That's all folks !
Hope it's help.
Regards.
Sayris

Related

A-Frame THREE.TextureLoader loading texture whice is looking whitewashed

I am updating an a-image scr using THREE.TextureLoader
let loader = new THREE.TextureLoader()
const imgload = loader.load(
'./test.png',
function ( texture ) {
firstFrameImage.getObject3D('mesh').material.map = texture
firstFrameImage.getObject3D('mesh').material.needsUpdate = true
},
// onProgress callback currently not supported
undefined,
// onError callback
function ( err ) {
console.error( 'An error happened.' );
}
)
Its updating the texture but its making the texture whitewashed. Can any one help?
Original image:
original
Updated texture coming as:
after update
Try to fix this by doing this:
texture.encoding = THREE.sRGBEncoding;
Color deviations like this mostly occur because of wrong color space definitions.

three.js failing to use pre-created canvas

I want to use a pre-created canvas with three.js. From the tutorials and other posts I've read, this should work:
const canvas = document.createElement('canvas');
const ctx = canvas.getContext("2d"); // <--- This causes the error below!
const renderer = new THREE.WebGLRenderer( { canvas: canvas } );
However, in my browser console (Safari v14 and Chrome v86), I get the following error:
THREE.WebGLRenderer: Error creating WebGL context.
I've also tried adding
<canvas id='myCanvas'></canvas>
and using:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d"); // <--- This causes the same error!
const renderer = new THREE.WebGLRenderer({
canvas: canvas,
});
and get the same issues.
I've also tried adding:
window.onload = function() {
...
};
to ensure the DOM has loaded, etc.
If I remove the getContext("2d") lines then it works?
I'm using three.js version 0.120.
Why does this cause an issue?
Three.js only throws this error in one place, and luckily it's doing something very simple: Getting a context from a canvas. It uses HTMLCanvasElement.getContext to do this, and only throws the error if the result is null.
HTMLCanvasElement.getContext will only allow you to request one context type. You can request the same type (or compatible, in the case of webgl and webgl2) again, but it will return the original context created on the canvas. After the first request establishes the in-use context, subsequent requests for incompatible types will return null.
let ctx_2d_1 = mycanvas.getContext( '2d' )
let ctx_2d_2 = mycanvas.getContext( '2d' )
console.log( ctx_2d_1 === ctx_2d_2 ) // true
let ctx_2d = mycanvas.getContext( '2d' )
let ctx_webgl = mycanvas.getContext( 'webgl' )
console.log( ctx_2d ) // CanvasRenderingContext2D
console.log( ctx_webgl ) // null
let ctx_webgl = mycanvas.getContext( 'webgl' )
let ctx_2d = mycanvas.getContext( '2d' )
console.log( ctx_webgl ) // WebGLRenderingContext
console.log( ctx_2d ) // null
Because you are creating the 2d context before calling the WebGLRenderer constructor, the constructor can't get a valid WebGLRenderingContext from the canvas. Instead, it gets a null, and so it throws the error.
If you want to draw 2D on top of 3D (or vice versa), you will either need to layer canvases of different contexts, or use a plane to render the 2D information as a texture within the WebGL (three.js) context.

Three.js clone FBX with animation

I can’t seem to be able to clone an FBX model (FBX downloaded from Mixamo) while retaining animation keyframes.
Have attempted a number of approaches including using the cloneFbx gist (included in the example below); all to no avail. Even placing the entire FBXLoader() function inside a loop does not work as expected since only one of the models will animate at a time.
This issue has been partially addressed here, but I cannot seem to ‘copy’ the animation sequence as answer suggests.
Can anyone point out where I’m going wrong?
Here's a rough example of one of my tests:
Load fbx model and store animation:
var loader = new THREE.FBXLoader();
loader.load( 'models/Walking.fbx', function ( fbx ) {
clip = fbx.animations[ 0 ];
// createVehicle(fbx); // Works! Creates one animated model via FBX
// cloneFbx via: https://gist.github.com/kevincharm/bf12a2c673b43a3988f0f171a05794c1
for (var i = 0; i < 2; i++) {
const model = cloneFbx(fbx);
createVehicle(model);
}
});
Add mixers and actions based on stored clip, add model to scene:
function createVehicle(model){
model.mixer = new THREE.AnimationMixer( model );
mixers.push( model.mixer );
var action = model.mixer.clipAction( clip );
action.play();
model.traverse( function ( child ) {
if ( child.isMesh ) {
child.castShadow = true;
child.receiveShadow = true;
}
});
const x = Math.random() * groundSize - groundSize/2;
const z = Math.random() * groundSize - groundSize/2;
model.position.set(x, 0, z);
const vehicle = new Vehicle(model, x, z);
vehicles.push(vehicle);
scene.add( model );
}
Animation cycle:
if ( mixers.length > 0 ) {
for ( var i = 0; i < mixers.length; i ++ ) {
mixers[ 0 ].update( clock.getDelta() );
}
}
Couldn’t figure out an elegant solution to this. Best I could come up with is creating a loop with the loading sequence inside of it; this is very slow (since the FBX has to be parsed each time).
The key here was having an animation mixer controlling the animated objects as a group as opposed to creating a mixer per animated object.
If anyone can figure out a better solution, I would be super keen to hear it (perhaps using the cloneFbx script properly).
Create mixer, load FBX:
// Create mixer to run animations
mixer = new THREE.AnimationMixer( scene );
// Load fbx
var loader = new THREE.FBXLoader();
for (var i = 0; i < 5; i++) {
loader.load( 'models/Walking.fbx', function ( fbx ) {
mixer.clipAction( fbx.animations[ 0 ], fbx )
.startAt( - Math.random() )
.play();
createVehicle(fbx);
});
}
Create class instances, add to scene:
function createVehicle(model){
const x = Math.random() * groundSize - groundSize/2;
const z = Math.random() * groundSize - groundSize/2;
model.position.set(x, 0, z);
const vehicle = new Vehicle(model, x, z);
vehicles.push(vehicle);
scene.add( model );
}
Draw cycle:
mixer.update( clock.getDelta() );
I found out that SkeletonUtils.clone() works good for me.
https://threejs.org/docs/index.html#examples/en/utils/SkeletonUtils.clone

How to clone a Skinned Mesh?

I need to have multiple identical, animated models on a scene. If possible, I would like them to have a shared geometry and material, but if it is impossible, having them instanced per model will suffice too.
Unfortunately, the only way to achieve this result I found is to go through JSONLoader for every model instance.
SkinnedMesh does have a clone() method, but it seems not to be fully implemented yet. If used and both original and cloned mesh are present on the scene, only one will appear, and cloned one will be without animation.
I have attempted to use this example with shared skeletons:
https://github.com/mrdoob/three.js/pull/11666
...and indeed it works, but I need to be able to play different animations for every model instance, having them all play the same one is not sufficient, sadly. I hoped I could do similar hax and insert my own skeleton (made out of bones from the JSON file), but it behaves very much like if I just used clone() from SkinnedMesh.
I am using this code:
https://github.com/arturitu/threejs-animation-workflow/blob/master/js/main.js
Basically what I'd like to achieve is
var onLoad = function (geometry, materials) {
window.geometry = geometry;
character = new THREE.SkinnedMesh(
geometry,
new THREE.MeshFaceMaterial(materials)
);
character2 = character.someMagicalClone();
scene.add(character);
scene.add(character2);
(...)
I need any clue... and while I wait for help, I am busily deconstructing constructor for SkinnedMesh and JSONLoader for clues ;)
Thanks in advance!
I found a solution in this pull request:
https://github.com/mrdoob/three.js/pull/14494
in short, there are two functions added:
function cloneAnimated( source ) {
var cloneLookup = new Map();
var clone = source.clone();
parallelTraverse( source, clone, function ( sourceNode, clonedNode ) {
cloneLookup.set( sourceNode, clonedNode );
} );
source.traverse( function ( sourceMesh ) {
if ( ! sourceMesh.isSkinnedMesh ) return;
var sourceBones = sourceMesh.skeleton.bones;
var clonedMesh = cloneLookup.get( sourceMesh );
clonedMesh.skeleton = sourceMesh.skeleton.clone();
clonedMesh.skeleton.bones = sourceBones.map( function ( sourceBone ) {
if ( ! cloneLookup.has( sourceBone ) ) {
throw new Error( 'THREE.AnimationUtils: Required bones are not descendants of the given object.' );
}
return cloneLookup.get( sourceBone );
} );
clonedMesh.bind( clonedMesh.skeleton, sourceMesh.bindMatrix );
} );
return clone;
}
function parallelTraverse( a, b, callback ) {
callback( a, b );
for ( var i = 0; i < a.children.length; i ++ ) {
parallelTraverse( a.children[ i ], b.children[ i ], callback );
}
}
As I understand it rebinds cloned skeleton to the cloned mesh.
so topic example could look like:
var onLoad = function (geometry, materials) {
window.geometry = geometry;
character = new THREE.SkinnedMesh(
geometry,
new THREE.MeshFaceMaterial(materials)
);
character2 = cloneAnimated(character); // <-- used that new function
scene.add(character);
scene.add(character2);
(...)

Using webgl-texture-utils with three.js for dds/crn support

I'm trying to use webgl-texture-utils ( https://github.com/toji/webgl-texture-utils ) with Three.js (r56) to take advantage of DDS and CRN (http://code.google.com/p/crunch/) textures.
I cannot figure out how to use the texture returned by textureLoader.load(src, callback); in THREE.Texture(image, mapping);
THREE.Texture expects javascript Image() object, but texture-utils returns something reported by Firebug to be XrayWrapper [Object WebGLTexture {} which I assume to be some native WebGL texture type.
Can I use that texture somehow as the image for THREE.Texture?
Here's some code I tried:
var mapping = new THREE.UVMapping();
var image = new Image();
var map = null;
var usetexturetools = true;
if (!usetexturetools) {
// normal way of loading
map = new THREE.Texture( image, mapping );
var loader = new THREE.ImageLoader();
loader.addEventListener( 'load', function ( event ) {
map.image = event.content;
map.needsUpdate = true;
});
loader.addEventListener( 'error', function ( event ) {
window.console.log("error loading " + texture);
});
loader.crossOrigin = 'anonymous';
loader.load(texture, image);
} else {
// using webgl-texture-tools - not working because i don't know how to use the object returned by textureLoader.load() with THREE.Texture..
var textureLoader = new TextureUtil.TextureLoader(renderer.getContext());
map = new THREE.Texture(textureLoader.load(texture, function(loaded) {
window.console.log(loaded);
map.needsUpdate = true;
}), mapping );
}
map.sourceFile = texture;
map.wrapS = THREE.RepeatWrapping;
map.wrapT = THREE.RepeatWrapping;
map.offset.x = this.getParameter("texture_offset_x");
map.offset.y = this.getParameter("texture_offset_y");
map.repeat.x = this.getParameter("texture_scale_x");
map.repeat.y = this.getParameter("texture_scale_y");
EDIT: I guess I could create a fork of webgl-texture-utils that instead of creating and returning WebGLTexture, would only return the raw data and as such, would allow me to use that data in THREE.DataTexture(). I'll try that when I get to it... Looking at the source looks like it might be quite a lot of work, but unless anything comes up, I'll try that.

Resources