BufferGeometry.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449
  1. import { Vector3 } from '../math/Vector3.js';
  2. import { Vector2 } from '../math/Vector2.js';
  3. import { Box3 } from '../math/Box3.js';
  4. import { EventDispatcher } from './EventDispatcher.js';
  5. import { BufferAttribute, Float32BufferAttribute, Uint16BufferAttribute, Uint32BufferAttribute } from './BufferAttribute.js';
  6. import { Sphere } from '../math/Sphere.js';
  7. import { Object3D } from './Object3D.js';
  8. import { Matrix4 } from '../math/Matrix4.js';
  9. import { Matrix3 } from '../math/Matrix3.js';
  10. import { generateUUID } from '../math/MathUtils.js';
  11. import { arrayNeedsUint32 } from '../utils.js';
  12. let _id = 0;
  13. const _m1 = /*@__PURE__*/ new Matrix4();
  14. const _obj = /*@__PURE__*/ new Object3D();
  15. const _offset = /*@__PURE__*/ new Vector3();
  16. const _box = /*@__PURE__*/ new Box3();
  17. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  18. const _vector = /*@__PURE__*/ new Vector3();
  19. /**
  20. * A representation of mesh, line, or point geometry. Includes vertex
  21. * positions, face indices, normals, colors, UVs, and custom attributes
  22. * within buffers, reducing the cost of passing all this data to the GPU.
  23. *
  24. * ```js
  25. * const geometry = new THREE.BufferGeometry();
  26. * // create a simple square shape. We duplicate the top left and bottom right
  27. * // vertices because each vertex needs to appear once per triangle.
  28. * const vertices = new Float32Array( [
  29. * -1.0, -1.0, 1.0, // v0
  30. * 1.0, -1.0, 1.0, // v1
  31. * 1.0, 1.0, 1.0, // v2
  32. *
  33. * 1.0, 1.0, 1.0, // v3
  34. * -1.0, 1.0, 1.0, // v4
  35. * -1.0, -1.0, 1.0 // v5
  36. * ] );
  37. * // itemSize = 3 because there are 3 values (components) per vertex
  38. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  39. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  40. * const mesh = new THREE.Mesh( geometry, material );
  41. * ```
  42. *
  43. * @augments EventDispatcher
  44. */
  45. class BufferGeometry extends EventDispatcher {
  46. /**
  47. * Constructs a new geometry.
  48. */
  49. constructor() {
  50. super();
  51. /**
  52. * This flag can be used for type testing.
  53. *
  54. * @type {boolean}
  55. * @readonly
  56. * @default true
  57. */
  58. this.isBufferGeometry = true;
  59. /**
  60. * The ID of the geometry.
  61. *
  62. * @name BufferGeometry#id
  63. * @type {number}
  64. * @readonly
  65. */
  66. Object.defineProperty( this, 'id', { value: _id ++ } );
  67. /**
  68. * The UUID of the geometry.
  69. *
  70. * @type {string}
  71. * @readonly
  72. */
  73. this.uuid = generateUUID();
  74. /**
  75. * The name of the geometry.
  76. *
  77. * @type {string}
  78. */
  79. this.name = '';
  80. this.type = 'BufferGeometry';
  81. /**
  82. * Allows for vertices to be re-used across multiple triangles; this is
  83. * called using "indexed triangles". Each triangle is associated with the
  84. * indices of three vertices. This attribute therefore stores the index of
  85. * each vertex for each triangular face. If this attribute is not set, the
  86. * renderer assumes that each three contiguous positions represent a single triangle.
  87. *
  88. * @type {?BufferAttribute}
  89. * @default null
  90. */
  91. this.index = null;
  92. /**
  93. * A (storage) buffer attribute which was generated with a compute shader and
  94. * now defines indirect draw calls.
  95. *
  96. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  97. *
  98. * @type {?BufferAttribute}
  99. * @default null
  100. */
  101. this.indirect = null;
  102. /**
  103. * This dictionary has as id the name of the attribute to be set and as value
  104. * the buffer attribute to set it to. Rather than accessing this property directly,
  105. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  106. *
  107. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  108. */
  109. this.attributes = {};
  110. /**
  111. * This dictionary holds the morph targets of the geometry.
  112. *
  113. * Note: Once the geometry has been rendered, the morph attribute data cannot
  114. * be changed. You will have to call `dispose()?, and create a new geometry instance.
  115. *
  116. * @type {Object}
  117. */
  118. this.morphAttributes = {};
  119. /**
  120. * Used to control the morph target behavior; when set to `true`, the morph
  121. * target data is treated as relative offsets, rather than as absolute
  122. * positions/normals.
  123. *
  124. * @type {boolean}
  125. * @default false
  126. */
  127. this.morphTargetsRelative = false;
  128. /**
  129. * Split the geometry into groups, each of which will be rendered in a
  130. * separate draw call. This allows an array of materials to be used with the geometry.
  131. *
  132. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  133. *
  134. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  135. * indices, and must not leave vertices or indices unused.
  136. *
  137. * @type {Array<Object>}
  138. */
  139. this.groups = [];
  140. /**
  141. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  142. *
  143. * @type {Box3}
  144. * @default null
  145. */
  146. this.boundingBox = null;
  147. /**
  148. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  149. *
  150. * @type {Sphere}
  151. * @default null
  152. */
  153. this.boundingSphere = null;
  154. /**
  155. * Determines the part of the geometry to render. This should not be set directly,
  156. * instead use `setDrawRange()`.
  157. *
  158. * @type {{start:number,count:number}}
  159. */
  160. this.drawRange = { start: 0, count: Infinity };
  161. /**
  162. * An object that can be used to store custom data about the geometry.
  163. * It should not hold references to functions as these will not be cloned.
  164. *
  165. * @type {Object}
  166. */
  167. this.userData = {};
  168. }
  169. /**
  170. * Returns the index of this geometry.
  171. *
  172. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  173. */
  174. getIndex() {
  175. return this.index;
  176. }
  177. /**
  178. * Sets the given index to this geometry.
  179. *
  180. * @param {Array<number>|BufferAttribute} index - The index to set.
  181. * @return {BufferGeometry} A reference to this instance.
  182. */
  183. setIndex( index ) {
  184. if ( Array.isArray( index ) ) {
  185. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  186. } else {
  187. this.index = index;
  188. }
  189. return this;
  190. }
  191. /**
  192. * Sets the given indirect attribute to this geometry.
  193. *
  194. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  195. * @return {BufferGeometry} A reference to this instance.
  196. */
  197. setIndirect( indirect ) {
  198. this.indirect = indirect;
  199. return this;
  200. }
  201. /**
  202. * Returns the indirect attribute of this geometry.
  203. *
  204. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  205. */
  206. getIndirect() {
  207. return this.indirect;
  208. }
  209. /**
  210. * Returns the buffer attribute for the given name.
  211. *
  212. * @param {string} name - The attribute name.
  213. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  214. * Returns `undefined` if not attribute has been found.
  215. */
  216. getAttribute( name ) {
  217. return this.attributes[ name ];
  218. }
  219. /**
  220. * Sets the given attribute for the given name.
  221. *
  222. * @param {string} name - The attribute name.
  223. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  224. * @return {BufferGeometry} A reference to this instance.
  225. */
  226. setAttribute( name, attribute ) {
  227. this.attributes[ name ] = attribute;
  228. return this;
  229. }
  230. /**
  231. * Deletes the attribute for the given name.
  232. *
  233. * @param {string} name - The attribute name to delete.
  234. * @return {BufferGeometry} A reference to this instance.
  235. */
  236. deleteAttribute( name ) {
  237. delete this.attributes[ name ];
  238. return this;
  239. }
  240. /**
  241. * Returns `true` if this geometry has an attribute for the given name.
  242. *
  243. * @param {string} name - The attribute name.
  244. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  245. */
  246. hasAttribute( name ) {
  247. return this.attributes[ name ] !== undefined;
  248. }
  249. /**
  250. * Adds a group to this geometry.
  251. *
  252. * @param {number} start - The first element in this draw call. That is the first
  253. * vertex for non-indexed geometry, otherwise the first triangle index.
  254. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  255. * @param {number} [materialIndex=0] - The material array index to use.
  256. */
  257. addGroup( start, count, materialIndex = 0 ) {
  258. this.groups.push( {
  259. start: start,
  260. count: count,
  261. materialIndex: materialIndex
  262. } );
  263. }
  264. /**
  265. * Clears all groups.
  266. */
  267. clearGroups() {
  268. this.groups = [];
  269. }
  270. /**
  271. * Sets the draw range for this geometry.
  272. *
  273. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  274. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  275. * For indexed BufferGeometry, `count` is the number of indices to render.
  276. */
  277. setDrawRange( start, count ) {
  278. this.drawRange.start = start;
  279. this.drawRange.count = count;
  280. }
  281. /**
  282. * Applies the given 4x4 transformation matrix to the geometry.
  283. *
  284. * @param {Matrix4} matrix - The matrix to apply.
  285. * @return {BufferGeometry} A reference to this instance.
  286. */
  287. applyMatrix4( matrix ) {
  288. const position = this.attributes.position;
  289. if ( position !== undefined ) {
  290. position.applyMatrix4( matrix );
  291. position.needsUpdate = true;
  292. }
  293. const normal = this.attributes.normal;
  294. if ( normal !== undefined ) {
  295. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  296. normal.applyNormalMatrix( normalMatrix );
  297. normal.needsUpdate = true;
  298. }
  299. const tangent = this.attributes.tangent;
  300. if ( tangent !== undefined ) {
  301. tangent.transformDirection( matrix );
  302. tangent.needsUpdate = true;
  303. }
  304. if ( this.boundingBox !== null ) {
  305. this.computeBoundingBox();
  306. }
  307. if ( this.boundingSphere !== null ) {
  308. this.computeBoundingSphere();
  309. }
  310. return this;
  311. }
  312. /**
  313. * Applies the rotation represented by the Quaternion to the geometry.
  314. *
  315. * @param {Quaternion} q - The Quaternion to apply.
  316. * @return {BufferGeometry} A reference to this instance.
  317. */
  318. applyQuaternion( q ) {
  319. _m1.makeRotationFromQuaternion( q );
  320. this.applyMatrix4( _m1 );
  321. return this;
  322. }
  323. /**
  324. * Rotates the geometry about the X axis. This is typically done as a one time
  325. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  326. * real-time mesh rotation.
  327. *
  328. * @param {number} angle - The angle in radians.
  329. * @return {BufferGeometry} A reference to this instance.
  330. */
  331. rotateX( angle ) {
  332. // rotate geometry around world x-axis
  333. _m1.makeRotationX( angle );
  334. this.applyMatrix4( _m1 );
  335. return this;
  336. }
  337. /**
  338. * Rotates the geometry about the Y axis. This is typically done as a one time
  339. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  340. * real-time mesh rotation.
  341. *
  342. * @param {number} angle - The angle in radians.
  343. * @return {BufferGeometry} A reference to this instance.
  344. */
  345. rotateY( angle ) {
  346. // rotate geometry around world y-axis
  347. _m1.makeRotationY( angle );
  348. this.applyMatrix4( _m1 );
  349. return this;
  350. }
  351. /**
  352. * Rotates the geometry about the Z axis. This is typically done as a one time
  353. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  354. * real-time mesh rotation.
  355. *
  356. * @param {number} angle - The angle in radians.
  357. * @return {BufferGeometry} A reference to this instance.
  358. */
  359. rotateZ( angle ) {
  360. // rotate geometry around world z-axis
  361. _m1.makeRotationZ( angle );
  362. this.applyMatrix4( _m1 );
  363. return this;
  364. }
  365. /**
  366. * Translates the geometry. This is typically done as a one time
  367. * operation, and not during a loop. Use {@link Object3D#position} for typical
  368. * real-time mesh rotation.
  369. *
  370. * @param {number} x - The x offset.
  371. * @param {number} y - The y offset.
  372. * @param {number} z - The z offset.
  373. * @return {BufferGeometry} A reference to this instance.
  374. */
  375. translate( x, y, z ) {
  376. // translate geometry
  377. _m1.makeTranslation( x, y, z );
  378. this.applyMatrix4( _m1 );
  379. return this;
  380. }
  381. /**
  382. * Scales the geometry. This is typically done as a one time
  383. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  384. * real-time mesh rotation.
  385. *
  386. * @param {number} x - The x scale.
  387. * @param {number} y - The y scale.
  388. * @param {number} z - The z scale.
  389. * @return {BufferGeometry} A reference to this instance.
  390. */
  391. scale( x, y, z ) {
  392. // scale geometry
  393. _m1.makeScale( x, y, z );
  394. this.applyMatrix4( _m1 );
  395. return this;
  396. }
  397. /**
  398. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  399. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  400. * real-time mesh rotation.
  401. *
  402. * @param {Vector3} vector - The target point.
  403. * @return {BufferGeometry} A reference to this instance.
  404. */
  405. lookAt( vector ) {
  406. _obj.lookAt( vector );
  407. _obj.updateMatrix();
  408. this.applyMatrix4( _obj.matrix );
  409. return this;
  410. }
  411. /**
  412. * Center the geometry based on its bounding box.
  413. *
  414. * @return {BufferGeometry} A reference to this instance.
  415. */
  416. center() {
  417. this.computeBoundingBox();
  418. this.boundingBox.getCenter( _offset ).negate();
  419. this.translate( _offset.x, _offset.y, _offset.z );
  420. return this;
  421. }
  422. /**
  423. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  424. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  425. * set to `0`.
  426. *
  427. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  428. * data from the array. The length of the array must match the vertex count.
  429. *
  430. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  431. * @return {BufferGeometry} A reference to this instance.
  432. */
  433. setFromPoints( points ) {
  434. const positionAttribute = this.getAttribute( 'position' );
  435. if ( positionAttribute === undefined ) {
  436. const position = [];
  437. for ( let i = 0, l = points.length; i < l; i ++ ) {
  438. const point = points[ i ];
  439. position.push( point.x, point.y, point.z || 0 );
  440. }
  441. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  442. } else {
  443. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  444. for ( let i = 0; i < l; i ++ ) {
  445. const point = points[ i ];
  446. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  447. }
  448. if ( points.length > positionAttribute.count ) {
  449. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  450. }
  451. positionAttribute.needsUpdate = true;
  452. }
  453. return this;
  454. }
  455. /**
  456. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  457. * The bounding box is not computed by the engine; it must be computed by your app.
  458. * You may need to recompute the bounding box if the geometry vertices are modified.
  459. */
  460. computeBoundingBox() {
  461. if ( this.boundingBox === null ) {
  462. this.boundingBox = new Box3();
  463. }
  464. const position = this.attributes.position;
  465. const morphAttributesPosition = this.morphAttributes.position;
  466. if ( position && position.isGLBufferAttribute ) {
  467. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  468. this.boundingBox.set(
  469. new Vector3( - Infinity, - Infinity, - Infinity ),
  470. new Vector3( + Infinity, + Infinity, + Infinity )
  471. );
  472. return;
  473. }
  474. if ( position !== undefined ) {
  475. this.boundingBox.setFromBufferAttribute( position );
  476. // process morph attributes if present
  477. if ( morphAttributesPosition ) {
  478. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  479. const morphAttribute = morphAttributesPosition[ i ];
  480. _box.setFromBufferAttribute( morphAttribute );
  481. if ( this.morphTargetsRelative ) {
  482. _vector.addVectors( this.boundingBox.min, _box.min );
  483. this.boundingBox.expandByPoint( _vector );
  484. _vector.addVectors( this.boundingBox.max, _box.max );
  485. this.boundingBox.expandByPoint( _vector );
  486. } else {
  487. this.boundingBox.expandByPoint( _box.min );
  488. this.boundingBox.expandByPoint( _box.max );
  489. }
  490. }
  491. }
  492. } else {
  493. this.boundingBox.makeEmpty();
  494. }
  495. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  496. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  497. }
  498. }
  499. /**
  500. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  501. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  502. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  503. */
  504. computeBoundingSphere() {
  505. if ( this.boundingSphere === null ) {
  506. this.boundingSphere = new Sphere();
  507. }
  508. const position = this.attributes.position;
  509. const morphAttributesPosition = this.morphAttributes.position;
  510. if ( position && position.isGLBufferAttribute ) {
  511. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  512. this.boundingSphere.set( new Vector3(), Infinity );
  513. return;
  514. }
  515. if ( position ) {
  516. // first, find the center of the bounding sphere
  517. const center = this.boundingSphere.center;
  518. _box.setFromBufferAttribute( position );
  519. // process morph attributes if present
  520. if ( morphAttributesPosition ) {
  521. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  522. const morphAttribute = morphAttributesPosition[ i ];
  523. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  524. if ( this.morphTargetsRelative ) {
  525. _vector.addVectors( _box.min, _boxMorphTargets.min );
  526. _box.expandByPoint( _vector );
  527. _vector.addVectors( _box.max, _boxMorphTargets.max );
  528. _box.expandByPoint( _vector );
  529. } else {
  530. _box.expandByPoint( _boxMorphTargets.min );
  531. _box.expandByPoint( _boxMorphTargets.max );
  532. }
  533. }
  534. }
  535. _box.getCenter( center );
  536. // second, try to find a boundingSphere with a radius smaller than the
  537. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  538. let maxRadiusSq = 0;
  539. for ( let i = 0, il = position.count; i < il; i ++ ) {
  540. _vector.fromBufferAttribute( position, i );
  541. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector ) );
  542. }
  543. // process morph attributes if present
  544. if ( morphAttributesPosition ) {
  545. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  546. const morphAttribute = morphAttributesPosition[ i ];
  547. const morphTargetsRelative = this.morphTargetsRelative;
  548. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  549. _vector.fromBufferAttribute( morphAttribute, j );
  550. if ( morphTargetsRelative ) {
  551. _offset.fromBufferAttribute( position, j );
  552. _vector.add( _offset );
  553. }
  554. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector ) );
  555. }
  556. }
  557. }
  558. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  559. if ( isNaN( this.boundingSphere.radius ) ) {
  560. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  561. }
  562. }
  563. }
  564. /**
  565. * Calculates and adds a tangent attribute to this geometry.
  566. *
  567. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  568. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  569. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  570. */
  571. computeTangents() {
  572. const index = this.index;
  573. const attributes = this.attributes;
  574. // based on http://www.terathon.com/code/tangent.html
  575. // (per vertex tangents)
  576. if ( index === null ||
  577. attributes.position === undefined ||
  578. attributes.normal === undefined ||
  579. attributes.uv === undefined ) {
  580. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  581. return;
  582. }
  583. const positionAttribute = attributes.position;
  584. const normalAttribute = attributes.normal;
  585. const uvAttribute = attributes.uv;
  586. if ( this.hasAttribute( 'tangent' ) === false ) {
  587. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  588. }
  589. const tangentAttribute = this.getAttribute( 'tangent' );
  590. const tan1 = [], tan2 = [];
  591. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  592. tan1[ i ] = new Vector3();
  593. tan2[ i ] = new Vector3();
  594. }
  595. const vA = new Vector3(),
  596. vB = new Vector3(),
  597. vC = new Vector3(),
  598. uvA = new Vector2(),
  599. uvB = new Vector2(),
  600. uvC = new Vector2(),
  601. sdir = new Vector3(),
  602. tdir = new Vector3();
  603. function handleTriangle( a, b, c ) {
  604. vA.fromBufferAttribute( positionAttribute, a );
  605. vB.fromBufferAttribute( positionAttribute, b );
  606. vC.fromBufferAttribute( positionAttribute, c );
  607. uvA.fromBufferAttribute( uvAttribute, a );
  608. uvB.fromBufferAttribute( uvAttribute, b );
  609. uvC.fromBufferAttribute( uvAttribute, c );
  610. vB.sub( vA );
  611. vC.sub( vA );
  612. uvB.sub( uvA );
  613. uvC.sub( uvA );
  614. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  615. // silently ignore degenerate uv triangles having coincident or colinear vertices
  616. if ( ! isFinite( r ) ) return;
  617. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  618. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  619. tan1[ a ].add( sdir );
  620. tan1[ b ].add( sdir );
  621. tan1[ c ].add( sdir );
  622. tan2[ a ].add( tdir );
  623. tan2[ b ].add( tdir );
  624. tan2[ c ].add( tdir );
  625. }
  626. let groups = this.groups;
  627. if ( groups.length === 0 ) {
  628. groups = [ {
  629. start: 0,
  630. count: index.count
  631. } ];
  632. }
  633. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  634. const group = groups[ i ];
  635. const start = group.start;
  636. const count = group.count;
  637. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  638. handleTriangle(
  639. index.getX( j + 0 ),
  640. index.getX( j + 1 ),
  641. index.getX( j + 2 )
  642. );
  643. }
  644. }
  645. const tmp = new Vector3(), tmp2 = new Vector3();
  646. const n = new Vector3(), n2 = new Vector3();
  647. function handleVertex( v ) {
  648. n.fromBufferAttribute( normalAttribute, v );
  649. n2.copy( n );
  650. const t = tan1[ v ];
  651. // Gram-Schmidt orthogonalize
  652. tmp.copy( t );
  653. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  654. // Calculate handedness
  655. tmp2.crossVectors( n2, t );
  656. const test = tmp2.dot( tan2[ v ] );
  657. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  658. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  659. }
  660. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  661. const group = groups[ i ];
  662. const start = group.start;
  663. const count = group.count;
  664. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  665. handleVertex( index.getX( j + 0 ) );
  666. handleVertex( index.getX( j + 1 ) );
  667. handleVertex( index.getX( j + 2 ) );
  668. }
  669. }
  670. }
  671. /**
  672. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  673. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  674. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  675. * to be the same as the face normal.
  676. */
  677. computeVertexNormals() {
  678. const index = this.index;
  679. const positionAttribute = this.getAttribute( 'position' );
  680. if ( positionAttribute !== undefined ) {
  681. let normalAttribute = this.getAttribute( 'normal' );
  682. if ( normalAttribute === undefined ) {
  683. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  684. this.setAttribute( 'normal', normalAttribute );
  685. } else {
  686. // reset existing normals to zero
  687. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  688. normalAttribute.setXYZ( i, 0, 0, 0 );
  689. }
  690. }
  691. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  692. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  693. const cb = new Vector3(), ab = new Vector3();
  694. // indexed elements
  695. if ( index ) {
  696. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  697. const vA = index.getX( i + 0 );
  698. const vB = index.getX( i + 1 );
  699. const vC = index.getX( i + 2 );
  700. pA.fromBufferAttribute( positionAttribute, vA );
  701. pB.fromBufferAttribute( positionAttribute, vB );
  702. pC.fromBufferAttribute( positionAttribute, vC );
  703. cb.subVectors( pC, pB );
  704. ab.subVectors( pA, pB );
  705. cb.cross( ab );
  706. nA.fromBufferAttribute( normalAttribute, vA );
  707. nB.fromBufferAttribute( normalAttribute, vB );
  708. nC.fromBufferAttribute( normalAttribute, vC );
  709. nA.add( cb );
  710. nB.add( cb );
  711. nC.add( cb );
  712. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  713. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  714. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  715. }
  716. } else {
  717. // non-indexed elements (unconnected triangle soup)
  718. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  719. pA.fromBufferAttribute( positionAttribute, i + 0 );
  720. pB.fromBufferAttribute( positionAttribute, i + 1 );
  721. pC.fromBufferAttribute( positionAttribute, i + 2 );
  722. cb.subVectors( pC, pB );
  723. ab.subVectors( pA, pB );
  724. cb.cross( ab );
  725. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  726. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  727. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  728. }
  729. }
  730. this.normalizeNormals();
  731. normalAttribute.needsUpdate = true;
  732. }
  733. }
  734. /**
  735. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  736. * correct lighting on the geometry surfaces.
  737. */
  738. normalizeNormals() {
  739. const normals = this.attributes.normal;
  740. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  741. _vector.fromBufferAttribute( normals, i );
  742. _vector.normalize();
  743. normals.setXYZ( i, _vector.x, _vector.y, _vector.z );
  744. }
  745. }
  746. /**
  747. * Return a new non-index version of this indexed geometry. If the geometry
  748. * is already non-indexed, the method is a NOOP.
  749. *
  750. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  751. */
  752. toNonIndexed() {
  753. function convertBufferAttribute( attribute, indices ) {
  754. const array = attribute.array;
  755. const itemSize = attribute.itemSize;
  756. const normalized = attribute.normalized;
  757. const array2 = new array.constructor( indices.length * itemSize );
  758. let index = 0, index2 = 0;
  759. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  760. if ( attribute.isInterleavedBufferAttribute ) {
  761. index = indices[ i ] * attribute.data.stride + attribute.offset;
  762. } else {
  763. index = indices[ i ] * itemSize;
  764. }
  765. for ( let j = 0; j < itemSize; j ++ ) {
  766. array2[ index2 ++ ] = array[ index ++ ];
  767. }
  768. }
  769. return new BufferAttribute( array2, itemSize, normalized );
  770. }
  771. //
  772. if ( this.index === null ) {
  773. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  774. return this;
  775. }
  776. const geometry2 = new BufferGeometry();
  777. const indices = this.index.array;
  778. const attributes = this.attributes;
  779. // attributes
  780. for ( const name in attributes ) {
  781. const attribute = attributes[ name ];
  782. const newAttribute = convertBufferAttribute( attribute, indices );
  783. geometry2.setAttribute( name, newAttribute );
  784. }
  785. // morph attributes
  786. const morphAttributes = this.morphAttributes;
  787. for ( const name in morphAttributes ) {
  788. const morphArray = [];
  789. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  790. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  791. const attribute = morphAttribute[ i ];
  792. const newAttribute = convertBufferAttribute( attribute, indices );
  793. morphArray.push( newAttribute );
  794. }
  795. geometry2.morphAttributes[ name ] = morphArray;
  796. }
  797. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  798. // groups
  799. const groups = this.groups;
  800. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  801. const group = groups[ i ];
  802. geometry2.addGroup( group.start, group.count, group.materialIndex );
  803. }
  804. return geometry2;
  805. }
  806. /**
  807. * Serializes the geometry into JSON.
  808. *
  809. * @return {Object} A JSON object representing the serialized geometry.
  810. */
  811. toJSON() {
  812. const data = {
  813. metadata: {
  814. version: 4.6,
  815. type: 'BufferGeometry',
  816. generator: 'BufferGeometry.toJSON'
  817. }
  818. };
  819. // standard BufferGeometry serialization
  820. data.uuid = this.uuid;
  821. data.type = this.type;
  822. if ( this.name !== '' ) data.name = this.name;
  823. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  824. if ( this.parameters !== undefined ) {
  825. const parameters = this.parameters;
  826. for ( const key in parameters ) {
  827. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  828. }
  829. return data;
  830. }
  831. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  832. data.data = { attributes: {} };
  833. const index = this.index;
  834. if ( index !== null ) {
  835. data.data.index = {
  836. type: index.array.constructor.name,
  837. array: Array.prototype.slice.call( index.array )
  838. };
  839. }
  840. const attributes = this.attributes;
  841. for ( const key in attributes ) {
  842. const attribute = attributes[ key ];
  843. data.data.attributes[ key ] = attribute.toJSON( data.data );
  844. }
  845. const morphAttributes = {};
  846. let hasMorphAttributes = false;
  847. for ( const key in this.morphAttributes ) {
  848. const attributeArray = this.morphAttributes[ key ];
  849. const array = [];
  850. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  851. const attribute = attributeArray[ i ];
  852. array.push( attribute.toJSON( data.data ) );
  853. }
  854. if ( array.length > 0 ) {
  855. morphAttributes[ key ] = array;
  856. hasMorphAttributes = true;
  857. }
  858. }
  859. if ( hasMorphAttributes ) {
  860. data.data.morphAttributes = morphAttributes;
  861. data.data.morphTargetsRelative = this.morphTargetsRelative;
  862. }
  863. const groups = this.groups;
  864. if ( groups.length > 0 ) {
  865. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  866. }
  867. const boundingSphere = this.boundingSphere;
  868. if ( boundingSphere !== null ) {
  869. data.data.boundingSphere = {
  870. center: boundingSphere.center.toArray(),
  871. radius: boundingSphere.radius
  872. };
  873. }
  874. return data;
  875. }
  876. /**
  877. * Returns a new geometry with copied values from this instance.
  878. *
  879. * @return {BufferGeometry} A clone of this instance.
  880. */
  881. clone() {
  882. return new this.constructor().copy( this );
  883. }
  884. /**
  885. * Copies the values of the given geometry to this instance.
  886. *
  887. * @param {BufferGeometry} source - The geometry to copy.
  888. * @return {BufferGeometry} A reference to this instance.
  889. */
  890. copy( source ) {
  891. // reset
  892. this.index = null;
  893. this.attributes = {};
  894. this.morphAttributes = {};
  895. this.groups = [];
  896. this.boundingBox = null;
  897. this.boundingSphere = null;
  898. // used for storing cloned, shared data
  899. const data = {};
  900. // name
  901. this.name = source.name;
  902. // index
  903. const index = source.index;
  904. if ( index !== null ) {
  905. this.setIndex( index.clone() );
  906. }
  907. // attributes
  908. const attributes = source.attributes;
  909. for ( const name in attributes ) {
  910. const attribute = attributes[ name ];
  911. this.setAttribute( name, attribute.clone( data ) );
  912. }
  913. // morph attributes
  914. const morphAttributes = source.morphAttributes;
  915. for ( const name in morphAttributes ) {
  916. const array = [];
  917. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  918. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  919. array.push( morphAttribute[ i ].clone( data ) );
  920. }
  921. this.morphAttributes[ name ] = array;
  922. }
  923. this.morphTargetsRelative = source.morphTargetsRelative;
  924. // groups
  925. const groups = source.groups;
  926. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  927. const group = groups[ i ];
  928. this.addGroup( group.start, group.count, group.materialIndex );
  929. }
  930. // bounding box
  931. const boundingBox = source.boundingBox;
  932. if ( boundingBox !== null ) {
  933. this.boundingBox = boundingBox.clone();
  934. }
  935. // bounding sphere
  936. const boundingSphere = source.boundingSphere;
  937. if ( boundingSphere !== null ) {
  938. this.boundingSphere = boundingSphere.clone();
  939. }
  940. // draw range
  941. this.drawRange.start = source.drawRange.start;
  942. this.drawRange.count = source.drawRange.count;
  943. // user data
  944. this.userData = source.userData;
  945. return this;
  946. }
  947. /**
  948. * Frees the GPU-related resources allocated by this instance. Call this
  949. * method whenever this instance is no longer used in your app.
  950. *
  951. * @fires BufferGeometry#dispose
  952. */
  953. dispose() {
  954. this.dispatchEvent( { type: 'dispose' } );
  955. }
  956. }
  957. export { BufferGeometry };
粤ICP备19079148号