I'm currently trying to integrate Three.JS into an AngularJS directive. At the moment I'm really just looking for a proof-of-concept execution that I can use as boilerplate for a more complex directive later on.
At the moment I'm using the link function of the directive to setup the Three.JS scene and initiate the animation.
The scene renders fine, and the animation is being called fine, but the object I've added to the scene isn't rendering.
I've tried:
Adjusting the camera POV, position, aspect ratio
Increasing the size of the object
Adjusting the color of the object
I'm not sure if it's a matter of the object simply being out of view/invisible for some reason, or if the object is just not in the scene.
Within the render function I did use console.log and confirmed that the object was being found in the scene.traversal function call, and its rotation was being adjusted as expected.
I've confirmed the same code renders and animates an object outside
Below is the directive in full, and here is a link to it in JSBin.
angular.module('nxGeometry', [])
.directive('nxGeometry', function(){
return {
restrict: 'A',
link: function(scope, element, attrs){
// Scene variables
var camera, scene, geometry, renderer, material, object, container;
// Element dimensions
scope.width = element[0].offsetWidth;
scope.height = element[0].offsetHeight;
scope.objectColor = '#ffaa44';
scope.backgroundColor = '#333333';
// Initialization function
scope.init = function(){
container = angular.element('<div>')[0];
element[0].appendChild(container);
camera = new THREE.PerspectiveCamera(20, scope.width / scope.height, 1, 1000);
camera.position.x = 5;
camera.position.y = 0;
camera.position.z = 0;
scene = new THREE.Scene();
geometry = new THREE.BoxGeometry(1,1,1);
material = new THREE.MeshBasicMaterial({color: "#ffffff"});
object = new THREE.Mesh(geometry, material);
object.position.x = 0;
object.position.y = 0;
object.position.z = 0;
scene.add(object);
renderer = new THREE.WebGLRenderer();
renderer.setSize(scope.width, scope.height);
renderer.setClearColor(scope.backgroundColor);
container.appendChild(renderer.domElement);
}; // #end scope.init
scope.render = function(){
camera.lookAt(scene);
// Traverse the scene, rotate the Mesh object(s)
scene.traverse(function(element){
if(element instanceof THREE.Mesh){
element.rotation.x += 0.0065;
element.rotation.y += 0.0065;
}
renderer.render(scene, camera);
});
}; // #end scope.render
scope.animate = function(){
requestAnimationFrame(scope.animate);
scope.render();
};
scope.init();
scope.animate();
}
};
});
Your camera was not pointing on the object. Just increase z to 5 and your object will be visible.
camera.lookAt(scene); is not working because you have to add the position of the scene. Like this camera.lookAt(scene.position);.
Please find the updated code here.
These things I've changed:
camera = new THREE.PerspectiveCamera(50, scope.width / scope.height, 1, 1000);
camera.position.x = 0;
camera.position.y = 0;
camera.position.z = 5;
....
camera.lookAt(scene.position);
Related
I'm setting up a 3d asset viewer in Three.js. I'm running the code on a Plesk server provided by the university and have it linked via Dreamweaver. I'm a total newbie to JS and it was suggested in many threads and posts that I wrap my code within an 'init();' function. Up doing so, and clearing any errors that the code had, it is now showing a black screen, rather than the 3d model it would show before.
I've spent the whole day error checking removing problems that I was having which included the 'canvas' not being created inside the 'container' div, and the 'onWindowResize' function. All these problems have been resolved, and there are no errors in the code apparently. I've got ambient lights in the code and there was a working skybox, so I'm sure its not a problem with position of camera or lack of lighting.
I know that you need as little code as possible, but I have no idea where the problem is coming from, so a majority of the code on the page is here :
<div id="container" ></div>
<script>
let container;
let camera;
let controls;
let scene;
let renderer;
init();
animate;
function init(){
// Renderer - WebGL is primary Renderer for Three.JS
var renderer = new THREE.WebGLRenderer({antialias : true});
renderer.setClearColor(0xEEEEEE, 0.5);
// Selects and applies parameters to the 'Container' div
var container = document.querySelector("#container");
container.appendChild(renderer.domElement);
renderer.setSize(container.clientWidth, container.clientHeight);
// Perspective Camera (FOV, aspect ratio based on container, near, far)
var camera = new THREE.PerspectiveCamera( 75, container.clientWidth / container.clientHeight, 0.1, 1000);
camera.position.x = 750;
camera.position.y = 500;
camera.position.z = 1250;
// Scene will contain all objects in the world
var scene = new THREE.Scene();
//Lighting (Colour, intensity)
var light1Ambient = new THREE.AmbientLight(0xffffff , 0.3);
scene.add(light1Ambient);
var light1Point = new THREE.PointLight(0xfff2c1, 0.5, 0, 2);
scene.add(light1Point);
var light2Point = new THREE.PointLight(0xd6e3ff, 0.4, 0, 2);
scene.add(light2Point);
// All basic Geomety
var newPlane = new THREE.PlaneGeometry(250,250,100,100);
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshBasicMaterial( {color: 0x00ff00} )
);
scene.add(mesh);
// Water
water = new THREE.Water(newPlane,
{
textureWidth: 512,
textureHeight: 512,
waterNormals: new THREE.TextureLoader().load( 'http://up826703.ct.port.ac.uk/CTPRO/textures/waternormals.jpg', function ( texture ) {
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
} ),
alpha: 1.0,
sunDirection: light1Point.position.clone().normalize(),
sunColor: 0xffffff,
waterColor: 0x001e0f,
distortionScale: 0.5,
fog: scene.fog !== undefined
}
);
water.rotation.x = - Math.PI / 2;
scene.add( water );
// All Materials (Normal for Debugging) (Lambert: color)
var material = new THREE.MeshLambertMaterial({color: 0xF3FFE2});
var materialNew = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
// Skybox
var skybox = new THREE.BoxGeometry(1000,1000, 1000);
var skyboxMaterials =
[
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_ft.jpg"), side: THREE.DoubleSide }),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_bk.jpg"), side: THREE.DoubleSide }),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_up.jpg"), side: THREE.DoubleSide }),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_dn.jpg"), side: THREE.DoubleSide }),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_rt.jpg"), side: THREE.DoubleSide }),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_lf.jpg"), side: THREE.DoubleSide }),
];
var skyboxMaterial = new THREE.MeshFaceMaterial(skyboxMaterials);
var skyMesh = new THREE.Mesh (skybox, skyboxMaterial);
scene.add(skyMesh);
//Grid Helper Beneath Ship
scene.add(new THREE.GridHelper(250, 250));
//OBJ Model Loading
var objLoader = new THREE.OBJLoader();
objLoader.load('http://up826703.ct.port.ac.uk/CTPRO/models/ship1.obj', function(object){
scene.add(object);
});
// Object positioning
water.position.y = -2.5;
// Misc Positioning
light1Point.position.z =20;
light1Point.position.x = 25;
// z - front-back position
light2Point.position.z = -400;
// x - left-right
light2Point.position.x = -25;
// y - up- down
light2Point.position.y = 250;
window.addEventListener("resize", onWindowResize, false);
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(container.clientWidth, container.clientHeight);
};
};
// Canvas adapts size based on changing windows size
//Render loop
var animate = function(){
water.material.uniforms[ "time" ].value += 1.0 / 120.0;
function drawFrame(ts){
var center = new THREE.Vector2(0,0);
window.requestAnimationFrame(drawFrame);
var vLength = newPlane.geometry.vertices.length;
for (var i = 0; i < vLength; i++) {
var v = newPlane.geometry.vertices[i];
var dist = new THREE.Vector2(v.x, v.y).sub(center);
var size = 2.0;
var magnitude = 8;
v.z = Math.sin(dist.length()/-size + (ts/900)) * magnitude;
}
newPlane.geometry.verticesNeedUpdate = true;
};
requestAnimationFrame(animate)
renderer.render(scene, camera);
controls.update();
}
</script>
I'm no professional, so I'm sorry if this is super rough for those of you with experience!
I need to point out, before wrapping all of this in the init(); function, it was working perfectly.
When working, I should see a crudely modeled ship sitting in some water, with a cloud skybox. The controls were working and it would auto rotate.
Right now it does none of this. The obj loader is working as seen in the chrome console log OBJLoader: 1661.970703125ms but again, nothing is actually displayed, it's just a black screen.
Thanks to anyone who's able to help me out with this!
this line
animate;
needs to a function call
animate();
Also you probably need to change the code below where you create the animate function from
var animate = function(){
To this
function animate(){
The reason is named functions are defined when the code is loaded but variables var are created when the code is executed. So with code like this
init();
animate();
var animate = function(){ ...
animate doesn't actually exist at the point the code tries to call it whereas with this
init();
animate();
function animate(){ ...
it does exist
You could also re-arrange the code so for example define animate before you use it should work.
var animate = function(){
...
};
init();
animate();
It also appear some are declared inside init which means that are not available to animate. So for example
var renderer = new THREE.WebGLRenderer({antialias : true});
declares a new variable renderer that only init can see. You wanted to set the renderer variable that is outside of init so change the code to
renderer = new THREE.WebGLRenderer({antialias : true});
controls is never defined so you probably need to define it or comment out
controls.update();
to
// controls.update();
note: you might find these tutorials helpful although if you're new to JavaScript you should probably spend time learning JavaScript
I created a canvas with an id of 'canvas' which I provided as an argument to the WebGLRenderer of Three.js. However, nothing is showing up on that canvas. If I append the domElement to the document, the canvas shows up on the bottom but I would like to draw on my existing canvas. Is there an extra setting I have to change?
I am using this example code to start off with:
ctx = $('canvas').getContext('2d');
var canvasElm = $('canvas');
canvasWidth = parseInt(canvasElm.width);
canvasHeight = parseInt(canvasElm.height);
canvasTop = parseInt(canvasElm.style.top);
canvasLeft = parseInt(canvasElm.style.left);
var scene = new THREE.Scene(); // Create a Three.js scene object.
var camera = new THREE.PerspectiveCamera(75, canvasWidth / canvasHeight, 0.1, 1000); // Define the perspective camera's attributes.
var renderer = window.WebGLRenderingContext ? new THREE.WebGLRenderer(canvasElm) : new THREE.CanvasRenderer(); // Fallback to canvas renderer, if necessary.
renderer.setSize(canvasWidth, canvasHeight); // Set the size of the WebGL viewport.
//document.body.appendChild(renderer.domElement); // Append the WebGL viewport to the DOM.
var geometry = new THREE.CubeGeometry(20, 20, 20); // Create a 20 by 20 by 20 cube.
var material = new THREE.MeshBasicMaterial({ color: 0x0000FF }); // Skin the cube with 100% blue.
var cube = new THREE.Mesh(geometry, material); // Create a mesh based on the specified geometry (cube) and material (blue skin).
scene.add(cube); // Add the cube at (0, 0, 0).
camera.position.z = 50; // Move the camera away from the origin, down the positive z-axis.
var render = function () {
cube.rotation.x += 0.01; // Rotate the sphere by a small amount about the x- and y-axes.
cube.rotation.y += 0.01;
renderer.render(scene, camera); // Each time we change the position of the cube object, we must re-render it.
requestAnimationFrame(render); // Call the render() function up to 60 times per second (i.e., up to 60 animation frames per second).
};
render(); // Start the rendering of the animation frames.
I am using Chrome 56.0.2924.87 (64-bit) if that helps.
Your jquery selector is wrong (I am assuming it is jquery).
var canvasElm = $('canvas'); creates a new canvas element.
If you want to select a canvas that has the id of 'canvas', use..
var canvasElm = $('#canvas');
But this then gets a jquery object / list, so to get the actual canvas (first item in the list) you could use..
var canvasElm = $('#canvas')[0];
eg.
var canvasElm = $('#canvas')[0];
renderer = new THREE.WebGLRenderer( { canvas: canvasElm } );
You would probably be better just using js without jquery.
eg.
canvasElm = document.getElementById('canvas');
renderer = new THREE.WebGLRenderer( { canvas: canvasElm } );
Are there any errors is this code? I am using a new version of Chrome to test on. I've written a similar program that displays a wireframe cube, with no issues. It ran well. I'm thinking I may have written or structured my code incorrectly.
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(50,window.innerWidth/window.innerHeight, 1, 10000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// create the particle variables
var particleCount = 1000;
var particles = new THREE.Geometry();
var pMaterial = new THREE.ParticleBasicMaterial({
color: 'red',
size: 20
});
// create the individual particles
for (var p = 0; p < particleCount; p++) {
var pX = Math.random()*500 - 250;
var pY = Math.random()*500 - 250;
var pZ = Math.random()*500 - 250;
var particle = new THREE.Vertex(
new THREE.Vector3(pX, pY, pZ)
);
particles.vertices.push(particle);
}
// create the particle system
var particleSystem = new THREE.ParticleSystem(
particles,
pMaterial);
// add the particle system to the scene
scene.add(particleSystem);
function render() {
particleSystem.rotation.y += 0.01;
renderer.render(scene, camera);
requestAnimationFrame(render);
}
render();
I'm not seeing any results, so to speak - just a black canvas element on the page.
Your code looks outdated -- as if you copied something from the net, or from an outdated book.
Update to the current version of three.js, and learn from the current three.js examples.
Create your particles like so:
var particle = new THREE.Vector3( pX, pY, pZ );
Also, ParticleSystem is now PointCloud, and ParticleBasicMaterial is now PointCloudMaterial.
three.js r.69
I'm using the Three.js javascript library. To test it I downloaded the an example from here.
I'm trying to display several times the same element using a for loop. There two questions related (1, 2) but it's not exactly what I want. My problem is that if I create the element inside the loop it will only display the last element of the iteration. In this particular case the element in position (12,12).
But, if I do an action like an alert it will display all the elements. Also if I have any other functions that delays the execution.
I saw some examples running, as the mrdoob examples, but I would like this code running because I need to load several mesh instead of generating primitive figures.
// Set up the scene, camera, and renderer as global variables.
var scene, camera, renderer;
var group;
// Call functions
init();
animate();
// Sets up the scene.
function init() {
// Iterator
var i, j;
// Create the scene and set the scene size.
scene = new THREE.Scene();
var WIDTH = window.innerWidth,
HEIGHT = window.innerHeight;
// Create a renderer and add it to the DOM.
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize(WIDTH, HEIGHT);
document.body.appendChild(renderer.domElement);
// Create a camera, zoom it out from the model a bit, and add it to the scene.
camera = new THREE.PerspectiveCamera(45, WIDTH / HEIGHT, 0.1, 20000);
camera.position.set(0,20,20);
scene.add(camera);
// Create an event listener that resizes the renderer with the browser window.
window.addEventListener('resize', function() {
var WIDTH = window.innerWidth,
HEIGHT = window.innerHeight;
renderer.setSize(WIDTH, HEIGHT);
camera.aspect = WIDTH / HEIGHT;
camera.updateProjectionMatrix();
});
// Set the background color of the scene.
renderer.setClearColor(0x333F47, 1);
// Create a light, set its position, and add it to the scene.
var light = new THREE.PointLight(0xffffff);
light.position.set(-100,200,100);
scene.add(light);
group = new THREE.Object3D();
for(i=0; i < 15; i+=3) {
for(j=0; j < 15; j+=3) {
var loader = new THREE.JSONLoader();
loader.load( "models/treehouse_logo.js", function(geometry){
var material = new THREE.MeshLambertMaterial({color: 0x55B663});
var mesh = new THREE.Mesh(geometry, material);
mesh.position.set(i,0,j);
group.add(mesh);
});
//alert("iteration"+i+" "+j);
}
}
scene.add( group );
// Add OrbitControls so that we can pan around with the mouse.
controls = new THREE.OrbitControls(camera, renderer.domElement);
}
// Renders the scene and updates the render as needed.
function animate() {
// Read more about requestAnimationFrame at http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
requestAnimationFrame(animate);
// Render the scene.
renderer.render(scene, camera);
controls.update();
}
What you are doing here is incredibly inefficient:
for(i=0; i < 15; i+=3) {
for(j=0; j < 15; j+=3) {
var loader = new THREE.JSONLoader();
loader.load( "models/treehouse_logo.js", function(geometry){
var material = new THREE.MeshLambertMaterial({color: 0x55B663});
var mesh = new THREE.Mesh(geometry, material);
mesh.position.set(i,0,j);
group.add(mesh);
});
//alert("iteration"+i+" "+j);
}
}
This would be much better done like this (untested):
var loader = new THREE.JSONLoader();
loader.load( "models/treehouse_logo.js", function( geometry ){
var material, mesh, i, j, instance;
material = new THREE.MeshLambertMaterial({ color: 0x55B663 });
mesh = new THREE.Mesh( geometry, material );
for ( i = 0; i < 15; i += 3 ) {
for ( j = 0; j < 15; j += 3 ) {
instance = mesh.clone();
instance.position.set( i, 0, j );
group.add( instance );
}
}
});
You'd need to do repeat this pattern for each unique mesh.
The problems your current approach has are:
More memory needed by the GPU for each identical mesh
More memory needed by the browser to remember each identical mesh
More processing power required by the GPU as more memory needs to be processed
Each time you call the loader, you instruct the browser to execute a request. That's some 25 identical requests in your case. They should come from the cache, but it'll still be slow.
You may have variables scoping issues too which gives issues with the loader callback, but I'm not entirely sure about that.
alert() makes for a very poor debugging tool by the way as it changes the way the browser reacts: it stops executing JavaScript when the alert is open and that affects the loader and similar things. You're better off with the Console logging methods.
I would say it is because you are setting the loader variable in each iteration of the loop which will override the loader of the last iteration.
Why is the actual loading being done in a loop? Why not load it once and clone it?
eg.
group = new THREE.Object3D();
var loader = new THREE.JSONLoader();
loader.load( "models/treehouse_logo.js", function(geometry){
var material = new THREE.MeshLambertMaterial({color: 0x55B663});
for(i=0; i < 15; i+=3) {
for(j=0; j < 15; j+=3) {
var mesh = new THREE.Mesh(geometry.clone(), material);
mesh.position.set(i,0,j);
group.add(mesh);
}
}
});
scene.add( group );
The above code is untested
I used the OBJMTLLoader class for one obj file and rotation worked well around a fixed point on the object by using object.rotation.y -= 0.5. Using the same code (minus changing the camera position), I replaced the .obj file with another and the rotation is now going in a circular motion, like around the camera instead of staying in place. Any idea why when I used the same code?
Thanks
EDIT:
var OBJLoaded;
function init()
{
container = document.getElementById('player');
camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 1, 2000);
camera.position.x = 110;
camera.position.z = -160;
camera.position.y = 15;
// camera.position.z = 40;
// camera.position.y = 2;
//scene
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight( 0x444444 );
scene.add( ambient );
var directionalLight = new THREE.DirectionalLight( 0xffffff );
directionalLight.position.set( 100, 90, 200 );
scene.add( directionalLight );
//model
var loader = new THREE.OBJMTLLoader();
//loader.load('./assets/Stereo_LowPoly.obj', './assets/Stereo_LowPoly.mtl', function(object)
loader.load('./assets/studio_beats.obj', './assets/studio_beats.mtl', function(object)
{
OBJLoaded = object;
console.log(object);
scene.add( object );
});
renderer = new THREE.WebGLRenderer({alpha: true});
renderer.setClearColor(0x000000, 0);
renderer.setSize($('#player').width(), $('#player').height());
container.appendChild(renderer.domElement);
scene.add(camera);
}
function animateBoombox()
{
requestAnimationFrame(animateBoombox);
render();
}
function render()
{
var rotSpeed = 0.004;
if (OBJLoaded)
{
OBJLoaded.rotation.y -= rotSpeed;
}
renderer.render(scene, camera);
}
The parts commented (camera and object load) is for the previous object that was loaded. That works fine, but the uncommented partdoes not work the same.
The object you loaded has a pivot point which came from the model creater software... You need to change the pivot point of the object before you load it with three.js.
If you cannot, you should do it like i had in loader callback:
var loader = new THREE.OBJMTLLoader();
loader.load('your_file.obj', 'your_file.mtl', function (object) {
object.traverse(function (child) {
child.centroid = new THREE.Vector3();
for (var i = 0, l = child.geometry.vertices.length; i < l; i++) {
child.centroid.add(child.geometry.vertices[i].clone());
}
child.centroid.divideScalar(child.geometry.vertices.length);
var offset = child.centroid.clone();
child.geometry.applyMatrix(new THREE.Matrix4().makeTranslation(-offset.x, -offset.y, -offset.z));
child.position.copy(child.centroid);
child.geometry.computeBoundingBox();
});
});
Then rotate your object...