THREE.js: calling lookAt method after rendering does not work - javascript

The script below isn't working properly. (It just needs jquery and three.js to run). The troublesome lines are these two:
// change the view so looking at the top of the airplane
views[1].camera.position.set( 0,5,0 );
views[1].camera.lookAt(objectManager.airplane.position);
Strangely, if those two lines are commented out, it can be seen that the two similar preceeding lines below do run as expected:
views[1].camera.lookAt(objectManager.airplane.position);
and
view.camera.position.set( 5,0,0 );
For some reason it seems that the call to camera.lookAt only works the first time. After that, the camera no longer follows the airplane object. I'd be extremely grateful if someone can figure out what I'm doing wrong!
The full script is below.
Thanks
$(function(){
var scene, renderer, viewPort, objectManager, views;
init();
animate();
function init() {
viewPort = $('body');
scene = new THREE.Scene();
// construct the two cameras
initialiseViews();
// construct airplane, lights and floor grid
objectManager = new ObjectManager();
objectManager.construct();
objectManager.addToScene(scene);
// make the second camera's position
// stay fixed relative to the airplane
objectManager.airplane.add(views[1].camera);
// make the second camera stay looking
// at the airplane
views[1].camera.lookAt(objectManager.airplane.position);
renderer = new THREE.WebGLRenderer();
renderer.setClearColorHex(0x000000, 1);
renderer.setSize( viewPort.innerWidth(), viewPort.innerHeight() );
viewPort.get(0).appendChild(renderer.domElement);
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
objectManager.tick();
for (var i in views){
views[i].render(scene, renderer);
}
}
function initialiseViews(){
views = [];
// ----------------------------------------------------
// Create the first view, static with respect to ground
// ----------------------------------------------------
views[0] = new View(viewPort, objectManager, scene);
var view = views[0];
view.fov = 40;
view.proportions.height = 0.5;
view.proportions.bottom = 0.5;
view.init();
view.camera.position.y = 1;
view.camera.position.z = 4;
// ----------------------------------------------------
// Create the second view, which follows the airplane
// ----------------------------------------------------
views[1] = new View(viewPort, objectManager, scene);
var view = views[1];
view.fov = 20;
view.proportions.height = 0.5;
view.init();
// set the initial position of the camera
// with respect to the airplane. Views from behind
view.camera.position.set( 5,0,0 );
view.updateCamera = function(){
// change the view so looking at the top of the airplane
views[1].camera.position.set( 0,5,0 );
views[1].camera.lookAt(objectManager.airplane.position);
views[1].camera.updateProjectionMatrix();
};
}
});
function View(viewport, om, scene){
this.scene = scene;
this.camera;
this.objectManager = om;
this.viewPort = viewport;
this.fov = 30;
// default: full width and height
this.proportions = { left: 0, bottom: 0, height: 1, width: 1 };
this.pixels = { left: 0, bottom: 0, height: 0, width: 0, aspect: 0 };
this.aspect;
this.init = function(){
this.pixels.left = Math.floor(this.proportions.left * this.viewPort.innerWidth());
this.pixels.width = Math.floor(this.proportions.width * this.viewPort.innerWidth());
this.pixels.bottom = Math.floor(this.proportions.bottom * this.viewPort.innerHeight());
this.pixels.height = Math.floor(this.proportions.height * this.viewPort.innerHeight());
this.pixels.aspect = this.pixels.width / this.pixels.height;
this.makeCamera();
};
this.makeCamera = function(){
this.camera = new THREE.PerspectiveCamera(
this.fov,
this.pixels.aspect,
0.1, 10000
);
this.camera.updateProjectionMatrix();
this.scene.add(this.camera);
};
this.render = function(scene, renderer){
this.updateCamera();
pixels = this.pixels;
renderer.setViewport(pixels.left, pixels.bottom, pixels.width, pixels.height);
renderer.setScissor(pixels.left, pixels.bottom, pixels.width, pixels.height);
renderer.enableScissorTest(true);
renderer.render( scene, this.camera );
};
this.updateCamera = function(){};
}
function ObjectManager(){
// manages all visible 3d objects (including lights)
this.airplane;
var grid;
var ambientLight;
var pointLight;
this.construct = function(){
this.constructAirplane();
this.constructLights();
this.constructFloorGrid();
};
this.constructAirplane = function(){
this.airplane = new THREE.Object3D();
var fuselage = newCube(
{x: 1, y: 0.1, z: 0.1},
{x: 0, y: 0, z: 0},
[0xffff00, 0x808000, 0x0000ff, 0xff00000, 0xffffff, 0x808080],
[0, 1, 2, 3, 4, 5]
);
this.airplane.add(fuselage);
var tail = newCube(
{x: 0.15, y: 0.2, z: 0.03},
{x: 0.5, y: 0.199, z: 0},
[0xffff00, 0x808000, 0x0000ff, 0xff00000, 0xffffff, 0x808080],
[0, 1, 2, 3, 4, 5]
);
this.airplane.add(tail);
var wings = newCube(
{x: 0.3, y: 0.05, z: 1},
{x: -0.05, y: 0, z: 0},
[0xffff00, 0x808000, 0x0000ff, 0xff00000, 0xffffff, 0x808080],
[0, 1, 2, 3, 4, 5]
);
this.airplane.add(wings);
};
this.constructLights = function(){
ambientLight = new THREE.AmbientLight(0x808080);
pointLight = new THREE.PointLight(0x808080);
pointLight.position = {x: 100, y: 100, z: 100};
};
this.constructFloorGrid = function(){
grid = new THREE.Object3D();
var geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3( - 200, 0, 0 ) );
geometry.vertices.push(new THREE.Vector3( 200, 0, 0 ) );
linesMaterial = new THREE.LineBasicMaterial( { color: 0x00ff00, opacity: 1, linewidth: .1 } );
for ( var i = 0; i <= 200; i ++ ) {
var line = new THREE.Line( geometry, linesMaterial );
line.position.z = ( i * 2 ) - 200;
grid.add( line );
var line = new THREE.Line( geometry, linesMaterial );
line.position.x = ( i * 2 ) - 200;
line.rotation.y = 90 * Math.PI / 180;
grid.add( line );
}
};
this.addToScene = function(scene){
scene.add( this.airplane );
scene.add( grid );
scene.add( ambientLight );
scene.add( pointLight );
};
this.tick = function(){
this.airplane.rotation.x += 0.005;
this.airplane.rotation.y += 0.01;
this.airplane.position.x -= 0.05;
};
};
function newCube(dims, pos, cols, colAss){
var mesh;
var geometry;
var materials = [];
geometry = new THREE.CubeGeometry( dims.x, dims.y, dims.z );
for (var i in cols){
materials[i] = new THREE.MeshLambertMaterial( { color: cols[i], ambient: cols[i], overdraw: true } );
}
geometry.materials = materials;
for (var i in colAss){
geometry.faces[i].materialIndex = colAss[i];
}
mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ) );
mesh.position = pos;
return mesh;
}

You need to do this:
views[1].camera.position.set( 0, 5, 0 );
views[1].camera.lookAt( new THREE.Vector3() );
and not this:
views[1].camera.position.set( 0, 5, 0 );
views[1].camera.lookAt( objectManager.airplane.position );
Your camera is a child of the airplane. It needs to lookAt ( 0, 0, 0 ) in it's local coordinate system -- not the airplane's position in world space.
Your calls to updateProjectionMatrix() are not necessary. Copy the three.js examples.

Related

Three.js Animated curve

I try to animate a 2D curve in Three.js over time.
I'll need more than 4 control points, so I'm not using Bezier curves.
I created a Three.Line based on a SplineCurve.
If I log the geometry.vertices position of my line they'll change over time, but geometry.attributes.position remains the same. Is it possible to animate the line based on the curve animation ? I managed to do this with Bezier Curves, but can't find a way with SplineCurve.
Thank you for your help, here's my code :
First I create the line :
var curve = new THREE.SplineCurve( [
new THREE.Vector3( -10, 0, 10 ),
new THREE.Vector3( -5, 5, 5 ),
new THREE.Vector3( 0, 0, 0 ),
new THREE.Vector3( 5, -5, 5 ),
new THREE.Vector3( 10, 0, 10 )
] );
var points = curve.getPoints( 50 );
var geometry = new THREE.BufferGeometry().setFromPoints( points );
var material = new THREE.LineBasicMaterial( { color : 0xff0000 } );
// Create the final object to add to the scene
curveObject = new THREE.Line( geometry, material );
scene.add( curveObject );
curveObject.curve = curve;
Then I try to update it :
curveObject.curve.points[0].x += 1;
curveObject.geometry.vertices = curveObject.curve.getPoints( 50 );
curveObject.geometry.verticesNeedUpdate = true;
curveObject.geometry.attributes.needsUpdate = true;
You can do it like that:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, 1, 1, 1000);
camera.position.set(8, 13, 25);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
var canvas = renderer.domElement;
document.body.appendChild(canvas);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
scene.add(new THREE.GridHelper(20, 40));
var curve = new THREE.CatmullRomCurve3([
new THREE.Vector3(-10, 0, 10),
new THREE.Vector3(-5, 5, 5),
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(5, -5, 5),
new THREE.Vector3(10, 0, 10)
]);
var points = curve.getPoints(50);
var geometry = new THREE.BufferGeometry().setFromPoints(points);
var material = new THREE.LineBasicMaterial({
color: 0x00ffff
});
var curveObject = new THREE.Line(geometry, material);
scene.add(curveObject);
var clock = new THREE.Clock();
var time = 0;
render();
function resize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function render() {
if (resize(renderer)) {
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
renderer.render(scene, camera);
time += clock.getDelta();
curve.points[1].y = Math.sin(time) * 2.5;
geometry = new THREE.BufferGeometry().setFromPoints(curve.getPoints(50));
curveObject.geometry.dispose();
curveObject.geometry = geometry;
requestAnimationFrame(render);
}
html,
body {
height: 100%;
margin: 0;
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
display;
block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/97/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

Paint cube faces as a whole, not the triangles that make up the face - three.js

Trying to paint each cube face with a different color, I found a thread that presents a way to achieve this:
var geometry = new THREE.BoxGeometry(5, 5, 5);
for (var i = 0; i < geometry.faces.length; i++) {
geometry.faces[i].color.setHex(Math.random() * 0xffffff);
}
var material = new THREE.MeshBasicMaterial({
color: 0xffffff,
vertexColors: THREE.FaceColors
});
But with three.js r86, I get the following result:
Got the triangles that make up each face, painted individually.
To achieve the desirable effect, I used the following adaptation of the above code:
var geometry = new THREE.BoxGeometry(5, 5, 5);
for ( var i = 0; i < geometry.faces.length; i += 2 ) {
var faceColor = Math.random() * 0xffffff;
geometry.faces[i].color.setHex(faceColor);
geometry.faces[i+1].color.setHex(faceColor);
}
var material = new THREE.MeshBasicMaterial({
color: 0xffffff,
vertexColors: THREE.FaceColors
});
But this all seems a bit over worked!
'use strict';
var camera, scene, renderer, cube;
init();
render();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
// renderer
renderer = new THREE.WebGLRenderer({
alpha: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
camera.position.z = 12;
// Mesh - cube
var geometry = new THREE.BoxGeometry(5, 5, 5);
for (var i = 0; i < geometry.faces.length; i += 2) {
var faceColor = Math.random() * 0xffffff;
geometry.faces[i].color.setHex(faceColor);
geometry.faces[i + 1].color.setHex(faceColor);
}
var material = new THREE.MeshBasicMaterial({
color: 0xffffff,
vertexColors: THREE.FaceColors
});
cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// Light
var pointLight = new THREE.PointLight(0xFFFFFF);
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
scene.add(pointLight);
}
function render() {
cube.rotation.x = 16;
cube.rotation.y = 4;
cube.rotation.z -= 5;
renderer.render(scene, camera);
}
body,
canvas {
margin: 0;
padding: 0;
}
body {
overflow: hidden;
background-color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/86/three.js"></script>
Am I missing something on three.js to accomplish the face painting as a whole ?
If you switch to BufferGeometry you can use groups to control the material of sections of your geometry. Groups are based on the vertex indices, and allow you to define a material index, which will reference a material inside an array of materials.
Consider:
// start, count, material index
bufferGeometry.addGroup(12, 6, 2)
This tells the geometry to start a new group of triangles at indices index 12, and accounts for 6 indices (which reference 6 vertices). The final parameter tells the group of triangles to use material index 2 (index 2 of the array of materials you use to create the mesh).
In the example below, I've given each side of a cube a different color. You might think this is the same effect as setting face colors, but note that this is setting a material per group, not just a color, which can lead to creating some really cool effects.
var renderer, scene, camera, controls, stats, mesh;
var WIDTH = window.innerWidth,
HEIGHT = window.innerHeight,
FOV = 35,
NEAR = 1,
FAR = 1000;
function populateScene() {
var bg = new THREE.BufferGeometry();
bg.addAttribute("position", new THREE.BufferAttribute(new Float32Array([
// front
-1, 1, 1, // 0
-1, -1, 1, // 1
1, 1, 1, // 2
1, -1, 1, // 3
// right
1, 1, 1, // 4
1, -1, 1, // 5
1, 1, -1, // 6
1, -1, -1, // 7
// back
1, 1, -1, // 8
1, -1, -1, // 9
-1, 1, -1, // 10
-1, -1, -1, // 11
// left
-1, 1, -1, // 12
-1, -1, -1, // 13
-1, 1, 1, // 14
-1, -1, 1, // 15
// top
-1, 1, -1, // 16
-1, 1, 1, // 17
1, 1, -1, // 18
1, 1, 1, // 19
// bottom
-1, -1, 1, // 20
-1, -1, -1, // 21
1, -1, 1, // 22
1, -1, -1 // 23
]), 3));
bg.addAttribute("normal", new THREE.BufferAttribute(new Float32Array([
// front
0, 0, 1, // 0
0, 0, 1, // 1
0, 0, 1, // 2
0, 0, 1, // 3
// right
1, 0, 0, // 4
1, 0, 0, // 5
1, 0, 0, // 6
1, 0, 0, // 7
// back
0, 0, -1, // 8
0, 0, -1, // 9
0, 0, -1, // 10
0, 0, -1, // 11
// left
-1, 0, 0, // 12
-1, 0, 0, // 13
-1, 0, 0, // 14
-1, 0, 0, // 15
// top
0, 1, 0, // 16
0, 1, 0, // 17
0, 1, 0, // 18
0, 1, 0, // 19
// bottom
0, -1, 0, // 20
0, -1, 0, // 21
0, -1, 0, // 22
0, -1, 0 // 23
]), 3));
bg.setIndex(new THREE.BufferAttribute(new Uint32Array([
// front 0
0, 1, 2,
3, 2, 1,
// right 6
4, 5, 6,
7, 6, 5,
// back 12
8, 9, 10,
11, 10, 9,
// left 18
12, 13, 14,
15, 14, 13,
// top 24
16, 17, 18,
19, 18, 17,
// bottom 30
20, 21, 22,
23, 22, 21
]), 1));
bg.clearGroups();
// start, count, material index
bg.addGroup(0, 6, 0);
bg.addGroup(6, 6, 1);
bg.addGroup(12, 6, 2);
bg.addGroup(18, 6, 3);
bg.addGroup(24, 6, 4);
bg.addGroup(30, 6, 5);
var materials = [
new THREE.MeshLambertMaterial({color:"red"}),
new THREE.MeshLambertMaterial({color:"green"}),
new THREE.MeshLambertMaterial({color:"blue"}),
new THREE.MeshLambertMaterial({color:"cyan"}),
new THREE.MeshLambertMaterial({color:"magenta"}),
new THREE.MeshLambertMaterial({color:"yellow"})
];
mesh = new THREE.Mesh(bg, materials);
mesh.scale.set(5, 5, 5);
scene.add(mesh);
}
function init() {
document.body.style.backgroundColor = "slateGray";
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.appendChild(renderer.domElement);
document.body.style.overflow = "hidden";
document.body.style.margin = "0";
document.body.style.padding = "0";
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(FOV, WIDTH / HEIGHT, NEAR, FAR);
camera.position.z = 50;
scene.add(camera);
controls = new THREE.TrackballControls(camera, renderer.domElement);
controls.dynamicDampingFactor = 0.5;
controls.rotateSpeed = 3;
var light = new THREE.PointLight(0xffffff, 1, Infinity);
camera.add(light);
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0';
document.body.appendChild(stats.domElement);
resize();
window.onresize = resize;
populateScene();
animate();
}
function resize() {
WIDTH = window.innerWidth;
HEIGHT = window.innerHeight;
if (renderer && camera && controls) {
renderer.setSize(WIDTH, HEIGHT);
camera.aspect = WIDTH / HEIGHT;
camera.updateProjectionMatrix();
controls.handleResize();
}
}
function render() {
renderer.render(scene, camera);
}
function animate() {
mesh.rotation.x += 0.015;
mesh.rotation.y += 0.017;
mesh.rotation.z += 0.019;
requestAnimationFrame(animate);
render();
controls.update();
stats.update();
}
function threeReady() {
init();
}
(function() {
function addScript(url, callback) {
callback = callback || function() {};
var script = document.createElement("script");
script.addEventListener("load", callback);
script.setAttribute("src", url);
document.head.appendChild(script);
}
addScript("https://threejs.org/build/three.js", function() {
addScript("https://threejs.org/examples/js/controls/TrackballControls.js", function() {
addScript("https://threejs.org/examples/js/libs/stats.min.js", function() {
threeReady();
})
})
})
})();
Edit: Adding a second example using the base BoxBufferGeometry
Based on pailhead's comment to the original post, here's a snippet which uses unmodified BoxBufferGeometry. But as they mentioned in their comment, you'll still need to know which group corresponds to which face.
var renderer, scene, camera, controls, stats, mesh;
var WIDTH = window.innerWidth,
HEIGHT = window.innerHeight,
FOV = 35,
NEAR = 1,
FAR = 1000;
function populateScene() {
var bg = new THREE.BoxBufferGeometry(1, 1, 1);
var materials = [
new THREE.MeshLambertMaterial({color:"red"}),
new THREE.MeshLambertMaterial({color:"green"}),
new THREE.MeshLambertMaterial({color:"blue"}),
new THREE.MeshLambertMaterial({color:"cyan"}),
new THREE.MeshLambertMaterial({color:"magenta"}),
new THREE.MeshLambertMaterial({color:"yellow"})
];
mesh = new THREE.Mesh(bg, materials);
mesh.scale.set(10, 10, 10);
scene.add(mesh);
}
function init() {
document.body.style.backgroundColor = "slateGray";
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.appendChild(renderer.domElement);
document.body.style.overflow = "hidden";
document.body.style.margin = "0";
document.body.style.padding = "0";
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(FOV, WIDTH / HEIGHT, NEAR, FAR);
camera.position.z = 50;
scene.add(camera);
controls = new THREE.TrackballControls(camera, renderer.domElement);
controls.dynamicDampingFactor = 0.5;
controls.rotateSpeed = 3;
var light = new THREE.PointLight(0xffffff, 1, Infinity);
camera.add(light);
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0';
document.body.appendChild(stats.domElement);
resize();
window.onresize = resize;
populateScene();
animate();
}
function resize() {
WIDTH = window.innerWidth;
HEIGHT = window.innerHeight;
if (renderer && camera && controls) {
renderer.setSize(WIDTH, HEIGHT);
camera.aspect = WIDTH / HEIGHT;
camera.updateProjectionMatrix();
controls.handleResize();
}
}
function render() {
renderer.render(scene, camera);
}
function animate() {
mesh.rotation.x += 0.015;
mesh.rotation.y += 0.017;
mesh.rotation.z += 0.019;
requestAnimationFrame(animate);
render();
controls.update();
stats.update();
}
function threeReady() {
init();
}
(function() {
function addScript(url, callback) {
callback = callback || function() {};
var script = document.createElement("script");
script.addEventListener("load", callback);
script.setAttribute("src", url);
document.head.appendChild(script);
}
addScript("https://threejs.org/build/three.js", function() {
addScript("https://threejs.org/examples/js/controls/TrackballControls.js", function() {
addScript("https://threejs.org/examples/js/libs/stats.min.js", function() {
threeReady();
})
})
})
})();
Using groups will split the geometry in 6 faces, for drawing a simple cube you can also use a simple custom ShaderMaterial.
Splitting geometry in 6 groups requires more draw calls, instead of using 1 draw call for drawing a cube you are using 6, one for each face.
Using a ShaderMaterial requires only 1 draw call:
Vertex Shader:
attribute vec3 vertexColor;
varying vec3 vColor;
void main() {
vColor = vertexColor;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.);
}
Fragment Shader:
varying vec3 vColor;
void main() {
gl_FragColor = vec4(vColor, 1.);
}
This way you could also use GLSL color blending for merging different colors.
Custom ShaderMaterial just setting vertex and fragment shader source strings:
const ColorCubeShader = function () {
THREE.ShaderMaterial.call(this, {
vertexShader: vertexShaderSrc,
fragmentShader: fragmentShaderSrc
})
}
ColorCubeShader.prototype = Object.create(THREE.ShaderMaterial.prototype)
ColorCubeShader.prototype.constructor = ColorCubeShader
Color Cube custom Mesh:
/**
* Convenience method for coloring a face
* #param {Number} r
* #param {Number} g
* #param {Number} b
* #returns {Array}
*/
const buildVertexColorArrayFace = function (r, g, b) {
return [
r, g, b,
r, g, b,
r, g, b,
r, g, b
]
}
const ColorCube = function (size) {
const geometry = new THREE.BoxBufferGeometry(size, size, size)
// build color array
let colorArray = []
colorArray = colorArray
.concat(buildVertexColorArrayFace(1, 0, 0))
.concat(buildVertexColorArrayFace(0, 1, 0))
.concat(buildVertexColorArrayFace(0, 0, 1))
.concat(buildVertexColorArrayFace(1, 0, 1))
.concat(buildVertexColorArrayFace(1, 1, 0))
.concat(buildVertexColorArrayFace(0, 1, 1))
// create a buffer attribute for the colors (for attribute vec3 vertexColor)
const colorAttribute = new THREE.Float32BufferAttribute(
new Float32Array(colorArray), 3)
// set attribute vertexColor in vertex shader
geometry.setAttribute('vertexColor', colorAttribute)
// custom Shader Material instance
const material = new ColorCubeShader()
THREE.Mesh.call(this, geometry, material)
}
ColorCube.prototype = Object.create(THREE.Mesh.prototype)
ColorCube.prototype.constructor = ColorCube
Use it:
const cube = new ColorCube(1)
cube.position.set(0, 2, -2)
scene.add(cube)

How to create perfect ring geometry in three.js?

I need to create perfect ring geometry in three.js. I am looking for something like this:
I spend more than a day to find how to do this, and I am stuck with code like this:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
var controls = new THREE.OrbitControls( camera, renderer.domElement );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
ring = '';
var loader = new THREE.TextureLoader();
loader.load('img/water.jpg', function ( texture ) {
var geometry = new THREE.TorusGeometry( 5, 1, 8, 1900 );
ring = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({map: texture, wireframe: true}));
scene.add(ring);
});
camera.position.z = 20;
var render = function () {
requestAnimationFrame( render );
ring.rotation.y = 0.4;
renderer.render(scene,camera);
};
render();
EDIT:
My code has changed, and now it looks like this:
var container, stats;
var camera, scene, renderer;
var group;
var targetRotation = 0;
var targetRotationOnMouseDown = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.set( 100, 350, 00 );
scene.add( camera );
var light = new THREE.PointLight( 0xffffff, 0.9 );
camera.add( light );
group = new THREE.Group();
group.position.y = 0;
scene.add( group );
var loader = new THREE.TextureLoader();
var texture = loader.load( "img/metal.png" );
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set( 0.008, 0.008 );
function addShape( shape, extrudeSettings, color, x, y, z, rx, ry, rz, s ) {
// flat shape with texture
// note: default UVs generated by ShapeGemoetry are simply the x- and y-coordinates of the vertices
var geometry = new THREE.ExtrudeGeometry( shape, extrudeSettings );
var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial( { color: color } ) );
mesh.position.set( x, y, z );
mesh.rotation.set( rx, ry, rz );
mesh.scale.set( s, s, s );
group.add( mesh );
}
// Arc circle 1
var x = 0, y = 0;
var arcShape1 = new THREE.Shape();
arcShape1.moveTo( 0, 0 );
arcShape1.absarc( 10, 10, 11, 0, Math.PI*2, false );
var holePath1 = new THREE.Path();
holePath1.moveTo( 20, 10 );
holePath1.absarc( 10, 10, 10, 0, Math.PI*2, true );
arcShape1.holes.push( holePath1 );
//
// Arc circle 2
var x = 0, y = 0;
var arcShape2 = new THREE.Shape();
arcShape2.moveTo( 0, 0 );
arcShape2.absarc( 10, 10, 13, 0, Math.PI*2, false );
var holePath2 = new THREE.Path();
holePath2.moveTo( 25, 10 );
holePath2.absarc( 10, 10, 12, 0, Math.PI*2, true );
arcShape2.holes.push( holePath2 );
//
var extrudeSettings = { amount: 1.6, bevelEnabled: true, bevelSegments: 30, steps: 30, bevelSize: 0.3, bevelThickness: 1.5, curveSegments: 100 };
// addShape( shape, color, x, y, z, rx, ry,rz, s );
//addShape( heartShape, extrudeSettings, 0xf00000, 60, 100, 0, 0, 0, Math.PI, 1 );
addShape( arcShape1, extrudeSettings, 0xffc107, -35, -30, -20, 0, 0, 0, 4 );
addShape( arcShape2, extrudeSettings, 0xffc107, -40, -22, -50, 0, 0.6, 0, 4 );
//
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setClearColor( 0xf0f0f0 );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.shadowMapEnabled = true;
renderer.shadowMapType = THREE.PCFSoftShadowMap;
group.castShadow = true;
group.receiveShadow = false;
container.appendChild( renderer.domElement );
var controls = new THREE.OrbitControls( camera, renderer.domElement );
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
renderer.render( scene, camera );
}
The result looks like this:
And now the questions: how to make this line on the ring dissapear, how to make my ring more shiny, how to make my ring more 'circular' on the left and right side?
Should works fine. It was the bevel at junction at PI*2 causing the 'line' thing. You can solve the problem by overlapping the two edges of the curve.
arcShape1.absarc( 10, 10, 11, 0, Math.PI*1.99, false );
holePath1.absarc( 10, 10, 10, 0, Math.PI*2.01, true );
arcShape2.absarc( 10, 10, 13, 0, Math.PI*1.99, false );
holePath2.absarc( 10, 10, 12, 0, Math.PI*2.01, true );
! Please click to see the screenshot. I do not have enough reputation to post the picture here.
I found that by adding more light sources in various locations and color, I could increase perceived reflectivity and shine, but this is assuming it is the only object in the scene.

Disappearing line object in Three.js

I have a strange problem, which can be a three.js bug, but it also can be my curve hands.
I have a scene with some meshes (in example below I used several transparent cubes and small spheres) and one line object (can be Line or LineSegments - doesn't matter) based on buffer geometry. While I rotating the camera line object sometimes disappears form view like it's covered by another object. It seems it also disappears if I cannot see the start point (if rotate camera to a degree where start point is offscreen, even without additional meshes) of the line while 90% of the line object should be in view.
The question is: Why does the line disappear and how should I prevent such its behavior?
This is how it looks on screencast:
http://screencast.com/t/HLC99OMmDdK
And this is an example of the problem:
http://jsfiddle.net/exiara/sa4bxhc3/
You should be able to see how line disappears when camera rotates.
The code of jsfiddle example:
var camera, controls, scene, renderer, dummy, projector,
stats, fps = 30, fpsTimeout = 1000 / fps,
linesGeometry,globalLine;
init();
animate();
function init() {
renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setClearColor(0xFFFFeF, 1);
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
scene = new THREE.Scene();
scene.fog = new THREE.Fog( 0xFFFFeF, 100, 2500 );
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 50000 );
camera.position.set(-450, 300, 650);
camera.target = new THREE.Vector3(0,0,0);
controls = new THREE.OrbitControls( camera );
controls.addEventListener('change', render );
// ------------ MAIN PART START ------------ //
var lines = 1000;
linesGeometry = new THREE.BufferGeometry();
var positions = new Float32Array( lines * 6 );
for ( var i = 0, j, ll = lines; i < ll; i++ ) {
j=i*6;
positions[j] = Math.random()*100;
positions[j+1] = Math.random()*100;
positions[j+2] = Math.random()*100;
positions[j+3] = Math.random()*100;
positions[j+4] = Math.random()*100;
positions[j+5] = Math.random()*100;
}
linesGeometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
globalLine = new THREE.Line( linesGeometry, new THREE.LineBasicMaterial({
color: 0x000000,
transparent: true,
opacity: 0.8
} ));
scene.add( globalLine );
// ------------ MAIN PART END ------------ //
// add cubes
var step = 400;
var gridSize = 4;
var offset = step*gridSize/2;
var cubeGeometry = new THREE.BoxGeometry(step, step, step);
var cubeMaterial = new THREE.MeshBasicMaterial({ color:0xFF0000, ambient: 0xCCCCCC, transparent: true, opacity: 0 });
var testCube, edge;
for (var x = -offset; x <= offset; x+=step) {
for (var y = -offset; y <= offset; y+=step) {
for (var z = -offset; z <= offset; z+=step) {
testCube = new THREE.Mesh(cubeGeometry,cubeMaterial);
testCube.position.set(x, y, z);
edge = new THREE.EdgesHelper( testCube, 0x000000 );
scene.add(testCube);
scene.add(edge);
}
}
}
// spheres
var sphereGeometry = new THREE.SphereGeometry( 10,32,16),
sphere;
var spheres = [
[0xff0000, 0, 0, 0 ], // red
[0x0000ff, 200, 0, 0 ], // blue
[0x00FF00, -200, 0, 0 ], // green
[0xFF00ff, 0, 200, 0 ], // magenta
[0x00ffff, 0, -200, 0 ], // aqua
[0xFFff00, 0, 0, 200 ], // lime
[0x000000, 0, 0, -200] // black
];
for (var i = 0, sl = spheres.length; i <sl; i++) {
sphere = new THREE.Mesh(sphereGeometry, new THREE.MeshBasicMaterial({color: spheres[i][0]}));
sphere.position.set(spheres[i][1], spheres[i][2], spheres[i][3]);
scene.add(sphere);
}
/* Stats */
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
document.body.appendChild( stats.domElement );
/* window observers */
window.addEventListener( 'resize', onWindowResize, false );
window.addEventListener( 'load', render, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function degInRad(deg) {
return deg * Math.PI / 180;
}
function animate()
{
setTimeout(function() {
requestAnimationFrame(animate);
}, fpsTimeout );
render();
}
function render() {
camera.lookAt(camera.target);
renderer.render( scene, camera );
stats.update();
}
The problem is that you are drawing multiple levels of opacity on top of each other and webgl needs to sort them. So the short answer is to add depthTest: false to your cube material.
var cubeMaterial = new THREE.MeshBasicMaterial({ color:0xFF0000, ambient: 0xCCCCCC, transparent: true, opacity: 0, depthTest: false });
But I would like to mention that what you are doing is inefficient. You should not be drawing a grid that way. Use lines instead.

Three.js ambient light unexpected effect

In the following code, I render some cubes and light them with a PointLight and AmbientLight. However the AmbientLight when set to 0xffffff changes the colour of the sides to white, no matter their assigned colours. Strangely, the point light is working as expected.
How can I make the ambient light behave like the point light, in that it shouldn't wash out the face colours, simply illuminate them? I.e. so setting ambient light to 0xffffff would be equivalent to having multiple point lights at full intensity around the object.
$(function(){
var camera, scene, renderer;
var airplane;
var fuselage;
var tail;
init();
animate();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 0.1, 10000 );
camera.position.z = 2;
airplane = new THREE.Object3D();
fuselage = newCube(
{x: 1, y: 0.1, z: 0.1},
{x: 0, y: 0, z: 0},
[0xffff00, 0x808000, 0x0000ff, 0xff00000, 0xffffff, 0x808080],
[0, 1, 2, 3, 4, 5]
);
airplane.add(fuselage);
tail = newCube(
{x: 0.15, y: 0.2, z: 0.05},
{x: 0.5, y: 0.199, z: 0},
[0xffff00, 0x808000, 0x0000ff, 0xff00000, 0xffffff, 0x808080],
[0, 1, 2, 3, 4, 5]
);
airplane.add(tail);
scene.add( airplane );
var ambientLight = new THREE.AmbientLight(0xffffff);
scene.add(ambientLight);
var pointLight = new THREE.PointLight(0x888888);
pointLight.position.x = 100;
pointLight.position.y = 100;
pointLight.position.z = 100;
scene.add(pointLight);
renderer = new THREE.WebGLRenderer();
renderer.setClearColorHex(0x000000, 1);
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
airplane.rotation.x += 0.005;
airplane.rotation.y += 0.01;
renderer.render( scene, camera );
}
});
function newCube(dims, pos, cols, colAss){
var mesh;
var geometry;
var materials = [];
geometry = new THREE.CubeGeometry( dims.x, dims.y, dims.z );
for (var i in cols){
materials[i] = new THREE.MeshLambertMaterial( { color: cols[i], overdraw: true } );
}
geometry.materials = materials;
for (var i in colAss){
geometry.faces[i].materialIndex = colAss[i];
}
mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ) );
mesh.position = pos;
return mesh;
}
EDIT - the three.js API has been changed; material.ambient has been deprecated.
The solution is to set the intensity of your ambient light to a reasonable value.
var ambientLight = new THREE.AmbientLight( 0xffffff, 0.2 );
Updated to three.js r.84

Categories

Resources