VRMLLoader.js 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. THREE.VRMLLoader = function ( manager ) {
  5. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6. };
  7. THREE.VRMLLoader.prototype = {
  8. constructor: THREE.VRMLLoader,
  9. // for IndexedFaceSet support
  10. isRecordingPoints: false,
  11. isRecordingFaces: false,
  12. points: [],
  13. indexes: [],
  14. // for Background support
  15. isRecordingAngles: false,
  16. isRecordingColors: false,
  17. angles: [],
  18. colors: [],
  19. recordingFieldname: null,
  20. crossOrigin: 'anonymous',
  21. load: function ( url, onLoad, onProgress, onError ) {
  22. var scope = this;
  23. var loader = new THREE.FileLoader( this.manager );
  24. loader.load( url, function ( text ) {
  25. onLoad( scope.parse( text ) );
  26. }, onProgress, onError );
  27. },
  28. setCrossOrigin: function ( value ) {
  29. this.crossOrigin = value;
  30. return this;
  31. },
  32. parse: function ( data ) {
  33. var scope = this;
  34. var texturePath = this.texturePath || '';
  35. var textureLoader = new THREE.TextureLoader( this.manager );
  36. textureLoader.setCrossOrigin( this.crossOrigin );
  37. function parseV2( lines, scene ) {
  38. var defines = {};
  39. var float_pattern = /(\b|\-|\+)([\d\.e]+)/;
  40. var float2_pattern = /([\d\.\+\-e]+)\s+([\d\.\+\-e]+)/g;
  41. var float3_pattern = /([\d\.\+\-e]+)\s+([\d\.\+\-e]+)\s+([\d\.\+\-e]+)/g;
  42. /**
  43. * Vertically paints the faces interpolating between the
  44. * specified colors at the specified angels. This is used for the Background
  45. * node, but could be applied to other nodes with multiple faces as well.
  46. *
  47. * When used with the Background node, default is directionIsDown is true if
  48. * interpolating the skyColor down from the Zenith. When interpolationg up from
  49. * the Nadir i.e. interpolating the groundColor, the directionIsDown is false.
  50. *
  51. * The first angle is never specified, it is the Zenith (0 rad). Angles are specified
  52. * in radians. The geometry is thought a sphere, but could be anything. The color interpolation
  53. * is linear along the Y axis in any case.
  54. *
  55. * You must specify one more color than you have angles at the beginning of the colors array.
  56. * This is the color of the Zenith (the top of the shape).
  57. *
  58. * @param geometry
  59. * @param radius
  60. * @param angles
  61. * @param colors
  62. * @param boolean topDown Whether to work top down or bottom up.
  63. */
  64. function paintFaces( geometry, radius, angles, colors, topDown ) {
  65. var direction = ( topDown === true ) ? 1 : - 1;
  66. var coord = [], A = {}, B = {}, applyColor = false;
  67. for ( var k = 0; k < angles.length; k ++ ) {
  68. // push the vector at which the color changes
  69. var vec = {
  70. x: direction * ( Math.cos( angles[ k ] ) * radius ),
  71. y: direction * ( Math.sin( angles[ k ] ) * radius )
  72. };
  73. coord.push( vec );
  74. }
  75. var index = geometry.index;
  76. var positionAttribute = geometry.attributes.position;
  77. var colorAttribute = new THREE.BufferAttribute( new Float32Array( geometry.attributes.position.count * 3 ), 3 );
  78. var position = new THREE.Vector3();
  79. var color = new THREE.Color();
  80. for ( var i = 0; i < index.count; i ++ ) {
  81. var vertexIndex = index.getX( i );
  82. position.fromBufferAttribute( positionAttribute, vertexIndex );
  83. for ( var j = 0; j < colors.length; j ++ ) {
  84. // linear interpolation between aColor and bColor, calculate proportion
  85. // A is previous point (angle)
  86. if ( j === 0 ) {
  87. A.x = 0;
  88. A.y = ( topDown === true ) ? radius : - 1 * radius;
  89. } else {
  90. A.x = coord[ j - 1 ].x;
  91. A.y = coord[ j - 1 ].y;
  92. }
  93. // B is current point (angle)
  94. B = coord[ j ];
  95. if ( B !== undefined ) {
  96. // p has to be between the points A and B which we interpolate
  97. applyColor = ( topDown === true ) ? ( position.y <= A.y && position.y > B.y ) : ( position.y >= A.y && position.y < B.y );
  98. if ( applyColor === true ) {
  99. var aColor = colors[ j ];
  100. var bColor = colors[ j + 1 ];
  101. // below is simple linear interpolation
  102. var t = Math.abs( position.y - A.y ) / ( A.y - B.y );
  103. // to make it faster, you can only calculate this if the y coord changes, the color is the same for points with the same y
  104. color.copy( aColor ).lerp( bColor, t );
  105. colorAttribute.setXYZ( vertexIndex, color.r, color.g, color.b );
  106. } else {
  107. var colorIndex = ( topDown === true ) ? colors.length - 1 : 0;
  108. var c = colors[ colorIndex ];
  109. colorAttribute.setXYZ( vertexIndex, c.r, c.g, c.b );
  110. }
  111. }
  112. }
  113. }
  114. geometry.addAttribute( 'color', colorAttribute );
  115. }
  116. var index = [];
  117. function parseProperty( node, line ) {
  118. var parts = [], part, property = {}, fieldName;
  119. /**
  120. * Expression for matching relevant information, such as a name or value, but not the separators
  121. * @type {RegExp}
  122. */
  123. var regex = /[^\s,\[\]]+/g;
  124. var point;
  125. while ( null !== ( part = regex.exec( line ) ) ) {
  126. parts.push( part[ 0 ] );
  127. }
  128. fieldName = parts[ 0 ];
  129. // trigger several recorders
  130. switch ( fieldName ) {
  131. case 'skyAngle':
  132. case 'groundAngle':
  133. scope.recordingFieldname = fieldName;
  134. scope.isRecordingAngles = true;
  135. scope.angles = [];
  136. break;
  137. case 'color':
  138. case 'skyColor':
  139. case 'groundColor':
  140. scope.recordingFieldname = fieldName;
  141. scope.isRecordingColors = true;
  142. scope.colors = [];
  143. break;
  144. case 'point':
  145. case 'vector':
  146. scope.recordingFieldname = fieldName;
  147. scope.isRecordingPoints = true;
  148. scope.points = [];
  149. break;
  150. case 'colorIndex':
  151. case 'coordIndex':
  152. case 'normalIndex':
  153. case 'texCoordIndex':
  154. scope.recordingFieldname = fieldName;
  155. scope.isRecordingFaces = true;
  156. scope.indexes = [];
  157. break;
  158. }
  159. if ( scope.isRecordingFaces ) {
  160. // the parts hold the indexes as strings
  161. if ( parts.length > 0 ) {
  162. for ( var ind = 0; ind < parts.length; ind ++ ) {
  163. // the part should either be positive integer or -1
  164. if ( ! /(-?\d+)/.test( parts[ ind ] ) ) {
  165. continue;
  166. }
  167. // end of current face
  168. if ( parts[ ind ] === '-1' ) {
  169. if ( index.length > 0 ) {
  170. scope.indexes.push( index );
  171. }
  172. // start new one
  173. index = [];
  174. } else {
  175. index.push( parseInt( parts[ ind ] ) );
  176. }
  177. }
  178. }
  179. // end
  180. if ( /]/.exec( line ) ) {
  181. if ( index.length > 0 ) {
  182. scope.indexes.push( index );
  183. }
  184. // start new one
  185. index = [];
  186. scope.isRecordingFaces = false;
  187. node[ scope.recordingFieldname ] = scope.indexes;
  188. }
  189. } else if ( scope.isRecordingPoints ) {
  190. if ( node.nodeType == 'Coordinate' ) {
  191. while ( null !== ( parts = float3_pattern.exec( line ) ) ) {
  192. point = {
  193. x: parseFloat( parts[ 1 ] ),
  194. y: parseFloat( parts[ 2 ] ),
  195. z: parseFloat( parts[ 3 ] )
  196. };
  197. scope.points.push( point );
  198. }
  199. }
  200. if ( node.nodeType == 'Normal' ) {
  201. while ( null !== ( parts = float3_pattern.exec( line ) ) ) {
  202. point = {
  203. x: parseFloat( parts[ 1 ] ),
  204. y: parseFloat( parts[ 2 ] ),
  205. z: parseFloat( parts[ 3 ] )
  206. };
  207. scope.points.push( point );
  208. }
  209. }
  210. if ( node.nodeType == 'TextureCoordinate' ) {
  211. while ( null !== ( parts = float2_pattern.exec( line ) ) ) {
  212. point = {
  213. x: parseFloat( parts[ 1 ] ),
  214. y: parseFloat( parts[ 2 ] )
  215. };
  216. scope.points.push( point );
  217. }
  218. }
  219. // end
  220. if ( /]/.exec( line ) ) {
  221. scope.isRecordingPoints = false;
  222. node.points = scope.points;
  223. }
  224. } else if ( scope.isRecordingAngles ) {
  225. // the parts hold the angles as strings
  226. if ( parts.length > 0 ) {
  227. for ( var ind = 0; ind < parts.length; ind ++ ) {
  228. // the part should be a float
  229. if ( ! float_pattern.test( parts[ ind ] ) ) {
  230. continue;
  231. }
  232. scope.angles.push( parseFloat( parts[ ind ] ) );
  233. }
  234. }
  235. // end
  236. if ( /]/.exec( line ) ) {
  237. scope.isRecordingAngles = false;
  238. node[ scope.recordingFieldname ] = scope.angles;
  239. }
  240. } else if ( scope.isRecordingColors ) {
  241. while ( null !== ( parts = float3_pattern.exec( line ) ) ) {
  242. var color = {
  243. r: parseFloat( parts[ 1 ] ),
  244. g: parseFloat( parts[ 2 ] ),
  245. b: parseFloat( parts[ 3 ] )
  246. };
  247. scope.colors.push( color );
  248. }
  249. // end
  250. if ( /]/.exec( line ) ) {
  251. scope.isRecordingColors = false;
  252. node[ scope.recordingFieldname ] = scope.colors;
  253. }
  254. } else if ( parts[ parts.length - 1 ] !== 'NULL' && fieldName !== 'children' ) {
  255. switch ( fieldName ) {
  256. case 'diffuseColor':
  257. case 'emissiveColor':
  258. case 'specularColor':
  259. case 'color':
  260. if ( parts.length !== 4 ) {
  261. console.warn( 'THREE.VRMLLoader: Invalid color format detected for %s.', fieldName );
  262. break;
  263. }
  264. property = {
  265. r: parseFloat( parts[ 1 ] ),
  266. g: parseFloat( parts[ 2 ] ),
  267. b: parseFloat( parts[ 3 ] )
  268. };
  269. break;
  270. case 'location':
  271. case 'direction':
  272. case 'translation':
  273. case 'scale':
  274. case 'size':
  275. if ( parts.length !== 4 ) {
  276. console.warn( 'THREE.VRMLLoader: Invalid vector format detected for %s.', fieldName );
  277. break;
  278. }
  279. property = {
  280. x: parseFloat( parts[ 1 ] ),
  281. y: parseFloat( parts[ 2 ] ),
  282. z: parseFloat( parts[ 3 ] )
  283. };
  284. break;
  285. case 'intensity':
  286. case 'cutOffAngle':
  287. case 'radius':
  288. case 'topRadius':
  289. case 'bottomRadius':
  290. case 'height':
  291. case 'transparency':
  292. case 'shininess':
  293. case 'ambientIntensity':
  294. case 'creaseAngle':
  295. if ( parts.length !== 2 ) {
  296. console.warn( 'THREE.VRMLLoader: Invalid single float value specification detected for %s.', fieldName );
  297. break;
  298. }
  299. property = parseFloat( parts[ 1 ] );
  300. break;
  301. case 'rotation':
  302. if ( parts.length !== 5 ) {
  303. console.warn( 'THREE.VRMLLoader: Invalid quaternion format detected for %s.', fieldName );
  304. break;
  305. }
  306. property = {
  307. x: parseFloat( parts[ 1 ] ),
  308. y: parseFloat( parts[ 2 ] ),
  309. z: parseFloat( parts[ 3 ] ),
  310. w: parseFloat( parts[ 4 ] )
  311. };
  312. break;
  313. case 'on':
  314. case 'ccw':
  315. case 'solid':
  316. case 'colorPerVertex':
  317. case 'convex':
  318. if ( parts.length !== 2 ) {
  319. console.warn( 'THREE.VRMLLoader: Invalid format detected for %s.', fieldName );
  320. break;
  321. }
  322. property = parts[ 1 ] === 'TRUE' ? true : false;
  323. break;
  324. }
  325. node[ fieldName ] = property;
  326. }
  327. return property;
  328. }
  329. function getTree( lines ) {
  330. var tree = { 'string': 'Scene', children: [] };
  331. var current = tree;
  332. var matches;
  333. var specification;
  334. for ( var i = 0; i < lines.length; i ++ ) {
  335. var comment = '';
  336. var line = lines[ i ];
  337. // omit whitespace only lines
  338. if ( null !== ( /^\s+?$/g.exec( line ) ) ) {
  339. continue;
  340. }
  341. line = line.trim();
  342. // skip empty lines
  343. if ( line === '' ) {
  344. continue;
  345. }
  346. if ( /#/.exec( line ) ) {
  347. var parts = line.split( '#' );
  348. // discard everything after the #, it is a comment
  349. line = parts[ 0 ];
  350. // well, let's also keep the comment
  351. comment = parts[ 1 ];
  352. }
  353. if ( matches = /([^\s]*){1}(?:\s+)?{/.exec( line ) ) {
  354. // first subpattern should match the Node name
  355. var block = { 'nodeType': matches[ 1 ], 'string': line, 'parent': current, 'children': [], 'comment': comment };
  356. current.children.push( block );
  357. current = block;
  358. if ( /}/.exec( line ) ) {
  359. // example: geometry Box { size 1 1 1 } # all on the same line
  360. specification = /{(.*)}/.exec( line )[ 1 ];
  361. // todo: remove once new parsing is complete?
  362. block.children.push( specification );
  363. parseProperty( current, specification );
  364. current = current.parent;
  365. }
  366. } else if ( /}/.exec( line ) ) {
  367. current = current.parent;
  368. } else if ( line !== '' ) {
  369. parseProperty( current, line );
  370. // todo: remove once new parsing is complete? we still do not parse geometry and appearance the new way
  371. current.children.push( line );
  372. }
  373. }
  374. return tree;
  375. }
  376. function parseNode( data, parent ) {
  377. var object;
  378. if ( typeof data === 'string' ) {
  379. if ( /USE/.exec( data ) ) {
  380. var defineKey = /USE\s+?([^\s]+)/.exec( data )[ 1 ];
  381. if ( undefined == defines[ defineKey ] ) {
  382. console.warn( 'THREE.VRMLLoader: %s is not defined.', defineKey );
  383. } else {
  384. if ( /appearance/.exec( data ) && defineKey ) {
  385. parent.material = defines[ defineKey ].clone();
  386. } else if ( /geometry/.exec( data ) && defineKey ) {
  387. parent.geometry = defines[ defineKey ].clone();
  388. // the solid property is not cloned with clone(), is only needed for VRML loading, so we need to transfer it
  389. if ( undefined !== defines[ defineKey ].solid && defines[ defineKey ].solid === false ) {
  390. parent.geometry.solid = false;
  391. parent.material.side = THREE.DoubleSide;
  392. }
  393. } else if ( defineKey ) {
  394. object = defines[ defineKey ].clone();
  395. parent.add( object );
  396. }
  397. }
  398. }
  399. return;
  400. }
  401. object = parent;
  402. if ( data.string.indexOf( 'AmbientLight' ) > - 1 && data.nodeType === 'PointLight' ) {
  403. data.nodeType = 'AmbientLight';
  404. }
  405. var l_visible = data.on !== undefined ? data.on : true;
  406. var l_intensity = data.intensity !== undefined ? data.intensity : 1;
  407. var l_color = new THREE.Color();
  408. if ( data.color ) {
  409. l_color.copy( data.color );
  410. }
  411. if ( data.nodeType === 'AmbientLight' ) {
  412. object = new THREE.AmbientLight( l_color, l_intensity );
  413. object.visible = l_visible;
  414. parent.add( object );
  415. } else if ( data.nodeType === 'PointLight' ) {
  416. var l_distance = 0;
  417. if ( data.radius !== undefined && data.radius < 1000 ) {
  418. l_distance = data.radius;
  419. }
  420. object = new THREE.PointLight( l_color, l_intensity, l_distance );
  421. object.visible = l_visible;
  422. parent.add( object );
  423. } else if ( data.nodeType === 'SpotLight' ) {
  424. var l_intensity = 1;
  425. var l_distance = 0;
  426. var l_angle = Math.PI / 3;
  427. var l_penumbra = 0;
  428. var l_visible = true;
  429. if ( data.radius !== undefined && data.radius < 1000 ) {
  430. l_distance = data.radius;
  431. }
  432. if ( data.cutOffAngle !== undefined ) {
  433. l_angle = data.cutOffAngle;
  434. }
  435. object = new THREE.SpotLight( l_color, l_intensity, l_distance, l_angle, l_penumbra );
  436. object.visible = l_visible;
  437. parent.add( object );
  438. } else if ( data.nodeType === 'Transform' || data.nodeType === 'Group' ) {
  439. object = new THREE.Object3D();
  440. if ( /DEF/.exec( data.string ) ) {
  441. object.name = /DEF\s+([^\s]+)/.exec( data.string )[ 1 ];
  442. defines[ object.name ] = object;
  443. }
  444. if ( data.translation !== undefined ) {
  445. var t = data.translation;
  446. object.position.set( t.x, t.y, t.z );
  447. }
  448. if ( data.rotation !== undefined ) {
  449. var r = data.rotation;
  450. object.quaternion.setFromAxisAngle( new THREE.Vector3( r.x, r.y, r.z ), r.w );
  451. }
  452. if ( data.scale !== undefined ) {
  453. var s = data.scale;
  454. object.scale.set( s.x, s.y, s.z );
  455. }
  456. parent.add( object );
  457. } else if ( data.nodeType === 'Shape' ) {
  458. object = new THREE.Mesh();
  459. if ( /DEF/.exec( data.string ) ) {
  460. object.name = /DEF\s+([^\s]+)/.exec( data.string )[ 1 ];
  461. defines[ object.name ] = object;
  462. }
  463. parent.add( object );
  464. } else if ( data.nodeType === 'Background' ) {
  465. var segments = 20;
  466. // sky (full sphere):
  467. var radius = 2e4;
  468. var skyGeometry = new THREE.SphereBufferGeometry( radius, segments, segments );
  469. var skyMaterial = new THREE.MeshBasicMaterial( { fog: false, side: THREE.BackSide } );
  470. if ( data.skyColor.length > 1 ) {
  471. paintFaces( skyGeometry, radius, data.skyAngle, data.skyColor, true );
  472. skyMaterial.vertexColors = THREE.VertexColors;
  473. } else {
  474. var color = data.skyColor[ 0 ];
  475. skyMaterial.color.setRGB( color.r, color.b, color.g );
  476. }
  477. scene.add( new THREE.Mesh( skyGeometry, skyMaterial ) );
  478. // ground (half sphere):
  479. if ( data.groundColor !== undefined ) {
  480. radius = 1.2e4;
  481. var groundGeometry = new THREE.SphereBufferGeometry( radius, segments, segments, 0, 2 * Math.PI, 0.5 * Math.PI, 1.5 * Math.PI );
  482. var groundMaterial = new THREE.MeshBasicMaterial( { fog: false, side: THREE.BackSide, vertexColors: THREE.VertexColors } );
  483. paintFaces( groundGeometry, radius, data.groundAngle, data.groundColor, false );
  484. scene.add( new THREE.Mesh( groundGeometry, groundMaterial ) );
  485. }
  486. } else if ( /geometry/.exec( data.string ) ) {
  487. if ( data.nodeType === 'Box' ) {
  488. var s = data.size;
  489. parent.geometry = new THREE.BoxBufferGeometry( s.x, s.y, s.z );
  490. } else if ( data.nodeType === 'Cylinder' ) {
  491. parent.geometry = new THREE.CylinderBufferGeometry( data.radius, data.radius, data.height );
  492. } else if ( data.nodeType === 'Cone' ) {
  493. parent.geometry = new THREE.CylinderBufferGeometry( data.topRadius, data.bottomRadius, data.height );
  494. } else if ( data.nodeType === 'Sphere' ) {
  495. parent.geometry = new THREE.SphereBufferGeometry( data.radius );
  496. } else if ( data.nodeType === 'IndexedFaceSet' ) {
  497. var geometry = new THREE.BufferGeometry();
  498. var positions = [];
  499. var colors = [];
  500. var normals = [];
  501. var uvs = [];
  502. var position, color, normal, uv;
  503. var i, il, j, jl;
  504. for ( i = 0, il = data.children.length; i < il; i ++ ) {
  505. var child = data.children[ i ];
  506. // uvs
  507. if ( child.nodeType === 'TextureCoordinate' ) {
  508. if ( child.points ) {
  509. for ( j = 0, jl = child.points.length; j < jl; j ++ ) {
  510. uv = child.points[ j ];
  511. uvs.push( uv.x, uv.y );
  512. }
  513. }
  514. }
  515. // normals
  516. if ( child.nodeType === 'Normal' ) {
  517. if ( child.points ) {
  518. for ( j = 0, jl = child.points.length; j < jl; j ++ ) {
  519. normal = child.points[ j ];
  520. normals.push( normal.x, normal.y, normal.z );
  521. }
  522. }
  523. }
  524. // colors
  525. if ( child.nodeType === 'Color' ) {
  526. if ( child.color ) {
  527. for ( j = 0, jl = child.color.length; j < jl; j ++ ) {
  528. color = child.color[ j ];
  529. colors.push( color.r, color.g, color.b );
  530. }
  531. }
  532. }
  533. // positions
  534. if ( child.nodeType === 'Coordinate' ) {
  535. if ( child.points ) {
  536. for ( j = 0, jl = child.points.length; j < jl; j ++ ) {
  537. position = child.points[ j ];
  538. positions.push( position.x, position.y, position.z );
  539. }
  540. }
  541. if ( child.string.indexOf( 'DEF' ) > - 1 ) {
  542. var name = /DEF\s+([^\s]+)/.exec( child.string )[ 1 ];
  543. defines[ name ] = positions.slice( 0 );
  544. }
  545. if ( child.string.indexOf( 'USE' ) > - 1 ) {
  546. var defineKey = /USE\s+([^\s]+)/.exec( child.string )[ 1 ];
  547. positions = defines[ defineKey ];
  548. }
  549. }
  550. }
  551. // some shapes only have vertices for use in other shapes
  552. if ( data.coordIndex ) {
  553. function triangulateIndexArray( indexArray, ccw ) {
  554. if ( ccw === undefined ) {
  555. // ccw is true by default
  556. ccw = true;
  557. }
  558. var triangulatedIndexArray = [];
  559. var skip = 0;
  560. for ( i = 0, il = indexArray.length; i < il; i ++ ) {
  561. var indexedFace = indexArray[ i ];
  562. // VRML support multipoint indexed face sets (more then 3 vertices). You must calculate the composing triangles here
  563. skip = 0;
  564. while ( indexedFace.length >= 3 && skip < ( indexedFace.length - 2 ) ) {
  565. var i1 = indexedFace[ 0 ];
  566. var i2 = indexedFace[ skip + ( ccw ? 1 : 2 ) ];
  567. var i3 = indexedFace[ skip + ( ccw ? 2 : 1 ) ];
  568. triangulatedIndexArray.push( i1, i2, i3 );
  569. skip ++;
  570. }
  571. }
  572. return triangulatedIndexArray;
  573. }
  574. var positionIndexes = data.coordIndex ? triangulateIndexArray( data.coordIndex, data.ccw ) : [];
  575. var normalIndexes = data.normalIndex ? triangulateIndexArray( data.normalIndex, data.ccw ) : positionIndexes;
  576. var colorIndexes = data.colorIndex ? triangulateIndexArray( data.colorIndex, data.ccw ) : positionIndexes;
  577. var uvIndexes = data.texCoordIndex ? triangulateIndexArray( data.texCoordIndex, data.ccw ) : positionIndexes;
  578. var newIndexes = [];
  579. var newPositions = [];
  580. var newNormals = [];
  581. var newColors = [];
  582. var newUvs = [];
  583. // if any other index array does not match the coordinate indexes, split any points that differ
  584. var pointMap = Object.create( null );
  585. for ( i = 0; i < positionIndexes.length; i ++ ) {
  586. var pointAttributes = [];
  587. var positionIndex = positionIndexes[ i ];
  588. var normalIndex = normalIndexes[ i ];
  589. var colorIndex = colorIndexes[ i ];
  590. var uvIndex = uvIndexes[ i ];
  591. var base = 10; // which base to use to represent each value
  592. pointAttributes.push( positionIndex.toString( base ) );
  593. if ( normalIndex !== undefined ) {
  594. pointAttributes.push( normalIndex.toString( base ) );
  595. }
  596. if ( colorIndex !== undefined ) {
  597. pointAttributes.push( colorIndex.toString( base ) );
  598. }
  599. if ( uvIndex !== undefined ) {
  600. pointAttributes.push( uvIndex.toString( base ) );
  601. }
  602. var pointId = pointAttributes.join( ',' );
  603. var newIndex = pointMap[ pointId ];
  604. if ( newIndex === undefined ) {
  605. newIndex = newPositions.length / 3;
  606. pointMap[ pointId ] = newIndex;
  607. newPositions.push(
  608. positions[ positionIndex * 3 ],
  609. positions[ positionIndex * 3 + 1 ],
  610. positions[ positionIndex * 3 + 2 ]
  611. );
  612. if ( normalIndex !== undefined && normals.length > 0 ) {
  613. newNormals.push(
  614. normals[ normalIndex * 3 ],
  615. normals[ normalIndex * 3 + 1 ],
  616. normals[ normalIndex * 3 + 2 ]
  617. );
  618. }
  619. if ( colorIndex !== undefined && colors.length > 0 ) {
  620. newColors.push(
  621. colors[ colorIndex * 3 ],
  622. colors[ colorIndex * 3 + 1 ],
  623. colors[ colorIndex * 3 + 2 ]
  624. );
  625. }
  626. if ( uvIndex !== undefined && uvs.length > 0 ) {
  627. newUvs.push(
  628. uvs[ uvIndex * 2 ],
  629. uvs[ uvIndex * 2 + 1 ]
  630. );
  631. }
  632. }
  633. newIndexes.push( newIndex );
  634. }
  635. positions = newPositions;
  636. normals = newNormals;
  637. color = newColors;
  638. uvs = newUvs;
  639. geometry.setIndex( newIndexes );
  640. } else {
  641. // do not add dummy mesh to the scene
  642. parent.parent.remove( parent );
  643. }
  644. if ( false === data.solid ) {
  645. parent.material.side = THREE.DoubleSide;
  646. }
  647. // we need to store it on the geometry for use with defines
  648. geometry.solid = data.solid;
  649. geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) );
  650. if ( colors.length > 0 ) {
  651. geometry.addAttribute( 'color', new THREE.Float32BufferAttribute( colors, 3 ) );
  652. }
  653. if ( uvs.length > 0 ) {
  654. geometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( uvs, 2 ) );
  655. }
  656. if ( normals.length > 0 ) {
  657. geometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) );
  658. } else {
  659. // convert geometry to non-indexed to get sharp normals
  660. geometry = geometry.toNonIndexed();
  661. geometry.computeVertexNormals();
  662. }
  663. geometry.computeBoundingSphere();
  664. // see if it's a define
  665. if ( /DEF/.exec( data.string ) ) {
  666. geometry.name = /DEF ([^\s]+)/.exec( data.string )[ 1 ];
  667. defines[ geometry.name ] = geometry;
  668. }
  669. parent.geometry = geometry;
  670. }
  671. return;
  672. } else if ( /appearance/.exec( data.string ) ) {
  673. for ( var i = 0; i < data.children.length; i ++ ) {
  674. var child = data.children[ i ];
  675. if ( child.nodeType === 'Material' ) {
  676. var material = new THREE.MeshPhongMaterial();
  677. if ( child.diffuseColor !== undefined ) {
  678. var d = child.diffuseColor;
  679. material.color.setRGB( d.r, d.g, d.b );
  680. }
  681. if ( child.emissiveColor !== undefined ) {
  682. var e = child.emissiveColor;
  683. material.emissive.setRGB( e.r, e.g, e.b );
  684. }
  685. if ( child.specularColor !== undefined ) {
  686. var s = child.specularColor;
  687. material.specular.setRGB( s.r, s.g, s.b );
  688. }
  689. if ( child.transparency !== undefined ) {
  690. var t = child.transparency;
  691. // transparency is opposite of opacity
  692. material.opacity = Math.abs( 1 - t );
  693. material.transparent = true;
  694. }
  695. if ( /DEF/.exec( data.string ) ) {
  696. material.name = /DEF ([^\s]+)/.exec( data.string )[ 1 ];
  697. defines[ material.name ] = material;
  698. }
  699. parent.material = material;
  700. }
  701. if ( child.nodeType === 'ImageTexture' ) {
  702. var textureName = /"([^"]+)"/.exec( child.children[ 0 ] );
  703. if ( textureName ) {
  704. parent.material.name = textureName[ 1 ];
  705. parent.material.map = textureLoader.load( texturePath + textureName[ 1 ] );
  706. }
  707. }
  708. }
  709. return;
  710. }
  711. for ( var i = 0, l = data.children.length; i < l; i ++ ) {
  712. parseNode( data.children[ i ], object );
  713. }
  714. }
  715. parseNode( getTree( lines ), scene );
  716. }
  717. var scene = new THREE.Scene();
  718. var lines = data.split( '\n' );
  719. // some lines do not have breaks
  720. for ( var i = lines.length - 1; i > - 1; i -- ) {
  721. var line = lines[ i ];
  722. // The # symbol indicates that all subsequent text, until the end of the line is a comment,
  723. // and should be ignored. (see http://gun.teipir.gr/VRML-amgem/spec/part1/grammar.html)
  724. line = line.replace( /(#.*)/, '' );
  725. // split lines with {..{ or {..[ - some have both
  726. if ( /{.*[{\[]/.test( line ) ) {
  727. var parts = line.split( '{' ).join( '{\n' ).split( '\n' );
  728. parts.unshift( 1 );
  729. parts.unshift( i );
  730. lines.splice.apply( lines, parts );
  731. } else if ( /\].*}/.test( line ) ) {
  732. // split lines with ]..}
  733. var parts = line.split( ']' ).join( ']\n' ).split( '\n' );
  734. parts.unshift( 1 );
  735. parts.unshift( i );
  736. lines.splice.apply( lines, parts );
  737. }
  738. if ( /}.*}/.test( line ) ) {
  739. // split lines with }..}
  740. var parts = line.split( '}' ).join( '}\n' ).split( '\n' );
  741. parts.unshift( 1 );
  742. parts.unshift( i );
  743. lines.splice.apply( lines, parts );
  744. }
  745. if ( /^\b[^\s]+\b$/.test( line.trim() ) ) {
  746. // prevent lines with single words like "coord" or "geometry", see #12209
  747. lines[ i + 1 ] = line + ' ' + lines[ i + 1 ].trim();
  748. lines.splice( i, 1 );
  749. } else if ( ( line.indexOf( 'coord' ) > - 1 ) && ( line.indexOf( '[' ) < 0 ) && ( line.indexOf( '{' ) < 0 ) ) {
  750. // force the parser to create Coordinate node for empty coords
  751. // coord USE something -> coord USE something Coordinate {}
  752. lines[ i ] += ' Coordinate {}';
  753. }
  754. }
  755. var header = lines.shift();
  756. if ( /V1.0/.exec( header ) ) {
  757. console.warn( 'THREE.VRMLLoader: V1.0 not supported yet.' );
  758. } else if ( /V2.0/.exec( header ) ) {
  759. parseV2( lines, scene );
  760. }
  761. return scene;
  762. }
  763. };