123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805 |
- import {
- BufferGeometry,
- FileLoader,
- Float32BufferAttribute,
- Loader,
- Color,
- SRGBColorSpace
- } from 'three';
- const _color = new Color();
- /**
- * A loader for PLY the PLY format (known as the Polygon
- * File Format or the Stanford Triangle Format).
- *
- * Limitations:
- * - ASCII decoding assumes file is UTF-8.
- *
- * ```js
- * const loader = new PLYLoader();
- * const geometry = await loader.loadAsync( './models/ply/ascii/dolphins.ply' );
- * scene.add( new THREE.Mesh( geometry ) );
- * ```
- *
- * @augments Loader
- * @three_import import { PLYLoader } from 'three/addons/loaders/PLYLoader.js';
- */
- class PLYLoader extends Loader {
- /**
- * Constructs a new PLY loader.
- *
- * @param {LoadingManager} [manager] - The loading manager.
- */
- constructor( manager ) {
- super( manager );
- // internals
- this.propertyNameMapping = {};
- this.customPropertyMapping = {};
- }
- /**
- * Starts loading from the given URL and passes the loaded PLY asset
- * to the `onLoad()` callback.
- *
- * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
- * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
- * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
- * @param {onErrorCallback} onError - Executed when errors occur.
- */
- load( url, onLoad, onProgress, onError ) {
- const scope = this;
- const loader = new FileLoader( this.manager );
- loader.setPath( this.path );
- loader.setResponseType( 'arraybuffer' );
- loader.setRequestHeader( this.requestHeader );
- loader.setWithCredentials( this.withCredentials );
- loader.load( url, function ( text ) {
- try {
- onLoad( scope.parse( text ) );
- } catch ( e ) {
- if ( onError ) {
- onError( e );
- } else {
- console.error( e );
- }
- scope.manager.itemError( url );
- }
- }, onProgress, onError );
- }
- /**
- * Sets a property name mapping that maps default property names
- * to custom ones. For example, the following maps the properties
- * “diffuse_(red|green|blue)” in the file to standard color names.
- *
- * ```js
- * loader.setPropertyNameMapping( {
- * diffuse_red: 'red',
- * diffuse_green: 'green',
- * diffuse_blue: 'blue'
- * } );
- * ```
- *
- * @param {Object} mapping - The mapping dictionary.
- */
- setPropertyNameMapping( mapping ) {
- this.propertyNameMapping = mapping;
- }
- /**
- * Custom properties outside of the defaults for position, uv, normal
- * and color attributes can be added using the setCustomPropertyNameMapping method.
- * For example, the following maps the element properties “custom_property_a”
- * and “custom_property_b” to an attribute “customAttribute” with an item size of 2.
- * Attribute item sizes are set from the number of element properties in the property array.
- *
- * ```js
- * loader.setCustomPropertyNameMapping( {
- * customAttribute: ['custom_property_a', 'custom_property_b'],
- * } );
- * ```
- * @param {Object} mapping - The mapping dictionary.
- */
- setCustomPropertyNameMapping( mapping ) {
- this.customPropertyMapping = mapping;
- }
- /**
- * Parses the given PLY data and returns the resulting geometry.
- *
- * @param {ArrayBuffer} data - The raw PLY data as an array buffer.
- * @return {BufferGeometry} The parsed geometry.
- */
- parse( data ) {
- function parseHeader( data, headerLength = 0 ) {
- const patternHeader = /^ply([\s\S]*)end_header(\r\n|\r|\n)/;
- let headerText = '';
- const result = patternHeader.exec( data );
- if ( result !== null ) {
- headerText = result[ 1 ];
- }
- const header = {
- comments: [],
- elements: [],
- headerLength: headerLength,
- objInfo: ''
- };
- const lines = headerText.split( /\r\n|\r|\n/ );
- let currentElement;
- function make_ply_element_property( propertyValues, propertyNameMapping ) {
- const property = { type: propertyValues[ 0 ] };
- if ( property.type === 'list' ) {
- property.name = propertyValues[ 3 ];
- property.countType = propertyValues[ 1 ];
- property.itemType = propertyValues[ 2 ];
- } else {
- property.name = propertyValues[ 1 ];
- }
- if ( property.name in propertyNameMapping ) {
- property.name = propertyNameMapping[ property.name ];
- }
- return property;
- }
- for ( let i = 0; i < lines.length; i ++ ) {
- let line = lines[ i ];
- line = line.trim();
- if ( line === '' ) continue;
- const lineValues = line.split( /\s+/ );
- const lineType = lineValues.shift();
- line = lineValues.join( ' ' );
- switch ( lineType ) {
- case 'format':
- header.format = lineValues[ 0 ];
- header.version = lineValues[ 1 ];
- break;
- case 'comment':
- header.comments.push( line );
- break;
- case 'element':
- if ( currentElement !== undefined ) {
- header.elements.push( currentElement );
- }
- currentElement = {};
- currentElement.name = lineValues[ 0 ];
- currentElement.count = parseInt( lineValues[ 1 ] );
- currentElement.properties = [];
- break;
- case 'property':
- currentElement.properties.push( make_ply_element_property( lineValues, scope.propertyNameMapping ) );
- break;
- case 'obj_info':
- header.objInfo = line;
- break;
- default:
- console.log( 'unhandled', lineType, lineValues );
- }
- }
- if ( currentElement !== undefined ) {
- header.elements.push( currentElement );
- }
- return header;
- }
- function parseASCIINumber( n, type ) {
- switch ( type ) {
- case 'char': case 'uchar': case 'short': case 'ushort': case 'int': case 'uint':
- case 'int8': case 'uint8': case 'int16': case 'uint16': case 'int32': case 'uint32':
- return parseInt( n );
- case 'float': case 'double': case 'float32': case 'float64':
- return parseFloat( n );
- }
- }
- function parseASCIIElement( properties, tokens ) {
- const element = {};
- for ( let i = 0; i < properties.length; i ++ ) {
- if ( tokens.empty() ) return null;
- if ( properties[ i ].type === 'list' ) {
- const list = [];
- const n = parseASCIINumber( tokens.next(), properties[ i ].countType );
- for ( let j = 0; j < n; j ++ ) {
- if ( tokens.empty() ) return null;
- list.push( parseASCIINumber( tokens.next(), properties[ i ].itemType ) );
- }
- element[ properties[ i ].name ] = list;
- } else {
- element[ properties[ i ].name ] = parseASCIINumber( tokens.next(), properties[ i ].type );
- }
- }
- return element;
- }
- function createBuffer() {
- const buffer = {
- indices: [],
- vertices: [],
- normals: [],
- uvs: [],
- faceVertexUvs: [],
- colors: [],
- faceVertexColors: []
- };
- for ( const customProperty of Object.keys( scope.customPropertyMapping ) ) {
- buffer[ customProperty ] = [];
- }
- return buffer;
- }
- function mapElementAttributes( properties ) {
- const elementNames = properties.map( property => {
- return property.name;
- } );
- function findAttrName( names ) {
- for ( let i = 0, l = names.length; i < l; i ++ ) {
- const name = names[ i ];
- if ( elementNames.includes( name ) ) return name;
- }
- return null;
- }
- return {
- attrX: findAttrName( [ 'x', 'px', 'posx' ] ) || 'x',
- attrY: findAttrName( [ 'y', 'py', 'posy' ] ) || 'y',
- attrZ: findAttrName( [ 'z', 'pz', 'posz' ] ) || 'z',
- attrNX: findAttrName( [ 'nx', 'normalx' ] ),
- attrNY: findAttrName( [ 'ny', 'normaly' ] ),
- attrNZ: findAttrName( [ 'nz', 'normalz' ] ),
- attrS: findAttrName( [ 's', 'u', 'texture_u', 'tx' ] ),
- attrT: findAttrName( [ 't', 'v', 'texture_v', 'ty' ] ),
- attrR: findAttrName( [ 'red', 'diffuse_red', 'r', 'diffuse_r' ] ),
- attrG: findAttrName( [ 'green', 'diffuse_green', 'g', 'diffuse_g' ] ),
- attrB: findAttrName( [ 'blue', 'diffuse_blue', 'b', 'diffuse_b' ] ),
- };
- }
- function parseASCII( data, header ) {
- // PLY ascii format specification, as per http://en.wikipedia.org/wiki/PLY_(file_format)
- const buffer = createBuffer();
- const patternBody = /end_header\s+(\S[\s\S]*\S|\S)\s*$/;
- let body, matches;
- if ( ( matches = patternBody.exec( data ) ) !== null ) {
- body = matches[ 1 ].split( /\s+/ );
- } else {
- body = [ ];
- }
- const tokens = new ArrayStream( body );
- loop: for ( let i = 0; i < header.elements.length; i ++ ) {
- const elementDesc = header.elements[ i ];
- const attributeMap = mapElementAttributes( elementDesc.properties );
- for ( let j = 0; j < elementDesc.count; j ++ ) {
- const element = parseASCIIElement( elementDesc.properties, tokens );
- if ( ! element ) break loop;
- handleElement( buffer, elementDesc.name, element, attributeMap );
- }
- }
- return postProcess( buffer );
- }
- function postProcess( buffer ) {
- let geometry = new BufferGeometry();
- // mandatory buffer data
- if ( buffer.indices.length > 0 ) {
- geometry.setIndex( buffer.indices );
- }
- geometry.setAttribute( 'position', new Float32BufferAttribute( buffer.vertices, 3 ) );
- // optional buffer data
- if ( buffer.normals.length > 0 ) {
- geometry.setAttribute( 'normal', new Float32BufferAttribute( buffer.normals, 3 ) );
- }
- if ( buffer.uvs.length > 0 ) {
- geometry.setAttribute( 'uv', new Float32BufferAttribute( buffer.uvs, 2 ) );
- }
- if ( buffer.colors.length > 0 ) {
- geometry.setAttribute( 'color', new Float32BufferAttribute( buffer.colors, 3 ) );
- }
- if ( buffer.faceVertexUvs.length > 0 || buffer.faceVertexColors.length > 0 ) {
- geometry = geometry.toNonIndexed();
- if ( buffer.faceVertexUvs.length > 0 ) geometry.setAttribute( 'uv', new Float32BufferAttribute( buffer.faceVertexUvs, 2 ) );
- if ( buffer.faceVertexColors.length > 0 ) geometry.setAttribute( 'color', new Float32BufferAttribute( buffer.faceVertexColors, 3 ) );
- }
- // custom buffer data
- for ( const customProperty of Object.keys( scope.customPropertyMapping ) ) {
- if ( buffer[ customProperty ].length > 0 ) {
- geometry.setAttribute(
- customProperty,
- new Float32BufferAttribute(
- buffer[ customProperty ],
- scope.customPropertyMapping[ customProperty ].length
- )
- );
- }
- }
- geometry.computeBoundingSphere();
- return geometry;
- }
- function handleElement( buffer, elementName, element, cacheEntry ) {
- if ( elementName === 'vertex' ) {
- buffer.vertices.push( element[ cacheEntry.attrX ], element[ cacheEntry.attrY ], element[ cacheEntry.attrZ ] );
- if ( cacheEntry.attrNX !== null && cacheEntry.attrNY !== null && cacheEntry.attrNZ !== null ) {
- buffer.normals.push( element[ cacheEntry.attrNX ], element[ cacheEntry.attrNY ], element[ cacheEntry.attrNZ ] );
- }
- if ( cacheEntry.attrS !== null && cacheEntry.attrT !== null ) {
- buffer.uvs.push( element[ cacheEntry.attrS ], element[ cacheEntry.attrT ] );
- }
- if ( cacheEntry.attrR !== null && cacheEntry.attrG !== null && cacheEntry.attrB !== null ) {
- _color.setRGB(
- element[ cacheEntry.attrR ] / 255.0,
- element[ cacheEntry.attrG ] / 255.0,
- element[ cacheEntry.attrB ] / 255.0,
- SRGBColorSpace
- );
- buffer.colors.push( _color.r, _color.g, _color.b );
- }
- for ( const customProperty of Object.keys( scope.customPropertyMapping ) ) {
- for ( const elementProperty of scope.customPropertyMapping[ customProperty ] ) {
- buffer[ customProperty ].push( element[ elementProperty ] );
- }
- }
- } else if ( elementName === 'face' ) {
- const vertex_indices = element.vertex_indices || element.vertex_index; // issue #9338
- const texcoord = element.texcoord;
- if ( vertex_indices.length === 3 ) {
- buffer.indices.push( vertex_indices[ 0 ], vertex_indices[ 1 ], vertex_indices[ 2 ] );
- if ( texcoord && texcoord.length === 6 ) {
- buffer.faceVertexUvs.push( texcoord[ 0 ], texcoord[ 1 ] );
- buffer.faceVertexUvs.push( texcoord[ 2 ], texcoord[ 3 ] );
- buffer.faceVertexUvs.push( texcoord[ 4 ], texcoord[ 5 ] );
- }
- } else if ( vertex_indices.length === 4 ) {
- buffer.indices.push( vertex_indices[ 0 ], vertex_indices[ 1 ], vertex_indices[ 3 ] );
- buffer.indices.push( vertex_indices[ 1 ], vertex_indices[ 2 ], vertex_indices[ 3 ] );
- }
- // face colors
- if ( cacheEntry.attrR !== null && cacheEntry.attrG !== null && cacheEntry.attrB !== null ) {
- _color.setRGB(
- element[ cacheEntry.attrR ] / 255.0,
- element[ cacheEntry.attrG ] / 255.0,
- element[ cacheEntry.attrB ] / 255.0,
- SRGBColorSpace
- );
- buffer.faceVertexColors.push( _color.r, _color.g, _color.b );
- buffer.faceVertexColors.push( _color.r, _color.g, _color.b );
- buffer.faceVertexColors.push( _color.r, _color.g, _color.b );
- }
- }
- }
- function binaryReadElement( at, properties ) {
- const element = {};
- let read = 0;
- for ( let i = 0; i < properties.length; i ++ ) {
- const property = properties[ i ];
- const valueReader = property.valueReader;
- if ( property.type === 'list' ) {
- const list = [];
- const n = property.countReader.read( at + read );
- read += property.countReader.size;
- for ( let j = 0; j < n; j ++ ) {
- list.push( valueReader.read( at + read ) );
- read += valueReader.size;
- }
- element[ property.name ] = list;
- } else {
- element[ property.name ] = valueReader.read( at + read );
- read += valueReader.size;
- }
- }
- return [ element, read ];
- }
- function setPropertyBinaryReaders( properties, body, little_endian ) {
- function getBinaryReader( dataview, type, little_endian ) {
- switch ( type ) {
- // correspondences for non-specific length types here match rply:
- case 'int8': case 'char': return { read: ( at ) => {
- return dataview.getInt8( at );
- }, size: 1 };
- case 'uint8': case 'uchar': return { read: ( at ) => {
- return dataview.getUint8( at );
- }, size: 1 };
- case 'int16': case 'short': return { read: ( at ) => {
- return dataview.getInt16( at, little_endian );
- }, size: 2 };
- case 'uint16': case 'ushort': return { read: ( at ) => {
- return dataview.getUint16( at, little_endian );
- }, size: 2 };
- case 'int32': case 'int': return { read: ( at ) => {
- return dataview.getInt32( at, little_endian );
- }, size: 4 };
- case 'uint32': case 'uint': return { read: ( at ) => {
- return dataview.getUint32( at, little_endian );
- }, size: 4 };
- case 'float32': case 'float': return { read: ( at ) => {
- return dataview.getFloat32( at, little_endian );
- }, size: 4 };
- case 'float64': case 'double': return { read: ( at ) => {
- return dataview.getFloat64( at, little_endian );
- }, size: 8 };
- }
- }
- for ( let i = 0, l = properties.length; i < l; i ++ ) {
- const property = properties[ i ];
- if ( property.type === 'list' ) {
- property.countReader = getBinaryReader( body, property.countType, little_endian );
- property.valueReader = getBinaryReader( body, property.itemType, little_endian );
- } else {
- property.valueReader = getBinaryReader( body, property.type, little_endian );
- }
- }
- }
- function parseBinary( data, header ) {
- const buffer = createBuffer();
- const little_endian = ( header.format === 'binary_little_endian' );
- const body = new DataView( data, header.headerLength );
- let result, loc = 0;
- for ( let currentElement = 0; currentElement < header.elements.length; currentElement ++ ) {
- const elementDesc = header.elements[ currentElement ];
- const properties = elementDesc.properties;
- const attributeMap = mapElementAttributes( properties );
- setPropertyBinaryReaders( properties, body, little_endian );
- for ( let currentElementCount = 0; currentElementCount < elementDesc.count; currentElementCount ++ ) {
- result = binaryReadElement( loc, properties );
- loc += result[ 1 ];
- const element = result[ 0 ];
- handleElement( buffer, elementDesc.name, element, attributeMap );
- }
- }
- return postProcess( buffer );
- }
- function extractHeaderText( bytes ) {
- let i = 0;
- let cont = true;
- let line = '';
- const lines = [];
- const startLine = new TextDecoder().decode( bytes.subarray( 0, 5 ) );
- const hasCRNL = /^ply\r\n/.test( startLine );
- do {
- const c = String.fromCharCode( bytes[ i ++ ] );
- if ( c !== '\n' && c !== '\r' ) {
- line += c;
- } else {
- if ( line === 'end_header' ) cont = false;
- if ( line !== '' ) {
- lines.push( line );
- line = '';
- }
- }
- } while ( cont && i < bytes.length );
- // ascii section using \r\n as line endings
- if ( hasCRNL === true ) i ++;
- return { headerText: lines.join( '\r' ) + '\r', headerLength: i };
- }
- //
- let geometry;
- const scope = this;
- if ( data instanceof ArrayBuffer ) {
- const bytes = new Uint8Array( data );
- const { headerText, headerLength } = extractHeaderText( bytes );
- const header = parseHeader( headerText, headerLength );
- if ( header.format === 'ascii' ) {
- const text = new TextDecoder().decode( bytes );
- geometry = parseASCII( text, header );
- } else {
- geometry = parseBinary( data, header );
- }
- } else {
- geometry = parseASCII( data, parseHeader( data ) );
- }
- return geometry;
- }
- }
- class ArrayStream {
- constructor( arr ) {
- this.arr = arr;
- this.i = 0;
- }
- empty() {
- return this.i >= this.arr.length;
- }
- next() {
- return this.arr[ this.i ++ ];
- }
- }
- export { PLYLoader };
|