I am working on a markup extension for autodesk forge. I want to be able to click on a position, and have a markup dynamically appear as a pointcloud.
Below is the load function for the extenision. The first time that I load the pointcloud it works, but when I try to add verticies to the geometry, and render that, the new points don't appear. However, the raycaster is able to detect the point. I know this because when I click on a location for the second time, I get a log telling me that the raycaster intercepted the pointcloud (even though that point is not rendered on the screen).
ClickableMarkup.prototype.load = function () {
const self = this;
/* Initizialize */
console.log('Start loading clickableMarkup extension');
this.camera = this.viewer.navigation.getCamera(); // Save camera instance
console.log(this.camera);
this.initCameraInfo(); // Populate cameraInfo array
this.overlayManager.addScene(this.sceneName); // Add scene to overlay manager
this.scene = this.viewer.impl.overlayScenes[this.sceneName].scene; // Save reference to the scene
/* Create pointCloud */
this.geometry = new THREE.Geometry();
this.cameraInfo.forEach( function(e) {
// console.log(` > add ${e.position}`)
self.geometry.vertices.push(e.position);
}
);
this.geometry.computeBoundingBox();
// const material = new THREE.PointCloudMaterial( { size: 50, color: 0Xff0000, opacity: 100, sizeAttenuation: true } );
const texture = THREE.ImageUtils.loadTexture(this.pointCloudTextureURL);
this.material = new THREE.ShaderMaterial({
vertexColors: THREE.VertexColors,
opacity: this.prefs.POINT_CLOUD_OPACITY,
fragmentShader: this.fragmentShader,
vertexShader: this.vertexShader,
depthWrite: true,
depthTest: true,
uniforms: {
size: {type: "f", value: self.size},
tex: {type: "t", value: texture}
}
});
this.points = new THREE.PointCloud( this.geometry, this.material );
/* Add the pointcloud to the scene */
this.overlayManager.addMesh(this.points, this.sceneName); /* >>> THIS WORKS SO IT RENDERS THE POINTCLOUD AT THE BEGINNING OF LAOD <<< */
/* Set up event listeners */
document.addEventListener('click', event => {
event.preventDefault();
this.setRaycasterIntersects(event); // Fill this.intersects with pointcloud indices that are currently selected
if (this.intersects.length > 0) {
console.log('Raycaster hit index: ' + this.hitIndex + JSON.stringify(this.intersects[0]));
this.setCameraView(this.hitIndex);
} else {
/* >>>> THE PROBLEM IS HERE - IT DOESN'T RENDER THE NEW POINTCLOUD POINTS <<<< */
const mousePos = this.screenToWorld(event);
if (mousePos) { // Only add point to scene if the user clicked on the building
const vertexMousePos = new THREE.Vector3(mousePos.x, mousePos.y, mousePos.z);
this.geometry.vertices.push(vertexMousePos);
this.geometry.verticesNeedUpdate = true;
this.geometry.computeBoundingBox();
this.points = new THREE.PointCloud(this.geometry, this.material);
this.overlayManager.addMesh(this.points, this.sceneName);
this.viewer.impl.invalidate(true); // Render the scene again
}
}
}, false);
console.log('ClickableMarkup extension is loaded!');
return true;
};
How do I make new pointcloud verticies render?
It looks like there might be a typo in the problematic code.
this.overlayManager.addMesh(this.points, 'this.sceneName');
Should probably be
this.overlayManager.addMesh(this.points, this.sceneName);
Related
I'm adding a custom layer to mapbox using three.js, using the official example from mapbox. I found that the shadows that worked perfectly in v122 are not working in v123. After reading carefully the release changelog for v123 and and the migration guide from v122, I cannot find any related commit or change that is making the shadows disappear. I also tested with the latest build available of three.js and it happens the same, but I found the change happens between these two releases. I have tested with different materials apart from ShadowMaterial but same result.
Exactly the same code, just changing the package version from:
https://unpkg.com/three#0.122.0/examples/js/loaders/GLTFLoader.js
https://unpkg.com/three#0.122.0/build/three.min.js
to
https://unpkg.com/three#0.123.0/examples/js/loaders/GLTFLoader.js
https://unpkg.com/three#0.123.0/build/three.min.js
From this:
Here is the Fiddle v122
To this...
Here is the Fiddle v123
Code is exactly the same:
mapboxgl.accessToken = 'pk.eyJ1IjoianNjYXN0cm8iLCJhIjoiY2s2YzB6Z25kMDVhejNrbXNpcmtjNGtpbiJ9.28ynPf1Y5Q8EyB_moOHylw';
var map = (window.map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v10',
zoom: 18,
center: [148.9819, -35.3981],
pitch: 60,
bearing: 45,
antialias: true // create the gl context with MSAA antialiasing, so custom layers are antialiased
}));
// parameters to ensure the model is georeferenced correctly on the map
var modelOrigin = [148.9819, -35.39847];
var modelAltitude = 0;
var modelRotate = [Math.PI / 2, 0, 0];
var modelAsMercatorCoordinate = mapboxgl.MercatorCoordinate.fromLngLat(
modelOrigin,
modelAltitude
);
// transformation parameters to position, rotate and scale the 3D model onto the map
var modelTransform = {
translateX: modelAsMercatorCoordinate.x,
translateY: modelAsMercatorCoordinate.y,
translateZ: modelAsMercatorCoordinate.z,
rotateX: modelRotate[0],
rotateY: modelRotate[1],
rotateZ: modelRotate[2],
/* Since our 3D model is in real world meters, a scale transform needs to be
* applied since the CustomLayerInterface expects units in MercatorCoordinates.
*/
scale: modelAsMercatorCoordinate.meterInMercatorCoordinateUnits()
};
var THREE = window.THREE;
// configuration of the custom layer for a 3D model per the CustomLayerInterface
var customLayer = {
id: '3d-model',
type: 'custom',
renderingMode: '3d',
onAdd: function(map, gl) {
this.camera = new THREE.Camera();
this.scene = new THREE.Scene();
const dirLight = new THREE.DirectionalLight(0xffffff, 1);
dirLight.position.set(0, 70, 100);
let d = 100;
let r = 2;
let mapSize = 1024;
dirLight.castShadow = true;
dirLight.shadow.radius = r;
dirLight.shadow.mapSize.width = mapSize;
dirLight.shadow.mapSize.height = mapSize;
dirLight.shadow.camera.top = dirLight.shadow.camera.right = d;
dirLight.shadow.camera.bottom = dirLight.shadow.camera.left = -d;
dirLight.shadow.camera.near = 1;
dirLight.shadow.camera.far = 400;
dirLight.shadow.camera.visible = true;
this.scene.add(dirLight);
this.scene.add(new THREE.DirectionalLightHelper(dirLight, 10));
this.scene.add(new THREE.CameraHelper(dirLight.shadow.camera))
// use the three.js GLTF loader to add the 3D model to the three.js scene
var loader = new THREE.GLTFLoader();
loader.load(
'https://docs.mapbox.com/mapbox-gl-js/assets/34M_17/34M_17.gltf',
function(gltf) {
gltf.scene.traverse(function(model) {
if (model.isMesh) {
model.castShadow = true;
}
});
this.scene.add(gltf.scene);
// we add the shadow plane automatically
const s = new THREE.Box3().setFromObject(gltf.scene).getSize(new THREE.Vector3(0, 0, 0));
const sizes = [s.x, s.y, s.z];
const planeSize = Math.max(...sizes) * 10;
const planeGeo = new THREE.PlaneBufferGeometry(planeSize, planeSize);
//const planeMat = new THREE.MeshStandardMaterial({ color: 0xffffff, side: THREE.DoubleSide});
const planeMat = new THREE.ShadowMaterial();
planeMat.opacity = 0.5;
let plane = new THREE.Mesh(planeGeo, planeMat);
plane.rotateX(-Math.PI / 2);
//plane.layers.enable(1); plane.layers.disable(0); // it makes the object invisible for the raycaster
plane.receiveShadow = true;
this.scene.add(plane);
}.bind(this)
);
this.map = map;
// use the Mapbox GL JS map canvas for three.js
this.renderer = new THREE.WebGLRenderer({
canvas: map.getCanvas(),
context: gl,
antialias: true
});
this.renderer.autoClear = false;
this.renderer.shadowMap.enabled = true;
},
render: function(gl, matrix) {
var rotationX = new THREE.Matrix4().makeRotationAxis(
new THREE.Vector3(1, 0, 0),
modelTransform.rotateX
);
var rotationY = new THREE.Matrix4().makeRotationAxis(
new THREE.Vector3(0, 1, 0),
modelTransform.rotateY
);
var rotationZ = new THREE.Matrix4().makeRotationAxis(
new THREE.Vector3(0, 0, 1),
modelTransform.rotateZ
);
var m = new THREE.Matrix4().fromArray(matrix);
var l = new THREE.Matrix4()
.makeTranslation(
modelTransform.translateX,
modelTransform.translateY,
modelTransform.translateZ
)
.scale(
new THREE.Vector3(
modelTransform.scale,
-modelTransform.scale,
modelTransform.scale
)
)
.multiply(rotationX)
.multiply(rotationY)
.multiply(rotationZ);
this.camera.projectionMatrix = m.multiply(l);
this.renderer.state.reset();
this.renderer.render(this.scene, this.camera);
this.map.triggerRepaint();
}
};
map.on('style.load', function() {
map.addLayer(customLayer, 'waterway-label');
});
It seems like a bug, but honestly I'd love is something I'm missing or I didn't realize. I even checked if with the files from different CDNs happens the same, and yes, it happens the same. Hoping one of the Three.js contributors or other devs can help me with this as I'm completely blocked with this and stopping me to migrate
Thanks in advance for any pointer!
A new implementation of WebGLState.reset() will be available with r126. It does not only reset engine internal state flags but also calls WebGL commands to reset the actual WebGL state. This approach should solve the reported issue.
Link to the PR at GitHub: https://github.com/mrdoob/three.js/pull/21281
I included this suggestion in the comments for the pull request on github https://github.com/mrdoob/three.js/pull/20732, but I'll add it here as well incase someone only finds this Stack Overflow question when searching.
I ran into a similar issue using another library that was sharing the WebGL context. What I found was that the other library (imgui-js) was setting gl.BLEND to true and then, with the change in the mentioned pull request, WebGLState.Reset() is now setting currentBlendingEnabled to null.
This caused a lot of textures in my scene to be displayed incorrectly because when setBlending is subsequently called on the WebGLState, it assumes that if the desired blending method is NoBlending and currentBlendingEnabled is null, that gl.BLEND is already disabled:
function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
if (blending === NoBlending) {
if ( currentBlendingEnabled ) {
disable(3042);
However, with reset nulling the currentBlendingEnabled value each frame but not setting gl.BLEND to false, I believe this assumption is no longer correct. Looking closer, even after removing the external library I was using that sets the gl.BLEND value to true, I found that the change in the pull request was having a negative impacting some of the textures in my scene. In my case I found that updating the setBlending function to honor NoBlending requests, including when currentBlendingEnabled is null, seems to have remedied the situation. Maybe that will work in your case too?
function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
if (blending === NoBlending) {
if (currentBlendingEnabled !== false) {
disable(3042);
I upload a large texture to my fragment shader as a map in three.js.
This texture is a 2D canvas on which I draw random shapes.
While drawing, I just want to update the part of the texture that has changed. Updating the whole texture (up to 3000x3000 pixel) is just too slow.
However, I can not get to perform a partial update. texSubImage2D doesn't have any effect in my scene.
No errors in the console - I expect that I am missing a step but can not figure it out yet.
//
// create drawing canvas 2D and related textures
//
this._canvas = document.createElement('canvas');
this._canvas.width = maxSliceDimensionsX;
this._canvas.height = maxSliceDimensionsY;
this._canvasContext = this._canvas.getContext('2d')!;
this._canvasContext.fillStyle = 'rgba(0, 0, 0, 0)';
this._canvasContext.fillRect(0, 0, window.innerWidth, window.innerHeight);
this._texture = new Texture(this._canvas);
this._texture.magFilter = NearestFilter;
this._texture.minFilter = NearestFilter;
// const data = new Uint8Array(maxSliceDimensionsX * maxSliceDimensionsY * 4);
// this._texture2 = new THREE.DataTexture(data, maxSliceDimensionsX, maxSliceDimensionsY, THREE.RGBAFormat);
this._brushMaterial = new MeshBasicMaterial({
map: this._texture,
side: DoubleSide,
transparent: true,
});
...
// in the render loop
renderLoop() {
...
// grab random values as a test
const imageData = this._canvasContext.getImageData(100, 100, 200, 200);
const uint8Array = new Uint8Array(imageData.data.buffer);
// activate texture?
renderer.setTexture2D(this._texture, 0 );
// update subtexture
const context = renderer.getContext();
context.texSubImage2D( context.TEXTURE_2D, 0, 0, 0, 200, 200, context.RGBA, context.UNSIGNED_BYTE, uint8Array);
// updating the whole texture works as expected but is slow
// this._texture.needsUpdate = true;
// Render new scene
renderer.render(scene, this._camera);
}
Thanks,
Nicolas
Right after creating the texture, we must notify three that the texture needs to be uploaded to the GPU.
We just have to set it 1 time at creation time and not in the render loop.
this._texture = new Texture(this._canvas);
this._texture.magFilter = NearestFilter;
this._texture.minFilter = NearestFilter;
// MUST BE ADDED
this._texture.needsUpdate = true;
I've recreated a bag model for my application and exported it into ThreeJs as an .obj:
I've assigned a different colour to every face found in the models geometry like this:
var geometry = new THREE.Geometry().fromBufferGeometry( bagMesh.children[0].geometry );
for (var i = 0; i < geometry.faces.length; i ++ ) {
var face = geometry.faces[i];
// 7 & 8 = front side
// can we flip its normal?
if(i === 7 || i === 8) {
face.color.setHex( 0xff0000 );
} else {
face.color.setHex( Math.random() * 0xffffff );
}
}
geometry.translate( 0, -1, 0.75);
mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial({ vertexColors: THREE.FaceColors, side: THREE.DoubleSide }) );
scene.add(mesh);
I've identified the faces of the front-side at indices 7 and 8 of the faces array and turned them red.
The problem is that this colour can be seen when I look inside of the bag too:
I realize that this is because I've set the object to THREE.DoubleSide but if I change it to THREE.FrontSide then the sides only partially visible.
So my question is how do I assign a different unique colour to each side (all 11 of them, counting the inside too) without that colour appearing on that sides respective opposite?
I'm trying to keep things simple here by only using colours as opposed to mapping images onto it, which is what I'll want to eventually get to.
Note - My previous model solved this problem by treating each side as a seperate mesh but this caused other issues like z-hiding and flickering problems.
Thanks
EDIT
#WestLangley I've setup a fiddle to demonstrate what you added in your comment. Assuming that I got it right it didn't have the desired affect:
(function onLoad() {
var canvasElement;
var width, height;
var scene, camera;
var renderer;
var controls;
var pivot;
var bagMesh;
var planeMesh;
const objLoader = new THREE.OBJLoader2();
const fileLoader = new THREE.FileLoader();
init();
function init() {
container = document.getElementById('container');
initScene();
addGridHelper();
addCamera();
addLighting();
addRenderer();
addOrbitControls();
loadPlaneObj();
// Logic
var update = function() {};
// Draw scene
var render = function() {
renderer.render(scene, camera);
};
// Run game logic (update, render, repeat)
var gameLoop = function() {
requestAnimationFrame(gameLoop);
update();
render();
};
gameLoop();
}
/**** Basic Scene Setup ****/
function initScene() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0xd3d3d3);
var axis = new THREE.AxesHelper();
scene.add(axis);
}
function addCamera() {
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(3,3,3);
scene.add(camera);
}
function addGridHelper() {
var planeGeometry = new THREE.PlaneGeometry(2000, 2000);
planeGeometry.rotateX(-Math.PI / 2);
var planeMaterial = new THREE.ShadowMaterial({
opacity: 0.2
});
var plane = new THREE.Mesh(planeGeometry, planeMaterial);
plane.position.y = -200;
plane.receiveShadow = true;
scene.add(plane);
var helper = new THREE.GridHelper(2000, 100);
helper.material.opacity = 0.25;
helper.material.transparent = true;
scene.add(helper);
var axis = new THREE.AxesHelper();
scene.add(axis);
}
// *********** Lighting settings **********************
function addLighting() {
var light = new THREE.HemisphereLight(0xffffff, 0xffffff, 1);
scene.add(light);
}
// ************** Material settings **************
function setMaterial(materialName) {
// get the object from the scene
var bagMesh = scene.getObjectByName('bag');
var material;
if (!materialName) {
materialName = materials.material;
}
if (bagMesh) {
var colour = parseInt(materials.colour);
switch (materialName) {
case 'MeshBasicMaterial':
material = new THREE.MeshBasicMaterial({
color: colour
});
break;
case 'MeshDepthMaterial':
material = new THREE.MeshDepthMaterial();
break;
case 'MeshLambertMaterial':
material = new THREE.MeshLambertMaterial({
color: colour
});
break;
case 'MeshNormalMaterial':
material = new THREE.MeshNormalMaterial();
break;
case 'MeshPhongMaterial':
material = new THREE.MeshPhongMaterial({
color: colour
});
break;
case 'MeshPhysicalMaterial':
material = new THREE.MeshPhysicalMaterial({
color: colour
});
break;
case 'MeshStandardMaterial':
material = new THREE.MeshStandardMaterial({
color: colour
});
break;
case 'MeshToonMaterial':
material = new THREE.MeshToonMaterial({
color: colour
});
break;
}
bagMesh.children.forEach(function(c) {
c.material = material;
});
}
}
function setMaterialColour(colour) {
materials.colour = colour;
setMaterial(null);
}
// ************** End of materials ***************
function addRenderer() {
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
container.appendChild(renderer.domElement);
}
function addOrbitControls() {
var controls = new THREE.OrbitControls(camera, renderer.domElement);
}
function addPivot() {
var cubeGeo = new THREE.BoxBufferGeometry(5, 5, 5);
var cubeMat = new THREE.MeshBasicMaterial();
pivot = new THREE.Mesh(cubeGeo, cubeMat);
bagMesh.position.x -= 15;
bagMesh.position.z -= 55;
pivot.add(bagMesh);
pivot.add(handle);
scene.add(pivot);
}
function loadPlaneObj() {
loadObj('Plane', 'https://rawgit.com/Katana24/threejs-experimentation/master/models/Plane.obj', 'https://rawgit.com/Katana24/threejs-experimentation/master/models/Plane.mtl', addPlaneToSceneSOAnswer);
}
function loadObj(objName, objUrl, mtlUrl, onLoadFunc) {
var onLoadMtl = function(materials) {
objLoader.setModelName(objName);
objLoader.setMaterials(materials);
fileLoader.setPath('');
fileLoader.setResponseType('arraybuffer');
fileLoader.load(objUrl,
function(onLoadContent) {
var mesh = objLoader.parse(onLoadContent);
onLoadFunc(mesh);
},
function(inProgress) {},
function(error) {
throw new Error('Couldnt load the model: ', error);
});
};
objLoader.loadMtl(mtlUrl, objName+'.mtl', onLoadMtl);
}
function addPlaneToSceneSOAnswer(mesh) {
var frontMaterial = new THREE.MeshBasicMaterial( { color : 0xff0000, side: THREE.FrontSide } );
var backMaterial = new THREE.MeshBasicMaterial( { color : 0x00ff00, side: THREE.BackSide } );
var geometry = new THREE.Geometry().fromBufferGeometry( mesh.children[0].geometry );
var length = geometry.faces.length;
geometry.faces.splice(14, 1);
for (var i = 0; i < geometry.faces.length; i ++ ) {
var face = geometry.faces[i];
face.color.setHex(Math.random() * 0xffffff);
}
mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial({ vertexColors: THREE.FaceColors, side: THREE.DoubleSide }) );
mesh.material.side = THREE.FrontSide;
var mesh2 = new THREE.Mesh( geometry, mesh.material.clone() );
mesh2.material.side = THREE.BackSide;
// mesh2.material.vertexColors = THREE.NoColors;
mesh2.material.vertexColors = [new THREE.Color(0xff0000), new THREE.Color(0x00ff00), new THREE.Color(0x0000ff)];
mesh.add( mesh2 );
scene.add(mesh);
}
})();
body {
background: transparent;
padding: 0;
margin: 0;
font-family: sans-serif;
}
#canvas {
margin: 10px auto;
width: 800px;
height: 350px;
margin-top: -44px;
}
<body>
<div id="container"></div>
<script src="https://threejs.org/build/three.js"></script>
<script src="https://threejs.org/examples/js/libs/dat.gui.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script src="https://threejs.org/examples/js/loaders/MTLLoader.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/dev/examples/js/loaders/LoaderSupport.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/dev/examples/js/loaders/OBJLoader2.js"></script>
</body>
What am I missing here?
I followed along with Don's suggestion about the different materials but didn't know entirely what he meant.
I examined this question which details setting the materialIndex. I investigated what this means and what it means is that when you pass a geometry and an array of materials to a mesh like this:
mesh = new THREE.Mesh( geometry, [frontMaterial, backMaterial, otherMaterial] );
then that face will get the material (frontMaterial because it's at position 0) assigned to it.
Coming back to my original question, I decided to simplify (for the moment) and see if I could apply what I want to just a Plane mesh exported from Blender.
The Plane has two Faces when added into 3JS. I found I could flip each face or assign a different material to each but I needed to duplicate the faces in order to achieve this:
function addMeshTwoToScene() {
var frontMaterial = new THREE.MeshBasicMaterial( { color : 0xff0000, side: THREE.FrontSide } );
var backMaterial = new THREE.MeshBasicMaterial( { color : 0x00ff00, side: THREE.BackSide } );
var geometry = new THREE.Geometry().fromBufferGeometry( planeMesh.children[0].geometry );
// Duplicates the face
var length = geometry.faces.length;
for (var i = 0; i < length; i++ ) {
var face = geometry.faces[i];
var newFace = Object.assign({}, face);
geometry.faces.push(newFace);
}
for (var i = 0; i < geometry.faces.length; i ++ ) {
var face = geometry.faces[i];
if(i === 0 || i === 3) {
face.materialIndex = 0;
} else {
face.materialIndex = 1;
}
}
var mesh = new THREE.Mesh( geometry, [frontMaterial, backMaterial] );
scene.add(mesh);
}
This results in the following:
I'm not going to mark this as the accepted answer yet as I still need to apply it to the more complex model in the question plus I think there could still be a better way to do this, like flipping a particular vertex to some other value.
One solution would be to use a ShaderMaterial and define the colors based on whether the face is front or back facing.
Let me walk you through this simple example
Hold left click to rotate the mesh. If you're not familiar with ShaderFrog, click "Edit Source" on the right and scroll down the bottom of the fragment shader.
if (!gl_FrontFacing) gl_FragColor = vec4(vec3(0.0, 0.0, 1.0) * brightness, 1.0);
gl_FrontFacing is a boolean. Quite self explanatory, it'll return true if a face is front, and false otherwise.
The line reads "if the face is not front facing, render it blue at with alpha = 1.0.
Hoping that helps.
I'm trying to load a model from Blender, apply a PointsMaterial to it and animate it. So far, I've been able to load the model and animate it successfully as long as I use a material other than THREE.PointsMaterial to create the mesh.
When I create a THREE.Points object, the animation doesn't play. I noticed that when I set the PointsMaterial's morphTargets property to true, there's a warning saying that there is no such property of PointsMaterial. Does Threejs not support animation of Points objects using morph targets?
monster refers to a mesh that works when animated. It uses the loaded geometry and material. ParticleSystem is the the THREE.Points object.
Code:
function loadObject(path){
var loader = new THREE.JSONLoader();
loader.load(
path,
function(geometry, materials){
var material = materials[ 0 ];
material.morphTargets = true;
material.color.setHex( 0xffaaaa );
monster = new THREE.Mesh( geometry, materials );
monster.position.set( 0, 0, 0 );
var s = .003;
monster.scale.set( s, s, s );
var particleMaterial = new THREE.PointsMaterial({
color: 0xffffff,
size: .005,
morphTargets: true
});
particleSystem = new THREE.Points(geometry, particleMaterial);
particleSystem.morphTargetInfluences = monster.morphTargetInfluences;
particleSystem.morphTargetDictionary = monster.morphTargetDictionary;
particleSystem.position.set(0, 0, 0);
particleSystem.scale.set(s, s, s);
particleSystem.matrixAutoUpdate = false;
particleSystem.updateMatrix();
particleSystem.geometry.verticesNeedUpdate = true;
scene.add(particleSystem);
mixer.clipAction( geometry.animations[ 0 ], particleSystem )
.setDuration( 5 ) // one second
.startAt( - Math.random() ) // random phase (already running)
.play(); // let's go
}
)
}
I am trying to change a cube image at run time by selecting an option from Select Form element. When running the code, the image changes after selecting, but the previous cube and image stays in the scene.
How I clear / refresh / update the scene properly when changing the material / image / texture.
<div id = "container"></div>
<form id = "changesForm">
Cube Image:
<br>
<select id = "cubeImage">
<option value = "random">Random</option>
<option value = "image1">First Image</option>
<option value = "Image2">Second Image</option>
</select>
<br>
</form>
<script type = "text/javascript">
window.onload = windowLoaded;
function windowLoaded(){
if (window.addEventListener){
init();
animate();
//document.getElementById('container').addEventListener('mousemove', containerMouseover, false);
window.addEventListener( 'resize', onWindowResize, false );
var cubeImage = document.getElementById('cubeImage');
cubeImage.addEventListener("change", changeCubeImage, false);
}
else if (window.attachEvent){
//init();
//animate();
//document.getElementById('container').attachEvent('onmousemove', containerMouseover);
//window.attachEvent( 'onresize', onWindowResize);
}
function changeCubeImage(e){
//e.preventDefault();
var target = e.target;
cubeImageCheck = target.value;
createCube();
}
// rest code .....
function createCube(){
//image
var cubeImg;
switch (cubeImageCheck){
case 'random': {
// should load the 2 images random - to do
cubeImg = new THREE.ImageUtils.loadTexture("img1.jpg");
break;
}
case 'image1': {
cubeImg = new THREE.ImageUtils.loadTexture("image1.jpg");
break;
}
case 'image2': {
cubeImg = new THREE.ImageUtils.loadTexture("image2.jpg");
break;
}
}
cubeImg.needsUpdate = true;
// geometry
var cubeGeometry = new THREE.CubeGeometry(200,200,200);;
// material
var cubeMaterial = new THREE.MeshPhongMaterial({
map: cubeImg,
side:THREE.DoubleSide,
transparent: true,
opacity:1,
shading: THREE.SmoothShading,
shininess: 90,
specular: 0xFFFFFF
});
cubeMaterial.map.needsUpdate = true;
//mesh
cubeMesh = new THREE.Mesh(cubeGeometry, cubeMaterial);
cubeMesh.needsUpdate = true;
scene.add(cubeMesh);
}
// rest ....
On select change you can update your existing mesh texture, don't need to remove or create new mesh :
mesh.material.map = THREE.ImageUtils.loadTexture( src );
mesh.material.needsUpdate = true;
Complete Example With Loader:
First, create your mesh and apply any material
//Add SPHERE
this.earthMesh = new THREE.Mesh(
new THREE.SphereBufferGeometry(3, 35, 35),
new THREE.MeshPhongMaterial()
);
this.scene.add(this.earthMesh);
Now Load your Texture image and apply it on the mesh material
//LOAD TEXTURE and on completion apply it on SPHERE
new THREE.TextureLoader().load(
"https://images.pexels.com/photos/1089438/pexels-photo-1089438.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260",
texture => {
//Update Texture
this.earthMesh.material.map = texture;
this.earthMesh.material.needsUpdate = true;
},
xhr => {
//Download Progress
console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
},
error => {
//Error CallBack
console.log("An error happened" + error);
}
);
Progress and Error Callbacks are optional