VRMLLoader.js 28 KB

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