PlaneBufferGeometry.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import { BufferGeometry } from '../core/BufferGeometry';
  2. import { BufferAttribute } from '../core/BufferAttribute';
  3. /**
  4. * @author mrdoob / http://mrdoob.com/
  5. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  6. */
  7. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  8. BufferGeometry.call( this );
  9. this.type = 'PlaneBufferGeometry';
  10. this.parameters = {
  11. width: width,
  12. height: height,
  13. widthSegments: widthSegments,
  14. heightSegments: heightSegments
  15. };
  16. var width_half = width / 2;
  17. var height_half = height / 2;
  18. var gridX = Math.floor( widthSegments ) || 1;
  19. var gridY = Math.floor( heightSegments ) || 1;
  20. var gridX1 = gridX + 1;
  21. var gridY1 = gridY + 1;
  22. var segment_width = width / gridX;
  23. var segment_height = height / gridY;
  24. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  25. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  26. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  27. var offset = 0;
  28. var offset2 = 0;
  29. for ( var iy = 0; iy < gridY1; iy ++ ) {
  30. var y = iy * segment_height - height_half;
  31. for ( var ix = 0; ix < gridX1; ix ++ ) {
  32. var x = ix * segment_width - width_half;
  33. vertices[ offset ] = x;
  34. vertices[ offset + 1 ] = - y;
  35. normals[ offset + 2 ] = 1;
  36. uvs[ offset2 ] = ix / gridX;
  37. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  38. offset += 3;
  39. offset2 += 2;
  40. }
  41. }
  42. offset = 0;
  43. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  44. for ( var iy = 0; iy < gridY; iy ++ ) {
  45. for ( var ix = 0; ix < gridX; ix ++ ) {
  46. var a = ix + gridX1 * iy;
  47. var b = ix + gridX1 * ( iy + 1 );
  48. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  49. var d = ( ix + 1 ) + gridX1 * iy;
  50. indices[ offset ] = a;
  51. indices[ offset + 1 ] = b;
  52. indices[ offset + 2 ] = d;
  53. indices[ offset + 3 ] = b;
  54. indices[ offset + 4 ] = c;
  55. indices[ offset + 5 ] = d;
  56. offset += 6;
  57. }
  58. }
  59. this.setIndex( new BufferAttribute( indices, 1 ) );
  60. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  61. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  62. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  63. }
  64. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  65. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  66. export { PlaneBufferGeometry };