PLYLoader.js 12 KB

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