PLYLoader.js 12 KB

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