Three JS: CTM file not loading - three.js

Here I tried to load a .ctm file in three JS using CTM Loader. But the CTM file is not getting loaded and the object is not visible in the screen, whereas when I load the js file with geometry properties it gets loaded and the object is visible on the screen. So, when I tried to load a ctm file the object is not visible and when I load a js file with geometry properties the object gets loaded.
I have attached the code below
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var FLOOR = -250;
var container;
var camera, scene, controls;
var renderer;
var mesh;
var textureCube;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(30, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000);
camera.position.set(185, 40, 170);
controls = new THREE.OrbitControls(camera);
controls.maxPolarAngle = Math.PI / 2;
controls.minDistance = 150;
controls.maxDistance = 500;
scene = new THREE.Scene();
scene.background = textureCube;
var light = new THREE.PointLight(0xffffff, 1);
light.position.set(2, 5, 1);
light.position.multiplyScalar(30);
scene.add(light);
var light = new THREE.PointLight(0xffffff, 0.75);
light.position.set(-12, 4.6, 2.4);
light.position.multiplyScalar(30);
scene.add(light);
scene.add(new THREE.AmbientLight(0x050505));
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
renderer.domElement.style.position = "relative";
container.appendChild(renderer.domElement);
renderer.gammaInput = true;
renderer.gammaOutput = true;
window.addEventListener('resize', onWindowResize, false);
window.addEventListener('mousemove', onDocumentMouseMove, false);
var start = Date.now();
var position = new THREE.Vector3(-105, -78, -30);
var scale = new THREE.Vector3(30, 30, 30);
var loader = new THREE.CTMLoader(true);
// loader.loadParts("models/ctm/camaro/camaro.js", function (geometries, materials) {
loader.load("models/ctm/camaro/camaro.ctm", function (geometries, materials) {
for (var i = 0; i < geometries.length; i++) {
var mesh = new THREE.Mesh(geometries[i], materials[i]);
mesh.name = "camaro car"
mesh.position.copy(position);
mesh.scale.copy(scale);
scene.add(mesh);
}
var end = Date.now();
console.log("load time:", end - start, "ms");
}, { useWorker: true });
}
function onWindowResize(event) {
SCREEN_WIDTH = window.innerWidth;
SCREEN_HEIGHT = window.innerHeight;
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT;
camera.updateProjectionMatrix();
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX);
mouseY = (event.clientY - windowHalfY);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
renderer.render(scene, camera);
}

Related

Three.js destroy on new page load

I'm helping a friend to set up a Three.js scene on a page in Wordpress that's running on the Lay theme. The theme is using some kind of page transition script that doesn't reload the site when navigating to a different page, creating a new initialization of the Three.js scene each time a new page is injected on the site.
I'm looking for ways to completely remove the whole instance of Three.js when a new page is loaded. So that it gets created from scratch when The Lay theme has this function window.laytheme.on("newpageshown", function(layoutObj, type, obj){} that kind of works as a substitute for window.onload.
I've tried different methods in order to remove everything, but as my Three.js code unfortunately is a mixed result of copy and pasting from different demos and examples, I'm not quite sure what exactly that needs to be destroyed and how to do it. To be honest I'm not entirely sure how the code is setup and I have very little experience with Three.js and it's lifecycle.
Here's the code creating the scene:
(function($) {
var base_url = window.location.origin;
var container, stats;
var camera, scene, renderer, controls, manager, loader, texture;
var mouseX = 0,
mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var $currentModel;
var modelName;
var initialGridPosition;
var initialScale;
window.laytheme.on("newpageshown", function(layoutObj, type, obj){
modelName = $(".modelLink.is-active").data("model-name");
initialScale = $(".modelLink.is-active").data("model-scale");
initialGridPosition = $(".modelLink.is-active").data("model-grid-position");
init();
animate();
});
function init() {
container = document.createElement('div');
container.id = "threejs-container";
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000);
camera.position.z = 300;
camera.position.y = 100;
// scene
scene = new THREE.Scene();
var ambientLight = new THREE.AmbientLight(0xffffff, 0.7);
scene.add(ambientLight);
var pointLight = new THREE.PointLight( 0xffffff, 0.3 );
camera.add( pointLight );
scene.add(camera);
// model
var onProgress = function(xhr) {
if (xhr.lengthComputable) {
var percentComplete = xhr.loaded / xhr.total * 100;
$("#domLoader").show();
$("#domLoader").text(Math.round(percentComplete, 2) + '%');
}
};
// texture
manager = new THREE.LoadingManager();
manager.onProgress = function(item, loaded, total) {
if (total == loaded) {
$("#domLoader").hide();
$(".col--row").removeClass("is-hidden");
$currentModel = $(".modelLink.is-active");
$("#meta-title").text('stevns_klint_' + $currentModel.data("model-name"));
$("#meta-vertices").text($currentModel.data("model-vertices"));
$("#meta-faces").text($currentModel.data("model-faces"));
$("#meta-coordinates").text($currentModel.data("model-coordinates"));
$("#meta-coordinates-url").attr("href", $currentModel.data("model-coordinates-url"));
$("#meta-date").text($currentModel.data("model-date"));
$("#meta-images").text($currentModel.data("model-images"));
}
console.log(item, loaded, total);
};
texture = new THREE.Texture();
var onProgress = function(xhr) {
if (xhr.lengthComputable) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log(Math.round(percentComplete, 2) + '% downloaded');
$("#domLoader").show();
$("#domLoader").text(Math.round(percentComplete, 2) + '%');
}
};
var onError = function() {};
// Create initial model
loader = new THREE.ImageLoader(manager)
loader.setPath(base_url + '/assets/' + modelName +'/').load('texture.jpg', function(image) {
texture.image = image;
texture.needsUpdate = true;
});
loader = new THREE.OBJLoader(manager);
loader.setPath(base_url + '/assets/' + modelName +'/').load('model.obj', function(object) {
object.traverse(function(child) {
if (child instanceof THREE.Mesh) {
child.material.map = texture;
}
if( child.material ) {
child.material.side = THREE.DoubleSide;
}
});
object.scale.x = initialScale;
object.scale.y = initialScale;
object.scale.z = initialScale;
object.name = "mainModel";
scene.add(object);
}, onProgress, onError);
renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0xffffff, 1);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
var size = 300;
var divisions = 30;
var gridHelper = new THREE.GridHelper( size, divisions, 0x000000, 0x000000 );
scene.add( gridHelper );
gridHelper.position.y = initialGridPosition;
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.screenSpacePanning = true;
controls.minDistance = 150;
controls.maxDistance = 300;
controls.target.set(0, 0, 0);
controls.enableDamping = true;
controls.enablePan = false;
controls.autoRotate = true;
controls.enableKeys = false;
controls.autoRotateSpeed = 0.04;
controls.dampingFactor = 0.07;
controls.rotateSpeed = 0.04;
controls.update();
window.addEventListener('resize', onWindowResize, false);
// Change model on model link click
$(".modelLink").on("click", function(){
$(".modelLink").removeClass("is-active");
$(this).addClass("is-active");
$(".col--row").addClass("is-hidden");
var modelName = $(this).data("model-name");
var modelScale = Number($(this).data("model-scale"));
var modelGridPosition = $(this).data("model-grid-position");
loader = new THREE.ImageLoader(manager)
loader.setPath(base_url + '/assets/' + modelName +'/').load('texture.jpg', function(image) {
texture.image = image;
texture.needsUpdate = true;
});
loader = new THREE.OBJLoader(manager);
loader.setPath(base_url + '/assets/' + modelName + '/').load('model.obj', function(object) {
object.traverse(function(child) {
if (child instanceof THREE.Mesh) {
child.material.map = texture;
}
if( child.material ) {
child.material.side = THREE.DoubleSide;
}
});
object.scale.x = modelScale;
object.scale.y = modelScale;
object.scale.z = modelScale;
var selectedObject = scene.getObjectByName("mainModel");
scene.remove( selectedObject );
object.name = "mainModel";
gridHelper.position.y = modelGridPosition;
scene.add(object);
}, onProgress, onError);
})
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
controls.update();
render();
}
function render() {
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
})( jQuery );
There code might be some code in there that's irrelevant and have nothing to do with Three.js. But I would appreciate if someone with more experience in the Three.js structure and lifecycle could help me with reading through the script and tell me what parts of the code related to Three.js that needs to be destroyed and how this would be done.

overlapping semitransparent objects are not rendered as expected

I have two overlapping semitransparent boxes and I'd expect to see both of them independent of the viewing angle. The first image shows a rendering from aside and the small box is visible within the bigger box. The second image shows the same scene but form another viewing angle. As you can see, the smaller box is visible but the part which is with the bigger box is invisible. What am I missing?
var camera, scene, renderer;
init();
animate();
function init() {
// Renderer.
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
// Add renderer to page
document.body.appendChild(renderer.domElement);
// Create camera.
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.1, 50);
camera.position.set(2, 2, 2);
camera.lookAt(new THREE.Vector3(0.0, 0.0, 0.0));
// Create scene.
scene = new THREE.Scene();
// Create material
var material = new THREE.MeshStandardMaterial();
material.transparent = true;
material.opacity = 0.5;
// Create cube and add to scene.
var geometry1 = new THREE.BoxGeometry(1, 1, 1);
var mesh1 = new THREE.Mesh(geometry1, material);
mesh1.position.set(0, 0, 0);
//mesh1.castShadow = true;
scene.add(mesh1);
// Create cube and add to scene.
var geometry2 = new THREE.BoxGeometry(0.5, 0.5, 0.5);
var mesh2 = new THREE.Mesh(geometry2, material);
mesh2.position.set(0.0, 0, 0.5);
//mesh2.castShadow = true;
scene.add(mesh2);
var spotLight = new THREE.SpotLight(0xffffff, 0.32);
spotLight.position.set(0, 5, 0);
spotLight.castShadow = true;
spotLight.shadow.mapSize.width = 2048;
spotLight.shadow.mapSize.height = 2048;
spotLight.shadow.camera.near = 0.1;
spotLight.shadow.camera.far = 20;
scene.add(spotLight);
let hemiLight = new THREE.HemisphereLight(0xffffbb, 0x080820, 0.8);
scene.add(hemiLight);
// Ground plane
var groundGeo = new THREE.PlaneBufferGeometry(50, 50);
var groundMat = new THREE.MeshStandardMaterial({color: 0xffffff});
var ground = new THREE.Mesh(groundGeo, groundMat);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.5;
ground.receiveShadow = true;
scene.add(ground);
// Add listener for window resize.
window.addEventListener('resize', onWindowResize, false);
let controls = new THREE.OrbitControls(camera);
controls.enableZoom = true;
controls.enablePan = false;
controls.maxDistance = 20.0;
controls.minPolarAngle = 0;
controls.maxPolarAngle = Math.PI / 2;
controls.target.set(0, 0, 0);
controls.update();
}
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
body {
padding: 0;
margin: 0;
}
canvas {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/98/three.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
Transparent objects in WebGL are sometimes rather problematic. It's all about the rendering order: If the small cube is rendered after the large cube, how should the rendering behave? This question has some information you might find useful.
In your particular case (though not necessarily always), one solution could be to disable renderer object sorting:
renderer.sortObjects = false;
and(!) make sure you add your objects in the correct order, i.e. the small cube first and the large one second. Here is an updated version of your snippet:
var camera, scene, renderer;
init();
animate();
function init() {
// Renderer.
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.sortObjects = false;
// Add renderer to page
document.body.appendChild(renderer.domElement);
// Create camera.
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.1, 50);
camera.position.set(2, 2, 2);
camera.lookAt(new THREE.Vector3(0.0, 0.0, 0.0));
// Create scene.
scene = new THREE.Scene();
// Create material
var material = new THREE.MeshStandardMaterial();
material.transparent = true;
material.opacity = 0.5;
// Create cube and add to scene.
var geometry2 = new THREE.BoxGeometry(0.5, 0.5, 0.5);
var mesh2 = new THREE.Mesh(geometry2, material);
mesh2.position.set(0.0, 0, 0.5);
//mesh2.castShadow = true;
scene.add(mesh2);
// Create cube and add to scene.
var geometry1 = new THREE.BoxGeometry(1, 1, 1);
var mesh1 = new THREE.Mesh(geometry1, material);
mesh1.position.set(0, 0, 0);
//mesh1.castShadow = true;
scene.add(mesh1);
var spotLight = new THREE.SpotLight(0xffffff, 0.32);
spotLight.position.set(0, 5, 0);
spotLight.castShadow = true;
spotLight.shadow.mapSize.width = 2048;
spotLight.shadow.mapSize.height = 2048;
spotLight.shadow.camera.near = 0.1;
spotLight.shadow.camera.far = 20;
scene.add(spotLight);
let hemiLight = new THREE.HemisphereLight(0xffffbb, 0x080820, 0.8);
scene.add(hemiLight);
// Ground plane
var groundGeo = new THREE.PlaneBufferGeometry(50, 50);
var groundMat = new THREE.MeshStandardMaterial({color: 0xffffff});
var ground = new THREE.Mesh(groundGeo, groundMat);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.5;
ground.receiveShadow = true;
scene.add(ground);
// Add listener for window resize.
window.addEventListener('resize', onWindowResize, false);
let controls = new THREE.OrbitControls(camera);
controls.enableZoom = true;
controls.enablePan = false;
controls.maxDistance = 20.0;
controls.minPolarAngle = 0;
controls.maxPolarAngle = Math.PI / 2;
controls.target.set(0, 0, 0);
controls.update();
}
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
body {
padding: 0;
margin: 0;
}
canvas {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/98/three.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

Three.js camera position shows three coordinates for 360 video

I have used a 360 video player, when I change the camera position and prints the value it shows all the three coordinates. Shouldn't it show only 2 coordinates while the third should remain constant.I am printing the Camera.position coordinates in render() function.
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r73/three.min.js"></script>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/211120/orbitControls.js"></script>
TEST
TEST2
<script>
var width = window.innerWidth;
var height = window.innerHeight;
var renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);
var video = document.createElement('video');
video.autoplay = true;
video.src = 'https://streams.kolor.com/streams/833ec36d-b115-43a2-bbf1-aaca49046bab/source.02-720p_HD.mp4';
video.crossOrigin = '';
videoTexture = new THREE.Texture(video);
videoTexture.minFilter = THREE.LinearFilter;
videoTexture.magFilter = THREE.LinearFilter;
videoTexture.format = THREE.RGBFormat;
var scene = new THREE.Scene();
var cubeGeometry = new THREE.SphereGeometry(500, 60, 40);
var sphereMat = new THREE.MeshBasicMaterial({map: videoTexture});
sphereMat.side = THREE.BackSide;
var cube = new THREE.Mesh(cubeGeometry, sphereMat);
scene.add(cube);
var camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 10000);
camera.position.y = 50;
camera.position.z = 100;
//camera.position.set(0,50,100);
scene.add(camera);
var controls = new THREE.OrbitControls( camera);
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = false;
controls.maxDistance = 50;
controls.minDistance = 50;
function render() {
if( video.readyState === video.HAVE_ENOUGH_DATA ){
videoTexture.needsUpdate = true;
}
controls.update();
renderer.render(scene, camera);
requestAnimationFrame(render);
console.log("X:"+camera.position.x +"Y:"+camera.position.y+"Z:"+camera.position.z);
}
render();
// test button function
// this does not work
var testButton = document.getElementById('testButton');
testButton.onclick = function ()
{
//camera.lookAt(new THREE.Vector3(50,60,70));
camera.position.y = 50;
camera.position.z = 100;
};
// another test button function
// this does work but then the camera bounces back to what it was looking at before
</script>
</body>
</html>

three.js png textures not transparent when using colladaloader

I saved a collada file from second life and am rendering it using 3js and colladaloader2. The image looks fine except for the part that is using the transparent texture file. The file is a png with transparency. The transparent part renders as white.
i am using REVISION:"78" of three.js
here is the code snippet
<script src="js/three.min.js"></script>
<script src="js/ColladaLoader2.js"></script>
<script src="js/Detector.js"></script>
<script>
var container;
var camera, scene, renderer;
var group;
var targetRotation = 0;
var targetRotationOnMouseDown = 0;
var mouseX = 0;
var mouseXOnMouseDown = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var loader = new THREE.ColladaLoader();
loader.options.convertUpAxis = true;
loader.load('models/collada/ASB1/American_Saddlebred.dae', function(collada) {
dae = collada.scene;
dae.scale.x = dae.scale.y = dae.scale.z = 100.0;
dae.updateMatrix();
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
var info = document.createElement('div');
info.style.position = 'absolute';
info.style.top = '10px';
info.style.width = '100%';
info.style.textAlign = 'center';
info.innerHTML = 'Drag to spin';
container.appendChild(info);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 50, 800);
scene.add(camera);
var light = new THREE.AmbientLight( 0xFFFFFF ); // soft white light
camera.add(light);
renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true} );
renderer.setClearColor( 0x333333, 1);
renderer.setClearAlpha = 0.003;
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild( renderer.domElement );

How to fix camera position in three.js

i have a canvas(webgl/3d Model ) like below
i want to make the model to the center of the canvas
like below
my code is like below
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var container;
var camera, scene;
var canvasRenderer, webglRenderer;
var mesh, zmesh, geometry, materials;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var meshes = [];
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 100000);
//camera.position.x = 2000;
//camera.position.y = 1400;
//camera.position.z = 1500;
camera.position.x = 2200;
camera.position.y = 1600;
camera.position.z = 1000;
scene = new THREE.Scene();
// LIGHTS
var ambient = new THREE.AmbientLight(0x666666);
scene.add(ambient);
var directionalLight = new THREE.DirectionalLight(0xffeedd);
directionalLight.position.set(0, 70, 100).normalize();
scene.add(directionalLight);
// RENDERER
webglRenderer = new THREE.WebGLRenderer();
webglRenderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
webglRenderer.domElement.style.position = "relative";
container.appendChild(webglRenderer.domElement);
var loader = new THREE.JSONLoader(),
callbackKey = function (geometry, materials) {
createScene(geometry, materials, 50, 50, 10, 2)
};
loader.load("ghghjghj.js", callbackKey);
window.addEventListener('resize', onWindowResize, false);
}
so what should be my camera position.
Try to increase camera.position.y until it looks better. Also, try playing around with camera.lookAt(). It takes vector3 as argument.

Resources