VRMLLoader.js 19 KB

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