PLYLoader.js 14 KB

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