VRMLLoader.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  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. load: function ( url, onLoad, onProgress, onError ) {
  21. var scope = this;
  22. var loader = new THREE.XHRLoader( this.manager );
  23. loader.setCrossOrigin( this.crossOrigin );
  24. loader.load( url, function ( text ) {
  25. onLoad( scope.parse( text ) );
  26. }, onProgress, onError );
  27. },
  28. setCrossOrigin: function ( value ) {
  29. this.crossOrigin = value;
  30. },
  31. parse: function ( data ) {
  32. var parseV1 = function ( lines, scene ) {
  33. console.warn( 'VRML V1.0 not supported yet' );
  34. };
  35. var parseV2 = function ( lines, scene ) {
  36. var defines = {};
  37. var float_pattern = /(\b|\-|\+)([\d\.e]+)/;
  38. var float3_pattern = /([\d\.\+\-e]+)\s+([\d\.\+\-e]+)\s+([\d\.\+\-e]+)/g;
  39. /**
  40. * Interpolates colors a and b following their relative distance
  41. * expressed by t.
  42. *
  43. * @param float a
  44. * @param float b
  45. * @param float t
  46. * @returns {Color}
  47. */
  48. var interpolateColors = function( a, b, t ) {
  49. var deltaR = a.r - b.r;
  50. var deltaG = a.g - b.g;
  51. var deltaB = a.b - b.b;
  52. var c = new THREE.Color();
  53. c.r = a.r - t * deltaR;
  54. c.g = a.g - t * deltaG;
  55. c.b = a.b - t * deltaB;
  56. return c;
  57. };
  58. /**
  59. * Vertically paints the faces interpolating between the
  60. * specified colors at the specified angels. This is used for the Background
  61. * node, but could be applied to other nodes with multiple faces as well.
  62. *
  63. * When used with the Background node, default is directionIsDown is true if
  64. * interpolating the skyColor down from the Zenith. When interpolationg up from
  65. * the Nadir i.e. interpolating the groundColor, the directionIsDown is false.
  66. *
  67. * The first angle is never specified, it is the Zenith (0 rad). Angles are specified
  68. * in radians. The geometry is thought a sphere, but could be anything. The color interpolation
  69. * is linear along the Y axis in any case.
  70. *
  71. * You must specify one more color than you have angles at the beginning of the colors array.
  72. * This is the color of the Zenith (the top of the shape).
  73. *
  74. * @param geometry
  75. * @param radius
  76. * @param angles
  77. * @param colors
  78. * @param boolean directionIsDown Whether to work bottom up or top down.
  79. */
  80. var paintFaces = function ( geometry, radius, angles, colors, directionIsDown ) {
  81. var f, n, p, vertexIndex, color;
  82. var direction = directionIsDown ? 1 : - 1;
  83. var faceIndices = [ 'a', 'b', 'c', 'd' ];
  84. var coord = [ ], aColor, bColor, t = 1, A = {}, B = {}, applyColor = false, colorIndex;
  85. for ( var k = 0; k < angles.length; k ++ ) {
  86. var vec = { };
  87. // push the vector at which the color changes
  88. vec.y = direction * ( Math.cos( angles[ k ] ) * radius );
  89. vec.x = direction * ( Math.sin( angles[ k ] ) * radius );
  90. coord.push( vec );
  91. }
  92. // painting the colors on the faces
  93. for ( var i = 0; i < geometry.faces.length ; i ++ ) {
  94. f = geometry.faces[ i ];
  95. n = ( f instanceof THREE.Face3 ) ? 3 : 4;
  96. for ( var j = 0; j < n; j ++ ) {
  97. vertexIndex = f[ faceIndices[ j ] ];
  98. p = geometry.vertices[ vertexIndex ];
  99. for ( var index = 0; index < colors.length; index ++ ) {
  100. // linear interpolation between aColor and bColor, calculate proportion
  101. // A is previous point (angle)
  102. if ( index === 0 ) {
  103. A.x = 0;
  104. A.y = directionIsDown ? radius : - 1 * radius;
  105. } else {
  106. A.x = coord[ index - 1 ].x;
  107. A.y = coord[ index - 1 ].y;
  108. }
  109. // B is current point (angle)
  110. B = coord[ index ];
  111. if ( undefined !== B ) {
  112. // p has to be between the points A and B which we interpolate
  113. applyColor = directionIsDown ? p.y <= A.y && p.y > B.y : p.y >= A.y && p.y < B.y;
  114. if ( applyColor ) {
  115. bColor = colors[ index + 1 ];
  116. aColor = colors[ index ];
  117. // below is simple linear interpolation
  118. t = Math.abs( p.y - A.y ) / ( A.y - B.y );
  119. // 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
  120. color = interpolateColors( aColor, bColor, t );
  121. f.vertexColors[ j ] = color;
  122. }
  123. } else if ( undefined === f.vertexColors[ j ] ) {
  124. colorIndex = directionIsDown ? colors.length - 1 : 0;
  125. f.vertexColors[ j ] = colors[ colorIndex ];
  126. }
  127. }
  128. }
  129. }
  130. };
  131. var parseProperty = function ( node, line ) {
  132. var parts = [], part, property = {}, fieldName;
  133. /**
  134. * Expression for matching relevant information, such as a name or value, but not the separators
  135. * @type {RegExp}
  136. */
  137. var regex = /[^\s,\[\]]+/g;
  138. var point, index, angles, colors;
  139. while ( null != ( part = regex.exec( line ) ) ) {
  140. parts.push( part[ 0 ] );
  141. }
  142. fieldName = parts[ 0 ];
  143. // trigger several recorders
  144. switch ( fieldName ) {
  145. case 'skyAngle':
  146. case 'groundAngle':
  147. this.recordingFieldname = fieldName;
  148. this.isRecordingAngles = true;
  149. this.angles = [];
  150. break;
  151. case 'skyColor':
  152. case 'groundColor':
  153. this.recordingFieldname = fieldName;
  154. this.isRecordingColors = true;
  155. this.colors = [];
  156. break;
  157. case 'point':
  158. this.recordingFieldname = fieldName;
  159. this.isRecordingPoints = true;
  160. this.points = [];
  161. break;
  162. case 'coordIndex':
  163. this.recordingFieldname = fieldName;
  164. this.isRecordingFaces = true;
  165. this.indexes = [];
  166. break;
  167. }
  168. if ( this.isRecordingFaces ) {
  169. // the parts hold the indexes as strings
  170. if ( parts.length > 0 ) {
  171. index = [];
  172. for ( var ind = 0; ind < parts.length; ind ++ ) {
  173. // the part should either be positive integer or -1
  174. if ( ! /(-?\d+)/.test( parts[ ind ] ) ) {
  175. continue;
  176. }
  177. // end of current face
  178. if ( parts[ ind ] === "-1" ) {
  179. if ( index.length > 0 ) {
  180. this.indexes.push( index );
  181. }
  182. // start new one
  183. index = [];
  184. } else {
  185. index.push( parseInt( parts[ ind ] ) );
  186. }
  187. }
  188. }
  189. // end
  190. if ( /]/.exec( line ) ) {
  191. this.isRecordingFaces = false;
  192. node.coordIndex = this.indexes;
  193. }
  194. } else if ( this.isRecordingPoints ) {
  195. while ( null !== ( parts = float3_pattern.exec( line ) ) ) {
  196. point = {
  197. x: parseFloat( parts[ 1 ] ),
  198. y: parseFloat( parts[ 2 ] ),
  199. z: parseFloat( parts[ 3 ] )
  200. };
  201. this.points.push( point );
  202. }
  203. // end
  204. if ( /]/.exec( line ) ) {
  205. this.isRecordingPoints = false;
  206. node.points = this.points;
  207. }
  208. } else if ( this.isRecordingAngles ) {
  209. // the parts hold the angles as strings
  210. if ( parts.length > 0 ) {
  211. for ( var ind = 0; ind < parts.length; ind ++ ) {
  212. // the part should be a float
  213. if ( ! float_pattern.test( parts[ ind ] ) ) {
  214. continue;
  215. }
  216. this.angles.push( parseFloat( parts[ ind ] ) );
  217. }
  218. }
  219. // end
  220. if ( /]/.exec( line ) ) {
  221. this.isRecordingAngles = false;
  222. node[ this.recordingFieldname ] = this.angles;
  223. }
  224. } else if ( this.isRecordingColors ) {
  225. while ( null !== ( parts = float3_pattern.exec( line ) ) ) {
  226. color = {
  227. r: parseFloat( parts[ 1 ] ),
  228. g: parseFloat( parts[ 2 ] ),
  229. b: parseFloat( parts[ 3 ] )
  230. };
  231. this.colors.push( color );
  232. }
  233. // end
  234. if ( /]/.exec( line ) ) {
  235. this.isRecordingColors = false;
  236. node[ this.recordingFieldname ] = this.colors;
  237. }
  238. } else if ( parts[ parts.length - 1 ] !== 'NULL' && fieldName !== 'children' ) {
  239. switch ( fieldName ) {
  240. case 'diffuseColor':
  241. case 'emissiveColor':
  242. case 'specularColor':
  243. case 'color':
  244. if ( parts.length != 4 ) {
  245. console.warn( 'Invalid color format detected for ' + fieldName );
  246. break;
  247. }
  248. property = {
  249. r: parseFloat( parts[ 1 ] ),
  250. g: parseFloat( parts[ 2 ] ),
  251. b: parseFloat( parts[ 3 ] )
  252. };
  253. break;
  254. case 'translation':
  255. case 'scale':
  256. case 'size':
  257. if ( parts.length != 4 ) {
  258. console.warn( 'Invalid vector format detected for ' + fieldName );
  259. break;
  260. }
  261. property = {
  262. x: parseFloat( parts[ 1 ] ),
  263. y: parseFloat( parts[ 2 ] ),
  264. z: parseFloat( parts[ 3 ] )
  265. };
  266. break;
  267. case 'radius':
  268. case 'topRadius':
  269. case 'bottomRadius':
  270. case 'height':
  271. case 'transparency':
  272. case 'shininess':
  273. case 'ambientIntensity':
  274. if ( parts.length != 2 ) {
  275. console.warn( 'Invalid single float value specification detected for ' + fieldName );
  276. break;
  277. }
  278. property = parseFloat( parts[ 1 ] );
  279. break;
  280. case 'rotation':
  281. if ( parts.length != 5 ) {
  282. console.warn( 'Invalid quaternion format detected for ' + fieldName );
  283. break;
  284. }
  285. property = {
  286. x: parseFloat( parts[ 1 ] ),
  287. y: parseFloat( parts[ 2 ] ),
  288. z: parseFloat( parts[ 3 ] ),
  289. w: parseFloat( parts[ 4 ] )
  290. };
  291. break;
  292. case 'ccw':
  293. case 'solid':
  294. case 'colorPerVertex':
  295. case 'convex':
  296. if ( parts.length != 2 ) {
  297. console.warn( 'Invalid format detected for ' + fieldName );
  298. break;
  299. }
  300. property = parts[ 1 ] === 'TRUE' ? true : false;
  301. break;
  302. }
  303. node[ fieldName ] = property;
  304. }
  305. return property;
  306. };
  307. var getTree = function ( lines ) {
  308. var tree = { 'string': 'Scene', children: [] };
  309. var current = tree;
  310. var matches;
  311. var specification;
  312. for ( var i = 0; i < lines.length; i ++ ) {
  313. var comment = '';
  314. var line = lines[ i ];
  315. // omit whitespace only lines
  316. if ( null !== ( result = /^\s+?$/g.exec( line ) ) ) {
  317. continue;
  318. }
  319. line = line.trim();
  320. // skip empty lines
  321. if ( line === '' ) {
  322. continue;
  323. }
  324. if ( /#/.exec( line ) ) {
  325. var parts = line.split( '#' );
  326. // discard everything after the #, it is a comment
  327. line = parts[ 0 ];
  328. // well, let's also keep the comment
  329. comment = parts[ 1 ];
  330. }
  331. if ( matches = /([^\s]*){1}\s?{/.exec( line ) ) {
  332. // first subpattern should match the Node name
  333. var block = { 'nodeType' : matches[ 1 ], 'string': line, 'parent': current, 'children': [], 'comment' : comment };
  334. current.children.push( block );
  335. current = block;
  336. if ( /}/.exec( line ) ) {
  337. // example: geometry Box { size 1 1 1 } # all on the same line
  338. specification = /{(.*)}/.exec( line )[ 1 ];
  339. // todo: remove once new parsing is complete?
  340. block.children.push( specification );
  341. parseProperty( current, specification );
  342. current = current.parent;
  343. }
  344. } else if ( /}/.exec( line ) ) {
  345. current = current.parent;
  346. } else if ( line !== '' ) {
  347. parseProperty( current, line );
  348. // todo: remove once new parsing is complete? we still do not parse geometry and appearance the new way
  349. current.children.push( line );
  350. }
  351. }
  352. return tree;
  353. };
  354. var parseNode = function ( data, parent ) {
  355. // console.log( data );
  356. if ( typeof data === 'string' ) {
  357. if ( /USE/.exec( data ) ) {
  358. var defineKey = /USE\s+?(\w+)/.exec( data )[ 1 ];
  359. if ( undefined == defines[ defineKey ] ) {
  360. console.warn( defineKey + ' is not defined.' );
  361. } else {
  362. if ( /appearance/.exec( data ) && defineKey ) {
  363. parent.material = defines[ defineKey ].clone();
  364. } else if ( /geometry/.exec( data ) && defineKey ) {
  365. parent.geometry = defines[ defineKey ].clone();
  366. // the solid property is not cloned with clone(), is only needed for VRML loading, so we need to transfer it
  367. if ( undefined !== defines[ defineKey ].solid && defines[ defineKey ].solid === false ) {
  368. parent.geometry.solid = false;
  369. parent.material.side = THREE.DoubleSide;
  370. }
  371. } else if ( defineKey ) {
  372. var object = defines[ defineKey ].clone();
  373. parent.add( object );
  374. }
  375. }
  376. }
  377. return;
  378. }
  379. var object = parent;
  380. if ( 'Transform' === data.nodeType || 'Group' === data.nodeType ) {
  381. object = new THREE.Object3D();
  382. if ( /DEF/.exec( data.string ) ) {
  383. object.name = /DEF\s+(\w+)/.exec( data.string )[ 1 ];
  384. defines[ object.name ] = object;
  385. }
  386. if ( undefined !== data[ 'translation' ] ) {
  387. var t = data.translation;
  388. object.position.set( t.x, t.y, t.z );
  389. }
  390. if ( undefined !== data.rotation ) {
  391. var r = data.rotation;
  392. object.quaternion.setFromAxisAngle( new THREE.Vector3( r.x, r.y, r.z ), r.w );
  393. }
  394. if ( undefined !== data.scale ) {
  395. var s = data.scale;
  396. object.scale.set( s.x, s.y, s.z );
  397. }
  398. parent.add( object );
  399. } else if ( 'Shape' === data.nodeType ) {
  400. object = new THREE.Mesh();
  401. if ( /DEF/.exec( data.string ) ) {
  402. object.name = /DEF (\w+)/.exec( data.string )[ 1 ];
  403. defines[ object.name ] = object;
  404. }
  405. parent.add( object );
  406. } else if ( 'Background' === data.nodeType ) {
  407. var segments = 20;
  408. // sky (full sphere):
  409. var radius = 2e4;
  410. var skyGeometry = new THREE.SphereGeometry( radius, segments, segments );
  411. var skyMaterial = new THREE.MeshBasicMaterial( { fog: false, side: THREE.BackSide } );
  412. if ( data.skyColor.length > 1 ) {
  413. paintFaces( skyGeometry, radius, data.skyAngle, data.skyColor, true );
  414. skyMaterial.vertexColors = THREE.VertexColors
  415. } else {
  416. var color = data.skyColor[ 0 ];
  417. skyMaterial.color.setRGB( color.r, color.b, color.g );
  418. }
  419. scene.add( new THREE.Mesh( skyGeometry, skyMaterial ) );
  420. // ground (half sphere):
  421. if ( data.groundColor !== undefined ) {
  422. radius = 1.2e4;
  423. var groundGeometry = new THREE.SphereGeometry( radius, segments, segments, 0, 2 * Math.PI, 0.5 * Math.PI, 1.5 * Math.PI );
  424. var groundMaterial = new THREE.MeshBasicMaterial( { fog: false, side: THREE.BackSide, vertexColors: THREE.VertexColors } );
  425. paintFaces( groundGeometry, radius, data.groundAngle, data.groundColor, false );
  426. scene.add( new THREE.Mesh( groundGeometry, groundMaterial ) );
  427. }
  428. } else if ( /geometry/.exec( data.string ) ) {
  429. if ( 'Box' === data.nodeType ) {
  430. var s = data.size;
  431. parent.geometry = new THREE.BoxGeometry( s.x, s.y, s.z );
  432. } else if ( 'Cylinder' === data.nodeType ) {
  433. parent.geometry = new THREE.CylinderGeometry( data.radius, data.radius, data.height );
  434. } else if ( 'Cone' === data.nodeType ) {
  435. parent.geometry = new THREE.CylinderGeometry( data.topRadius, data.bottomRadius, data.height );
  436. } else if ( 'Sphere' === data.nodeType ) {
  437. parent.geometry = new THREE.SphereGeometry( data.radius );
  438. } else if ( 'IndexedFaceSet' === data.nodeType ) {
  439. var geometry = new THREE.Geometry();
  440. var indexes;
  441. for ( var i = 0, j = data.children.length; i < j; i ++ ) {
  442. var child = data.children[ i ];
  443. var vec;
  444. if ( 'Coordinate' === child.nodeType ) {
  445. for ( var k = 0, l = child.points.length; k < l; k ++ ) {
  446. var point = child.points[ k ];
  447. vec = new THREE.Vector3( point.x, point.y, point.z );
  448. geometry.vertices.push( vec );
  449. }
  450. break;
  451. }
  452. }
  453. var skip = 0;
  454. // read this: http://math.hws.edu/eck/cs424/notes2013/16_Threejs_Advanced.html
  455. for ( var i = 0, j = data.coordIndex.length; i < j; i ++ ) {
  456. indexes = data.coordIndex[ i ];
  457. // vrml support multipoint indexed face sets (more then 3 vertices). You must calculate the composing triangles here
  458. skip = 0;
  459. // todo: this is the time to check if the faces are ordered ccw or not (cw)
  460. // Face3 only works with triangles, but IndexedFaceSet allows shapes with more then three vertices, build them of triangles
  461. while ( indexes.length >= 3 && skip < ( indexes.length - 2 ) ) {
  462. var face = new THREE.Face3(
  463. indexes[ 0 ],
  464. indexes[ skip + 1 ],
  465. indexes[ skip + 2 ],
  466. null // normal, will be added later
  467. // todo: pass in the color, if a color index is present
  468. );
  469. skip ++;
  470. geometry.faces.push( face );
  471. }
  472. }
  473. if ( false === data.solid ) {
  474. parent.material.side = THREE.DoubleSide;
  475. }
  476. // we need to store it on the geometry for use with defines
  477. geometry.solid = data.solid;
  478. geometry.computeFaceNormals();
  479. //geometry.computeVertexNormals(); // does not show
  480. geometry.computeBoundingSphere();
  481. // see if it's a define
  482. if ( /DEF/.exec( data.string ) ) {
  483. geometry.name = /DEF (\w+)/.exec( data.string )[ 1 ];
  484. defines[ geometry.name ] = geometry;
  485. }
  486. parent.geometry = geometry;
  487. }
  488. return;
  489. } else if ( /appearance/.exec( data.string ) ) {
  490. for ( var i = 0; i < data.children.length; i ++ ) {
  491. var child = data.children[ i ];
  492. if ( 'Material' === child.nodeType ) {
  493. var material = new THREE.MeshPhongMaterial();
  494. if ( undefined !== child.diffuseColor ) {
  495. var d = child.diffuseColor;
  496. material.color.setRGB( d.r, d.g, d.b );
  497. }
  498. if ( undefined !== child.emissiveColor ) {
  499. var e = child.emissiveColor;
  500. material.emissive.setRGB( e.r, e.g, e.b );
  501. }
  502. if ( undefined !== child.specularColor ) {
  503. var s = child.specularColor;
  504. material.specular.setRGB( s.r, s.g, s.b );
  505. }
  506. if ( undefined !== child.transparency ) {
  507. var t = child.transparency;
  508. // transparency is opposite of opacity
  509. material.opacity = Math.abs( 1 - t );
  510. material.transparent = true;
  511. }
  512. if ( /DEF/.exec( data.string ) ) {
  513. material.name = /DEF (\w+)/.exec( data.string )[ 1 ];
  514. defines[ material.name ] = material;
  515. }
  516. parent.material = material;
  517. // material found, stop looping
  518. break;
  519. }
  520. }
  521. return;
  522. }
  523. for ( var i = 0, l = data.children.length; i < l; i ++ ) {
  524. var child = data.children[ i ];
  525. parseNode( data.children[ i ], object );
  526. }
  527. };
  528. parseNode( getTree( lines ), scene );
  529. };
  530. var scene = new THREE.Scene();
  531. var lines = data.split( '\n' );
  532. var header = lines.shift();
  533. if ( /V1.0/.exec( header ) ) {
  534. parseV1( lines, scene );
  535. } else if ( /V2.0/.exec( header ) ) {
  536. parseV2( lines, scene );
  537. }
  538. return scene;
  539. }
  540. };