How can I create a custom THREE.MeshStandardMaterial? - javascript

I'm looking to create a material with three.js identical to MeshStandardMaterial.
I want to do this because I need all of its features except with small changes to the GLSL code.
I attempted to recreate MeshStandardMaterial using ShaderMaterial.
WAFFLE.StandardMaterial = function( parameters ) {
parameters.uniforms = THREE.UniformsUtils.merge( [
THREE.UniformsLib.common,
THREE.UniformsLib.aomap,
THREE.UniformsLib.lightmap,
THREE.UniformsLib.emissivemap,
THREE.UniformsLib.bumpmap,
THREE.UniformsLib.normalmap,
THREE.UniformsLib.displacementmap,
THREE.UniformsLib.roughnessmap,
THREE.UniformsLib.metalnessmap,
THREE.UniformsLib.fog,
THREE.UniformsLib.lights,
{
emissive: { value: new THREE.Color( 0x000000 ) },
roughness: { value: 0.5 },
metalness: { value: 0 },
envMapIntensity: { value: 1 } // temporary
}
] );
parameters.vertexShader = THREE.ShaderChunk.meshphysical_vert;
parameters.fragmentShader = THREE.ShaderChunk.meshphysical_frag;
THREE.ShaderMaterial.call( this, parameters );
}
WAFFLE.StandardMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
WAFFLE.StandardMaterial.prototype.constructor = WAFFLE.StandardMaterial;
I haven't been successful thus far.
How can I recreate MeshStandardMaterial?

Related

Cesium polygon callback using javascript

I am trying to edit the change the edit or redraw the polygon. this is my code.
Error
An error occurred while rendering. Rendering has stopped.
TypeError: this._callback is not a function
TypeError: this._callback is not a function
using pickedObject.id i got the exect polygon i want to reposition, but call back issue.
var points = [-95.8079865631313, 30.24038650541154, -
60.10509002138564, 23.526593580490083, -59.06372427570612, 2.245934026097194, -
117.00668212362282, 3.938434130034481
];
function loadPoly(points) {
redPolygon = viewer.entities.add({
id: "myArray",
name: "myArray",
polygon: {
hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
material: Cesium.Color.fromBytes(221, 240, 235, 160)
}
});
polygonCollection.push(redPolygon);
adding_billboard(-95.8079865631313, 30.24038650541154, "A", "-95.8079865631313, 30.24038650541154");
adding_billboard(-60.10509002138564, 23.526593580490083, "A", "-60.10509002138564, 23.526593580490083");
adding_billboard(-59.06372427570612, 2.245934026097194, "A", "-59.06372427570612, 2.245934026097194");
adding_billboard(-117.00668212362282, 3.938434130034481, "A", "-117.00668212362282, 3.938434130034481");
viewer.flyTo(redPolygon);
}
function adding_billboard(lon, lat, name, popup) {
var entity = viewer.entities.add({
name: name,
position: Cesium.Cartesian3.fromDegrees(lon, lat, 2000),
billboard: {
image: 'https://cdn0.iconfinder.com/data/icons/small-n-flat/24/678111-map-marker-512.png',
show: true, // default
pixelOffset: new Cesium.Cartesian2(0, -20), // default: (0, 0)
eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0), // default
horizontalOrigin: Cesium.HorizontalOrigin.bottom, // default
alignedAxis: Cesium.Cartesian3.ZERO, // default
width: 20, // default: undefined
height: 25, // default: undefined
//disableDepthTestDistance: Number.POSITIVE_INFINITY, // draws the label in front of terrain
// on ground show
},
label: {
text: popup,
font: "7pt sans-serif",
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
verticalOrigin: Cesium.VerticalOrigin.BASELINE,
fillColor: Cesium.Color.BLACK,
showBackground: true,
backgroundColor: new Cesium.Color(1, 1, 1, 0.7),
backgroundPadding: new Cesium.Cartesian2(8, 4),
disableDepthTestDistance: Number
.POSITIVE_INFINITY, // draws the label in front of terrain
},
});
pointsCollection.push(entity);
}
var coordinates = [76.82071632075994, 33.4134542888633, 77.83750798568438, 33.39276536442791, 77.32892923803021,
32.93547457354476
];
var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
handler.setInputAction(function(click) {
var pickedObject = scene.pick(click.position);
if (Cesium.defined(pickedObject)) {
console.log("Second ");
console.log("pickedObject.id.id ", pickedObject.id.id);
console.log("pickedObject.id.name ", pickedObject.id.name);
console.log("pickedObject.id..polygon.hierarchy ", pickedObject.id.polygon.hierarchy.valueOf());
var data = pickedObject.id.polygon.hierarchy.valueOf();
console.log("data ", data.positions.valueOf());
pickedObject.id.polygon = {
hierarchy: new Cesium.CallbackProperty(new Cesium.Cartesian3.fromDegreesArray(coordinates),
false),
material: Cesium.Color.fromBytes(221, 240, 235, 160)
//pickedObject.id = redPolygon;// tried this but dailed due to same id then i removed it.
if (pickedObject.id.name == 'C') {
// $('#modal-activity').modal('show');
}
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
i want to shift polygon to some other coordiante but unable to use call back properly can some one guild me how can I do ?
i did some google searches which are given below but my issues not solved.
here i was trying to make polygon points dynamic but line disappers in tarrains. fist time it was ok after moving point it disappers.
https://sandcastle.cesium.com/?#c=zVTRbpswFP2VK14gEjMhWTaJ0Whd0odpnVpl0vZQ+uDCTWvN2Mg2yVjVf5/BkKRZ1VV9mnjhHp9zfH2uYUMVbBhuUcEJCNzCAjWrS/K9wwI/78qFFIYygcoffchE+2ysDoVhpomt0DmQDmCoCS2K4D4TAKxIwP+8jP2wrQQtESywwgLOOGeVRpACdK3WNEfHqaS2HlIkMLSyoMrYNyqmZK1kucRbhaiDN3E8I+MQpu/JeNRLmTAJdBvbiv1C/o39xgSm49BhueRSJTvjtiKrs2W/KmvD7SEXT5A+nZ8uvjym/WCFuUsgJrMWfsjEg8tmn8zkBclMXpPMP4N52wXz7v8Lpl1/LpVK8qbl7JvtD62Tw9t52aOXSlaoTHOqFG2CKyeBQ+YK16hQ5DhQg6O9w/5+whX4w2Y+XMMofLXb5Am3wex677t1Oc12QEkNKkb50VFdIhcu3K89Z9fA/aB+foQvHuLxGCdujHaQo8NxeqGXatNwnLvVj6yspDJQKx4QEhksK25b1dFNnf9EQ3KtW1kaDaK0YBv7EZxk3tEvJvMg51Rru7KueXdRM2+eRpb/SMYlLZi4vdig4rRpKXfx/NyBhJA0suXfKiMlv6HqwPEP
second :Dynamically change polygon position in cesium
it also gives error because i don't know where to use callback.
please guild me. thank you.
Here's Sandcastle link.
const {
Cartesian3,
CallbackProperty,
Color,
defined,
ScreenSpaceEventHandler,
ScreenSpaceEventType,
Viewer
} = window.Cesium;
const viewer = new Viewer("cesiumContainer");
let redPolygon;
const polygonCollection = [];
const pointsCollection = [];
const polygonId = "myArray";
let polygonPoints = [
-95.8079865631313, 30.24038650541154, -60.10509002138564, 23.526593580490083, -59.06372427570612,
2.245934026097194, -117.00668212362282, 3.938434130034481
];
function loadPoly() {
redPolygon = viewer.entities.add({
id: polygonId,
name: "myArray",
polygon: {
hierarchy: new CallbackProperty(() => {
return {
positions: Cartesian3.fromDegreesArray(polygonPoints)
};
}, false),
material: Color.fromBytes(221, 240, 235, 160)
}
});
polygonCollection.push(redPolygon);
adding_billboard(-95.8079865631313, 30.24038650541154, "A", "-95.8079865631313, 30.24038650541154");
adding_billboard(-60.10509002138564, 23.526593580490083, "A", "-60.10509002138564, 23.526593580490083");
adding_billboard(-59.06372427570612, 2.245934026097194, "A", "-59.06372427570612, 2.245934026097194");
adding_billboard(-117.00668212362282, 3.938434130034481, "A", "-117.00668212362282, 3.938434130034481");
viewer.flyTo(redPolygon);
}
function adding_billboard(lon, lat, name, popup) {
const entity = viewer.entities.add({
name: name,
position: Cartesian3.fromDegrees(lon, lat, 2000),
billboard: {
image: "https://cdn0.iconfinder.com/data/icons/small-n-flat/24/678111-map-marker-512.png",
show: true, // default
pixelOffset: new Cesium.Cartesian2(0, -20), // default: (0, 0)
eyeOffset: new Cartesian3(0.0, 0.0, 0.0), // default
horizontalOrigin: Cesium.HorizontalOrigin.bottom, // default
alignedAxis: Cesium.Cartesian3.ZERO, // default
width: 20, // default: undefined
height: 25 // default: undefined
//disableDepthTestDistance: Number.POSITIVE_INFINITY, // draws the label in front of terrain
// on ground show
},
label: {
text: popup,
font: "7pt sans-serif",
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
verticalOrigin: Cesium.VerticalOrigin.BASELINE,
fillColor: Color.BLACK,
showBackground: true,
backgroundColor: new Color(1, 1, 1, 0.7),
backgroundPadding: new Cesium.Cartesian2(8, 4),
disableDepthTestDistance: Number.POSITIVE_INFINITY // draws the label in front of terrain
}
});
pointsCollection.push(entity);
}
loadPoly();
const scene = viewer.scene;
const handler = new ScreenSpaceEventHandler(scene.canvas);
handler.setInputAction(function (click) {
const pickedObject = scene.pick(click.position);
if (defined(pickedObject) && pickedObject.id && pickedObject.id.id === polygonId) {
const newPolygonPoints = [
76.82071632075994, 33.4134542888633, 77.83750798568438, 33.39276536442791, 77.32892923803021,
32.93547457354476
];
polygonPoints = newPolygonPoints;
viewer.camera.flyTo({
destination: Cartesian3.fromDegrees(76.82071632075994, 33.4134542888633, 1000)
});
}
}, ScreenSpaceEventType.LEFT_CLICK);

How to change Shader color in ThreeJS

I'm new to Three Js and i do not know how to change the color of my material when i press a button on the html page.
Do you have any suggestion? I'll attach here the code
here is how i declare my material:
var color2= new THREE.Color(0xff0000)
var customMaterial = new THREE.ShaderMaterial(
{
uniforms: {
p: { type: "f", value: 2 },
glowColor: { type: "c", value: color2 },
},
vertexShader: $('#vertexShader').text,
fragmentShader: $('#fragmentShader').text,
side: THREE.DoubleSide,
blending: THREE.AdditiveBlending,
transparent: true,
depthWrite: false
});
here is how i update my color:
function render() {
renderer.render(scene, camera);
document.getElementById("colore").onclick= function(){
console.log("prova caramella");
var customMaterial = new THREE.ShaderMaterial(
{
uniforms: {
p: { type: "f", value: 2 },
glowColor: { type: "c", value: new THREE.Color(0x00ff00) },
},
vertexShader: $('#vertexShader').text,
fragmentShader: $('#fragmentShader').text,
side: THREE.DoubleSide,
blending: THREE.AdditiveBlending,
transparent: true,
depthWrite: false
});
customMaterial.needsUpdate = true
}
and lastly this is how i link the material to my 3d model:
function petali2(){
var loaderpetali = new THREE.ColladaLoader();
loaderpetali.load('petali3.dae', function (collada) {
petali = collada.scene;
petali.traverse( function ( child ) {
if (child instanceof THREE.Mesh) {
console.log(child);
child.material = customMaterial;
}
} );
petali.scale.x = 2;
petali.scale.y = 2;
petali.scale.z = 2;
//flower = dae;
scene.add(petali);
});
}
When updating the color, it's sufficient to do this:
customMaterial.uniforms.glowColor.value.set( 0x00ff00 );
There is no need to create a new material.
Besides, when using a latest version of three.js, it's not necessary to define the type for a uniform. The type is automatically derived from the compiled shader. On app level, it's sufficient to do.
uniforms: {
p: { value: 2 },
glowColor: { value: new THREE.Color(0x00ff00) },
},

Make a Global Scope of a mesh using Three.js

I am making my first steps coding with JavaScript and playing with Three.js too.
In my code I made this function:
var loader = new THREE.BinaryLoader();
loader.load( "sources/obj/mmlogo/mm_logo.js", function ( geometry ) {
uniforms = {
color: {
type: "c",
value: new THREE.Color(0x000000),
},
envMap: {
type: "t",
value: reflectionCube
},
fresnelBias: {
type: "f",
value: 0.1
},
fresnelScale: {
type: "f",
value: 1.0
},
fresnelPower: {
type: 'f',
value: 2.0
}
};
material = new THREE.ShaderMaterial( {
uniforms : uniforms,
vertexShader : vertexShader,
fragmentShader : fragmentShader,
wireframe: false,
side: THREE.DoubleSide,
});
monogram = new THREE.Mesh( geometry, material );
monogram.scale.set( 1, 1, 1 );
monogram.position.z = -9;
scene.add( monogram );
});
and then I made this render function:
function render() {
frame += 0.1/3;
monogram.scale.z += Math.sin(frame)/600;
TWEEN.update();
targetX = mouseX * .0005;
targetY = mouseY * .0005;
if ( monogram ) {
monogram.rotation.y += 0.05 * ( targetX - monogram.rotation.y );
monogram.rotation.x += 0.05 * ( targetY - monogram.rotation.x );
}
renderer.render( scene, camera );
}
I can see everything and everything works ok. But my console says that there is an error: Uncaught ReferenceError: monogram is not defined.
I think that I have to make a Global Scope of monogram. So I wrote var before monogram and it doesnt work, then I wrote
monogram = new THREE.Mesh( geometry, material );
monogram.scale.set( 1, 1, 1 );
monogram.position.z = -9;
scene.add( monogram );
outside my function and it doesnt work.
Do you have some suggestion? My app works, even if the console says that there is n error, I think that is better if my console says that everything is ok.

How Repeat ThreeJS Matcap use fragmentShader Texture

here is vertex and fragmentshader material :
material = new THREE.ShaderMaterial( {
uniforms: {
textureMap: { type: 't', value: THREE.ImageUtils.loadTexture( 'img/matcap/green.jpg' ) },
normalMap: { type: 't', value: THREE.ImageUtils.loadTexture( 'img/normalmap/stamp.jpg' ) },
normalScale: { type: 'f', value: 0.5 },
texScale: { type: 'f', value: 5 },
useSSS: { type: 'f', value: 10 },
useScreen: { type: 'f', value: 0 },
color: { type: 'c', value: new THREE.Color( 0, 0, 0 ) }
},
vertexShader: document.getElementById( 'vertexShader' ).textContent,
fragmentShader: document.getElementById( 'fragmentShader' ).textContent,
side: THREE.DoubleSide
} );
I want repeat texture use like this
material.uniforms.textureMap.value.wrapS = material.uniforms.textureMap.value.wrapT =
THREE.ClampToEdgeWrapping;
material.uniforms.normalMap.value.wrapS = material.uniforms.normalMap.value.wrapT =
THREE.RepeatWrapping;
material.uniforms.normalMap.value.repeat.set( 20, 20 );
but not work in three.js why? how fix it
thanks all friends!
By default the texture are Clamp To Edge means no wrapping to zero. Your main texture is Clamp TO Edge repeat and normal texture is Repeat Wrapping probably you normal map texture quality is not so bright to make a difference try to revert the thing or texture ( means make some bright normal map texture or dull texture map any).
your approach is correct it seems. One more thing which you can do to increase readability:
var textureMap = THREE.ImageUtils.loadTexture( 'img/matcap/green.jpg' );
var normalMap = THREE.ImageUtils.loadTexture( 'img/normalmap/stamp.jpg' )
textureMap.repeat.set(20,20);
normalMap.repeat.set(10,10);
//then shader code

three.js; Cannot read property 'position' of undefined and don't know why

I'm gonna make my SUN!!!!!!!!!!!!!!!!! SUNGOD!!! urg---!
..sorry.
It doesn't work as well.
Error message shown on console and it said;
// Uncaught TypeError: Cannot read property 'position' of undefined;
Here is source
// Constructing * The Solar *
var shape = new THREE.BufferGeometry();
shape.addAttribute('position', new THREE.Float32Attribute(6,3));
// console shows problem is here but I can't find any
shape.addAttribute('textureOrder', new THREE.Int8Attribute(6,1));
for(var i=0; i<6; i++) {
shape.attribute.position.setXYZ(i, 0, 0, 0);
shape.attribute.textureOrder.setX(i, i);
};
var d = new Date();
var mater = new THREE.ShaderMaterial({
uniforms: {
time: { type: 'f', value: d.getTime() },
tsun_core: { type: 't', value: loadTexture('./sun_core.png') },
tsun_innerglow: { type: 't', value: loadTexture('./sun_innerglow.png') },
tsun_starlight: { type: 't', value: loadTexture('./sun_starlight.png') },
tsun_outerglow: { type: 't', value: loadTexture('./sun_outerglow.png') },
tsun_shortjetlight: { type: 't', value: loadTexture('./sun_shortjetlight.png') },
tsun_longjetlight: { type: 't', value: loadTexture('./sun_longjetlight.png') }
},
vertexShader: document.getElementById('vs-sun').textContent,
fragmentShader: document.getElementById('fs-sun').textContent
});
mater.depthTest = false;
mater.vertexColor = true;
mater.transparent = true;
mater.blending = THREE.AdditiveBlending;
sun = new THREE.ParticleSystem(shape, mater);
scene.add(sun);
My goal is, change gl_FragColor opacity by uniform time in fragment shader so my sun(?) to be more dynamic...
My opinion, cause of problem be somewhere above source. Please guide me..
Calling the addAttribute method on a THREE.BufferGeometry instance creates properties under the attributes property, not attribute.
Replaces these lines
shape.attribute.position.setXYZ(i, 0, 0, 0);
shape.attribute.textureOrder.setX(i, i);
With the following lines
shape.attributes.position.setXYZ(i, 0, 0, 0);
shape.attributes.textureOrder.setX(i, i);

Categories

Resources