Mesh positions not updating in Three JS Plane Buffer Geometry - javascript

I am trying to create a 2d mesh plane in Three JS, and update the position of each vertex by accessing the position attribute like so:
function planeGeometry()
{
var mat = new THREE.MeshBasicMaterial({color: "red", wireframe: true, transparent: true, opacity: 1});
const geometry = new THREE.PlaneBufferGeometry( 2, 3, 0.01, 0.1 );
const plane = new THREE.Mesh( geometry, mat );
scene.add( plane );
}
const geometry = new THREE.BufferGeometry();
const vertices = new Float32Array( [
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0,
-1.0, -1.0, 1.0
] );
// itemSize = 3 because there are 3 values (components) per vertex
geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
const mesh = new THREE.Mesh( geometry, material );
scene.add(mesh);
function animate()
{
requestAnimationFrame(animate);
mesh.geometry.attributes.position[0] += 0.01;
mesh.geometry.attributes.position.needsUpdate = true;
renderer.render(scene, camera);
}
animate();
But I get no change in position. What am I doing wrong?

Related

Trouble loading images onto a BufferGeometry surface with THREE.js

I am trying to make a cube in THREE.js with BufferGeometry, but the image won't load correctly. I have tried a few things but nothing seems to work, and it looks like the uv's aren't working.
script.js
//Load the canvas to draw on
var canvas = document.querySelector('#canvas')
// The three.js scene: the 3D world where you put objects
const scene = new THREE.Scene();
function degrees_to_radians(degrees) {
let pi = Math.PI;
return degrees * (pi / 180);
}
// The camera
const camera = new THREE.PerspectiveCamera(
60,
window.innerWidth / window.innerHeight,
0.0001,
10000
);
// The renderer: something that draws 3D objects onto the canvas
const renderer = new THREE.WebGLRenderer({ canvas: canvas });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x4a4a4a, 1);
document.body.appendChild(renderer.domElement);
const controls = new THREE.PointerLockControls(camera, document.body);
document.addEventListener('click', function () {
controls.lock();
});
var key_map = {}; // You could also use an array
onkeydown = onkeyup = function (e) {
e = e || event; // to deal with IE
key_map[e.keyCode] = e.type == 'keydown';
}
const light = new THREE.PointLight( 0xffffff, 2, 0, 2 );
light.position.set( 10, 50, 10 );
scene.add( light );
camera.position.z = 4
const vertices = new Float32Array([
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0,
1.0, 1.0, 0.0,
1.0, 1.0, 0.0,
-1.0, 1.0, 0.0,
-1.0, -1.0, 0.0
]);
const uvs = new Float32Array([
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
1.0, 1.0,
0.0, 1.0,
0.0, 0.0
]);
let textureLoader = new THREE.TextureLoader();
var texture = textureLoader.load('./images/grass.jpg');
const material = new THREE.MeshLambertMaterial({ map: texture });
const geometry = new THREE.BufferGeometry();
geometry.addAttribute('position', new THREE.BufferAttribute(vertices, 3));
geometry.addAttribute('uv', new THREE.BufferAttribute(uvs, 3));
geometry.computeVertexNormals();
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
const walk_speed = 0.05;
const sprint_speed = 0.15;
const fly_speed = 0.06;
var speed = 0;
var f_speed = 0;
var b_speed = 0;
var l_speed = 0;
var r_speed = 0;
function render() {
//handle keypresses
var cameraDirection = controls.getDirection(new THREE.Vector3()).clone();
var angle = Math.atan2(cameraDirection.x, cameraDirection.z);
if (key_map[87]) {
//forwards
if (key_map[17]) {
f_speed = sprint_speed;
} else {
f_speed = walk_speed;
}
controls.getObject().position.z += (Math.cos(angle)) * f_speed;
controls.getObject().position.x += (Math.sin(angle)) * f_speed;
}
if (key_map[83]) {
//backwards
if (key_map[17]) {
speed = sprint_speed;
} else {
speed = walk_speed;
}
controls.getObject().position.z -= (Math.cos(angle)) * speed;
controls.getObject().position.x -= (Math.sin(angle)) * speed;
}
if (key_map[65]) {
//left
if (key_map[17]) {
speed = sprint_speed;
} else {
speed = walk_speed;
}
controls.getObject().position.z -= (Math.sin(angle)) * speed;
controls.getObject().position.x += (Math.cos(angle)) * speed;
}
if (key_map[68]) {
//right
if (key_map[17]) {
speed = sprint_speed;
} else {
speed = walk_speed;
}
controls.getObject().position.z += (Math.sin(angle)) * speed;
controls.getObject().position.x -= (Math.cos(angle)) * speed;
}
if (key_map[16]) {
//down
camera.position.y -= fly_speed;
}
if (key_map[32]) {
//up
camera.position.y += fly_speed;
}
renderer.render(scene, camera);
// Make it call the render() function about every 1/60 second
requestAnimationFrame(render);
}
render();
I have a weird error where the texture doesn't work.
Picture
I don't see that you set any UV texture coordinates. Without them the renderer, shader, WebGL programm (or where the magic happens) does not know how to apply the texture to the mesh.
const vertices = new Float32Array([
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0,
-1.0, -1.0, 1.0
]);
const uvs = new Float32Array([
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
1.0, 1.0,
0.0, 1.0,
0.0, 0.0
]);
this.geometry.addAttribute('position', new THREE.BufferAttribute(vertices, 3));
this.geometry.addAttribute('uv', new THREE.BufferAttribute(uvs, 2));
If you try to create a cube with different textures on each side, you could also just utilize BoxGeometry. It already has a different material index for each side. So, you would only need to apply an array of 6 materials to the mesh.

How do I rotate a triangle around an edge?

How can a triangle, made with three.js, be rotated around one of its edges? When I try to rotate it, it does around its center as it seems.
The triangle is made by:
var triangleMesh;
var triangleGeometry = new THREE.Geometry();
triangleGeometry.vertices.push( new THREE.Vector3( 0.0, 1.0, 0.0 ) );
triangleGeometry.vertices.push( new THREE.Vector3( -1.0, -1.0, 0.0 ) );
triangleGeometry.vertices.push( new THREE.Vector3( 1.0, -1.0, 0.0 ) );
triangleGeometry.faces.push( new THREE.Face3( 0, 1, 2 ) );
triangleGeometry.faces[0].vertexColors[0] = new THREE.Color(0xFF0000);
triangleGeometry.faces[0].vertexColors[1] = new THREE.Color(0x00FF00);
triangleGeometry.faces[0].vertexColors[2] = new THREE.Color(0x0000FF);
var triangleMaterial = new THREE.MeshBasicMaterial({ vertexColors:THREE.VertexColors, side:THREE.DoubleSide });
triangleMesh = new THREE.Mesh( triangleGeometry, triangleMaterial );
triangleMesh.position.set(-1.5, 0.0, 4.0 );
triangleMesh.position.z -= 5;
triangleMesh.rotation.z += angle * Math.PI / 180; // angle is from outer for loop
parent.add( triangleMesh );
I would need to rotate it around one edge to build prisms/hexagons.
To rotate a triangle around one of its corners, that corner must be in the center of coordinates. For this purpose you can use .translate ( x, y, z ) method of THREE.Geometry().
Take a look at the code snippet.
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 5);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var ngon = 11;
var radius = 2;
var angle = Math.PI / ngon;
var triHeight = Math.cos(angle) * radius;
var triWidth = Math.sin(angle) * radius;
var triangleMesh;
var triangleGeometry = new THREE.Geometry();
triangleGeometry.vertices.push(new THREE.Vector3(0.0, triHeight, 0.0));
triangleGeometry.vertices.push(new THREE.Vector3(-triWidth, 0, 0.0));
triangleGeometry.vertices.push(new THREE.Vector3(triWidth, 0, 0.0));
triangleGeometry.faces.push(new THREE.Face3(0, 1, 2));
triangleGeometry.faces[0].vertexColors[0] = new THREE.Color(0xFF0000);
triangleGeometry.faces[0].vertexColors[1] = new THREE.Color(0x00FF00);
triangleGeometry.faces[0].vertexColors[2] = new THREE.Color(0x0000FF);
triangleGeometry.translate(0, -triHeight, 0); // the upper vertex is at the center now
var triangleMaterial = new THREE.MeshBasicMaterial({
vertexColors: THREE.VertexColors,
side: THREE.DoubleSide
});
triangleMesh = new THREE.Mesh(triangleGeometry, triangleMaterial);
for (var i = 1; i < ngon; i++) {
var newTri = triangleMesh.clone();
newTri.rotation.z = i * angle * 2;
scene.add(newTri);
}
scene.add(triangleMesh);
render();
function render() {
requestAnimationFrame(render);
renderer.render(scene, camera);
}
body {
overflow: hidden;
margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>

WebGLRenderingContext GL ERROR : GL_INVALID_OPERATION : glDrawElements: attempt to access out of range vertices in attribute 2

I'm learning how to use canvas in Webgl but im having some problems with textures. I want to draw a cube, an sphere, the axis and a grid. Everything is perfect if i only add the sphere, axis and grid but when i add the cube to the scene the grid disappears and shows me this error:
WebGL error INVALID_OPERATION in drawElements(TRIANGLES, 357, UNSIGNED_SHORT, 0)
[.WebGLRenderingContext]GL ERROR :GL_INVALID_OPERATION : glDrawElements: attempt to access out of range vertices in attribute 2.
this is my render class:
define([
'text!shaders/vertex-shader.glsl',
'text!shaders/fragment-shader.glsl',
'./Ejes',
'./Mesh',
'glMatrix',
'CuonUtils'], function(vsSource, fsSource,Ejes,Mesh,glMatrix, CuonUtils) {
var canvas = document.getElementById('canvas');
var gl = CuonUtils.getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
// Initialize shaders
if (!CuonUtils.initShaders(gl, vsSource, fsSource)) {
console.log('Failed to intialize shaders.');
return;
}
var program = gl.program;
// Cache attribute/uniform location
var aPostion = gl.getAttribLocation(program, 'aPostion');
var aNormal = gl.getAttribLocation(program, 'aNormal');
var aTexCoord = gl.getAttribLocation(program, 'aTexCoord');
var uModelMatrix = gl.getUniformLocation(program, 'uModelMatrix');
var uViewMatrix = gl.getUniformLocation(program, 'uViewMatrix');
var uProjectionMatrix = gl.getUniformLocation(program, 'uProjectionMatrix');
var uNormalMatrix = gl.getUniformLocation(program, 'uNormalMatrix');
var uLightColor = gl.getUniformLocation(program, 'uLightColor');
var uLightPosition = gl.getUniformLocation(program, 'uLightPosition');
var uAmbientLight = gl.getUniformLocation(program, 'uAmbientLight');
var uColor = gl.getUniformLocation(program, 'uColor');
var uSampler = gl.getUniformLocation(program, 'uSampler');
var uUseLighting = gl.getUniformLocation(program, 'uUseLighting');
var uUseTexture = gl.getUniformLocation(program, 'uUseTexture');
function initBuffers(gl, mesh){
if(mesh._webgl){
return;
}
mesh._webgl = {};
// Create Vertex Buffer Object
var VBOData = new Float32Array(
mesh.geometry.vertices);
var VBO = mesh._webgl.vbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, VBO);
gl.bufferData(gl.ARRAY_BUFFER, VBOData, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
// Create Index Buffer Object
var IBOData = new Uint16Array(
mesh.geometry.faces);
var IBO = mesh._webgl.ibo = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, IBO);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, IBOData, gl.STATIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
mesh._webgl.ibo.dataSize = IBOData.length;
// Create Normal Buffer Object
var NBOData = new Float32Array(
mesh.geometry.normals);
var NBO = mesh._webgl.nbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, NBO);
gl.bufferData(gl.ARRAY_BUFFER, NBOData, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
if(mesh.useTexture){
// Create st Buffer Object
var STBOData = new Float32Array(
mesh.geometry.st);
var STBO = mesh._webgl.stbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, STBO);
gl.bufferData(gl.ARRAY_BUFFER, STBOData, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
var TBO = mesh._webgl.tbo = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, TBO);
gl.texImage2D(
gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE,
new Uint8Array([255, 255, 255, 255])
);
loadTexture(gl, mesh.imgSrc, mesh._webgl.tbo, function() {
bindTextureToSampler(gl, mesh._webgl.tbo);
});
}
}
function render(scene, camera) {
// Specify the color for clearing <canvas>
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.enable(gl.DEPTH_TEST);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// seteo las luces
gl.uniform3fv(uLightColor, scene.pointLight.getLightColor());
gl.uniform3fv(uLightPosition, scene.pointLight.getLightPosition());
gl.uniform3fv(uAmbientLight, scene.ambientLight.getLightColor());
for( var i = 0; i < scene.meshes.length; i++){
var mesh = scene.meshes[i];
initBuffers(gl, mesh);
gl.uniform1i(uUseLighting, mesh.useLight);
gl.uniform1i(uUseTexture, mesh.useTexture);
gl.enableVertexAttribArray(aPostion);
gl.bindBuffer(gl.ARRAY_BUFFER, mesh._webgl.vbo);
gl.vertexAttribPointer(
aPostion, 3, gl.FLOAT, false, 0, 0
);
gl.enableVertexAttribArray(aNormal);
gl.bindBuffer(gl.ARRAY_BUFFER, mesh._webgl.nbo);
gl.vertexAttribPointer(
aNormal, 3, gl.FLOAT, false, 0, 0
);
// Clean up
gl.bindBuffer(gl.ARRAY_BUFFER, null);
gl.uniformMatrix4fv(uModelMatrix, false, mesh.getModelMatrix());
gl.uniformMatrix4fv(uViewMatrix, false, camera.getViewMatrix());
gl.uniformMatrix4fv(uProjectionMatrix, false, camera.getProjectionMatrix());
gl.uniformMatrix4fv(uNormalMatrix, false, mesh.getNormalMatrix());
gl.uniform4fv(uColor, mesh.material.getColor());
if(mesh.useTexture){
gl.enableVertexAttribArray(aTexCoord);
gl.bindBuffer(gl.ARRAY_BUFFER, mesh._webgl.stbo);
gl.vertexAttribPointer(
aTexCoord, 2, gl.FLOAT, false, 0, 0
);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, mesh._webgl.tbo);
gl.uniform1i(uSampler, 0);
}
draw(gl,mesh);
}
}
function loadTexture(gl, imageSrc, textureBO, callback) {
var image = new Image();
image.src = imageSrc;
image.onload = function () {
gl.bindTexture(gl.TEXTURE_2D, textureBO);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
setupTexture(image.width, image.height);
gl.bindTexture(gl.TEXTURE_2D, null);
callback();
};
}
function bindTextureToSampler(gl, textureBO) {
gl.bindTexture(gl.TEXTURE_2D, textureBO);
gl.uniform1i(uSampler, 0);
}
function setupTexture(width, height) {
if (isPowerOf2(width) && isPowerOf2(height) ){
// the dimensions are power of 2 so generate mips and turn on
// tri-linear filtering.
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
} else {
// at least one of the dimensions is not a power of 2 so set the filtering
// so WebGL will render it.
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
}
}
function isPowerOf2(value) {
return (value & (value - 1)) === 0;
}
function draw(gl, mesh) {
// gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, mesh._webgl.ibo);
gl.drawElements(mesh.tipe, mesh._webgl.ibo.dataSize, gl.UNSIGNED_SHORT, 0);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
gl.bindTexture(gl.TEXTURE_2D, null);
}
return {
render: render
};
});
and this is my main class:
define([
'./WebGLRenderer',
'./Scene',
'./Mesh',
'./Geometry',
'./Material',
'./RegularConvexPolygonGeometry',
'./Cubo',
'./Sphere',
'./Cylinder',
'./PerspectiveCamera',
'./OrthographicCamera',
'./Light',
'./PointLight',
'./Ejes',
'dat',
'./cuadrado',
'CuonUtils'
], function(WebGLRenderer, Scene, Mesh, Geometry, Material,
RegularConvexPolygonGeometry, Cubo, Sphere, Cylinder,
PerspectiveCamera, OrthographicCamera, Light, PointLight,
Ejes, dat, Cuadrado, CuonUtils) {
var canvas = document.getElementById('canvas');
var gl = CuonUtils.getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
////////////
// ESCENA //
////////////
var clearColor = [0.0,0.0,0.0];
//Ambient Light
var light = Object.create(Light);
light.init();
light.hex = Math.floor( 0xaaaaaa );
//Point Light
var pointLight = Object.create(PointLight);
pointLight.init();
var scene = Object.create(Scene);
scene.init(clearColor, light, pointLight);
//////////
// EJES //
//////////
//GRID
var GrillaGeometry = Object.create(Ejes);
GrillaGeometry.getGrillaGeometry();
var grillaMaterial = Object.create(Material);
grillaMaterial.init();
grillaMaterial.hex = Math.floor( 0x0f0f0f );
var GrillaMesh = Object.create(Mesh);
GrillaMesh.init(GrillaGeometry,grillaMaterial);
GrillaMesh.tipe = gl.LINES;
GrillaMesh.useLight = false;
GrillaMesh.useTexture = false;
//X
var EjeXGeometry = Object.create(Ejes);
EjeXGeometry.getXGeometry();
var EjeXMaterial = Object.create(Material);
EjeXMaterial.init();
EjeXMaterial.hex = Math.floor( 0xff0000 );
var EjeXMesh = Object.create(Mesh);
EjeXMesh.init(EjeXGeometry,EjeXMaterial);
EjeXMesh.tipe = gl.LINES;
EjeXMesh.useLight = false;
EjeXMesh.useTexture = false;
//Y
var EjeYGeometry = Object.create(Ejes);
EjeYGeometry.getYGeometry();
var EjeYMaterial = Object.create(Material);
EjeYMaterial.init();
EjeYMaterial.hex = Math.floor( 0x00ff00 );
var EjeYMesh = Object.create(Mesh);
EjeYMesh.init(EjeYGeometry,EjeYMaterial);
EjeYMesh.tipe = gl.LINES;
EjeYMesh.useLight = false;
EjeYMesh.useTexture = false;
//Z
var EjeZGeometry = Object.create(Ejes);
EjeZGeometry.getZGeometry();
var EjeZMaterial = Object.create(Material);
EjeZMaterial.init();
EjeZMaterial.hex = Math.floor( 0x0000ff );
var EjeZMesh = Object.create(Mesh);
EjeZMesh.init(EjeZGeometry,EjeZMaterial);
EjeZMesh.tipe = gl.LINES;
EjeZMesh.useLight = false;
EjeZMesh.useTexture = false;
scene.addMesh(GrillaMesh);
scene.addMesh(EjeXMesh);
scene.addMesh(EjeYMesh);
scene.addMesh(EjeZMesh);
////////////////
// ESFERA //
////////////////
var sphereGeometry = Object.create(Sphere);
sphereGeometry.init();
var sphereMaterial = Object.create(Material);
sphereMaterial.init();
sphereMaterial.hex = Math.floor( 0xffffff );
var sphereMesh = Object.create(Mesh);
sphereMesh.init(sphereGeometry,sphereMaterial);
sphereMesh.tipe = gl.TRIANGLES;
sphereMesh.tx = 5.0;
sphereMesh.useLight = true;
sphereMesh.useTexture = true;
sphereMesh.imgSrc = 'scripts/texture/earthmap.jpg';
scene.addMesh(sphereMesh);
////////////////
// CUBO //
////////////////
var cubeGeometry = Object.create(Cubo);
cubeGeometry.init();
var cubeMaterial = Object.create(Material);
cubeMaterial.init();
cubeMaterial.hex = Math.floor( 0xffffff );
var cubeMesh = Object.create(Mesh);
cubeMesh.init(cubeGeometry,cubeMaterial);
cubeMesh.tipe = gl.TRIANGLES;
cubeMesh.tz = 5.0;
cubeMesh.useLight = true;
cubeMesh.useTexture = true;
cubeMesh.imgSrc = 'scripts/texture/firefox-icon3.png';
scene.addMesh(cubeMesh);
//////////////////////////////
/// PERSPECTIVE PROJECTION ///
//////////////////////////////
// var camera = Object.create(PerspectiveCamera);
// PerspectiveCamera.init(Math.PI / 4,1,0.1,200);
///////////////////////////////
/// ORTHOGRAPHIC PROJECTION ///
///////////////////////////////
var camera = Object.create(OrthographicCamera);
OrthographicCamera.init(-8,8,-8,8,0.1,1000);
function tick(){
WebGLRenderer.render(scene, camera);
requestAnimationFrame(tick);
}
tick();
});
I'm almost sure that the problem is my render class but just in case i'll post the other classes too.
cube:
define(['glMatrix','./Geometry'], function(glMatrix, Geometry) {
var Cubo = Object.create(Geometry);
Cubo.init = function(){
var vertices = new Float32Array([
1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0,-1.0, 1.0, 1.0,-1.0, 1.0, // v0-v1-v2-v3 front
1.0, 1.0, 1.0, 1.0,-1.0, 1.0, 1.0,-1.0,-1.0, 1.0, 1.0,-1.0, // v0-v3-v4-v5 right
1.0, 1.0, 1.0, 1.0, 1.0,-1.0, -1.0, 1.0,-1.0, -1.0, 1.0, 1.0, // v0-v5-v6-v1 up
-1.0, 1.0, 1.0, -1.0, 1.0,-1.0, -1.0,-1.0,-1.0, -1.0,-1.0, 1.0, // v1-v6-v7-v2 left
-1.0,-1.0,-1.0, 1.0,-1.0,-1.0, 1.0,-1.0, 1.0, -1.0,-1.0, 1.0, // v7-v4-v3-v2 down
1.0,-1.0,-1.0, -1.0,-1.0,-1.0, -1.0, 1.0,-1.0, 1.0, 1.0,-1.0 // v4-v7-v6-v5 back
]);
//Creo las caras
var indexVertices = new Uint16Array([
0, 1, 2, 0, 2, 3, // front
4, 5, 6, 4, 6, 7, // right
8, 9,10, 8,10,11, // up
12,13,14, 12,14,15, // left
16,17,18, 16,18,19, // down
20,21,22, 20,22,23 // back
]);
//Normales
var normales = new Float32Array([
0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, // v0-v1-v2-v3 front
1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, // v0-v3-v4-v5 right
0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, // v0-v5-v6-v1 up
-1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, // v1-v6-v7-v2 left
0.0,-1.0, 0.0, 0.0,-1.0, 0.0, 0.0,-1.0, 0.0, 0.0,-1.0, 0.0, // v7-v4-v3-v2 down
0.0, 0.0,-1.0, 0.0, 0.0,-1.0, 0.0, 0.0,-1.0, 0.0, 0.0,-1.0 // v4-v7-v6-v5 back
]);
var st = new Float32Array([
// Front
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
// Back
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
// Top
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
// Bottom
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
// Right
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
// Left
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0
]);
Geometry.init.call(this, vertices, indexVertices, normales, st);
};
return Cubo;
});
sphere:
define(['./Geometry'], function(Geometry) {
var Sphere = Object.create(Geometry);
Sphere.init = function(){
var SPHERE_DIV = 13;
var i, ai, si, ci;
var j, aj, sj, cj;
var p1, p2;
var vertices = [];
var indexVertices = [];
var st = [];
//Creo los vertices
for (j = 0; j <= SPHERE_DIV; j++) {
aj = j * Math.PI / SPHERE_DIV;
sj = Math.sin(aj);
cj = Math.cos(aj);
for (i = 0; i <= SPHERE_DIV; i++) {
ai = i * 2 * Math.PI / SPHERE_DIV;
si = Math.sin(ai);
ci = Math.cos(ai);
vertices.push(si * sj); // X
vertices.push(cj); // Y
vertices.push(ci * sj); // Z
st.push(1 - (i / SPHERE_DIV) );
st.push(1 - (j / SPHERE_DIV) );
}
}
//Creo los indices
for (j = 0; j < SPHERE_DIV; j++) {
for (i = 0; i < SPHERE_DIV; i++) {
p1 = j * (SPHERE_DIV+1) + i;
p2 = p1 + (SPHERE_DIV+1);
indexVertices.push(p1);
indexVertices.push(p2);
indexVertices.push(p1 + 1);
indexVertices.push(p1 + 1);
indexVertices.push(p2);
indexVertices.push(p2 + 1);
}
}
Geometry.init.call(this, vertices, indexVertices, vertices, st);
};
return Sphere;
});
grid:
define(['./Geometry'], function(Geometry) {
var Ejes = Object.create(Geometry);
Ejes.getXGeometry = function(){
var vertices = [];
var indexVertices = [];
var st = [];
vertices.push(0.0,0.0,0.0);
vertices.push(10.0,0.0,0.0);
indexVertices.push(0,1);
Geometry.init.call(this,vertices,indexVertices, vertices, st);
};
Ejes.getYGeometry = function(){
var vertices = [];
var indexVertices = [];
var st = [];
vertices.push(0.0,0.0,0.0);
vertices.push(0.0,10.0,0.0);
indexVertices.push(0,1);
Geometry.init.call(this,vertices,indexVertices, vertices, st);
};
Ejes.getZGeometry = function(){
var vertices = [];
var indexVertices = [];
var st = [];
vertices.push(0.0,0.0,0.0);
vertices.push(0.0,0.0,10.0);
indexVertices.push(0,1);
Geometry.init.call(this,vertices,indexVertices,vertices, st);
};
Ejes.getGrillaGeometry = function(){
var vertices = [];
var indexVertices = [];
var st = [];
for(var i=-10; i<0; i+=1)
{
// verticales
vertices.push(i,0,-10);
vertices.push(i,0,10);
// horizontales
vertices.push(-10,0,i);
vertices.push(10,0,i);
}
vertices.push(0,0,-10);
vertices.push(0,0,0);
vertices.push(-10,0,0);
vertices.push(0,0,0);
for(i=1; i<=10; i+=1)
{
// verticales
vertices.push(i,0,-10);
vertices.push(i,0,10);
// horizontales
vertices.push(-10,0,i);
vertices.push(10,0,i);
}
for(i=0; i<84;i+=1)
{
indexVertices.push(i);
}
Geometry.init.call(this,vertices,indexVertices,vertices, vertices);
};
return Ejes;
});
I'd really appreciate any help you could give me.

three.js - Draw custom mesh with MeshLambertMaterial and point light

I'm currently learning webGL and three.js. So, for test reasons, I tried to create a plane geometry and two cube geometries and a point light:
function initLights () {
var c = context;
var pointLight = new THREE.PointLight( 0xffffff, 1, 100 );
pointLight.position.set( 10, 10, 10 );
c.scene.add(pointLight);
}
function initObjects () {
var c = context;
/**
* Defining the materials
*/
var lambertRedMaterial = new THREE.MeshLambertMaterial({
color : 0xff0000
, side : THREE.DoubleSide
});
var lambertWhiteMaterial = new THREE.MeshLambertMaterial({
color : 0xffffff
, side : THREE.DoubleSide
});
/**
* Defining the floor
*/
var floorGeometry = new THREE.Geometry();
floorGeometry.vertices.push(new THREE.Vector3(-5.0, 0.0, -5.0));
floorGeometry.vertices.push(new THREE.Vector3( 5.0, 0.0, -5.0));
floorGeometry.vertices.push(new THREE.Vector3( 5.0, 0.0, 5.0));
floorGeometry.vertices.push(new THREE.Vector3(-5.0, 0.0, 5.0));
floorGeometry.faces.push(new THREE.Face3(2, 1, 0));
floorGeometry.faces.push(new THREE.Face3(3, 2, 0));
var floorMesh = new THREE.Mesh(floorGeometry, lambertWhiteMaterial);
floorMesh.position.set(0.0, 0.0, 0.0);
/**
* Defining a cube
*/
var cubeGeometry1 = new THREE.CubeGeometry(2.0,0.25,1);
var cube1 = new THREE.Mesh( cubeGeometry1, lambertRedMaterial );
cube1.position.set(0.0, 1.0, 0.0);
var cubeGeometry2 = new THREE.CubeGeometry(2.0,0.25,1);
var cube2 = new THREE.Mesh( cubeGeometry2, lambertRedMaterial );
cube2.position.set(0.0, 1.35, 0.0);
c.scene.add(floorMesh);
c.scene.add(cube1);
c.scene.add(cube2);
}
The context with a camera and the scene was defined before.
The weird thing is, that the cubes are displayed correctly, but the plane is not displayed.
When I set the y-position of the plane to 1.0, then I can see, that it intersects with the lower cube. Also, it's displayed when I use MeshBasicMaterial, but I want to use MeshLambertMaterial for lighting reasons.
Has anybody an idea, if I forgot something, or what the problem could be?
Many thanks in advance.
MeshLambertMaterial requires face normals or vertex normals for the lighting calculation.
Face normals are used for "flat shading" and vertex normals are used for "smooth shading".
You can compute face normals by calling geometry.computeFaceNormals();. For vertex normals, you can call geometry.computeVertexNormals();.
For visual cues, use the three.js helpers, such as this one:
scene.add( new THREE.FaceNormalsHelper( mesh ) );
Also, if you are just learning, the advice in this answer may be helpful to you.
three.js r.65

how to see Custom 2D shape on both side in three.js

I'm new to three.js and 3d programming in general,I used the three.js draw a Sector,I can the object in one direction ,but i can't see it in the opposite direction,it seems that the three.js examplehere have the same phenomenon,how can i see the object in both dretions?
var squareShape = new THREE.Shape();
var arc = 1/6*Math.PI
var len = 20
squareShape.moveTo( 0,0 );
squareShape.absarc( 0, 0, 20, 4/3*Math.PI, 5/3*Math.PI, false );
squareShape.moveTo( 0, 0 );
var geometry = new THREE.ExtrudeGeometry( squareShape, {amount:0.1} );
var mesh = THREE.SceneUtils.createMultiMaterialObject( geometry, [ new THREE.MeshLambertMaterial( { color: 0xff0000 ,opacity: 1.0} ), new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true, transparent: true ,opacity: 1.0} ) ] );
mesh.position.set( 10, 10, 10 );
mesh.rotation.set( Math.PI/2, 0, Math.PI/2 );
scene.add( mesh );
In your case, it would be
new THREE.MeshLambertMaterial( { color: 0xff0000, opacity: 1.0, side: THREE.DoubleSide } )

Categories