PLYLoader.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. import {
  2. BufferGeometry,
  3. FileLoader,
  4. Float32BufferAttribute,
  5. Loader,
  6. Color
  7. } from 'three';
  8. /**
  9. * Description: A THREE loader for PLY ASCII files (known as the Polygon
  10. * File Format or the Stanford Triangle Format).
  11. *
  12. * Limitations: ASCII decoding assumes file is UTF-8.
  13. *
  14. * Usage:
  15. * const loader = new PLYLoader();
  16. * loader.load('./models/ply/ascii/dolphins.ply', function (geometry) {
  17. *
  18. * scene.add( new THREE.Mesh( geometry ) );
  19. *
  20. * } );
  21. *
  22. * If the PLY file uses non standard property names, they can be mapped while
  23. * loading. For example, the following maps the properties
  24. * “diffuse_(red|green|blue)” in the file to standard color names.
  25. *
  26. * loader.setPropertyNameMapping( {
  27. * diffuse_red: 'red',
  28. * diffuse_green: 'green',
  29. * diffuse_blue: 'blue'
  30. * } );
  31. *
  32. * Custom properties outside of the defaults for position, uv, normal
  33. * and color attributes can be added using the setCustomPropertyMapping method.
  34. * For example, the following maps the element properties “custom_property_a”
  35. * and “custom_property_b” to an attribute “customAttribute” with an item size of 2.
  36. * Attribute item sizes are set from the number of element properties in the property array.
  37. *
  38. * loader.setCustomPropertyMapping( {
  39. * customAttribute: ['custom_property_a', 'custom_property_b'],
  40. * } );
  41. *
  42. */
  43. const _color = new Color();
  44. class PLYLoader extends Loader {
  45. constructor( manager ) {
  46. super( manager );
  47. this.propertyNameMapping = {};
  48. this.customPropertyMapping = {};
  49. }
  50. load( url, onLoad, onProgress, onError ) {
  51. const scope = this;
  52. const loader = new FileLoader( this.manager );
  53. loader.setPath( this.path );
  54. loader.setResponseType( 'arraybuffer' );
  55. loader.setRequestHeader( this.requestHeader );
  56. loader.setWithCredentials( this.withCredentials );
  57. loader.load( url, function ( text ) {
  58. try {
  59. onLoad( scope.parse( text ) );
  60. } catch ( e ) {
  61. if ( onError ) {
  62. onError( e );
  63. } else {
  64. console.error( e );
  65. }
  66. scope.manager.itemError( url );
  67. }
  68. }, onProgress, onError );
  69. }
  70. setPropertyNameMapping( mapping ) {
  71. this.propertyNameMapping = mapping;
  72. }
  73. setCustomPropertyNameMapping( mapping ) {
  74. this.customPropertyMapping = mapping;
  75. }
  76. parse( data ) {
  77. function parseHeader( data ) {
  78. const patternHeader = /^ply([\s\S]*)end_header(\r\n|\r|\n)/;
  79. let headerText = '';
  80. let headerLength = 0;
  81. const result = patternHeader.exec( data );
  82. if ( result !== null ) {
  83. headerText = result[ 1 ];
  84. headerLength = new Blob( [ result[ 0 ] ] ).size;
  85. }
  86. const header = {
  87. comments: [],
  88. elements: [],
  89. headerLength: headerLength,
  90. objInfo: ''
  91. };
  92. const lines = headerText.split( /\r\n|\r|\n/ );
  93. let currentElement;
  94. function make_ply_element_property( propertValues, propertyNameMapping ) {
  95. const property = { type: propertValues[ 0 ] };
  96. if ( property.type === 'list' ) {
  97. property.name = propertValues[ 3 ];
  98. property.countType = propertValues[ 1 ];
  99. property.itemType = propertValues[ 2 ];
  100. } else {
  101. property.name = propertValues[ 1 ];
  102. }
  103. if ( property.name in propertyNameMapping ) {
  104. property.name = propertyNameMapping[ property.name ];
  105. }
  106. return property;
  107. }
  108. for ( let i = 0; i < lines.length; i ++ ) {
  109. let line = lines[ i ];
  110. line = line.trim();
  111. if ( line === '' ) continue;
  112. const lineValues = line.split( /\s+/ );
  113. const lineType = lineValues.shift();
  114. line = lineValues.join( ' ' );
  115. switch ( lineType ) {
  116. case 'format':
  117. header.format = lineValues[ 0 ];
  118. header.version = lineValues[ 1 ];
  119. break;
  120. case 'comment':
  121. header.comments.push( line );
  122. break;
  123. case 'element':
  124. if ( currentElement !== undefined ) {
  125. header.elements.push( currentElement );
  126. }
  127. currentElement = {};
  128. currentElement.name = lineValues[ 0 ];
  129. currentElement.count = parseInt( lineValues[ 1 ] );
  130. currentElement.properties = [];
  131. break;
  132. case 'property':
  133. currentElement.properties.push( make_ply_element_property( lineValues, scope.propertyNameMapping ) );
  134. break;
  135. case 'obj_info':
  136. header.objInfo = line;
  137. break;
  138. default:
  139. console.log( 'unhandled', lineType, lineValues );
  140. }
  141. }
  142. if ( currentElement !== undefined ) {
  143. header.elements.push( currentElement );
  144. }
  145. return header;
  146. }
  147. function parseASCIINumber( n, type ) {
  148. switch ( type ) {
  149. case 'char': case 'uchar': case 'short': case 'ushort': case 'int': case 'uint':
  150. case 'int8': case 'uint8': case 'int16': case 'uint16': case 'int32': case 'uint32':
  151. return parseInt( n );
  152. case 'float': case 'double': case 'float32': case 'float64':
  153. return parseFloat( n );
  154. }
  155. }
  156. function parseASCIIElement( properties, line ) {
  157. const values = line.split( /\s+/ );
  158. const element = {};
  159. for ( let i = 0; i < properties.length; i ++ ) {
  160. if ( properties[ i ].type === 'list' ) {
  161. const list = [];
  162. const n = parseASCIINumber( values.shift(), properties[ i ].countType );
  163. for ( let j = 0; j < n; j ++ ) {
  164. list.push( parseASCIINumber( values.shift(), properties[ i ].itemType ) );
  165. }
  166. element[ properties[ i ].name ] = list;
  167. } else {
  168. element[ properties[ i ].name ] = parseASCIINumber( values.shift(), properties[ i ].type );
  169. }
  170. }
  171. return element;
  172. }
  173. function createBuffer() {
  174. const buffer = {
  175. indices: [],
  176. vertices: [],
  177. normals: [],
  178. uvs: [],
  179. faceVertexUvs: [],
  180. colors: [],
  181. };
  182. for ( const customProperty of Object.keys( scope.customPropertyMapping ) ) {
  183. buffer[ customProperty ] = [];
  184. }
  185. return buffer;
  186. }
  187. function mapElementAttributes( properties ) {
  188. const elementNames = properties.map( property => {
  189. return property.name;
  190. } );
  191. function findAttrName( names ) {
  192. for ( let i = 0, l = names.length; i < l; i ++ ) {
  193. const name = names[ i ];
  194. if ( elementNames.includes( name ) ) return name;
  195. }
  196. return null;
  197. }
  198. return {
  199. attrX: findAttrName( [ 'x', 'px', 'posx' ] ) || 'x',
  200. attrY: findAttrName( [ 'y', 'py', 'posy' ] ) || 'y',
  201. attrZ: findAttrName( [ 'z', 'pz', 'posz' ] ) || 'z',
  202. attrNX: findAttrName( [ 'nx', 'normalx' ] ),
  203. attrNY: findAttrName( [ 'ny', 'normaly' ] ),
  204. attrNZ: findAttrName( [ 'nz', 'normalz' ] ),
  205. attrS: findAttrName( [ 's', 'u', 'texture_u', 'tx' ] ),
  206. attrT: findAttrName( [ 't', 'v', 'texture_v', 'ty' ] ),
  207. attrR: findAttrName( [ 'red', 'diffuse_red', 'r', 'diffuse_r' ] ),
  208. attrG: findAttrName( [ 'green', 'diffuse_green', 'g', 'diffuse_g' ] ),
  209. attrB: findAttrName( [ 'blue', 'diffuse_blue', 'b', 'diffuse_b' ] ),
  210. };
  211. }
  212. function parseASCII( data, header ) {
  213. // PLY ascii format specification, as per http://en.wikipedia.org/wiki/PLY_(file_format)
  214. const buffer = createBuffer();
  215. let result;
  216. const patternBody = /end_header\s([\s\S]*)$/;
  217. let body = '';
  218. if ( ( result = patternBody.exec( data ) ) !== null ) {
  219. body = result[ 1 ];
  220. }
  221. const lines = body.split( /\r\n|\r|\n/ );
  222. let currentElement = 0;
  223. let currentElementCount = 0;
  224. let elementDesc = header.elements[ currentElement ];
  225. let attributeMap = mapElementAttributes( elementDesc.properties );
  226. for ( let i = 0; i < lines.length; i ++ ) {
  227. let line = lines[ i ];
  228. line = line.trim();
  229. if ( line === '' ) {
  230. continue;
  231. }
  232. if ( currentElementCount >= elementDesc.count ) {
  233. currentElement ++;
  234. currentElementCount = 0;
  235. elementDesc = header.elements[ currentElement ];
  236. attributeMap = mapElementAttributes( elementDesc.properties );
  237. }
  238. const element = parseASCIIElement( elementDesc.properties, line );
  239. handleElement( buffer, elementDesc.name, element, attributeMap );
  240. currentElementCount ++;
  241. }
  242. return postProcess( buffer );
  243. }
  244. function postProcess( buffer ) {
  245. let geometry = new BufferGeometry();
  246. // mandatory buffer data
  247. if ( buffer.indices.length > 0 ) {
  248. geometry.setIndex( buffer.indices );
  249. }
  250. geometry.setAttribute( 'position', new Float32BufferAttribute( buffer.vertices, 3 ) );
  251. // optional buffer data
  252. if ( buffer.normals.length > 0 ) {
  253. geometry.setAttribute( 'normal', new Float32BufferAttribute( buffer.normals, 3 ) );
  254. }
  255. if ( buffer.uvs.length > 0 ) {
  256. geometry.setAttribute( 'uv', new Float32BufferAttribute( buffer.uvs, 2 ) );
  257. }
  258. if ( buffer.colors.length > 0 ) {
  259. geometry.setAttribute( 'color', new Float32BufferAttribute( buffer.colors, 3 ) );
  260. }
  261. if ( buffer.faceVertexUvs.length > 0 ) {
  262. geometry = geometry.toNonIndexed();
  263. geometry.setAttribute( 'uv', new Float32BufferAttribute( buffer.faceVertexUvs, 2 ) );
  264. }
  265. // custom buffer data
  266. for ( const customProperty of Object.keys( scope.customPropertyMapping ) ) {
  267. if ( buffer[ customProperty ].length > 0 ) {
  268. geometry.setAttribute(
  269. customProperty,
  270. new Float32BufferAttribute(
  271. buffer[ customProperty ],
  272. scope.customPropertyMapping[ customProperty ].length
  273. )
  274. );
  275. }
  276. }
  277. geometry.computeBoundingSphere();
  278. return geometry;
  279. }
  280. function handleElement( buffer, elementName, element, cacheEntry ) {
  281. if ( elementName === 'vertex' ) {
  282. buffer.vertices.push( element[ cacheEntry.attrX ], element[ cacheEntry.attrY ], element[ cacheEntry.attrZ ] );
  283. if ( cacheEntry.attrNX !== null && cacheEntry.attrNY !== null && cacheEntry.attrNZ !== null ) {
  284. buffer.normals.push( element[ cacheEntry.attrNX ], element[ cacheEntry.attrNY ], element[ cacheEntry.attrNZ ] );
  285. }
  286. if ( cacheEntry.attrS !== null && cacheEntry.attrT !== null ) {
  287. buffer.uvs.push( element[ cacheEntry.attrS ], element[ cacheEntry.attrT ] );
  288. }
  289. if ( cacheEntry.attrR !== null && cacheEntry.attrG !== null && cacheEntry.attrB !== null ) {
  290. _color.setRGB(
  291. element[ cacheEntry.attrR ] / 255.0,
  292. element[ cacheEntry.attrG ] / 255.0,
  293. element[ cacheEntry.attrB ] / 255.0
  294. ).convertSRGBToLinear();
  295. buffer.colors.push( _color.r, _color.g, _color.b );
  296. }
  297. for ( const customProperty of Object.keys( scope.customPropertyMapping ) ) {
  298. for ( const elementProperty of scope.customPropertyMapping[ customProperty ] ) {
  299. buffer[ customProperty ].push( element[ elementProperty ] );
  300. }
  301. }
  302. } else if ( elementName === 'face' ) {
  303. const vertex_indices = element.vertex_indices || element.vertex_index; // issue #9338
  304. const texcoord = element.texcoord;
  305. if ( vertex_indices.length === 3 ) {
  306. buffer.indices.push( vertex_indices[ 0 ], vertex_indices[ 1 ], vertex_indices[ 2 ] );
  307. if ( texcoord && texcoord.length === 6 ) {
  308. buffer.faceVertexUvs.push( texcoord[ 0 ], texcoord[ 1 ] );
  309. buffer.faceVertexUvs.push( texcoord[ 2 ], texcoord[ 3 ] );
  310. buffer.faceVertexUvs.push( texcoord[ 4 ], texcoord[ 5 ] );
  311. }
  312. } else if ( vertex_indices.length === 4 ) {
  313. buffer.indices.push( vertex_indices[ 0 ], vertex_indices[ 1 ], vertex_indices[ 3 ] );
  314. buffer.indices.push( vertex_indices[ 1 ], vertex_indices[ 2 ], vertex_indices[ 3 ] );
  315. }
  316. }
  317. }
  318. function binaryReadElement( at, properties ) {
  319. const element = {};
  320. let read = 0;
  321. for ( let i = 0; i < properties.length; i ++ ) {
  322. const property = properties[ i ];
  323. const valueReader = property.valueReader;
  324. if ( property.type === 'list' ) {
  325. const list = [];
  326. const n = property.countReader.read( at + read );
  327. read += property.countReader.size;
  328. for ( let j = 0; j < n; j ++ ) {
  329. list.push( valueReader.read( at + read ) );
  330. read += valueReader.size;
  331. }
  332. element[ property.name ] = list;
  333. } else {
  334. element[ property.name ] = valueReader.read( at + read );
  335. read += valueReader.size;
  336. }
  337. }
  338. return [ element, read ];
  339. }
  340. function setPropertyBinaryReaders( properties, body, little_endian ) {
  341. function getBinaryReader( dataview, type, little_endian ) {
  342. switch ( type ) {
  343. // corespondences for non-specific length types here match rply:
  344. case 'int8': case 'char': return { read: ( at ) => {
  345. return dataview.getInt8( at );
  346. }, size: 1 };
  347. case 'uint8': case 'uchar': return { read: ( at ) => {
  348. return dataview.getUint8( at );
  349. }, size: 1 };
  350. case 'int16': case 'short': return { read: ( at ) => {
  351. return dataview.getInt16( at, little_endian );
  352. }, size: 2 };
  353. case 'uint16': case 'ushort': return { read: ( at ) => {
  354. return dataview.getUint16( at, little_endian );
  355. }, size: 2 };
  356. case 'int32': case 'int': return { read: ( at ) => {
  357. return dataview.getInt32( at, little_endian );
  358. }, size: 4 };
  359. case 'uint32': case 'uint': return { read: ( at ) => {
  360. return dataview.getUint32( at, little_endian );
  361. }, size: 4 };
  362. case 'float32': case 'float': return { read: ( at ) => {
  363. return dataview.getFloat32( at, little_endian );
  364. }, size: 4 };
  365. case 'float64': case 'double': return { read: ( at ) => {
  366. return dataview.getFloat64( at, little_endian );
  367. }, size: 8 };
  368. }
  369. }
  370. for ( let i = 0, l = properties.length; i < l; i ++ ) {
  371. const property = properties[ i ];
  372. if ( property.type === 'list' ) {
  373. property.countReader = getBinaryReader( body, property.countType, little_endian );
  374. property.valueReader = getBinaryReader( body, property.itemType, little_endian );
  375. } else {
  376. property.valueReader = getBinaryReader( body, property.type, little_endian );
  377. }
  378. }
  379. }
  380. function parseBinary( data, header ) {
  381. const buffer = createBuffer();
  382. const little_endian = ( header.format === 'binary_little_endian' );
  383. const body = new DataView( data, header.headerLength );
  384. let result, loc = 0;
  385. for ( let currentElement = 0; currentElement < header.elements.length; currentElement ++ ) {
  386. const elementDesc = header.elements[ currentElement ];
  387. const properties = elementDesc.properties;
  388. const attributeMap = mapElementAttributes( properties );
  389. setPropertyBinaryReaders( properties, body, little_endian );
  390. for ( let currentElementCount = 0; currentElementCount < elementDesc.count; currentElementCount ++ ) {
  391. result = binaryReadElement( loc, properties );
  392. loc += result[ 1 ];
  393. const element = result[ 0 ];
  394. handleElement( buffer, elementDesc.name, element, attributeMap );
  395. }
  396. }
  397. return postProcess( buffer );
  398. }
  399. function extractHeaderText( bytes ) {
  400. let i = 0;
  401. let cont = true;
  402. let line = '';
  403. const lines = [];
  404. do {
  405. const c = String.fromCharCode( bytes[ i ++ ] );
  406. if ( c !== '\n' && c !== '\r' ) {
  407. line += c;
  408. } else {
  409. if ( line === 'end_header' ) cont = false;
  410. if ( line !== '' ) {
  411. lines.push( line );
  412. line = '';
  413. }
  414. }
  415. } while ( cont && i < bytes.length );
  416. return lines.join( '\r' ) + '\r';
  417. }
  418. //
  419. let geometry;
  420. const scope = this;
  421. if ( data instanceof ArrayBuffer ) {
  422. const bytes = new Uint8Array( data );
  423. const headerText = extractHeaderText( bytes );
  424. const header = parseHeader( headerText );
  425. if ( header.format === 'ascii' ) {
  426. const text = new TextDecoder().decode( bytes );
  427. geometry = parseASCII( text, header );
  428. } else {
  429. geometry = parseBinary( data, header );
  430. }
  431. } else {
  432. geometry = parseASCII( data, parseHeader( data ) );
  433. }
  434. return geometry;
  435. }
  436. }
  437. export { PLYLoader };