VRMLLoader.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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 ) ) { // first subpattern should match the Node name
  332. var block = { 'nodeType' : matches[1], 'string': line, 'parent': current, 'children': [],'comment' : comment };
  333. current.children.push( block );
  334. current = block;
  335. if ( /}/.exec( line ) ) {
  336. // example: geometry Box { size 1 1 1 } # all on the same line
  337. specification = /{(.*)}/.exec( line )[ 1 ];
  338. // todo: remove once new parsing is complete?
  339. block.children.push( specification );
  340. parseProperty(current, specification);
  341. current = current.parent;
  342. }
  343. } else if ( /}/.exec( line ) ) {
  344. current = current.parent;
  345. } else if ( line !== '' ) {
  346. parseProperty(current, line);
  347. // todo: remove once new parsing is complete? we still do not parse geometry and appearance the new way
  348. current.children.push( line );
  349. }
  350. }
  351. return tree;
  352. };
  353. var parseNode = function ( data, parent ) {
  354. // console.log( data );
  355. if ( typeof data === 'string' ) {
  356. if ( /USE/.exec( data ) ) {
  357. var defineKey = /USE\s+?(\w+)/.exec( data )[ 1 ];
  358. if (undefined == defines[defineKey]) {
  359. console.warn(defineKey + ' is not defined.');
  360. } else {
  361. if ( /appearance/.exec( data ) && defineKey ) {
  362. parent.material = defines[ defineKey ].clone();
  363. } else if ( /geometry/.exec( data ) && defineKey ) {
  364. parent.geometry = defines[ defineKey ].clone();
  365. // the solid property is not cloned with clone(), is only needed for VRML loading, so we need to transfer it
  366. if (undefined !== defines[ defineKey ].solid && defines[ defineKey ].solid === false) {
  367. parent.geometry.solid = false;
  368. parent.material.side = THREE.DoubleSide;
  369. }
  370. } else if (defineKey) {
  371. var object = defines[ defineKey ].clone();
  372. parent.add( object );
  373. }
  374. }
  375. }
  376. return;
  377. }
  378. var object = parent;
  379. if ( 'Transform' === data.nodeType || 'Group' === data.nodeType ) {
  380. object = new THREE.Object3D();
  381. if ( /DEF/.exec( data.string ) ) {
  382. object.name = /DEF\s+(\w+)/.exec( data.string )[ 1 ];
  383. defines[ object.name ] = object;
  384. }
  385. if ( undefined !== data['translation'] ) {
  386. var t = data.translation;
  387. object.position.set(t.x, t.y, t.z);
  388. }
  389. if ( undefined !== data.rotation ) {
  390. var r = data.rotation;
  391. object.quaternion.setFromAxisAngle( new THREE.Vector3( r.x, r.y, r.z ), r.w );
  392. }
  393. if ( undefined !== data.scale ) {
  394. var s = data.scale;
  395. object.scale.set( s.x, s.y, s.z );
  396. }
  397. parent.add( object );
  398. } else if ( 'Shape' === data.nodeType ) {
  399. object = new THREE.Mesh();
  400. if ( /DEF/.exec( data.string ) ) {
  401. object.name = /DEF (\w+)/.exec( data.string )[ 1 ];
  402. defines[ object.name ] = object;
  403. }
  404. parent.add( object );
  405. } else if ( 'Background' === data.nodeType ) {
  406. var segments = 20;
  407. // sky (full sphere):
  408. var radius = 2e4;
  409. var skyGeometry = new THREE.SphereGeometry( radius, segments, segments );
  410. var skyMaterial = new THREE.MeshBasicMaterial( { fog: false, side: THREE.BackSide } );
  411. if ( data.skyColor.length > 1 ) {
  412. paintFaces( skyGeometry, radius, data.skyAngle, data.skyColor, true );
  413. skyMaterial.vertexColors = THREE.VertexColors
  414. } else {
  415. var color = data.skyColor[ 0 ];
  416. skyMaterial.color.setRGB( color.r, color.b, color.g );
  417. }
  418. scene.add( new THREE.Mesh( skyGeometry, skyMaterial ) );
  419. // ground (half sphere):
  420. if ( data.groundColor !== undefined ) {
  421. radius = 1.2e4;
  422. var groundGeometry = new THREE.SphereGeometry( radius, segments, segments, 0, 2 * Math.PI, 0.5 * Math.PI, 1.5 * Math.PI );
  423. var groundMaterial = new THREE.MeshBasicMaterial( { fog: false, side: THREE.BackSide, vertexColors: THREE.VertexColors } );
  424. paintFaces( groundGeometry, radius, data.groundAngle, data.groundColor, false );
  425. scene.add( new THREE.Mesh( groundGeometry, groundMaterial ) );
  426. }
  427. } else if ( /geometry/.exec( data.string ) ) {
  428. if ( 'Box' === data.nodeType ) {
  429. var s = data.size;
  430. parent.geometry = new THREE.BoxGeometry( s.x, s.y, s.z );
  431. } else if ( 'Cylinder' === data.nodeType ) {
  432. parent.geometry = new THREE.CylinderGeometry( data.radius, data.radius, data.height );
  433. } else if ( 'Cone' === data.nodeType ) {
  434. parent.geometry = new THREE.CylinderGeometry( data.topRadius, data.bottomRadius, data.height );
  435. } else if ( 'Sphere' === data.nodeType ) {
  436. parent.geometry = new THREE.SphereGeometry( data.radius );
  437. } else if ( 'IndexedFaceSet' === data.nodeType ) {
  438. var geometry = new THREE.Geometry();
  439. var indexes;
  440. for ( var i = 0, j = data.children.length; i < j; i ++ ) {
  441. var child = data.children[ i ];
  442. var vec;
  443. if ( 'Coordinate' === child.nodeType ) {
  444. for ( var k = 0, l = child.points.length; k < l; k ++ ) {
  445. var point = child.points[ k ];
  446. vec = new THREE.Vector3( point.x, point.y, point.z );
  447. geometry.vertices.push( vec );
  448. }
  449. break;
  450. }
  451. }
  452. var skip = 0;
  453. // read this: http://math.hws.edu/eck/cs424/notes2013/16_Threejs_Advanced.html
  454. for ( var i = 0, j = data.coordIndex.length; i < j; i ++ ) {
  455. indexes = data.coordIndex[i];
  456. // vrml support multipoint indexed face sets (more then 3 vertices). You must calculate the composing triangles here
  457. skip = 0;
  458. // todo: this is the time to check if the faces are ordered ccw or not (cw)
  459. // Face3 only works with triangles, but IndexedFaceSet allows shapes with more then three vertices, build them of triangles
  460. while ( indexes.length >= 3 && skip < ( indexes.length - 2 ) ) {
  461. var face = new THREE.Face3(
  462. indexes[0],
  463. indexes[skip + 1],
  464. indexes[skip + 2],
  465. null // normal, will be added later
  466. // todo: pass in the color, if a color index is present
  467. );
  468. skip ++;
  469. geometry.faces.push( face );
  470. }
  471. }
  472. if ( false === data.solid ) {
  473. parent.material.side = THREE.DoubleSide;
  474. }
  475. // we need to store it on the geometry for use with defines
  476. geometry.solid = data.solid;
  477. geometry.computeFaceNormals();
  478. //geometry.computeVertexNormals(); // does not show
  479. geometry.computeBoundingSphere();
  480. // see if it's a define
  481. if ( /DEF/.exec( data.string ) ) {
  482. geometry.name = /DEF (\w+)/.exec( data.string )[ 1 ];
  483. defines[ geometry.name ] = geometry;
  484. }
  485. parent.geometry = geometry;
  486. }
  487. return;
  488. } else if ( /appearance/.exec( data.string ) ) {
  489. for ( var i = 0; i < data.children.length; i ++ ) {
  490. var child = data.children[ i ];
  491. if ( 'Material' === child.nodeType ) {
  492. var material = new THREE.MeshPhongMaterial();
  493. if ( undefined !== child.diffuseColor ) {
  494. var d = child.diffuseColor;
  495. material.color.setRGB( d.r, d.g, d.b );
  496. }
  497. if ( undefined !== child.emissiveColor ) {
  498. var e = child.emissiveColor;
  499. material.emissive.setRGB( e.r, e.g, e.b );
  500. }
  501. if ( undefined !== child.specularColor ) {
  502. var s = child.specularColor;
  503. material.specular.setRGB( s.r, s.g, s.b );
  504. }
  505. if ( undefined !== child.transparency ) {
  506. var t = child.transparency;
  507. // transparency is opposite of opacity
  508. material.opacity = Math.abs( 1 - t );
  509. material.transparent = true;
  510. }
  511. if ( /DEF/.exec( data.string ) ) {
  512. material.name = /DEF (\w+)/.exec( data.string )[ 1 ];
  513. defines[ material.name ] = material;
  514. }
  515. parent.material = material;
  516. // material found, stop looping
  517. break;
  518. }
  519. }
  520. return;
  521. }
  522. for ( var i = 0, l = data.children.length; i < l; i ++ ) {
  523. var child = data.children[ i ];
  524. parseNode( data.children[ i ], object );
  525. }
  526. };
  527. parseNode( getTree( lines ), scene );
  528. };
  529. var scene = new THREE.Scene();
  530. var lines = data.split( '\n' );
  531. var header = lines.shift();
  532. if ( /V1.0/.exec( header ) ) {
  533. parseV1( lines, scene );
  534. } else if ( /V2.0/.exec( header ) ) {
  535. parseV2( lines, scene );
  536. }
  537. return scene;
  538. }
  539. };