I want to animate this cow with the file sleep.fbx but the cow is rendering but not animating and i don't found the error.render cow sleep, however i couldn't find the error in the code:
//Variables for setup
import * as THREE from 'three';
import {FBXLoader} from 'three/addons/loaders/FBXLoader.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
let container;
let camara;
let renderer;
let scene;
function init(){
container= document.querySelector('.scene');
console.log(GLTFLoader);
//Create scene
scene = new THREE.Scene();
const fov=35;
const aspect= container.clientWidth/container.clientHeight;
const near= 0.1;
const far = 1000;
//camara setup
camara = new THREE.PerspectiveCamera(fov,aspect,near, far);
camara.position.set(0,2,10);
const ambient = new THREE.AmbientLight(0x404040, 2);
scene.add(ambient);
const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(10, 25, 20);
scene.add(light);
//renderer setup
renderer = new THREE.WebGLRenderer({antialias:true, alpha:true});
renderer.setSize(container.clientWidth,container.clientHeight);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.outputEncoding = THREE.sRGBEncoding;
container.appendChild(renderer.domElement);
const controls = new OrbitControls(camara, renderer.domElement)
controls.enableDamping = true
controls.target.set(0, 1, 0)
// Setup Textures and the FBX Files URLs
let Cow = "static/lib/admin-3.2.0/3d_1/FBX/source/Cow.FBX";
let modelUrl2 = "static/lib/admin-3.2.0/3d_1/textures/Cow.tga.png";
let modelUrl3 = "static/lib/admin-3.2.0/3d_1/textures/Eye_Brown.tga.png";
let modelUrl4 = "static/lib/admin-3.2.0/3d_1/textures/Cow_Normals.tga.png";
let modelUrl5 = "static/lib/admin-3.2.0/3d_1/textures/Eye_Shine.tga.png";
// Setup Animations and the FBX Files URLs
let Animate_Sleep = "static/lib/admin-3.2.0/3d_1/FBX/source/animations/Sleep.FBX";
const fbxLoader = new FBXLoader()
fbxLoader.load(Cow, function(fbx) {
//Initialize each png Textures
let textureLoader = new THREE.TextureLoader();
const texture1 = textureLoader.load( modelUrl2 );
texture1.flipY = true;
const texture2 = textureLoader.load( modelUrl3 );
texture2.flipY = true;
const normalTexture = textureLoader.load( modelUrl4 );
normalTexture.flipY = true;
const Eye_Shine = textureLoader.load( modelUrl5 );
normalTexture.flipY = false;
fbx.traverse((child) => {
if ( child.isMesh && child.geometry ) {
// note: for a multi-material mesh, `o.material` may be an array,
// in which case you'd need to set `.map` on each value.s
if (child.name == "Cow_Mesh") {
child.material = new THREE.MeshPhongMaterial({
map:texture1,
normalMap: normalTexture
})}
else if (child.name == "Eye_Left") {
child.material = new THREE.MeshPhongMaterial({
map:texture2,
normalMap: Eye_Shine})
};
if (child.name == "Eye_Right") {
child.material = new THREE.MeshPhongMaterial({
map:texture2,
normalMap: Eye_Shine})
};
child.receiveShadow = true;
child.castShadow = true;
}
});
fbx.scale.setScalar(0.02);
fbx.rotation.x = -1.5;
scene.add(fbx);
const mixer = new THREE.AnimationMixer(fbx);
// Carga las animaciones
const loaderAnimations = new FBXLoader();
loaderAnimations.load(Animate_Sleep, function (anim) {
// Crea un AnimationMixer
let action = mixer.clipAction(anim.animations[0]);
console.log(action);
action.play();
});
animate();
const clock = new THREE.Clock()
function animate() {
requestAnimationFrame(animate);
controls.update(scene);
/* mixer.update(clock.getDelta()) ; */
renderer.render(scene,camara);}
});
}
init()
function onWindowResize() {
camara.aspect = container.clientWidth/container.clientHeight;
camara.updateProjectionMatrix();
renderer.setSize(container.clientWidth, container.clientHeight);
}
window.addEventListener('resize', onWindowResize);
I am trying to animate the cow with the function THREE.AnimationMixer(fbx); but is not animating and i am getting a empty canvas when i am trying to animate the cow, i want to animate and renderize the sleep.FBX in the webpage.
Related
I loaded a Sprite in a scene with Bloom, the trouble is that my Sprite map is using an externally loaded Png texture. Not the usual solid color material. I know it's possible to make all the textures black first and then back to the original color. But if my material is using the png Map.what should I do? Let the Sprite display normally and not have Bloom .
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from '../jsm/controls/OrbitControls.js';
import Stats from '../jsm/libs/stats.module.js';
import { GUI } from '../jsm/libs/lil-gui.module.min.js';
import { EffectComposer } from '../jsm/postprocessing/EffectComposer.js';
import { RenderPass } from '../jsm/postprocessing/RenderPass.js';
import { UnrealBloomPass } from '../jsm/postprocessing/UnrealBloomPass.js';
import { FBXLoader } from '../Loader/FBXLoader/FBXLoader.js';
import { OBJLoader } from '../Loader/OBJLoader.js';
import { MTLLoader } from '../Loader/MTLLoader.js'
import { GLTFLoader } from "../Loader/GLTFLoader.js";
import { ShaderPass } from '../jsm/postprocessing/ShaderPass.js';
const ENTIRE_SCENE = 0, BLOOM_SCENE = 1;
const bloomLayer = new THREE.Layers();
bloomLayer.set(BLOOM_SCENE);
let params = {
exposure: 1,
bloomThreshold: 0.41,
bloomStrength: 0.66,
bloomRadius: 0.05,
scene: 'Scene with Glow'
};
//set MeshBasicMaterial
const darkMaterial = new THREE.MeshBasicMaterial({ color: 'black' });
const materials = {};
/*--------renderer--------*/
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
//add scene
const scene = new THREE.Scene();
/*--------camera--------*/
const camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 0.1, 100000000);
camera.position.set(0, 10, 10);
camera.lookAt(0, 0, 0);
//makeLabelCanvas
function makeLabelCanvas(size, name) {
const borderSize = 0;
const ctx = document.createElement('canvas').getContext('2d');
const font = `${size}px bold sans-serif`;
ctx.font = font;
// measure how long the name will be
const doubleBorderSize = borderSize * 2;
const width = ctx.measureText(name).width + doubleBorderSize;
const height = 70 + doubleBorderSize;
ctx.canvas.width = width;
ctx.canvas.height = height;
console.log(ctx);
ctx.font = font;
ctx.textBaseline = 'top';
return ctx.canvas;
}
/*--------OrbitControls--------*/
let controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0, 0);
controls.enablePan = false;
controls.maxPolarAngle = Math.PI / 2;
controls.enableDamping = true;
//Render
const renderScene = new RenderPass(scene, camera);
const bloomPass = new UnrealBloomPass(new THREE.Vector2(window.innerWidth, window.innerHeight), 1.5, 0.4, 0.85);
bloomPass.threshold = params.bloomThreshold;
bloomPass.strength = params.bloomStrength;
bloomPass.radius = params.bloomRadius;
const bloomComposer = new EffectComposer(renderer);
bloomComposer.renderToScreen = false;
bloomComposer.addPass(renderScene);
bloomComposer.addPass(bloomPass);
const finalPass = new ShaderPass(
new THREE.ShaderMaterial({
uniforms: {
baseTexture: { value: null },
bloomTexture: { value: bloomComposer.renderTarget2.texture }
},
vertexShader: document.getElementById('vertexshader').textContent,
fragmentShader: document.getElementById('fragmentshader').textContent,
defines: {}
}), 'baseTexture'
);
finalPass.needsSwap = true;
const finalComposer = new EffectComposer(renderer);
finalComposer.addPass(renderScene);
finalComposer.addPass(finalPass);
/*--------Stats--------*/
const stats = Stats();
stats.showPanel(0);
/*--------AmbientLight-1--------*/
scene.add(new THREE.AmbientLight(0xffffff, 1));
//light1
const light1 = new THREE.PointLight(0xddffdd, 1);
light1.position.z = 0;
light1.position.y = 300;
light1.position.x = 200;
scene.add(light1);
/*--------cube--------*/
const geometry = new THREE.BoxGeometry(4, 4, 4);
const material = new THREE.MeshBasicMaterial({ color: 0x000050 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
/*--------label--------*/
const canvas = makeLabelCanvas(100, 'name');
const texture = new THREE.CanvasTexture(canvas);
texture.wrapS = THREE.ClampToEdgeWrapping;
texture.wrapT = THREE.ClampToEdgeWrapping;
//Material
const loader = new THREE.TextureLoader();
const labelMaterial = new THREE.SpriteMaterial({
map: loader.load('../img/moudle-lable/Wood-storage-tank/stokehold.png'),
side: THREE.DoubleSide,
transparent: true,
});
const label = new THREE.Sprite(labelMaterial);
cube.add(label);
label.position.x = -5;
label.position.y = 3;
label.position.z = 0;
const label_BaseScale_X = 0.05;
const label_BaseScale_Y = 0.05;
label.scale.x = canvas.width * label_BaseScale_X;
label.scale.y = canvas.height * label_BaseScale_Y;
//window.onresize
window.onresize = function () {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
};
function disposeMaterial(obj) {
if (obj.material) {
obj.material.dispose();
}
}
//render
function render() {
switch (params.scene) {
case 'Scene only':
renderer.render(scene, camera);
break;
case 'Scene with Glow':
default:
// render scene with bloom
renderBloom(true);
// render the entire scene, then render bloom scene on top
finalComposer.render();
break;
}
}
function renderBloom(mask) {
if (mask === true) {
renderer.setClearColor(0x000000); // all must be black, including background
scene.traverse(darkenNonBloomed);
bloomComposer.render();
renderer.setClearColor(0xffffff); // set the color you want
scene.traverse(restoreMaterial);
} else {
camera.layers.set(BLOOM_SCENE);
bloomComposer.render();
camera.layers.set(ENTIRE_SCENE);
}
}
function darkenNonBloomed(obj) {
if (obj.isMesh && bloomLayer.test(obj.layers) === false) {
materials[obj.uuid] = obj.material;
obj.material = darkMaterial;
}
}
function restoreMaterial(obj) {
if (materials[obj.uuid]) {
obj.material = materials[obj.uuid];
delete materials[obj.uuid];
}
}
function animate() {
render();
requestAnimationFrame(animate);
};
animate();
var axes = new THREE.AxisHelper(20);
scene.add(axes);
</script>
this is my png
And this is use PlaneBufferGeometry do .
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from '../jsm/controls/OrbitControls.js';
import Stats from '../jsm/libs/stats.module.js';
import { GUI } from '../jsm/libs/lil-gui.module.min.js';
import { EffectComposer } from '../jsm/postprocessing/EffectComposer.js';
import { RenderPass } from '../jsm/postprocessing/RenderPass.js';
import { UnrealBloomPass } from '../jsm/postprocessing/UnrealBloomPass.js';
import { FBXLoader } from '../Loader/FBXLoader/FBXLoader.js';
import { OBJLoader } from '../Loader/OBJLoader.js';
import { MTLLoader } from '../Loader/MTLLoader.js'
import { GLTFLoader } from "../Loader/GLTFLoader.js";
import { ShaderPass } from '../jsm/postprocessing/ShaderPass.js';
const ENTIRE_SCENE = 0, BLOOM_SCENE = 1;
const bloomLayer = new THREE.Layers();
bloomLayer.set(BLOOM_SCENE);
let params = {
exposure: 1,
bloomThreshold: 0.41,
bloomStrength: 0.66,
bloomRadius: 0.05,
scene: 'Scene with Glow'
};
//set MeshBasicMaterial
const darkMaterial = new THREE.MeshBasicMaterial({ color: 'black' });
const materials = {};
/*--------renderer--------*/
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
//add scene
const scene = new THREE.Scene();
/*--------camera--------*/
const camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 0.1, 100000000);
camera.position.set(0, 10, 10);
camera.lookAt(0, 0, 0);
//makeLabelCanvas
function makeLabelCanvas(size, name) {
const borderSize = 0;
const ctx = document.createElement('canvas').getContext('2d');
const font = `${size}px bold sans-serif`;
ctx.font = font;
// measure how long the name will be
const doubleBorderSize = borderSize * 2;
const width = ctx.measureText(name).width + doubleBorderSize;
const height = 70 + doubleBorderSize;
ctx.canvas.width = width;
ctx.canvas.height = height;
console.log(ctx);
ctx.font = font;
ctx.textBaseline = 'top';
return ctx.canvas;
}
/*--------OrbitControls--------*/
let controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0, 0);
controls.enablePan = false;
controls.maxPolarAngle = Math.PI / 2;
controls.enableDamping = true;
//Render
const renderScene = new RenderPass(scene, camera);
const bloomPass = new UnrealBloomPass(new THREE.Vector2(window.innerWidth, window.innerHeight), 1.5, 0.4, 0.85);
bloomPass.threshold = params.bloomThreshold;
bloomPass.strength = params.bloomStrength;
bloomPass.radius = params.bloomRadius;
const bloomComposer = new EffectComposer(renderer);
bloomComposer.renderToScreen = false;
bloomComposer.addPass(renderScene);
bloomComposer.addPass(bloomPass);
const finalPass = new ShaderPass(
new THREE.ShaderMaterial({
uniforms: {
baseTexture: { value: null },
bloomTexture: { value: bloomComposer.renderTarget2.texture }
},
vertexShader: document.getElementById('vertexshader').textContent,
fragmentShader: document.getElementById('fragmentshader').textContent,
defines: {}
}), 'baseTexture'
);
finalPass.needsSwap = true;
const finalComposer = new EffectComposer(renderer);
finalComposer.addPass(renderScene);
finalComposer.addPass(finalPass);
/*--------Stats--------*/
const stats = Stats();
stats.showPanel(0);
/*--------AmbientLight-1--------*/
scene.add(new THREE.AmbientLight(0xffffff, 1));
//light1
const light1 = new THREE.PointLight(0xddffdd, 1);
light1.position.z = 0;
light1.position.y = 300;
light1.position.x = 200;
scene.add(light1);
/*--------cube--------*/
const geometry = new THREE.BoxGeometry(4, 4, 4);
const material = new THREE.MeshBasicMaterial({ color: 0x000050 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
/*--------label--------*/
const labelGeometry = new THREE.PlaneBufferGeometry(1, 1);
const canvas = makeLabelCanvas(100, 'name');
const texture = new THREE.CanvasTexture(canvas);
texture.wrapS = THREE.ClampToEdgeWrapping;
texture.wrapT = THREE.ClampToEdgeWrapping;
//Material
const loader = new THREE.TextureLoader();
const labelMaterial = new THREE.MeshBasicMaterial({
map: loader.load('../img/moudle-lable/Wood-storage-tank/stokehold.png'),
side: THREE.DoubleSide,
transparent: true,
});
const label = new THREE.Mesh(labelGeometry, labelMaterial);
cube.add(label);
label.position.x = -5;
label.position.y = 3;
label.position.z = 0;
const label_BaseScale_X = 0.05;
const label_BaseScale_Y = 0.05;
label.scale.x = canvas.width * label_BaseScale_X;
label.scale.y = canvas.height * label_BaseScale_Y;
//window.onresize
window.onresize = function () {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
};
function disposeMaterial(obj) {
if (obj.material) {
obj.material.dispose();
}
}
//render
function render() {
switch (params.scene) {
case 'Scene only':
renderer.render(scene, camera);
break;
case 'Scene with Glow':
default:
// render scene with bloom
renderBloom(true);
// render the entire scene, then render bloom scene on top
finalComposer.render();
break;
}
}
function renderBloom(mask) {
if (mask === true) {
renderer.setClearColor(0x000000); // all must be black, including background
scene.traverse(darkenNonBloomed);
bloomComposer.render();
renderer.setClearColor(0xffffff); // set the color you want
scene.traverse(restoreMaterial);
} else {
camera.layers.set(BLOOM_SCENE);
bloomComposer.render();
camera.layers.set(ENTIRE_SCENE);
}
}
function darkenNonBloomed(obj) {
if (obj.isMesh && bloomLayer.test(obj.layers) === false) {
materials[obj.uuid] = obj.material;
obj.material = darkMaterial;
}
}
function restoreMaterial(obj) {
if (materials[obj.uuid]) {
obj.material = materials[obj.uuid];
delete materials[obj.uuid];
}
}
function animate() {
controls.update();
render();
requestAnimationFrame(animate);
};
animate();
var axes = new THREE.AxisHelper(20);
scene.add(axes);
</script>
It displays normally, but the PlaneBufferGeometry doesn't always face the camera.
Here are examples if needed https://smile881225.github.io/AskQuestions/backup/標籤發光問題.html
Been futzing around with the three.js library a bit this past week, and I ran into a problem applying transformations to loaded models (gltf). Whenever I try to update the rotation I get "Uncaught TypeError: Cannot read property 'position' of undefined." I'm very confused; it seems like I can only access the .position/.rotation attributes in onLoad?
let container;
let camera;
let controls;
let renderer;
let scene;
let mesh;
const mixers = [];
const clock = new THREE.Clock();
function init() {
container = document.querySelector('#scene-container');
scene = new THREE.Scene();
scene.background = new THREE.Color(0x8FBCD4);
createCamera();
createLights();
loadModels();
createRenderer();
createControls();
renderer.setAnimationLoop(() => {
update();
render();
});
}
function createCamera() {
const fov = 35;
const aspect = container.clientWidth / container.clientHeight;
const near = 0.1; //near clipping plane
const far = 100; //far clipping plane
camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(-1.5, 1.5, 6.5);
}
function createLights() {
const ambientLight = new THREE.HemisphereLight(
0xddeeff, //bright sky color
0x202020, //dim ground color
3 //intensity
);
//this is a specular light
const mainLight = new THREE.DirectionalLight(0xffffff, 10);
mainLight.position.set(10, 10, 10);
scene.add(ambientLight, mainLight);
}
function createRenderer() {
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(container.clientWidth, container.clientHeight);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.gammaFactor = 2.2;
renderer.gammaFactor = true;
renderer.physicallyCorrectLights = true; //allows us to use lux, candela and lumens to set lighting
container.appendChild(renderer.domElement);
}
function loadModels() {
const loader = new THREE.GLTFLoader();
const onLoad = ( gltf, position ) => {
const model = gltf.scene.children[ 0 ]; //get reference to the model
model.position.copy( position ); //passes the position parameter into the models position value
const animation = gltf.animations[ 0 ];
const mixer = new THREE.AnimationMixer( model ); //instances a animation controller
mixers.push( mixer );
const action = mixer.clipAction( animation );
action.play();
mesh = model;
scene.add( model );
};
const onProgress = () => {};
const onError = (errorMessage) => { console.log(errorMessage); };
//loads a position the model and the position
const suzannePosition = new THREE.Vector3(0, 0, 2.5);
loader.load('models/test/suzanne.glb', gltf => onLoad(gltf, suzannePosition), onProgress, onError);
}
function update() {
const delta = clock.getDelta();
for (const mixer of mixers) {
mixer.update(delta);
}
/* ---THIS DOESN'T WORK---
mesh.rotation.x += .01;
console.log(mesh.rotation);
*/
}
function createControls() {
controls = new THREE.OrbitControls(camera, container);
}
function render() {
renderer.render(scene, camera);
}
function onWindowResize() {
camera.aspect = container.clientWidth / container.clientHeight;
//update camera's frustum
camera.updateProjectionMatrix();
renderer.setSize(container.clientWidth, container.clientHeight);
}
window.addEventListener('resize', onWindowResize);
init();
mesh = model;
This assignment happens in the onLoad() callback of GLTFLoader.load(). It's important to understand that this callback is executed asynchronously when the model is loaded.
In the meanwhile, mesh is undefined. So change your code to the following to get rid of the runtime error:
if ( mesh ) mesh.rotation.x += .01;
I am new in ROS and THREE.js and have been trying to implement a web visualization for a robot movement using mqtt. I used this github project for that https://github.com/dersimn/robotWebView. So far the visualization works alright. However,i will like to change the color of the robot to make the movements even more visible. I tried changing the color of in the "THREE.MeshPhongMaterial" method in the "index.js" file but that did not help. Any idea on how to do this?
Update: This is the code i used
var scene = new THREE.Scene();
scene.background = new THREE.Color(0xb5d3e7);
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 0, 3);
controls = new THREE.OrbitControls(camera);
controls.update();
var light = new THREE.HemisphereLight(0xffffbb, 0x080820, 1);
scene.add(light);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const manager = new THREE.LoadingManager();
const loader = new URDFLoader(manager);
var material = new THREE.MeshPhongMaterial({color: 0xce8821, specular: 0xce8821, shininess: 200});
var geometryLoader = new THREE.STLLoader();
//var geometryLoader = new THREE.ColladaLoader();
var myrobot = null;
loader.load('urdf/iiwa14/urdf/iiwa14.urdf', {}, robot => {
myrobot = robot;
console.log('complete', robot);
scene.add(robot);
}, { loadMeshCb: (path, ext, done) => {
geometryLoader.load(path, geometry => {
console.log(path);
var mesh = new THREE.Mesh( geometry, material );
mesh.castShadow = true;
mesh.receiveShadow = true;
//scene.add(mesh);
done(mesh);
});
}});
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
// MQTT
var mqttUrl = 'ws://MyIPAdress:portNumber/mqtt';
var clientId = 'webui_'+Math.random().toString(36).substring(2,15);
console.log('MQTT conenct to', mqttUrl, clientId);
var client = new Paho.MQTT.Client(mqttUrl, clientId);
client.onMessageArrived = function(recv) {
let topic = recv.destinationName;
let message = JSON.parse(recv.payloadString);
console.log(topic, message);
myrobot.joints.iiwa_joint_1.setAngle(message[0]);
myrobot.joints.iiwa_joint_2.setAngle(message[1]);
myrobot.joints.iiwa_joint_3.setAngle(message[2]);
myrobot.joints.iiwa_joint_4.setAngle(message[3]);
myrobot.joints.iiwa_joint_5.setAngle(message[4]);
myrobot.joints.iiwa_joint_6.setAngle(message[5]);
myrobot.joints.iiwa_joint_7.setAngle(message[6]);
};
client.onConnectionLost = function() {
console.log('mqtt disconencted');
};
client.connect({onSuccess:function() {
console.log('mqtt conencted');
client.subscribe('kuka/status/1/currentJointPosition');
}});
I've been trying for over a week now to get the orientation controls of my smartphone to control my three js scene. I had saved an example which was placed under a tutorial, I lost the tutorial but found the example. I looked at how he managed to get the controls working and I can't seem to get the same effect. I hope someone else might spot it...
This is my script.js (I'm loading threejs via cdn in my index.html)
import {sets} from './data/';
import threeOrbitControls from 'three-orbit-controls';
import ColladaLoader from 'three-collada-loader';
import threeStereoEffect from 'three-stereo-effect';
// import FirstPersonControls from 'three-first-person-controls';
const DeviceOrientationControls = require(`./modules/util/DeviceOrientationControls`);
import {BufferLoader} from './modules/sound';
import {SpawnObject} from './modules/render';
const OrbitControls = threeOrbitControls(THREE);
const StereoEffect = threeStereoEffect(THREE);
let scene, camera, renderer, element, container, controls;
let audioCtx, bufferLoader;
const notes = [];
let stereoEffect = null;
const init = () => {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
audioCtx = new AudioContext();
bufferLoader = new BufferLoader(audioCtx);
bufferLoader.load(sets.drums)
.then(data => spawnObject(data));
initEnvironment();
};
const spawnObject = data => {
for (let i = 0;i < 5;i ++) {
const bol = new SpawnObject(`object.dae`, audioCtx, data[0], scene, false);
notes.push(bol);
}
// console.log(notes);
};
const initEnvironment = () => {
//Three.js Scene
scene = new THREE.Scene();
//Create renderer, set size + append to the container
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
element = renderer.domElement;
container = document.querySelector(`main`);
container.appendChild(element);
//Create camera, set position + add to scene
camera = new THREE.PerspectiveCamera(
45, window.innerWidth / window.innerHeight,
1, 10000
);
camera.position.set(0, 0, 2);
camera.lookAt(scene.position);
//Creates stereo effect
stereoEffect = new StereoEffect(renderer);
stereoEffect.setSize(window.innerWidth, window.innerHeight);
//Controls
controls = new OrbitControls(camera);
// controls = new THREE.OrbitControls(camera, element);
// camera.position.x = 100;
// camera.position.y = 1000;
// camera.position.z = 3000;
const setOrientationControls = e => {
if (!e.alpha) {
return;
}
controls = new THREE.DeviceOrientationControls(camera, true);
controls.connect();
controls.update();
element.addEventListener(`click`, fullscreen, false);
window.removeEventListener(`deviceorientation`, setOrientationControls, true);
};
window.addEventListener(`deviceorientation`, setOrientationControls, true);
//LIGHTS
const light = new THREE.PointLight(0xFFFFFF);
light.position.set(0, 0, 9);
light.castShadow = true;
light.shadow.mapSize.width = 1024;
light.shadow.mapSize.height = 1024;
light.shadow.camera.near = 10;
light.shadow.camera.far = 100;
scene.add(light);
// const hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.6);
// hemiLight.color.setHSL(0.6, 1, 0.6);
// hemiLight.groundColor.setHSL(0.095, 1, 0.75);
// hemiLight.position.set(0, 500, 0);
// scene.add(hemiLight);
//
// const dirLight = new THREE.DirectionalLight(0xffffff, 1);
// dirLight.color.setHSL(0.1, 1, 0.95);
// dirLight.position.set(- 1, 1.75, 1);
// dirLight.position.multiplyScalar(50);
// scene.add(dirLight);
// dirLight.castShadow = true;
//FLOOR
const matFloor = new THREE.MeshPhongMaterial();
const geoFloor = new THREE.BoxGeometry(2000, 1, 2000);
const mshFloor = new THREE.Mesh(geoFloor, matFloor);
matFloor.color.set(0x212E39);
mshFloor.receiveShadow = true;
mshFloor.position.set(0, - 1, 0);
scene.add(mshFloor);
//ENVIRONMENT
const loader = new ColladaLoader();
loader.load(`../assets/environment.dae`, collada => {
collada.scene.traverse(child => {
child.castShadow = true;
child.receiveShadow = true;
});
scene.add(collada.scene);
render();
});
};
controls = THREE.DeviceOrientationControls;
console.log(controls);
function setOrientationControls(e) {
if (!e.alpha) {
return;
}
controls = new THREE.DeviceOrientationControls(camera, true);
controls.connect();
controls.update();
element.addEventListener(`click`, fullscreen, false);
window.removeEventListener(`deviceorientation`, setOrientationControls, true);
}
window.addEventListener(`deviceorientation`, setOrientationControls, true);
const render = () => {
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.setClearColor(0xdddddd, 1);
stereoEffect.render(scene, camera);
requestAnimationFrame(render);
};
function fullscreen() {
if (container.requestFullscreen) {
container.requestFullscreen();
} else if (container.msRequestFullscreen) {
container.msRequestFullscreen();
} else if (container.mozRequestFullScreen) {
container.mozRequestFullScreen();
} else if (container.webkitRequestFullscreen) {
container.webkitRequestFullscreen();
}
}
init();
I'm not sure how I fixed it, but I didn't use the function around the defining of the DeviceOrientationControls, instead I used a regex to check whether I'm on the browser or on a mobile device.
That seems to work.
each time i wants to load load my model and change its texture the model not loading, and there is nothing in the screen. i am a noob in three.js/webgl languages and javascript. please help me to proceed with right information.
here is the following code.
https://drive.google.com/open?id=0BxJJ7XpRqKz4S3JONlAwSHJxdFk this link provides the assets im using in this projects.
// once everything is loaded, we run our Three.js stuff.
function init() {
var stats = initStats();
// create a scene, that will hold all our elements such as objects, cameras and lights.
var scene = new THREE.Scene();
// create a camera, which defines where we're looking at.
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
// create a render and set the size
var webGLRenderer = new THREE.WebGLRenderer();
webGLRenderer.setClearColor(new THREE.Color(0xaaaaff, 1.0));
webGLRenderer.setSize(window.innerWidth, window.innerHeight);
webGLRenderer.shadowMapEnabled = true;
// position and point the camera to the center of the scene
camera.position.x = 100;
camera.position.y = 40;
camera.position.z = 50;
camera.lookAt(scene.position);
scene.add(camera);
// add spotlight for the shadows
var spotLight = new THREE.DirectionalLight(0xfa93e5);
spotLight.position.set(30, 40, 50);
spotLight.intensity = 0.5;
scene.add(spotLight);
// add the output of the renderer to the html element
document.getElementById("WebGL-output").appendChild(webGLRenderer.domElement);
// call the render function
var step = 0;
// setup the control gui
var controls = new function () {
// we need the first child, since it's a multimaterial
};
var gui = new dat.GUI();
//model
var loader = new THREE.OBJLoader();
loader.load( 'sofa 1.obj', function (object) );
var sofa = new THREE.Mesh(object,fabric_1);
var texture = new THREE.ImageUtils.loadTexture("defaultMat_Base_Color(1).png");
var texture2 = new THREE.ImageUtils.loadTexture("defaultMat_Base_Color_1.png");
var material = THREE.ImageUtils.loadTexture("defaultMat_Normal_DirectX bump.png");
var material1 = THREE.ImageUtils.loadTexture("sofa new final4 high-AO_u0_v0.png");
var material2 = THREE.ImageUtils.loadTexture("lambert2SG_Roughness specular.png");
var fabric_1 = new THREE.MeshPhongMaterial(
{ fabric_1.map = texture;
fabric_1.normalMap = material;
fabric_1.aoMap = material1;
fabric_1.specularMap = material2; });
var fabric_2 = new THREE.MeshPhongMaterial(
{ fabric_2.map = texture_2;
fabric_2.normalMap = material;
fabric_2.aoMap = material1;
fabric_2.specularMap = material2;
});
scene.add(sofa),
function setfabric_1 () {
sofa.traverse(function(child){
if(child instanceof THREE.Mesh){
child.material = fabric_1;
}
sofa.geometry.uvsNeedUpdate = true;
sofa.needsupdate = true;
});
}
function setfabric_2 () {
sofa.traverse(function(child){
if(child instanceof THREE.Mesh){
child.material = fabric_2;
}
sofa.geometry.uvsNeedUpdate = true;
sofa.needsupdate = true;
});
}
render();
function render() {
stats.update();
if (mesh) {
mesh.rotation.y += 0.006;
;
}
// render using requestAnimationFrame
requestAnimationFrame(render);
webGLRenderer.render(scene, camera);
}
function initStats() {
var stats = new Stats();
stats.setMode(0); // 0: fps, 1: ms
// Align top-left
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.top = '0px';
document.getElementById("Stats-output").appendChild(stats.domElement);
return stats;
}
}
window.onload = init;
Use uniforms to link local variables to the shader, make sure you preload the textures first though. threejs.org/uniforms. Better yet use
"uTexArray" : { type: "tv", value: [ new THREE.Texture(), new THREE.Texture() ] } // texture array (regular)
enter link description here