使用InstancedBufferGeometry时索引未定义

时间:2019-03-22 09:49:20

标签: three.js

我正在尝试使用InstancedBufferGeometry将具有不同位置和比例属性的同一对象(最终将是一棵树)的许多副本添加到模型中。对于我的示例,我只是从三个对象开始,但是当它按预期方式工作时,它将使用更多的东西,而这些值来自外部来源。

我一直在尝试在线查看各种示例,包括https://github.com/mrdoob/three.js/blob/master/examples/webgl_buffergeometry_instancing.htmlthreejs instance multiple objects with different sizes and positions,但我得到的是“索引未定义”。

我的示例页面位于https://haddons.net/threejs/instanced.html,相关代码位为:

<script id="vertexShader" type="x-shader/x-vertex">
  precision highp float;

  uniform mat4 modelViewMatrix;
  uniform mat4 projectionMatrix;

  attribute vec3 position;
  attribute vec3 scale;

  void main(){
    gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  }
</script>
<script id="fragmentShader" type="x-shader/x-fragment">
  precision highp float;
  void main(){
    gl_FragColor = color;
  }
</script>

还有:


  var treePositions = [ -407, -1426, 0, 599, -1408, 237.637607058056, -207, -1400, 219.96670816865293 ];
  var treeScales = [ 13.253584152956366, 13.253584152956366, 13.253584152956366, 12.133671566054215, 12.133671566054215,
    12.133671566054215, 9.152234330749572, 9.152234330749572, 9.152234330749572 ];

  var treeGeometry = new THREE.CylinderGeometry(0.2,0.2,1,16,1);
  var treeMaterial = new THREE.MeshLambertMaterial({color: 0x885522});
  var tree = new THREE.Mesh(geometry, material);
  tree.rotation.x += Math.PI / 2;

  var instanceNum = 3;

  var geometry = new THREE.InstancedBufferGeometry();
  geometry.copy(treeGeometry);
  geometry.maxInstancedCount = instanceNum;
  geometry.addAttribute( 'position', new THREE.InstancedBufferAttribute( new Float32Array(treePositions), 3));
  geometry.addAttribute( 'scale', new THREE.InstancedBufferAttribute( new Float32Array(treeScales), 3));

  var material = new THREE.RawShaderMaterial( {
    uniforms: {},
    vertexShader: document.getElementById( 'vertexShader' ).textContent,
    fragmentShader: document.getElementById( 'fragmentShader' ).textContent,
  });

  var mesh = new THREE.Mesh( geometry, material );
  scene.add( mesh );

显然,我还没有弄清楚如何应用要传递的任何属性,因此vertexShader和fragementShader片段可能完全错误。

任何帮助表示赞赏。谢谢。

1 个答案:

答案 0 :(得分:0)

您需要一个

geometry.setIndex(some array);

定义了顶点的连接方式。