VRMLLoader.js 29 KB

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