Three.js does not show texture on sphere - google-chrome

There are some threads about textures which do not showing up. I have tried them all, but nothing helped.
I have spent a few hours on this now. Every time I end up looking at a black sphere.
I am working on Chrome v18 and Windows 7. I also tried Firefox, but this browser does not really support Three.js.
This is the body of the script:
<body>
<script src="../build/Three.js"></script>
<script src="js/Stats.js"></script>
<script src="../build/jquery-1.7.2.min.js"></script>
This is the script itself:
// stap1) camera, set the scene size
var WIDTH = 400,
HEIGHT = 300;
// set some camera attributes
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.1,
FAR = 10000;
var camera = new THREE.PerspectiveCamera(
VIEW_ANGLE,
ASPECT,
NEAR,
FAR );
// stap2) scene:
var scene = new THREE.Scene();
// the camera starts at 0,0,0 so pull it back
scene.add(camera);
camera.position.z = +300;
// get the DOM element to attach to
// - assume we've got jQuery to hand
var container = $('#container');
// stap3)create a WebGL renderer:
var renderer = new THREE.WebGLRenderer();
// start the renderer
renderer.setSize(WIDTH, HEIGHT);
// attach the render-supplied DOM element
container.append(renderer.domElement);
// bol maken:
// create the sphere's material
// b.v: THREE.MeshBasicMaterial
var sphereMaterial = new THREE.MeshLambertMaterial(
{
map: THREE.ImageUtils.loadTexture("http://dev.root.nl/tree/examples/textures/ash_uvgrid01.jpg")
});
// set up the sphere vars
var radius = 50, segments = 16, rings = 16;
var sphereGeometry = new THREE.SphereGeometry(radius, segments, rings);
// create a new mesh with sphere geometry -
var sphere = new THREE.Mesh(
sphereGeometry,
sphereMaterial
);
sphere.position.x=0;
var s=1;
sphere.scale.set(s, s, s);
// add the sphere to the scene
scene.add(sphere);
// create a point light
var pointLight = new THREE.PointLight( 0xFFFFFF );
// set its position
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
// add to the scene
scene.add(pointLight);
// draw!
renderer.render(scene, camera);

You need to wait until the image used as texture is fully downloaded.
I have put your code on the web: http://jsfiddle.net/4Qg7K/ and just added a classic "render loop":
requestAnimationFrame(render);
function render(){
requestAnimationFrame(render);
sphere.rotation.y += 0.005; //rotation stuff, just for fun
renderer.render(scene, camera);
};
requestAnimationFrame function works like a timer, calling to the render function each time the browser is ready to update the web page.
BTW, Three.js works fine with Firefox.

Related

THEE.JSONLoader Object as public variable

I was wondering if its possible to add an object that is loaded via THREE.JSONLoader as public variable? Ideally, I'd like all my loaded textures, material creation, and geometry to be public variables at the top of my script for easy manipulation (I have strong 3D background but new to js and webGL). I'm finding that my public vars that are declared something - are no longer public once they're added as a parameter to a function - in this case the JSONLoader. However, just naming a var, without declaring its value "runs" but I get weird THREE.min.js error I can't comprehend. I've included my code below - know it has other issues - please feel free to let me know how bad it is - it helps me learn :)
//webGL
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.position.set(0, 16, 25);
camera.rotation.x += -0.32;
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
cubeCamera = new THREE.CubeCamera(1, 1000, 256); // parameters: near, far, resolution
cubeCamera.renderTarget.texture.minFilter = THREE.LinearMipMapLinearFilter; // mipmap filter
scene.add(cubeCamera);
///LOADERS
var loadTexture = new THREE.TextureLoader();
var loaderJs = new THREE.JSONLoader();
///TEXTURES
var skyTexture = loadTexture.load("textures/background.jpg");
var seatTexture = loadTexture.load("textures/abc_Diffuse.jpg");
///MATERIALS
var skyMaterial = new THREE.MeshBasicMaterial({
side: THREE.DoubleSide,
map: skyTexture
});
var frameMaterial = new THREE.MeshLambertMaterial({
//envMap: cubeCamera.renderTarget,
color: 0xffffff
});
var seatMaterial = new THREE.MeshLambertMaterial({
map: seatTexture
});
///GEOMETRY and MESHES
var frameGeo;
var skyGeo = new THREE.SphereGeometry(30, 30, 30);
var skySphere = new THREE.Mesh(skyGeo, skyMaterial);
scene.add(skySphere);
loaderJs.load("models/stoolFrame.js", function (){
frameGeo = new THREE.Mesh(frameGeo, frameMaterial);
frameGeo.scale.set(.5, .5, .5);
barStool.add(frameGeo);
});
loaderJs.load("models/stoolSeat.js", function (seatGeo){
seatGeo = new THREE.Mesh(seatGeo, seatMaterial);
seatGeo.scale.set(.5, .5, .5);
barStool.add(seatGeo);
});
var barStool = new THREE.Object3D();
scene.add(barStool);
var render = function () {
requestAnimationFrame(render);
barStool.rotation.y += 0.01;
frameGeo.visible = false;
cubeCamera.position.copy(frameGeo.position);
cubeCamera.updateCubeMap(renderer, scene);
frameGeo.visible = true;
renderer.render(scene, camera);
};
render();
When loading your stoolFrame, you forgot to add the parameters for the callback function, check the documentation example. The callback function takes a geometry and a material. When loading the stoolSeat you forgot the material aswell (provided you have a material for the stool)
var frameGeometry;
var frameMaterial;
var frameMesh;
loaderJs.load("models/stoolFrame.js", function (geometry, material){
frameGeometry = geometry;
frameMaterial = material
frameMesh = new THREE.Mesh(frameGeometry, frameMaterial);
frameMesh.scale.set(.5, .5, .5);
barStool.add(frameMesh);
});
Above is an example on how to make the geometry, material and mesh into global variables. However you probably dont need to save the geometry and material as global vars (you can access them from the mesh anyway: frameMesh.material; frameMesh.geometry).
If the parameter names are the same as a global variable name, javascript will use the parameter variable instead of the global one when trying to access it.

three. scene is not a function

I'm using three.js and the attached code is returning the following error
Uncaught TypeError: THREE.Scene is not a function
init # new 1.html:18
on this line
scene=new THREE.Scene();
What could be causing this and how can I go about fixing it?
window.onload = init
var scene, camera, render;
function init() {
container = document.createElement('div');
document.body.appendChild(container);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 0.1, 200); //перспективная проекция
camera.position.y = 150;
camera.position.z = 500;
var line_geometry = new THREE.Geometry();
line_geometry.vertices.push(new THREE.Vector3(0, 0, 0));
line_geometry.vertices.push(new THREE.Verctor3(0, 40, 50));
var line = new THREE.Line(line_geometry);
scene.add(line);
render = new THREE.WebGLRender(); //рендеринг
render = setSize(window.innerWidth, window.innerHeight); //инициализация рендеринга
container.appendChild(render.domElement); //??
render.render(scene);
}
Here is a screen shot of the error.
You have many typos in your code:
Verctor3 instead of Vector3
WebGLRender instead of WebGLRenderer
render.render(scene); instead of render.render(scene, camera);
and so on.
Also you should just run init() at start instead of window.onload=init.
Generally - please refer to this page. There are many working examples there.

ThreeJS load time and texture rendering problems

I have a 3D object of a chair made in Blender and exported as a .obj and .mtl. First of all, the load time is a horrendous 40+ seconds; I have no idea why (Visual Studio possibly?) Second, the images textures are not loading properly. With no ambient or directional lighting I get a silhouette. With the lighting I get a slight hint of gray to give a little depth but nothing close to the many colors in the original object. I have only been working with ThreeJS for a few days now so I'm quite new to it. Hence, I am at a loss. I have read several artciles related to my issue but none seem to solve the problem. I even went so far as to add an addon to Blender to export to .js. I could not get it to even load properly (I assume it had to do with the fact I kept the same loader info from the .OBJMTLLoader and the .JSONLoader doesn't support or needs more than what I gave; I just am not familiar enough with it know). Any ideas/suggestions? Here is my script:
`
<script src="js/three.min.js"></script>
<script src="js/controls/TrackballControls.js"></script>
<script src="js/loaders/MTLLoader.js"></script>
<script src="js/loaders/OBJMTLLoader.js"></script>
<script src="js/Detector.js"></script>
<script>
if (!Detector.webgl) Detector.addGetWebGLMessage();
var container;
var camera, controls, scene, renderer;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 0.01, 1e10);
camera.position.z = 2;
//controls
controls = new THREE.TrackballControls(camera);
controls.rotateSpeed = 5.0;
controls.zoomSpeed = 5;
controls.panSpeed = 2;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
scene = new THREE.Scene();
scene.add(camera);
//lights
var ambient = new THREE.AmbientLight(0xCCCCCC);
scene.add(ambient);
var directionalLight = new THREE.DirectionalLight(0xCCCCCC);
directionalLight.position.set(0, 0, 2).normalize();
scene.add(directionalLight);
//main img
var material = new THREE.MeshBasicMaterial({ color: '0xCCCCCC' });
var loader = new THREE.OBJMTLLoader();
loader.addEventListener('load', function (event) {
var geometry = event.content;
//var mesh = new THREE.Mesh(geometry);
scene.add(geometry, material);
});
loader.load('chair.obj', 'chair.mtl');
// renderer
renderer = new THREE.WebGLRenderer({ antialias: false });
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
//
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
controls.handleResize();
}
function animate() {
requestAnimationFrame(animate);
render();
controls.update();
}
function render() {
var timer = Date.now() * 0.0005;
renderer.render(scene, camera);
}
</script>
`
Well, you are defining a gray MeshBasicMaterial to use with your obj instead of using the material(s) that the loader will create for you, i guess.
Just use this. The "object" should have the material defined in your mtl-file.
loader.addEventListener( 'load', function ( event ) {
var object = event.content;
scene.add( object );
});
loader.load( 'chair.obj', 'chair.mtl' );
Concerning your load time: Could be your local server. Also, be aware that the obj file format ist quite big in raw ascii format. Also, if the mtl-file defines textures, they are maybe quite big in file size, too.
#GuyGood was correct in my case for the long load time. I was using the python simplehttpserver and switch to a node server and no more slow texture loading problems. Check out the threejs wiki for other local server options.

How to see back face of sphere?

// set the scene size
var WIDTH = 800;
var HEIGHT = 640;
// set some camera attributes
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.1,
FAR = 10000;
var $container = $('#container');
// create a WebGL renderer, camera
var renderer = new THREE.WebGLRenderer();
var camera = new THREE.PerspectiveCamera(VIEW_ANGLE,
ASPECT,
NEAR,
FAR);
var scene = new THREE.Scene();
// the camera starts at 0,0,0 so pull it back
camera.position.z = 1000;
// start the renderer
renderer.setSize(WIDTH, HEIGHT);
// attach the render-supplied DOM element
$container.append(renderer.domElement);
// create the sphere's material
var sphereMaterial = new THREE.MeshLambertMaterial({
color: 0xCC0000
});
// set up the sphere vars
var radius = 50, segments = 16, rings = 16;
// create a new mesh with sphere geometry -
// we will cover the sphereMaterial next!
var sphere = new THREE.Mesh(
new THREE.SphereGeometry(radius, segments, rings),
sphereMaterial);
sphere.position.x = 20;
sphere.doubleSided = true;
// add the sphere to the scene
scene.add(sphere);
// and the camera
scene.add(camera);
/* Light it up */
var pointLight = new THREE.PointLight(0xFFFFFF);
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
scene.add(pointLight);
window.setInterval(update, 16.66666666);
var keyboard = new THREEx.KeyboardState();
function update() {
if (keyboard.pressed("W")) {
camera.position.z -= 5;
} else if (keyboard.pressed("S")) {
camera.position.z += 5;
}
renderer.render(scene, camera);
}
That is my code, a simple demow here using W and S keys makes me go zoom in/out a 3D Sphere.
However, when I get "inside" the sphere, I can't see it's back face, even though I put sphere.doubleSided = true;.
I tried putting renderer.setFaceCulling(true); (and false too), but none of them fixed it.
Any ideas?
use side: THREE.DoubleSide in material
which version of three.js are you using ?
jsfiddle

Three.js: tiling textures, buffering and browser compatibility

I am working on a project in html 5 canvas. For this I use the three.js library to draw some simple cubes in the shape of a simple cupboard. I have already added ambient lighting, anti-aliasing and textures. If all goes well it renders the cupboard and you can use your mouse to move it around.
Current issues:
var textureMap = map: THREE.ImageUtils.loadTexture("wood1.jpg")
textureMap.wrapS = THREE.RepeatWrapping;
textureMap.wrapT = THREE.RepeatWrapping;
textureMap.repeat.x = 100;
textureMap.repeat.y = 100;
material = new THREE.MeshLambertMaterial(textureMap);
The texture is currently stretched over each surface. I prefer tiling but can't seem to get it working. The code above was the best guess I came up with based on what I found on a site (sorry, can't share more links with my current reputation). It is commented out because it stops the script from running at all.
I used to have some lag issues. After a quick search I found a site (sorry, can't share more links with my current reputation) that told me I had to put a timeout in the main loop and that I should use a second canvas for buffering. Adding the timeout worked like a charm but I'm still curious about the buffering canvas. I'm unsure how to go about this since I'm dealing with a renderer and a canvas. I don't even know if I should still bother with a buffer, since it seems to work just fine now, although that may change in the future when I try to render more meshes at a time.
My code currently only runs in firefox for me. Chrome and Internet explorer both just show a blank screen. Any ideas what I need to change in order to fix this?
When I run the code in firefox the cupboard is completely black at first. When I move it (at all) it immediately changes to the texture. Any ideas? I could come up with a dirty fix that moves the camera up and down 1 pixel in the setup but I'd rather not.
I tried uploading the code to jsfiddle (importing the texture from tinypic) but that doesn't go so well. Either I'm importing the texture wrong or jsfiddle just doesn't like it when I use external pictures. However, if you download the texture and put it in the same folder as the code you should be able to open it in firefox (only works in firefox (see issue 4)). So if you want to see what's going on: copy the code into a .html file and download the texture.
<!DOCTYPE HTML>
<html>
<head>
<title>Canvas demo</title>
<script type="text/javascript" src="http://www.html5canvastutorials.com/libraries/Three.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
//three.js vars
var camera;
var scene;
var renderer;
var material;
var directionalLight;
//input vars
var lastX = 0;
var lastY = 450;
var clickX;
var clickY;
var mousedown;
function rerender(){
//draw
renderer.render(scene, camera);
//redraw after 25 ms (the 25 ms delay reduces lag)
setTimeOut( requestAnimFrame(function(){rerender()}), 25);
}
$(document).ready(function() {
//initialize renderer
renderer = new THREE.WebGLRenderer({antialias : true});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.domElement.id = "visiblecanvas";
document.body.appendChild(renderer.domElement);
//camera
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.y = -450;
camera.position.z = 400;
camera.rotation.x = 45.2;
//scene
scene = new THREE.Scene();
//material
//non-working tiled texture
/*
var textureMap = map: THREE.ImageUtils.loadTexture("wood1.jpg")
textureMap.wrapS = THREE.RepeatWrapping;
textureMap.wrapT = THREE.RepeatWrapping;
textureMap.repeat.x = 100;
textureMap.repeat.y = 100;
*/
//workingg stretched texture
material = new THREE.MeshLambertMaterial({map: THREE.ImageUtils.loadTexture("wood1.jpg")});
//the cupboard
//cube
var cube1 = new THREE.Mesh(new THREE.CubeGeometry(300,50,10), material);
cube1.overdraw = true;
scene.add(cube1);
//cube
var cube2 = new THREE.Mesh(new THREE.CubeGeometry(300,10,300), material);
cube2.overdraw = true;
cube2.position.z += 150;
cube2.position.y += 20;
scene.add(cube2);
//cube
var cube3 = new THREE.Mesh(new THREE.CubeGeometry(10,50,300), material);
cube3.overdraw = true;
cube3.position.z += 150;
cube3.position.x += 145;
scene.add(cube3);
//cube
var cube4 = new THREE.Mesh(new THREE.CubeGeometry(10,50,300), material);
cube4.overdraw = true;
cube4.position.z += 150;
cube4.position.x -= 145;
scene.add(cube4);
//cube
var cube5 = new THREE.Mesh(new THREE.CubeGeometry(300,50,10), material);
cube5.overdraw = true;
cube5.position.z += 300;
scene.add(cube5);
// add subtle ambient lighting
var ambientLight = new THREE.AmbientLight(0x555555);
scene.add(ambientLight);
// add directional light source
directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);
//mousedown event
$('#visiblecanvas').mousedown(function(e){
clickX = e.pageX - this.offsetLeft + lastX;
clickY = e.pageY - this.offsetLeft + lastY;
mousedown = true;
});
//mousemove event, act if mousedown
$('#visiblecanvas').mousemove(function(e){
if(mousedown) {
var xDiff = e.pageX - this.offsetLeft - clickX;
var yDiff = e.pageY - this.offsetLeft - clickY;
lastX = -xDiff;
lastY = -yDiff;
camera.position.x = lastX;
camera.position.y = -lastY;
rerender();
}
delay(5);
});
//mouseup event
$('#visiblecanvas').mouseup(function(e){
mousedown = false;
});
//mouseleave event (mouse leaves canvas, stop moving cupboard)
$('#visiblecanvas').mouseleave(function(e){
mousedown = false;
});
rerender();
});
//request new frame
window.requestAnimFrame = (function (callback){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback){
window.setTimeout(callback, 1000 / 60);
};
})();
</script>
</body>
</html>
Thanks for taking a look! hope you can answer any of my questions.
1) Use JavaScript console to debug the code.
2) The jsfiddle is missing jQuery.
3) This line:
var textureMap = map: THREE.ImageUtils.loadTexture("wood1.jpg")
must be:
var textureMap = THREE.ImageUtils.loadTexture("wood1.jpg");
See the extra map: and the missing semicolon.
4) The repeat texture parameters are too big. Default value is 1, to repeat the texture one time. Try to change that values to 2, 3, ... and so.
5) delay function is undefined, remove it
6) setTimeOut function is undefined (setTimeout?, JavaScript is case sensitive)
7) Rewrite the rendererer function to this:
function rerender(){
requestAnimFrame(rerender);
renderer.render(scene, camera);
}
Take a look at this: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
8) Remove the call to the rerender function inside the mousemove event
9) IE and WebGL?
Try:
function rerender(){
requestAnimFrame(rerender);
renderer.render(scene, camera);
}