PLYLoader.js 12 KB

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