gpt4 book ai didi

javascript - InstancedBufferGeometry 的 PhongMaterial

转载 作者:行者123 更新时间:2023-12-01 02:04:50 24 4
gpt4 key购买 nike

我需要创建一个包含数千个简单网格的场景,因此我决定使用 InstancedBufferGeometry。我从这个例子中复制了大部分代码:https://threejs.org/examples/#webgl_buffergeometry_instancing_dynamic

实例化有效,但仅限于示例中的 THREE.RawShaderMaterial:

instancedMaterial = new THREE.RawShaderMaterial( {
uniforms: {
map: { value: new THREE.TextureLoader().load( 'textures/grassAlpha.png' ) },
time: { value: 0 }
},
vertexShader: document.getElementById( 'vertexShader' ).textContent,
fragmentShader: document.getElementById( 'fragmentShader' ).textContent
} );

和着色器:

<script id="vertexShader" type="x-shader/x-vertex">
precision highp float;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
uniform float time;
attribute vec3 position;
attribute vec3 offset;
attribute vec2 uv;
attribute vec4 orientation;
varying vec2 vUv;
void main() {
vec3 vPosition = position;
vec3 vcV = cross( orientation.xyz, vPosition );
vPosition = vcV * ( 2.0 * orientation.w ) + ( cross( orientation.xyz, vcV ) * 2.0 + vPosition );
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( offset + vPosition, 1.0 );
}
</script>

<script id="fragmentShader" type="x-shader/x-fragment">
precision highp float;
uniform sampler2D map;
varying vec2 vUv;
void main() {
vec4 texelColor = texture2D( map, vUv );
if ( texelColor.a < 0.4 ) discard;
gl_FragColor = texelColor;
}
</script>

但是我如何使用THREE.MeshPhongMaterial代替这个简单的着色器?如果我使用其他 Material (例如 basic 或 phong)创建网格,它就会消失(或者可能变得完全透明,但控制台中没有错误)。

最佳答案

您可以使用Material.onBeforeCompile 。代码如下所示,带有单个实例化属性 offset

material.onBeforeCompile = function ( shader ) {
shader.vertexShader = 'attribute vec3 offset;\n' + shader.vertexShader;
shader.vertexShader = shader.vertexShader.replace( '#include <begin_vertex>',
[
'vec3 transformed = vec3( position + offset );',
].join( '\n' )
);
materialShader = shader;
};

演示:https://codepen.io/anon/pen/erGbXj?editors=1010

关于javascript - InstancedBufferGeometry 的 PhongMaterial,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50197946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com