AMFLoader.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. import {
  2. BufferGeometry,
  3. Color,
  4. FileLoader,
  5. Float32BufferAttribute,
  6. Group,
  7. Loader,
  8. Mesh,
  9. MeshPhongMaterial
  10. } from 'three';
  11. import * as fflate from '../libs/fflate.module.js';
  12. /**
  13. * A loader for the AMF format.
  14. *
  15. * The loader supports materials, color and ZIP compressed files.
  16. * No constellation support (yet).
  17. *
  18. * ```js
  19. * const loader = new AMFLoader();
  20. *
  21. * const object = await loader.loadAsync( './models/amf/rook.amf' );
  22. * scene.add( object );
  23. * ```
  24. *
  25. * @augments Loader
  26. */
  27. class AMFLoader extends Loader {
  28. /**
  29. * Constructs a new AMF loader.
  30. *
  31. * @param {LoadingManager} [manager] - The loading manager.
  32. */
  33. constructor( manager ) {
  34. super( manager );
  35. }
  36. /**
  37. * Starts loading from the given URL and passes the loaded AMF asset
  38. * to the `onLoad()` callback.
  39. *
  40. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  41. * @param {function(Group)} onLoad - Executed when the loading process has been finished.
  42. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  43. * @param {onErrorCallback} onError - Executed when errors occur.
  44. */
  45. load( url, onLoad, onProgress, onError ) {
  46. const scope = this;
  47. const loader = new FileLoader( scope.manager );
  48. loader.setPath( scope.path );
  49. loader.setResponseType( 'arraybuffer' );
  50. loader.setRequestHeader( scope.requestHeader );
  51. loader.setWithCredentials( scope.withCredentials );
  52. loader.load( url, function ( text ) {
  53. try {
  54. onLoad( scope.parse( text ) );
  55. } catch ( e ) {
  56. if ( onError ) {
  57. onError( e );
  58. } else {
  59. console.error( e );
  60. }
  61. scope.manager.itemError( url );
  62. }
  63. }, onProgress, onError );
  64. }
  65. /**
  66. * Parses the given AMF data and returns the resulting group.
  67. *
  68. * @param {ArrayBuffer} data - The raw AMF asset data as an array buffer.
  69. * @return {Group} A group representing the parsed asset.
  70. */
  71. parse( data ) {
  72. function loadDocument( data ) {
  73. let view = new DataView( data );
  74. const magic = String.fromCharCode( view.getUint8( 0 ), view.getUint8( 1 ) );
  75. if ( magic === 'PK' ) {
  76. let zip = null;
  77. let file = null;
  78. console.log( 'THREE.AMFLoader: Loading Zip' );
  79. try {
  80. zip = fflate.unzipSync( new Uint8Array( data ) );
  81. } catch ( e ) {
  82. if ( e instanceof ReferenceError ) {
  83. console.log( 'THREE.AMFLoader: fflate missing and file is compressed.' );
  84. return null;
  85. }
  86. }
  87. for ( file in zip ) {
  88. if ( file.toLowerCase().slice( - 4 ) === '.amf' ) {
  89. break;
  90. }
  91. }
  92. console.log( 'THREE.AMFLoader: Trying to load file asset: ' + file );
  93. view = new DataView( zip[ file ].buffer );
  94. }
  95. const fileText = new TextDecoder().decode( view );
  96. const xmlData = new DOMParser().parseFromString( fileText, 'application/xml' );
  97. if ( xmlData.documentElement.nodeName.toLowerCase() !== 'amf' ) {
  98. console.log( 'THREE.AMFLoader: Error loading AMF - no AMF document found.' );
  99. return null;
  100. }
  101. return xmlData;
  102. }
  103. function loadDocumentScale( node ) {
  104. let scale = 1.0;
  105. let unit = 'millimeter';
  106. if ( node.documentElement.attributes.unit !== undefined ) {
  107. unit = node.documentElement.attributes.unit.value.toLowerCase();
  108. }
  109. const scaleUnits = {
  110. millimeter: 1.0,
  111. inch: 25.4,
  112. feet: 304.8,
  113. meter: 1000.0,
  114. micron: 0.001
  115. };
  116. if ( scaleUnits[ unit ] !== undefined ) {
  117. scale = scaleUnits[ unit ];
  118. }
  119. console.log( 'THREE.AMFLoader: Unit scale: ' + scale );
  120. return scale;
  121. }
  122. function loadMaterials( node ) {
  123. let matName = 'AMF Material';
  124. const matId = node.attributes.id.textContent;
  125. let color = { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };
  126. let loadedMaterial = null;
  127. for ( let i = 0; i < node.childNodes.length; i ++ ) {
  128. const matChildEl = node.childNodes[ i ];
  129. if ( matChildEl.nodeName === 'metadata' && matChildEl.attributes.type !== undefined ) {
  130. if ( matChildEl.attributes.type.value === 'name' ) {
  131. matName = matChildEl.textContent;
  132. }
  133. } else if ( matChildEl.nodeName === 'color' ) {
  134. color = loadColor( matChildEl );
  135. }
  136. }
  137. loadedMaterial = new MeshPhongMaterial( {
  138. flatShading: true,
  139. color: new Color( color.r, color.g, color.b ),
  140. name: matName
  141. } );
  142. if ( color.a !== 1.0 ) {
  143. loadedMaterial.transparent = true;
  144. loadedMaterial.opacity = color.a;
  145. }
  146. return { id: matId, material: loadedMaterial };
  147. }
  148. function loadColor( node ) {
  149. const color = { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };
  150. for ( let i = 0; i < node.childNodes.length; i ++ ) {
  151. const matColor = node.childNodes[ i ];
  152. if ( matColor.nodeName === 'r' ) {
  153. color.r = matColor.textContent;
  154. } else if ( matColor.nodeName === 'g' ) {
  155. color.g = matColor.textContent;
  156. } else if ( matColor.nodeName === 'b' ) {
  157. color.b = matColor.textContent;
  158. } else if ( matColor.nodeName === 'a' ) {
  159. color.a = matColor.textContent;
  160. }
  161. }
  162. return color;
  163. }
  164. function loadMeshVolume( node ) {
  165. const volume = { name: '', triangles: [], materialId: null };
  166. let currVolumeNode = node.firstElementChild;
  167. if ( node.attributes.materialid !== undefined ) {
  168. volume.materialId = node.attributes.materialid.nodeValue;
  169. }
  170. while ( currVolumeNode ) {
  171. if ( currVolumeNode.nodeName === 'metadata' ) {
  172. if ( currVolumeNode.attributes.type !== undefined ) {
  173. if ( currVolumeNode.attributes.type.value === 'name' ) {
  174. volume.name = currVolumeNode.textContent;
  175. }
  176. }
  177. } else if ( currVolumeNode.nodeName === 'triangle' ) {
  178. const v1 = currVolumeNode.getElementsByTagName( 'v1' )[ 0 ].textContent;
  179. const v2 = currVolumeNode.getElementsByTagName( 'v2' )[ 0 ].textContent;
  180. const v3 = currVolumeNode.getElementsByTagName( 'v3' )[ 0 ].textContent;
  181. volume.triangles.push( v1, v2, v3 );
  182. }
  183. currVolumeNode = currVolumeNode.nextElementSibling;
  184. }
  185. return volume;
  186. }
  187. function loadMeshVertices( node ) {
  188. const vertArray = [];
  189. const normalArray = [];
  190. let currVerticesNode = node.firstElementChild;
  191. while ( currVerticesNode ) {
  192. if ( currVerticesNode.nodeName === 'vertex' ) {
  193. let vNode = currVerticesNode.firstElementChild;
  194. while ( vNode ) {
  195. if ( vNode.nodeName === 'coordinates' ) {
  196. const x = vNode.getElementsByTagName( 'x' )[ 0 ].textContent;
  197. const y = vNode.getElementsByTagName( 'y' )[ 0 ].textContent;
  198. const z = vNode.getElementsByTagName( 'z' )[ 0 ].textContent;
  199. vertArray.push( x, y, z );
  200. } else if ( vNode.nodeName === 'normal' ) {
  201. const nx = vNode.getElementsByTagName( 'nx' )[ 0 ].textContent;
  202. const ny = vNode.getElementsByTagName( 'ny' )[ 0 ].textContent;
  203. const nz = vNode.getElementsByTagName( 'nz' )[ 0 ].textContent;
  204. normalArray.push( nx, ny, nz );
  205. }
  206. vNode = vNode.nextElementSibling;
  207. }
  208. }
  209. currVerticesNode = currVerticesNode.nextElementSibling;
  210. }
  211. return { 'vertices': vertArray, 'normals': normalArray };
  212. }
  213. function loadObject( node ) {
  214. const objId = node.attributes.id.textContent;
  215. const loadedObject = { name: 'amfobject', meshes: [] };
  216. let currColor = null;
  217. let currObjNode = node.firstElementChild;
  218. while ( currObjNode ) {
  219. if ( currObjNode.nodeName === 'metadata' ) {
  220. if ( currObjNode.attributes.type !== undefined ) {
  221. if ( currObjNode.attributes.type.value === 'name' ) {
  222. loadedObject.name = currObjNode.textContent;
  223. }
  224. }
  225. } else if ( currObjNode.nodeName === 'color' ) {
  226. currColor = loadColor( currObjNode );
  227. } else if ( currObjNode.nodeName === 'mesh' ) {
  228. let currMeshNode = currObjNode.firstElementChild;
  229. const mesh = { vertices: [], normals: [], volumes: [], color: currColor };
  230. while ( currMeshNode ) {
  231. if ( currMeshNode.nodeName === 'vertices' ) {
  232. const loadedVertices = loadMeshVertices( currMeshNode );
  233. mesh.normals = mesh.normals.concat( loadedVertices.normals );
  234. mesh.vertices = mesh.vertices.concat( loadedVertices.vertices );
  235. } else if ( currMeshNode.nodeName === 'volume' ) {
  236. mesh.volumes.push( loadMeshVolume( currMeshNode ) );
  237. }
  238. currMeshNode = currMeshNode.nextElementSibling;
  239. }
  240. loadedObject.meshes.push( mesh );
  241. }
  242. currObjNode = currObjNode.nextElementSibling;
  243. }
  244. return { 'id': objId, 'obj': loadedObject };
  245. }
  246. const xmlData = loadDocument( data );
  247. let amfName = '';
  248. let amfAuthor = '';
  249. const amfScale = loadDocumentScale( xmlData );
  250. const amfMaterials = {};
  251. const amfObjects = {};
  252. const childNodes = xmlData.documentElement.childNodes;
  253. let i, j;
  254. for ( i = 0; i < childNodes.length; i ++ ) {
  255. const child = childNodes[ i ];
  256. if ( child.nodeName === 'metadata' ) {
  257. if ( child.attributes.type !== undefined ) {
  258. if ( child.attributes.type.value === 'name' ) {
  259. amfName = child.textContent;
  260. } else if ( child.attributes.type.value === 'author' ) {
  261. amfAuthor = child.textContent;
  262. }
  263. }
  264. } else if ( child.nodeName === 'material' ) {
  265. const loadedMaterial = loadMaterials( child );
  266. amfMaterials[ loadedMaterial.id ] = loadedMaterial.material;
  267. } else if ( child.nodeName === 'object' ) {
  268. const loadedObject = loadObject( child );
  269. amfObjects[ loadedObject.id ] = loadedObject.obj;
  270. }
  271. }
  272. const sceneObject = new Group();
  273. const defaultMaterial = new MeshPhongMaterial( {
  274. name: Loader.DEFAULT_MATERIAL_NAME,
  275. color: 0xaaaaff,
  276. flatShading: true
  277. } );
  278. sceneObject.name = amfName;
  279. sceneObject.userData.author = amfAuthor;
  280. sceneObject.userData.loader = 'AMF';
  281. for ( const id in amfObjects ) {
  282. const part = amfObjects[ id ];
  283. const meshes = part.meshes;
  284. const newObject = new Group();
  285. newObject.name = part.name || '';
  286. for ( i = 0; i < meshes.length; i ++ ) {
  287. let objDefaultMaterial = defaultMaterial;
  288. const mesh = meshes[ i ];
  289. const vertices = new Float32BufferAttribute( mesh.vertices, 3 );
  290. let normals = null;
  291. if ( mesh.normals.length ) {
  292. normals = new Float32BufferAttribute( mesh.normals, 3 );
  293. }
  294. if ( mesh.color ) {
  295. const color = mesh.color;
  296. objDefaultMaterial = defaultMaterial.clone();
  297. objDefaultMaterial.color = new Color( color.r, color.g, color.b );
  298. if ( color.a !== 1.0 ) {
  299. objDefaultMaterial.transparent = true;
  300. objDefaultMaterial.opacity = color.a;
  301. }
  302. }
  303. const volumes = mesh.volumes;
  304. for ( j = 0; j < volumes.length; j ++ ) {
  305. const volume = volumes[ j ];
  306. const newGeometry = new BufferGeometry();
  307. let material = objDefaultMaterial;
  308. newGeometry.setIndex( volume.triangles );
  309. newGeometry.setAttribute( 'position', vertices.clone() );
  310. if ( normals ) {
  311. newGeometry.setAttribute( 'normal', normals.clone() );
  312. }
  313. if ( amfMaterials[ volume.materialId ] !== undefined ) {
  314. material = amfMaterials[ volume.materialId ];
  315. }
  316. newGeometry.scale( amfScale, amfScale, amfScale );
  317. newObject.add( new Mesh( newGeometry, material.clone() ) );
  318. }
  319. }
  320. sceneObject.add( newObject );
  321. }
  322. return sceneObject;
  323. }
  324. }
  325. export { AMFLoader };
粤ICP备19079148号