ObjectLoader.js 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  1. import {
  2. UVMapping,
  3. CubeReflectionMapping,
  4. CubeRefractionMapping,
  5. EquirectangularReflectionMapping,
  6. EquirectangularRefractionMapping,
  7. CubeUVReflectionMapping,
  8. RepeatWrapping,
  9. ClampToEdgeWrapping,
  10. MirroredRepeatWrapping,
  11. NearestFilter,
  12. NearestMipmapNearestFilter,
  13. NearestMipmapLinearFilter,
  14. LinearFilter,
  15. LinearMipmapNearestFilter,
  16. LinearMipmapLinearFilter
  17. } from '../constants.js';
  18. import { InstancedBufferAttribute } from '../core/InstancedBufferAttribute.js';
  19. import { Color } from '../math/Color.js';
  20. import { Vector3 } from '../math/Vector3.js';
  21. import { Object3D } from '../core/Object3D.js';
  22. import { Group } from '../objects/Group.js';
  23. import { InstancedMesh } from '../objects/InstancedMesh.js';
  24. import { BatchedMesh } from '../objects/BatchedMesh.js';
  25. import { Sprite } from '../objects/Sprite.js';
  26. import { Points } from '../objects/Points.js';
  27. import { Line } from '../objects/Line.js';
  28. import { LineLoop } from '../objects/LineLoop.js';
  29. import { LineSegments } from '../objects/LineSegments.js';
  30. import { LOD } from '../objects/LOD.js';
  31. import { Mesh } from '../objects/Mesh.js';
  32. import { SkinnedMesh } from '../objects/SkinnedMesh.js';
  33. import { Bone } from '../objects/Bone.js';
  34. import { Skeleton } from '../objects/Skeleton.js';
  35. import { Shape } from '../extras/core/Shape.js';
  36. import { Fog } from '../scenes/Fog.js';
  37. import { FogExp2 } from '../scenes/FogExp2.js';
  38. import { HemisphereLight } from '../lights/HemisphereLight.js';
  39. import { SpotLight } from '../lights/SpotLight.js';
  40. import { PointLight } from '../lights/PointLight.js';
  41. import { DirectionalLight } from '../lights/DirectionalLight.js';
  42. import { AmbientLight } from '../lights/AmbientLight.js';
  43. import { RectAreaLight } from '../lights/RectAreaLight.js';
  44. import { LightProbe } from '../lights/LightProbe.js';
  45. import { OrthographicCamera } from '../cameras/OrthographicCamera.js';
  46. import { PerspectiveCamera } from '../cameras/PerspectiveCamera.js';
  47. import { Scene } from '../scenes/Scene.js';
  48. import { CubeTexture } from '../textures/CubeTexture.js';
  49. import { Texture } from '../textures/Texture.js';
  50. import { Source } from '../textures/Source.js';
  51. import { DataTexture } from '../textures/DataTexture.js';
  52. import { ImageLoader } from './ImageLoader.js';
  53. import { LoadingManager } from './LoadingManager.js';
  54. import { AnimationClip } from '../animation/AnimationClip.js';
  55. import { MaterialLoader } from './MaterialLoader.js';
  56. import { LoaderUtils } from './LoaderUtils.js';
  57. import { BufferGeometryLoader } from './BufferGeometryLoader.js';
  58. import { Loader } from './Loader.js';
  59. import { FileLoader } from './FileLoader.js';
  60. import * as Geometries from '../geometries/Geometries.js';
  61. import { getTypedArray, error, warn } from '../utils.js';
  62. import { Box3 } from '../math/Box3.js';
  63. import { Sphere } from '../math/Sphere.js';
  64. import { SphericalHarmonics3 } from '../math/SphericalHarmonics3.js';
  65. /**
  66. * A loader for loading a JSON resource in the [JSON Object/Scene format](https://github.com/mrdoob/three.js/wiki/JSON-Object-Scene-format-4).
  67. * The files are internally loaded via {@link FileLoader}.
  68. *
  69. * ```js
  70. * const loader = new THREE.ObjectLoader();
  71. * const obj = await loader.loadAsync( 'models/json/example.json' );
  72. * scene.add( obj );
  73. *
  74. * // Alternatively, to parse a previously loaded JSON structure
  75. * const object = await loader.parseAsync( a_json_object );
  76. * scene.add( object );
  77. * ```
  78. *
  79. * @augments Loader
  80. */
  81. class ObjectLoader extends Loader {
  82. /**
  83. * Constructs a new object loader.
  84. *
  85. * @param {LoadingManager} [manager] - The loading manager.
  86. */
  87. constructor( manager ) {
  88. super( manager );
  89. }
  90. /**
  91. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  92. *
  93. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  94. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  95. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  96. * @param {onErrorCallback} onError - Executed when errors occur.
  97. */
  98. load( url, onLoad, onProgress, onError ) {
  99. const scope = this;
  100. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  101. this.resourcePath = this.resourcePath || path;
  102. const loader = new FileLoader( this.manager );
  103. loader.setPath( this.path );
  104. loader.setRequestHeader( this.requestHeader );
  105. loader.setWithCredentials( this.withCredentials );
  106. loader.load( url, function ( text ) {
  107. let json = null;
  108. try {
  109. json = JSON.parse( text );
  110. } catch ( error ) {
  111. if ( onError !== undefined ) onError( error );
  112. error( 'ObjectLoader: Can\'t parse ' + url + '.', error.message );
  113. return;
  114. }
  115. const metadata = json.metadata;
  116. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  117. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  118. error( 'ObjectLoader: Can\'t load ' + url );
  119. return;
  120. }
  121. scope.parse( json, onLoad );
  122. }, onProgress, onError );
  123. }
  124. /**
  125. * Async version of {@link ObjectLoader#load}.
  126. *
  127. * @async
  128. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  129. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  130. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  131. */
  132. async loadAsync( url, onProgress ) {
  133. const scope = this;
  134. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  135. this.resourcePath = this.resourcePath || path;
  136. const loader = new FileLoader( this.manager );
  137. loader.setPath( this.path );
  138. loader.setRequestHeader( this.requestHeader );
  139. loader.setWithCredentials( this.withCredentials );
  140. const text = await loader.loadAsync( url, onProgress );
  141. const json = JSON.parse( text );
  142. const metadata = json.metadata;
  143. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  144. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  145. }
  146. return await scope.parseAsync( json );
  147. }
  148. /**
  149. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  150. * but can also be used directly to parse a previously loaded JSON structure.
  151. *
  152. * @param {Object} json - The serialized 3D object.
  153. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  154. * @return {Object3D} The parsed 3D object.
  155. */
  156. parse( json, onLoad ) {
  157. const animations = this.parseAnimations( json.animations );
  158. const shapes = this.parseShapes( json.shapes );
  159. const geometries = this.parseGeometries( json.geometries, shapes );
  160. const images = this.parseImages( json.images, function () {
  161. if ( onLoad !== undefined ) onLoad( object );
  162. } );
  163. const textures = this.parseTextures( json.textures, images );
  164. const materials = this.parseMaterials( json.materials, textures );
  165. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  166. const skeletons = this.parseSkeletons( json.skeletons, object );
  167. this.bindSkeletons( object, skeletons );
  168. this.bindLightTargets( object );
  169. //
  170. if ( onLoad !== undefined ) {
  171. let hasImages = false;
  172. for ( const uuid in images ) {
  173. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  174. hasImages = true;
  175. break;
  176. }
  177. }
  178. if ( hasImages === false ) onLoad( object );
  179. }
  180. return object;
  181. }
  182. /**
  183. * Async version of {@link ObjectLoader#parse}.
  184. *
  185. * @param {Object} json - The serialized 3D object.
  186. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  187. */
  188. async parseAsync( json ) {
  189. const animations = this.parseAnimations( json.animations );
  190. const shapes = this.parseShapes( json.shapes );
  191. const geometries = this.parseGeometries( json.geometries, shapes );
  192. const images = await this.parseImagesAsync( json.images );
  193. const textures = this.parseTextures( json.textures, images );
  194. const materials = this.parseMaterials( json.materials, textures );
  195. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  196. const skeletons = this.parseSkeletons( json.skeletons, object );
  197. this.bindSkeletons( object, skeletons );
  198. this.bindLightTargets( object );
  199. return object;
  200. }
  201. // internals
  202. parseShapes( json ) {
  203. const shapes = {};
  204. if ( json !== undefined ) {
  205. for ( let i = 0, l = json.length; i < l; i ++ ) {
  206. const shape = new Shape().fromJSON( json[ i ] );
  207. shapes[ shape.uuid ] = shape;
  208. }
  209. }
  210. return shapes;
  211. }
  212. parseSkeletons( json, object ) {
  213. const skeletons = {};
  214. const bones = {};
  215. // generate bone lookup table
  216. object.traverse( function ( child ) {
  217. if ( child.isBone ) bones[ child.uuid ] = child;
  218. } );
  219. // create skeletons
  220. if ( json !== undefined ) {
  221. for ( let i = 0, l = json.length; i < l; i ++ ) {
  222. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  223. skeletons[ skeleton.uuid ] = skeleton;
  224. }
  225. }
  226. return skeletons;
  227. }
  228. parseGeometries( json, shapes ) {
  229. const geometries = {};
  230. if ( json !== undefined ) {
  231. const bufferGeometryLoader = new BufferGeometryLoader();
  232. for ( let i = 0, l = json.length; i < l; i ++ ) {
  233. let geometry;
  234. const data = json[ i ];
  235. switch ( data.type ) {
  236. case 'BufferGeometry':
  237. case 'InstancedBufferGeometry':
  238. geometry = bufferGeometryLoader.parse( data );
  239. break;
  240. default:
  241. if ( data.type in Geometries ) {
  242. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  243. } else {
  244. warn( `ObjectLoader: Unsupported geometry type "${ data.type }"` );
  245. }
  246. }
  247. geometry.uuid = data.uuid;
  248. if ( data.name !== undefined ) geometry.name = data.name;
  249. if ( data.userData !== undefined ) geometry.userData = data.userData;
  250. geometries[ data.uuid ] = geometry;
  251. }
  252. }
  253. return geometries;
  254. }
  255. parseMaterials( json, textures ) {
  256. const cache = {}; // MultiMaterial
  257. const materials = {};
  258. if ( json !== undefined ) {
  259. const loader = new MaterialLoader();
  260. loader.setTextures( textures );
  261. for ( let i = 0, l = json.length; i < l; i ++ ) {
  262. const data = json[ i ];
  263. if ( cache[ data.uuid ] === undefined ) {
  264. cache[ data.uuid ] = loader.parse( data );
  265. }
  266. materials[ data.uuid ] = cache[ data.uuid ];
  267. }
  268. }
  269. return materials;
  270. }
  271. parseAnimations( json ) {
  272. const animations = {};
  273. if ( json !== undefined ) {
  274. for ( let i = 0; i < json.length; i ++ ) {
  275. const data = json[ i ];
  276. const clip = AnimationClip.parse( data );
  277. animations[ clip.uuid ] = clip;
  278. }
  279. }
  280. return animations;
  281. }
  282. parseImages( json, onLoad ) {
  283. const scope = this;
  284. const images = {};
  285. let loader;
  286. function loadImage( url ) {
  287. scope.manager.itemStart( url );
  288. return loader.load( url, function () {
  289. scope.manager.itemEnd( url );
  290. }, undefined, function () {
  291. scope.manager.itemError( url );
  292. scope.manager.itemEnd( url );
  293. } );
  294. }
  295. function deserializeImage( image ) {
  296. if ( typeof image === 'string' ) {
  297. const url = image;
  298. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  299. return loadImage( path );
  300. } else {
  301. if ( image.data ) {
  302. return {
  303. data: getTypedArray( image.type, image.data ),
  304. width: image.width,
  305. height: image.height
  306. };
  307. } else {
  308. return null;
  309. }
  310. }
  311. }
  312. if ( json !== undefined && json.length > 0 ) {
  313. const manager = new LoadingManager( onLoad );
  314. loader = new ImageLoader( manager );
  315. loader.setCrossOrigin( this.crossOrigin );
  316. for ( let i = 0, il = json.length; i < il; i ++ ) {
  317. const image = json[ i ];
  318. const url = image.url;
  319. if ( Array.isArray( url ) ) {
  320. // load array of images e.g CubeTexture
  321. const imageArray = [];
  322. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  323. const currentUrl = url[ j ];
  324. const deserializedImage = deserializeImage( currentUrl );
  325. if ( deserializedImage !== null ) {
  326. if ( deserializedImage instanceof HTMLImageElement ) {
  327. imageArray.push( deserializedImage );
  328. } else {
  329. // special case: handle array of data textures for cube textures
  330. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  331. }
  332. }
  333. }
  334. images[ image.uuid ] = new Source( imageArray );
  335. } else {
  336. // load single image
  337. const deserializedImage = deserializeImage( image.url );
  338. images[ image.uuid ] = new Source( deserializedImage );
  339. }
  340. }
  341. }
  342. return images;
  343. }
  344. async parseImagesAsync( json ) {
  345. const scope = this;
  346. const images = {};
  347. let loader;
  348. async function deserializeImage( image ) {
  349. if ( typeof image === 'string' ) {
  350. const url = image;
  351. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  352. return await loader.loadAsync( path );
  353. } else {
  354. if ( image.data ) {
  355. return {
  356. data: getTypedArray( image.type, image.data ),
  357. width: image.width,
  358. height: image.height
  359. };
  360. } else {
  361. return null;
  362. }
  363. }
  364. }
  365. if ( json !== undefined && json.length > 0 ) {
  366. loader = new ImageLoader( this.manager );
  367. loader.setCrossOrigin( this.crossOrigin );
  368. for ( let i = 0, il = json.length; i < il; i ++ ) {
  369. const image = json[ i ];
  370. const url = image.url;
  371. if ( Array.isArray( url ) ) {
  372. // load array of images e.g CubeTexture
  373. const imageArray = [];
  374. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  375. const currentUrl = url[ j ];
  376. const deserializedImage = await deserializeImage( currentUrl );
  377. if ( deserializedImage !== null ) {
  378. if ( deserializedImage instanceof HTMLImageElement ) {
  379. imageArray.push( deserializedImage );
  380. } else {
  381. // special case: handle array of data textures for cube textures
  382. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  383. }
  384. }
  385. }
  386. images[ image.uuid ] = new Source( imageArray );
  387. } else {
  388. // load single image
  389. const deserializedImage = await deserializeImage( image.url );
  390. images[ image.uuid ] = new Source( deserializedImage );
  391. }
  392. }
  393. }
  394. return images;
  395. }
  396. parseTextures( json, images ) {
  397. function parseConstant( value, type ) {
  398. if ( typeof value === 'number' ) return value;
  399. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  400. return type[ value ];
  401. }
  402. const textures = {};
  403. if ( json !== undefined ) {
  404. for ( let i = 0, l = json.length; i < l; i ++ ) {
  405. const data = json[ i ];
  406. if ( data.image === undefined ) {
  407. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  408. }
  409. if ( images[ data.image ] === undefined ) {
  410. warn( 'ObjectLoader: Undefined image', data.image );
  411. }
  412. const source = images[ data.image ];
  413. const image = source.data;
  414. let texture;
  415. if ( Array.isArray( image ) ) {
  416. texture = new CubeTexture();
  417. if ( image.length === 6 ) texture.needsUpdate = true;
  418. } else {
  419. if ( image && image.data ) {
  420. texture = new DataTexture();
  421. } else {
  422. texture = new Texture();
  423. }
  424. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  425. }
  426. texture.source = source;
  427. texture.uuid = data.uuid;
  428. if ( data.name !== undefined ) texture.name = data.name;
  429. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  430. if ( data.channel !== undefined ) texture.channel = data.channel;
  431. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  432. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  433. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  434. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  435. if ( data.wrap !== undefined ) {
  436. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  437. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  438. }
  439. if ( data.format !== undefined ) texture.format = data.format;
  440. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  441. if ( data.type !== undefined ) texture.type = data.type;
  442. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  443. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  444. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  445. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  446. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  447. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  448. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  449. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  450. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  451. if ( data.userData !== undefined ) texture.userData = data.userData;
  452. textures[ data.uuid ] = texture;
  453. }
  454. }
  455. return textures;
  456. }
  457. parseObject( data, geometries, materials, textures, animations ) {
  458. let object;
  459. function getGeometry( name ) {
  460. if ( geometries[ name ] === undefined ) {
  461. warn( 'ObjectLoader: Undefined geometry', name );
  462. }
  463. return geometries[ name ];
  464. }
  465. function getMaterial( name ) {
  466. if ( name === undefined ) return undefined;
  467. if ( Array.isArray( name ) ) {
  468. const array = [];
  469. for ( let i = 0, l = name.length; i < l; i ++ ) {
  470. const uuid = name[ i ];
  471. if ( materials[ uuid ] === undefined ) {
  472. warn( 'ObjectLoader: Undefined material', uuid );
  473. }
  474. array.push( materials[ uuid ] );
  475. }
  476. return array;
  477. }
  478. if ( materials[ name ] === undefined ) {
  479. warn( 'ObjectLoader: Undefined material', name );
  480. }
  481. return materials[ name ];
  482. }
  483. function getTexture( uuid ) {
  484. if ( textures[ uuid ] === undefined ) {
  485. warn( 'ObjectLoader: Undefined texture', uuid );
  486. }
  487. return textures[ uuid ];
  488. }
  489. let geometry, material;
  490. switch ( data.type ) {
  491. case 'Scene':
  492. object = new Scene();
  493. if ( data.background !== undefined ) {
  494. if ( Number.isInteger( data.background ) ) {
  495. object.background = new Color( data.background );
  496. } else {
  497. object.background = getTexture( data.background );
  498. }
  499. }
  500. if ( data.environment !== undefined ) {
  501. object.environment = getTexture( data.environment );
  502. }
  503. if ( data.fog !== undefined ) {
  504. if ( data.fog.type === 'Fog' ) {
  505. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  506. } else if ( data.fog.type === 'FogExp2' ) {
  507. object.fog = new FogExp2( data.fog.color, data.fog.density );
  508. }
  509. if ( data.fog.name !== '' ) {
  510. object.fog.name = data.fog.name;
  511. }
  512. }
  513. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  514. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  515. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  516. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  517. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  518. break;
  519. case 'PerspectiveCamera':
  520. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  521. if ( data.focus !== undefined ) object.focus = data.focus;
  522. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  523. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  524. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  525. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  526. break;
  527. case 'OrthographicCamera':
  528. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  529. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  530. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  531. break;
  532. case 'AmbientLight':
  533. object = new AmbientLight( data.color, data.intensity );
  534. break;
  535. case 'DirectionalLight':
  536. object = new DirectionalLight( data.color, data.intensity );
  537. object.target = data.target || '';
  538. break;
  539. case 'PointLight':
  540. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  541. break;
  542. case 'RectAreaLight':
  543. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  544. break;
  545. case 'SpotLight':
  546. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  547. object.target = data.target || '';
  548. break;
  549. case 'HemisphereLight':
  550. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  551. break;
  552. case 'LightProbe':
  553. const sh = new SphericalHarmonics3().fromArray( data.sh );
  554. object = new LightProbe( sh, data.intensity );
  555. break;
  556. case 'SkinnedMesh':
  557. geometry = getGeometry( data.geometry );
  558. material = getMaterial( data.material );
  559. object = new SkinnedMesh( geometry, material );
  560. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  561. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  562. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  563. break;
  564. case 'Mesh':
  565. geometry = getGeometry( data.geometry );
  566. material = getMaterial( data.material );
  567. object = new Mesh( geometry, material );
  568. break;
  569. case 'InstancedMesh':
  570. geometry = getGeometry( data.geometry );
  571. material = getMaterial( data.material );
  572. const count = data.count;
  573. const instanceMatrix = data.instanceMatrix;
  574. const instanceColor = data.instanceColor;
  575. object = new InstancedMesh( geometry, material, count );
  576. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  577. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  578. break;
  579. case 'BatchedMesh':
  580. geometry = getGeometry( data.geometry );
  581. material = getMaterial( data.material );
  582. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  583. object.geometry = geometry;
  584. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  585. object.sortObjects = data.sortObjects;
  586. object._drawRanges = data.drawRanges;
  587. object._reservedRanges = data.reservedRanges;
  588. object._geometryInfo = data.geometryInfo.map( info => {
  589. let box = null;
  590. let sphere = null;
  591. if ( info.boundingBox !== undefined ) {
  592. box = new Box3().fromJSON( info.boundingBox );
  593. }
  594. if ( info.boundingSphere !== undefined ) {
  595. sphere = new Sphere().fromJSON( info.boundingSphere );
  596. }
  597. return {
  598. ...info,
  599. boundingBox: box,
  600. boundingSphere: sphere
  601. };
  602. } );
  603. object._instanceInfo = data.instanceInfo;
  604. object._availableInstanceIds = data._availableInstanceIds;
  605. object._availableGeometryIds = data._availableGeometryIds;
  606. object._nextIndexStart = data.nextIndexStart;
  607. object._nextVertexStart = data.nextVertexStart;
  608. object._geometryCount = data.geometryCount;
  609. object._maxInstanceCount = data.maxInstanceCount;
  610. object._maxVertexCount = data.maxVertexCount;
  611. object._maxIndexCount = data.maxIndexCount;
  612. object._geometryInitialized = data.geometryInitialized;
  613. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  614. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  615. if ( data.colorsTexture !== undefined ) {
  616. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  617. }
  618. if ( data.boundingSphere !== undefined ) {
  619. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  620. }
  621. if ( data.boundingBox !== undefined ) {
  622. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  623. }
  624. break;
  625. case 'LOD':
  626. object = new LOD();
  627. break;
  628. case 'Line':
  629. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  630. break;
  631. case 'LineLoop':
  632. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  633. break;
  634. case 'LineSegments':
  635. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  636. break;
  637. case 'PointCloud':
  638. case 'Points':
  639. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  640. break;
  641. case 'Sprite':
  642. object = new Sprite( getMaterial( data.material ) );
  643. break;
  644. case 'Group':
  645. object = new Group();
  646. break;
  647. case 'Bone':
  648. object = new Bone();
  649. break;
  650. default:
  651. object = new Object3D();
  652. }
  653. object.uuid = data.uuid;
  654. if ( data.name !== undefined ) object.name = data.name;
  655. if ( data.matrix !== undefined ) {
  656. object.matrix.fromArray( data.matrix );
  657. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  658. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  659. } else {
  660. if ( data.position !== undefined ) object.position.fromArray( data.position );
  661. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  662. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  663. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  664. }
  665. if ( data.up !== undefined ) object.up.fromArray( data.up );
  666. if ( data.pivot !== undefined ) object.pivot = new Vector3().fromArray( data.pivot );
  667. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  668. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  669. if ( data.shadow ) {
  670. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  671. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  672. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  673. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  674. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  675. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  676. }
  677. if ( data.visible !== undefined ) object.visible = data.visible;
  678. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  679. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  680. if ( data.static !== undefined ) object.static = data.static;
  681. if ( data.userData !== undefined ) object.userData = data.userData;
  682. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  683. if ( data.children !== undefined ) {
  684. const children = data.children;
  685. for ( let i = 0; i < children.length; i ++ ) {
  686. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  687. }
  688. }
  689. if ( data.animations !== undefined ) {
  690. const objectAnimations = data.animations;
  691. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  692. const uuid = objectAnimations[ i ];
  693. object.animations.push( animations[ uuid ] );
  694. }
  695. }
  696. if ( data.type === 'LOD' ) {
  697. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  698. const levels = data.levels;
  699. for ( let l = 0; l < levels.length; l ++ ) {
  700. const level = levels[ l ];
  701. const child = object.getObjectByProperty( 'uuid', level.object );
  702. if ( child !== undefined ) {
  703. object.addLevel( child, level.distance, level.hysteresis );
  704. }
  705. }
  706. }
  707. return object;
  708. }
  709. bindSkeletons( object, skeletons ) {
  710. if ( Object.keys( skeletons ).length === 0 ) return;
  711. object.traverse( function ( child ) {
  712. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  713. const skeleton = skeletons[ child.skeleton ];
  714. if ( skeleton === undefined ) {
  715. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  716. } else {
  717. child.bind( skeleton, child.bindMatrix );
  718. }
  719. }
  720. } );
  721. }
  722. bindLightTargets( object ) {
  723. object.traverse( function ( child ) {
  724. if ( child.isDirectionalLight || child.isSpotLight ) {
  725. const uuid = child.target;
  726. const target = object.getObjectByProperty( 'uuid', uuid );
  727. if ( target !== undefined ) {
  728. child.target = target;
  729. } else {
  730. child.target = new Object3D();
  731. }
  732. }
  733. } );
  734. }
  735. }
  736. const TEXTURE_MAPPING = {
  737. UVMapping: UVMapping,
  738. CubeReflectionMapping: CubeReflectionMapping,
  739. CubeRefractionMapping: CubeRefractionMapping,
  740. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  741. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  742. CubeUVReflectionMapping: CubeUVReflectionMapping
  743. };
  744. const TEXTURE_WRAPPING = {
  745. RepeatWrapping: RepeatWrapping,
  746. ClampToEdgeWrapping: ClampToEdgeWrapping,
  747. MirroredRepeatWrapping: MirroredRepeatWrapping
  748. };
  749. const TEXTURE_FILTER = {
  750. NearestFilter: NearestFilter,
  751. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  752. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  753. LinearFilter: LinearFilter,
  754. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  755. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  756. };
  757. export { ObjectLoader };
粤ICP备19079148号