VRMLLoader.js 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124
  1. /**
  2. * @author Mugen87 / https://github.com/Mugen87
  3. */
  4. /* global chevrotain */
  5. THREE.VRMLLoader = ( function () {
  6. // dependency check
  7. if ( typeof chevrotain === 'undefined' ) {
  8. throw Error( 'THREE.VRMLLoader: External library chevrotain.min.js required.' );
  9. }
  10. // class definitions
  11. function VRMLLoader( manager ) {
  12. THREE.Loader.call( this, manager );
  13. }
  14. VRMLLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  15. constructor: VRMLLoader,
  16. load: function ( url, onLoad, onProgress, onError ) {
  17. var scope = this;
  18. var path = ( scope.path === '' ) ? THREE.LoaderUtils.extractUrlBase( url ) : scope.path;
  19. var loader = new THREE.FileLoader( this.manager );
  20. loader.setPath( scope.path );
  21. loader.load( url, function ( text ) {
  22. onLoad( scope.parse( text, path ) );
  23. }, onProgress, onError );
  24. },
  25. parse: function ( data, path ) {
  26. var nodeMap = {};
  27. function generateVRMLTree( data ) {
  28. // create lexer, parser and visitor
  29. var tokenData = createTokens();
  30. var lexer = new VRMLLexer( tokenData.tokens );
  31. var parser = new VRMLParser( tokenData.tokenVocabulary );
  32. var visitor = createVisitor( parser.getBaseCstVisitorConstructor() );
  33. // lexing
  34. var lexingResult = lexer.lex( data );
  35. parser.input = lexingResult.tokens;
  36. // parsing
  37. var cstOutput = parser.vrml();
  38. if ( parser.errors.length > 0 ) {
  39. console.error( parser.errors );
  40. throw Error( 'THREE.VRMLLoader: Parsing errors detected.' );
  41. }
  42. // actions
  43. var ast = visitor.visit( cstOutput );
  44. return ast;
  45. }
  46. function createTokens() {
  47. var createToken = chevrotain.createToken;
  48. // from http://gun.teipir.gr/VRML-amgem/spec/part1/concepts.html#SyntaxBasics
  49. var RouteIdentifier = createToken( { name: 'RouteIdentifier', pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*[\.][^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/ } );
  50. var Identifier = createToken( { name: 'Identifier', pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/, longer_alt: RouteIdentifier } );
  51. // from http://gun.teipir.gr/VRML-amgem/spec/part1/nodesRef.html
  52. var nodeTypes = [
  53. 'Anchor', 'Billboard', 'Collision', 'Group', 'Transform', // grouping nodes
  54. 'Inline', 'LOD', 'Switch', // special groups
  55. 'AudioClip', 'DirectionalLight', 'PointLight', 'Script', 'Shape', 'Sound', 'SpotLight', 'WorldInfo', // common nodes
  56. 'CylinderSensor', 'PlaneSensor', 'ProximitySensor', 'SphereSensor', 'TimeSensor', 'TouchSensor', 'VisibilitySensor', // sensors
  57. 'Box', 'Cone', 'Cylinder', 'ElevationGrid', 'Extrusion', 'IndexedFaceSet', 'IndexedLineSet', 'PointSet', 'Sphere', // geometries
  58. 'Color', 'Coordinate', 'Normal', 'TextureCoordinate', // geometric properties
  59. 'Appearance', 'FontStyle', 'ImageTexture', 'Material', 'MovieTexture', 'PixelTexture', 'TextureTransform', // appearance
  60. 'ColorInterpolator', 'CoordinateInterpolator', 'NormalInterpolator', 'OrientationInterpolator', 'PositionInterpolator', 'ScalarInterpolator', // interpolators
  61. 'Background', 'Fog', 'NavigationInfo', 'Viewpoint', // bindable nodes
  62. 'Text' // Text must be placed at the end of the regex so there are no matches for TextureTransform and TextureCoordinate
  63. ];
  64. //
  65. var Version = createToken( {
  66. name: 'Version',
  67. pattern: /#VRML.*/,
  68. longer_alt: Identifier
  69. } );
  70. var NodeName = createToken( {
  71. name: 'NodeName',
  72. pattern: new RegExp( nodeTypes.join( '|' ) ),
  73. longer_alt: Identifier
  74. } );
  75. var DEF = createToken( {
  76. name: 'DEF',
  77. pattern: /DEF/,
  78. longer_alt: Identifier
  79. } );
  80. var USE = createToken( {
  81. name: 'USE',
  82. pattern: /USE/,
  83. longer_alt: Identifier
  84. } );
  85. var ROUTE = createToken( {
  86. name: 'ROUTE',
  87. pattern: /ROUTE/,
  88. longer_alt: Identifier
  89. } );
  90. var TO = createToken( {
  91. name: 'TO',
  92. pattern: /TO/,
  93. longer_alt: Identifier
  94. } );
  95. //
  96. var StringLiteral = createToken( { name: "StringLiteral", pattern: /"(:?[^\\"\n\r]+|\\(:?[bfnrtv"\\/]|u[0-9a-fA-F]{4}))*"/ } );
  97. var HexLiteral = createToken( { name: 'HexLiteral', pattern: /0[xX][0-9a-fA-F]+/ } );
  98. var NumberLiteral = createToken( { name: 'NumberLiteral', pattern: /[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/ } );
  99. var TrueLiteral = createToken( { name: 'TrueLiteral', pattern: /TRUE/ } );
  100. var FalseLiteral = createToken( { name: 'FalseLiteral', pattern: /FALSE/ } );
  101. var NullLiteral = createToken( { name: 'NullLiteral', pattern: /NULL/ } );
  102. var LSquare = createToken( { name: 'LSquare', pattern: /\[/ } );
  103. var RSquare = createToken( { name: 'RSquare', pattern: /]/ } );
  104. var LCurly = createToken( { name: 'LCurly', pattern: /{/ } );
  105. var RCurly = createToken( { name: 'RCurly', pattern: /}/ } );
  106. var Comment = createToken( {
  107. name: 'Comment',
  108. pattern: /#.*/,
  109. group: chevrotain.Lexer.SKIPPED
  110. } );
  111. // commas, blanks, tabs, newlines and carriage returns are whitespace characters wherever they appear outside of string fields
  112. var WhiteSpace = createToken( {
  113. name: 'WhiteSpace',
  114. pattern: /[ ,\s]/,
  115. group: chevrotain.Lexer.SKIPPED
  116. } );
  117. var tokens = [
  118. WhiteSpace,
  119. // keywords appear before the Identifier
  120. NodeName,
  121. DEF,
  122. USE,
  123. ROUTE,
  124. TO,
  125. TrueLiteral,
  126. FalseLiteral,
  127. NullLiteral,
  128. // the Identifier must appear after the keywords because all keywords are valid identifiers
  129. Version,
  130. Identifier,
  131. RouteIdentifier,
  132. StringLiteral,
  133. HexLiteral,
  134. NumberLiteral,
  135. LSquare,
  136. RSquare,
  137. LCurly,
  138. RCurly,
  139. Comment
  140. ];
  141. var tokenVocabulary = {};
  142. for ( var i = 0, l = tokens.length; i < l; i ++ ) {
  143. var token = tokens[ i ];
  144. tokenVocabulary[ token.name ] = token;
  145. }
  146. return { tokens: tokens, tokenVocabulary: tokenVocabulary };
  147. }
  148. function createVisitor( BaseVRMLVisitor ) {
  149. // the visitor is created dynmaically based on the given base class
  150. function VRMLToASTVisitor() {
  151. BaseVRMLVisitor.call( this );
  152. this.validateVisitor();
  153. }
  154. VRMLToASTVisitor.prototype = Object.assign( Object.create( BaseVRMLVisitor.prototype ), {
  155. constructor: VRMLToASTVisitor,
  156. vrml: function ( ctx ) {
  157. var data = {
  158. version: this.visit( ctx.version ),
  159. nodes: [],
  160. routes: []
  161. };
  162. for ( var i = 0, l = ctx.node.length; i < l; i ++ ) {
  163. var node = ctx.node[ i ];
  164. data.nodes.push( this.visit( node ) );
  165. }
  166. if ( ctx.route ) {
  167. for ( var i = 0, l = ctx.route.length; i < l; i ++ ) {
  168. var route = ctx.route[ i ];
  169. data.routes.push( this.visit( route ) );
  170. }
  171. }
  172. return data;
  173. },
  174. version: function ( ctx ) {
  175. return ctx.Version[ 0 ].image;
  176. },
  177. node: function ( ctx ) {
  178. var data = {
  179. name: ctx.NodeName[ 0 ].image,
  180. fields: []
  181. };
  182. if ( ctx.field ) {
  183. for ( var i = 0, l = ctx.field.length; i < l; i ++ ) {
  184. var field = ctx.field[ i ];
  185. data.fields.push( this.visit( field ) );
  186. }
  187. }
  188. // DEF
  189. if ( ctx.def ) {
  190. data.DEF = this.visit( ctx.def[ 0 ] );
  191. }
  192. return data;
  193. },
  194. field: function ( ctx ) {
  195. var data = {
  196. name: ctx.Identifier[ 0 ].image,
  197. type: null,
  198. values: null
  199. };
  200. var result;
  201. // SFValue
  202. if ( ctx.singleFieldValue ) {
  203. result = this.visit( ctx.singleFieldValue[ 0 ] );
  204. }
  205. // MFValue
  206. if ( ctx.multiFieldValue ) {
  207. result = this.visit( ctx.multiFieldValue[ 0 ] );
  208. }
  209. data.type = result.type;
  210. data.values = result.values;
  211. return data;
  212. },
  213. def: function ( ctx ) {
  214. return ctx.Identifier[ 0 ].image;
  215. },
  216. use: function ( ctx ) {
  217. return { USE: ctx.Identifier[ 0 ].image };
  218. },
  219. singleFieldValue: function ( ctx ) {
  220. return processField( this, ctx );
  221. },
  222. multiFieldValue: function ( ctx ) {
  223. return processField( this, ctx );
  224. },
  225. route: function ( ctx ) {
  226. var data = {
  227. FROM: ctx.RouteIdentifier[ 0 ].image,
  228. TO: ctx.RouteIdentifier[ 1 ].image
  229. };
  230. return data;
  231. }
  232. } );
  233. function processField( scope, ctx ) {
  234. var field = {
  235. type: null,
  236. values: []
  237. };
  238. if ( ctx.node ) {
  239. field.type = 'node';
  240. for ( var i = 0, l = ctx.node.length; i < l; i ++ ) {
  241. var node = ctx.node[ i ];
  242. field.values.push( scope.visit( node ) );
  243. }
  244. }
  245. if ( ctx.use ) {
  246. field.type = 'use';
  247. for ( var i = 0, l = ctx.use.length; i < l; i ++ ) {
  248. var use = ctx.use[ i ];
  249. field.values.push( scope.visit( use ) );
  250. }
  251. }
  252. if ( ctx.StringLiteral ) {
  253. field.type = 'string';
  254. for ( var i = 0, l = ctx.StringLiteral.length; i < l; i ++ ) {
  255. var stringLiteral = ctx.StringLiteral[ i ];
  256. field.values.push( stringLiteral.image.replace( /'|"/g, '' ) );
  257. }
  258. }
  259. if ( ctx.NumberLiteral ) {
  260. field.type = 'number';
  261. for ( var i = 0, l = ctx.NumberLiteral.length; i < l; i ++ ) {
  262. var numberLiteral = ctx.NumberLiteral[ i ];
  263. field.values.push( parseFloat( numberLiteral.image ) );
  264. }
  265. }
  266. if ( ctx.HexLiteral ) {
  267. field.type = 'hex';
  268. for ( var i = 0, l = ctx.HexLiteral.length; i < l; i ++ ) {
  269. var hexLiteral = ctx.HexLiteral[ i ];
  270. field.values.push( hexLiteral.image );
  271. }
  272. }
  273. if ( ctx.TrueLiteral ) {
  274. field.type = 'boolean';
  275. for ( var i = 0, l = ctx.TrueLiteral.length; i < l; i ++ ) {
  276. var trueLiteral = ctx.TrueLiteral[ i ];
  277. if ( trueLiteral.image === 'TRUE' ) field.values.push( true );
  278. }
  279. }
  280. if ( ctx.FalseLiteral ) {
  281. field.type = 'boolean';
  282. for ( var i = 0, l = ctx.FalseLiteral.length; i < l; i ++ ) {
  283. var falseLiteral = ctx.FalseLiteral[ i ];
  284. if ( falseLiteral.image === 'FALSE' ) field.values.push( false );
  285. }
  286. }
  287. if ( ctx.NullLiteral ) {
  288. field.type = 'null';
  289. ctx.NullLiteral.forEach( function () {
  290. field.values.push( null );
  291. } );
  292. }
  293. return field;
  294. }
  295. return new VRMLToASTVisitor();
  296. }
  297. function parseTree( tree ) {
  298. // console.log( JSON.stringify( tree, null, 2 ) );
  299. var nodes = tree.nodes;
  300. var scene = new THREE.Scene();
  301. // first iteration: build nodemap based on DEF statements
  302. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  303. var node = nodes[ i ];
  304. buildNodeMap( node );
  305. }
  306. // second iteration: build nodes
  307. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  308. var node = nodes[ i ];
  309. var object = getNode( node );
  310. if ( object instanceof THREE.Object3D ) scene.add( object );
  311. }
  312. return scene;
  313. }
  314. function buildNodeMap( node ) {
  315. if ( node.DEF ) {
  316. nodeMap[ node.DEF ] = node;
  317. }
  318. var fields = node.fields;
  319. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  320. var field = fields[ i ];
  321. if ( field.type === 'node' ) {
  322. var fieldValues = field.values;
  323. for ( var j = 0, jl = fieldValues.length; j < jl; j ++ ) {
  324. buildNodeMap( fieldValues[ j ] );
  325. }
  326. }
  327. }
  328. }
  329. function getNode( node ) {
  330. // handle case where a node refers to a different one
  331. if ( node.USE ) {
  332. return resolveUSE( node.USE );
  333. }
  334. if ( node.build !== undefined ) return node.build;
  335. node.build = buildNode( node );
  336. return node.build;
  337. }
  338. // node builder
  339. function buildNode( node ) {
  340. var nodeName = node.name;
  341. var build;
  342. switch ( nodeName ) {
  343. case 'Group':
  344. case 'Transform':
  345. build = buildGroupingNode( node );
  346. break;
  347. case 'Background':
  348. build = buildBackgroundNode( node );
  349. break;
  350. case 'Shape':
  351. build = buildShapeNode( node );
  352. break;
  353. case 'Appearance':
  354. build = buildAppearanceNode( node );
  355. break;
  356. case 'Material':
  357. build = buildMaterialNode( node );
  358. break;
  359. case 'ImageTexture':
  360. build = buildImageTextureNode( node );
  361. break;
  362. case 'PixelTexture':
  363. build = buildPixelTextureNode( node );
  364. break;
  365. case 'TextureTransform':
  366. build = buildTextureTransformNode( node );
  367. break;
  368. case 'IndexedFaceSet':
  369. build = buildIndexedFaceSetNode( node );
  370. break;
  371. case 'IndexedLineSet':
  372. build = buildIndexedLineSetNode( node );
  373. break;
  374. case 'PointSet':
  375. build = buildPointSetNode( node );
  376. break;
  377. case 'Box':
  378. build = buildBoxNode( node );
  379. break;
  380. case 'Cone':
  381. build = buildConeNode( node );
  382. break;
  383. case 'Cylinder':
  384. build = buildCylinderNode( node );
  385. break;
  386. case 'Sphere':
  387. build = buildSphereNode( node );
  388. break;
  389. case 'ElevationGrid':
  390. build = buildElevationGridNode( node );
  391. break;
  392. case 'Color':
  393. case 'Coordinate':
  394. case 'Normal':
  395. case 'TextureCoordinate':
  396. build = buildGeometricNode( node );
  397. break;
  398. case 'Anchor':
  399. case 'Billboard':
  400. case 'Collision':
  401. case 'Inline':
  402. case 'LOD':
  403. case 'Switch':
  404. case 'AudioClip':
  405. case 'DirectionalLight':
  406. case 'PointLight':
  407. case 'Script':
  408. case 'Sound':
  409. case 'SpotLight':
  410. case 'WorldInfo':
  411. case 'CylinderSensor':
  412. case 'PlaneSensor':
  413. case 'ProximitySensor':
  414. case 'SphereSensor':
  415. case 'TimeSensor':
  416. case 'TouchSensor':
  417. case 'VisibilitySensor':
  418. case 'Extrusion':
  419. case 'Text':
  420. case 'FontStyle':
  421. case 'MovieTexture':
  422. case 'ColorInterpolator':
  423. case 'CoordinateInterpolator':
  424. case 'NormalInterpolator':
  425. case 'OrientationInterpolator':
  426. case 'PositionInterpolator':
  427. case 'ScalarInterpolator':
  428. case 'Fog':
  429. case 'NavigationInfo':
  430. case 'Viewpoint':
  431. // node not supported yet
  432. break;
  433. default:
  434. console.warn( 'THREE.VRMLLoader: Unknown node:', nodeName );
  435. break;
  436. }
  437. return build;
  438. }
  439. function buildGroupingNode( node ) {
  440. var object = new THREE.Group();
  441. //
  442. var fields = node.fields;
  443. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  444. var field = fields[ i ];
  445. var fieldName = field.name;
  446. var fieldValues = field.values;
  447. switch ( fieldName ) {
  448. case 'center':
  449. // field not supported
  450. break;
  451. case 'children':
  452. parseFieldChildren( fieldValues, object );
  453. break;
  454. case 'rotation':
  455. var axis = new THREE.Vector3( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] );
  456. var angle = fieldValues[ 3 ];
  457. object.quaternion.setFromAxisAngle( axis, angle );
  458. break;
  459. case 'scale':
  460. object.scale.set( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] );
  461. break;
  462. case 'scaleOrientation':
  463. // field not supported
  464. break;
  465. case 'translation':
  466. object.position.set( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] );
  467. break;
  468. case 'bboxCenter':
  469. // field not supported
  470. break;
  471. case 'bboxSize':
  472. // field not supported
  473. break;
  474. default:
  475. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  476. break;
  477. }
  478. }
  479. return object;
  480. }
  481. function buildBackgroundNode( node ) {
  482. var group = new THREE.Group();
  483. var groundAngle, groundColor;
  484. var skyAngle, skyColor;
  485. var fields = node.fields;
  486. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  487. var field = fields[ i ];
  488. var fieldName = field.name;
  489. var fieldValues = field.values;
  490. switch ( fieldName ) {
  491. case 'groundAngle':
  492. groundAngle = fieldValues;
  493. break;
  494. case 'groundColor':
  495. groundColor = fieldValues;
  496. break;
  497. case 'backUrl':
  498. // field not supported
  499. break;
  500. case 'bottomUrl':
  501. // field not supported
  502. break;
  503. case 'frontUrl':
  504. // field not supported
  505. break;
  506. case 'leftUrl':
  507. // field not supported
  508. break;
  509. case 'rightUrl':
  510. // field not supported
  511. break;
  512. case 'topUrl':
  513. // field not supported
  514. break;
  515. case 'skyAngle':
  516. skyAngle = fieldValues;
  517. break;
  518. case 'skyColor':
  519. skyColor = fieldValues;
  520. break;
  521. default:
  522. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  523. break;
  524. }
  525. }
  526. var radius = 10000;
  527. // sky
  528. if ( skyColor ) {
  529. var skyGeometry = new THREE.SphereBufferGeometry( radius, 32, 16 );
  530. var skyMaterial = new THREE.MeshBasicMaterial( { fog: false, side: THREE.BackSide, depthWrite: false, depthTest: false } );
  531. if ( skyColor.length > 3 ) {
  532. paintFaces( skyGeometry, radius, skyAngle, toColorArray( skyColor ), true );
  533. skyMaterial.vertexColors = true;
  534. } else {
  535. skyMaterial.color.setRGB( skyColor[ 0 ], skyColor[ 1 ], skyColor[ 2 ] );
  536. }
  537. var sky = new THREE.Mesh( skyGeometry, skyMaterial );
  538. group.add( sky );
  539. }
  540. // ground
  541. if ( groundColor ) {
  542. if ( groundColor.length > 0 ) {
  543. var groundGeometry = new THREE.SphereBufferGeometry( radius, 32, 16, 0, 2 * Math.PI, 0.5 * Math.PI, 1.5 * Math.PI );
  544. var groundMaterial = new THREE.MeshBasicMaterial( { fog: false, side: THREE.BackSide, vertexColors: true, depthWrite: false, depthTest: false } );
  545. paintFaces( groundGeometry, radius, groundAngle, toColorArray( groundColor ), false );
  546. var ground = new THREE.Mesh( groundGeometry, groundMaterial );
  547. group.add( ground );
  548. }
  549. }
  550. // render background group first
  551. group.renderOrder = - Infinity;
  552. return group;
  553. }
  554. function buildShapeNode( node ) {
  555. var fields = node.fields;
  556. // if the appearance field is NULL or unspecified, lighting is off and the unlit object color is (0, 0, 0)
  557. var material = new THREE.MeshBasicMaterial( { color: 0x000000 } );
  558. var geometry;
  559. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  560. var field = fields[ i ];
  561. var fieldName = field.name;
  562. var fieldValues = field.values;
  563. switch ( fieldName ) {
  564. case 'appearance':
  565. if ( fieldValues[ 0 ] !== null ) {
  566. material = getNode( fieldValues[ 0 ] );
  567. }
  568. break;
  569. case 'geometry':
  570. if ( fieldValues[ 0 ] !== null ) {
  571. geometry = getNode( fieldValues[ 0 ] );
  572. }
  573. break;
  574. default:
  575. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  576. break;
  577. }
  578. }
  579. // build 3D object
  580. var object;
  581. if ( geometry && geometry.attributes.position ) {
  582. var type = geometry._type;
  583. if ( type === 'points' ) { // points
  584. var pointsMaterial = new THREE.PointsMaterial( { color: 0xffffff } );
  585. if ( geometry.attributes.color !== undefined ) {
  586. pointsMaterial.vertexColors = true;
  587. } else {
  588. // if the color field is NULL and there is a material defined for the appearance affecting this PointSet, then use the emissiveColor of the material to draw the points
  589. if ( material.isMeshPhongMaterial ) {
  590. pointsMaterial.color.copy( material.emissive );
  591. }
  592. }
  593. object = new THREE.Points( geometry, pointsMaterial );
  594. } else if ( type === 'line' ) { // lines
  595. var lineMaterial = new THREE.LineBasicMaterial( { color: 0xffffff } );
  596. if ( geometry.attributes.color !== undefined ) {
  597. lineMaterial.vertexColors = true;
  598. } else {
  599. // if the color field is NULL and there is a material defined for the appearance affecting this IndexedLineSet, then use the emissiveColor of the material to draw the lines
  600. if ( material.isMeshPhongMaterial ) {
  601. lineMaterial.color.copy( material.emissive );
  602. }
  603. }
  604. object = new THREE.LineSegments( geometry, lineMaterial );
  605. } else { // consider meshes
  606. // check "solid" hint (it's placed in the geometry but affects the material)
  607. if ( geometry._solid !== undefined ) {
  608. material.side = ( geometry._solid ) ? THREE.FrontSide : THREE.DoubleSide;
  609. }
  610. // check for vertex colors
  611. if ( geometry.attributes.color !== undefined ) {
  612. material.vertexColors = true;
  613. }
  614. object = new THREE.Mesh( geometry, material );
  615. }
  616. } else {
  617. object = new THREE.Object3D();
  618. // if the geometry field is NULL or no vertices are defined the object is not drawn
  619. object.visible = false;
  620. }
  621. return object;
  622. }
  623. function buildAppearanceNode( node ) {
  624. var material = new THREE.MeshPhongMaterial();
  625. var transformData;
  626. var fields = node.fields;
  627. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  628. var field = fields[ i ];
  629. var fieldName = field.name;
  630. var fieldValues = field.values;
  631. switch ( fieldName ) {
  632. case 'material':
  633. if ( fieldValues[ 0 ] !== null ) {
  634. var materialData = getNode( fieldValues[ 0 ] );
  635. if ( materialData.diffuseColor ) material.color.copy( materialData.diffuseColor );
  636. if ( materialData.emissiveColor ) material.emissive.copy( materialData.emissiveColor );
  637. if ( materialData.shininess ) material.shininess = materialData.shininess;
  638. if ( materialData.specularColor ) material.specular.copy( materialData.specularColor );
  639. if ( materialData.transparency ) material.opacity = 1 - materialData.transparency;
  640. if ( materialData.transparency > 0 ) material.transparent = true;
  641. } else {
  642. // if the material field is NULL or unspecified, lighting is off and the unlit object color is (0, 0, 0)
  643. material = new THREE.MeshBasicMaterial( { color: 0x000000 } );
  644. }
  645. break;
  646. case 'texture':
  647. var textureNode = fieldValues[ 0 ];
  648. if ( textureNode !== null ) {
  649. if ( textureNode.name === 'ImageTexture' || textureNode.name === 'PixelTexture' ) {
  650. material.map = getNode( textureNode );
  651. } else {
  652. // MovieTexture not supported yet
  653. }
  654. }
  655. break;
  656. case 'textureTransform':
  657. if ( fieldValues[ 0 ] !== null ) {
  658. transformData = getNode( fieldValues[ 0 ] );
  659. }
  660. break;
  661. default:
  662. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  663. break;
  664. }
  665. }
  666. // only apply texture transform data if a texture was defined
  667. if ( material.map ) {
  668. // respect VRML lighting model
  669. if ( material.map.__type ) {
  670. switch ( material.map.__type ) {
  671. case TEXTURE_TYPE.INTENSITY_ALPHA:
  672. material.opacity = 1; // ignore transparency
  673. break;
  674. case TEXTURE_TYPE.RGB:
  675. material.color.set( 0xffffff ); // ignore material color
  676. break;
  677. case TEXTURE_TYPE.RGBA:
  678. material.color.set( 0xffffff ); // ignore material color
  679. material.opacity = 1; // ignore transparency
  680. break;
  681. default:
  682. }
  683. delete material.map.__type;
  684. }
  685. // apply texture transform
  686. if ( transformData ) {
  687. material.map.center.copy( transformData.center );
  688. material.map.rotation = transformData.rotation;
  689. material.map.repeat.copy( transformData.scale );
  690. material.map.offset.copy( transformData.translation );
  691. }
  692. }
  693. return material;
  694. }
  695. function buildMaterialNode( node ) {
  696. var materialData = {};
  697. var fields = node.fields;
  698. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  699. var field = fields[ i ];
  700. var fieldName = field.name;
  701. var fieldValues = field.values;
  702. switch ( fieldName ) {
  703. case 'ambientIntensity':
  704. // field not supported
  705. break;
  706. case 'diffuseColor':
  707. materialData.diffuseColor = new THREE.Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] );
  708. break;
  709. case 'emissiveColor':
  710. materialData.emissiveColor = new THREE.Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] );
  711. break;
  712. case 'shininess':
  713. materialData.shininess = fieldValues[ 0 ];
  714. break;
  715. case 'specularColor':
  716. materialData.emissiveColor = new THREE.Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] );
  717. break;
  718. case 'transparency':
  719. materialData.transparency = fieldValues[ 0 ];
  720. break;
  721. default:
  722. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  723. break;
  724. }
  725. }
  726. return materialData;
  727. }
  728. function parseHexColor( hex, textureType, color ) {
  729. switch ( textureType ) {
  730. case TEXTURE_TYPE.INTENSITY:
  731. // Intensity texture: A one-component image specifies one-byte hexadecimal or integer values representing the intensity of the image
  732. var value = parseInt( hex );
  733. color.r = value;
  734. color.g = value;
  735. color.b = value;
  736. break;
  737. case TEXTURE_TYPE.INTENSITY_ALPHA:
  738. // Intensity+Alpha texture: A two-component image specifies the intensity in the first (high) byte and the alpha opacity in the second (low) byte.
  739. var value = parseInt( "0x" + hex.substring( 2, 4 ) );
  740. color.r = value;
  741. color.g = value;
  742. color.b = value;
  743. color.a = parseInt( "0x" + hex.substring( 4, 6 ) );
  744. break;
  745. case TEXTURE_TYPE.RGB:
  746. // RGB texture: Pixels in a three-component image specify the red component in the first (high) byte, followed by the green and blue components
  747. color.r = parseInt( "0x" + hex.substring( 2, 4 ) );
  748. color.g = parseInt( "0x" + hex.substring( 4, 6 ) );
  749. color.b = parseInt( "0x" + hex.substring( 6, 8 ) );
  750. break;
  751. case TEXTURE_TYPE.RGBA:
  752. // RGBA texture: Four-component images specify the alpha opacity byte after red/green/blue
  753. color.r = parseInt( "0x" + hex.substring( 2, 4 ) );
  754. color.g = parseInt( "0x" + hex.substring( 4, 6 ) );
  755. color.b = parseInt( "0x" + hex.substring( 6, 8 ) );
  756. color.a = parseInt( "0x" + hex.substring( 8, 10 ) );
  757. break;
  758. default:
  759. }
  760. }
  761. function getTextureType( num_components ) {
  762. var type;
  763. switch ( num_components ) {
  764. case 1:
  765. type = TEXTURE_TYPE.INTENSITY;
  766. break;
  767. case 2:
  768. type = TEXTURE_TYPE.INTENSITY_ALPHA;
  769. break;
  770. case 3:
  771. type = TEXTURE_TYPE.RGB;
  772. break;
  773. case 4:
  774. type = TEXTURE_TYPE.RGBA;
  775. break;
  776. default:
  777. }
  778. return type;
  779. }
  780. function buildPixelTextureNode( node ) {
  781. var texture;
  782. var wrapS = THREE.RepeatWrapping;
  783. var wrapT = THREE.RepeatWrapping;
  784. var fields = node.fields;
  785. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  786. var field = fields[ i ];
  787. var fieldName = field.name;
  788. var fieldValues = field.values;
  789. switch ( fieldName ) {
  790. case 'image':
  791. var width = fieldValues[ 0 ];
  792. var height = fieldValues[ 1 ];
  793. var num_components = fieldValues[ 2 ];
  794. var useAlpha = ( num_components === 2 || num_components === 4 );
  795. var textureType = getTextureType( num_components );
  796. var size = ( ( useAlpha === true ) ? 4 : 3 ) * ( width * height );
  797. var data = new Uint8Array( size );
  798. var color = { r: 0, g: 0, b: 0, a: 0 };
  799. for ( var j = 3, k = 0, jl = fieldValues.length; j < jl; j ++, k ++ ) {
  800. parseHexColor( fieldValues[ j ], textureType, color );
  801. if ( useAlpha === true ) {
  802. var stride = k * 4;
  803. data[ stride + 0 ] = color.r;
  804. data[ stride + 1 ] = color.g;
  805. data[ stride + 2 ] = color.b;
  806. data[ stride + 3 ] = color.a;
  807. } else {
  808. var stride = k * 3;
  809. data[ stride + 0 ] = color.r;
  810. data[ stride + 1 ] = color.g;
  811. data[ stride + 2 ] = color.b;
  812. }
  813. }
  814. texture = new THREE.DataTexture( data, width, height, ( useAlpha === true ) ? THREE.RGBAFormat : THREE.RGBFormat );
  815. texture.__type = textureType; // needed for material modifications
  816. break;
  817. case 'repeatS':
  818. if ( fieldValues[ 0 ] === false ) wrapS = THREE.ClampToEdgeWrapping;
  819. break;
  820. case 'repeatT':
  821. if ( fieldValues[ 0 ] === false ) wrapT = THREE.ClampToEdgeWrapping;
  822. break;
  823. default:
  824. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  825. break;
  826. }
  827. }
  828. if ( texture ) {
  829. texture.wrapS = wrapS;
  830. texture.wrapT = wrapT;
  831. }
  832. return texture;
  833. }
  834. function buildImageTextureNode( node ) {
  835. var texture;
  836. var wrapS = THREE.RepeatWrapping;
  837. var wrapT = THREE.RepeatWrapping;
  838. var fields = node.fields;
  839. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  840. var field = fields[ i ];
  841. var fieldName = field.name;
  842. var fieldValues = field.values;
  843. switch ( fieldName ) {
  844. case 'url':
  845. var url = fieldValues[ 0 ];
  846. if ( url ) texture = textureLoader.load( url );
  847. break;
  848. case 'repeatS':
  849. if ( fieldValues[ 0 ] === false ) wrapS = THREE.ClampToEdgeWrapping;
  850. break;
  851. case 'repeatT':
  852. if ( fieldValues[ 0 ] === false ) wrapT = THREE.ClampToEdgeWrapping;
  853. break;
  854. default:
  855. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  856. break;
  857. }
  858. }
  859. if ( texture ) {
  860. texture.wrapS = wrapS;
  861. texture.wrapT = wrapT;
  862. }
  863. return texture;
  864. }
  865. function buildTextureTransformNode( node ) {
  866. var transformData = {
  867. center: new THREE.Vector2(),
  868. rotation: new THREE.Vector2(),
  869. scale: new THREE.Vector2(),
  870. translation: new THREE.Vector2()
  871. };
  872. var fields = node.fields;
  873. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  874. var field = fields[ i ];
  875. var fieldName = field.name;
  876. var fieldValues = field.values;
  877. switch ( fieldName ) {
  878. case 'center':
  879. transformData.center.set( fieldValues[ 0 ], fieldValues[ 1 ] );
  880. break;
  881. case 'rotation':
  882. transformData.rotation = fieldValues[ 0 ];
  883. break;
  884. case 'scale':
  885. transformData.scale.set( fieldValues[ 0 ], fieldValues[ 1 ] );
  886. break;
  887. case 'translation':
  888. transformData.translation.set( fieldValues[ 0 ], fieldValues[ 1 ] );
  889. break;
  890. default:
  891. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  892. break;
  893. }
  894. }
  895. return transformData;
  896. }
  897. function buildGeometricNode( node ) {
  898. return node.fields[ 0 ].values;
  899. }
  900. function buildIndexedFaceSetNode( node ) {
  901. var color, coord, normal, texCoord;
  902. var ccw = true, solid = true, creaseAngle = 0;
  903. var colorIndex, coordIndex, normalIndex, texCoordIndex;
  904. var colorPerVertex = true, normalPerVertex = true;
  905. var fields = node.fields;
  906. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  907. var field = fields[ i ];
  908. var fieldName = field.name;
  909. var fieldValues = field.values;
  910. switch ( fieldName ) {
  911. case 'color':
  912. var colorNode = fieldValues[ 0 ];
  913. if ( colorNode !== null ) {
  914. color = getNode( colorNode );
  915. }
  916. break;
  917. case 'coord':
  918. var coordNode = fieldValues[ 0 ];
  919. if ( coordNode !== null ) {
  920. coord = getNode( coordNode );
  921. }
  922. break;
  923. case 'normal':
  924. var normalNode = fieldValues[ 0 ];
  925. if ( normalNode !== null ) {
  926. normal = getNode( normalNode );
  927. }
  928. break;
  929. case 'texCoord':
  930. var texCoordNode = fieldValues[ 0 ];
  931. if ( texCoordNode !== null ) {
  932. texCoord = getNode( texCoordNode );
  933. }
  934. break;
  935. case 'ccw':
  936. ccw = fieldValues[ 0 ];
  937. break;
  938. case 'colorIndex':
  939. colorIndex = fieldValues;
  940. break;
  941. case 'colorPerVertex':
  942. colorPerVertex = fieldValues[ 0 ];
  943. break;
  944. case 'convex':
  945. // field not supported
  946. break;
  947. case 'coordIndex':
  948. coordIndex = fieldValues;
  949. break;
  950. case 'creaseAngle':
  951. creaseAngle = fieldValues[ 0 ];
  952. break;
  953. case 'normalIndex':
  954. normalIndex = fieldValues;
  955. break;
  956. case 'normalPerVertex':
  957. normalPerVertex = fieldValues[ 0 ];
  958. break;
  959. case 'solid':
  960. solid = fieldValues[ 0 ];
  961. break;
  962. case 'texCoordIndex':
  963. texCoordIndex = fieldValues;
  964. break;
  965. default:
  966. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  967. break;
  968. }
  969. }
  970. if ( coordIndex === undefined ) {
  971. console.warn( 'THREE.VRMLLoader: Missing coordIndex.' );
  972. return new THREE.BufferGeometry(); // handle VRML files with incomplete geometry definition
  973. }
  974. var triangulatedCoordIndex = triangulateFaceIndex( coordIndex, ccw );
  975. var positionAttribute;
  976. var colorAttribute;
  977. var normalAttribute;
  978. var uvAttribute;
  979. if ( color ) {
  980. if ( colorPerVertex === true ) {
  981. if ( colorIndex && colorIndex.length > 0 ) {
  982. // if the colorIndex field is not empty, then it is used to choose colors for each vertex of the IndexedFaceSet.
  983. var triangulatedColorIndex = triangulateFaceIndex( colorIndex, ccw );
  984. colorAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedColorIndex, color, 3 );
  985. } else {
  986. // if the colorIndex field is empty, then the coordIndex field is used to choose colors from the Color node
  987. colorAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( color, 3 ) );
  988. }
  989. } else {
  990. if ( colorIndex && colorIndex.length > 0 ) {
  991. // if the colorIndex field is not empty, then they are used to choose one color for each face of the IndexedFaceSet
  992. var flattenFaceColors = flattenData( color, colorIndex );
  993. var triangulatedFaceColors = triangulateFaceData( flattenFaceColors, coordIndex );
  994. colorAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceColors );
  995. } else {
  996. // if the colorIndex field is empty, then the color are applied to each face of the IndexedFaceSet in order
  997. var triangulatedFaceColors = triangulateFaceData( color, coordIndex );
  998. colorAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceColors );
  999. }
  1000. }
  1001. }
  1002. if ( normal ) {
  1003. if ( normalPerVertex === true ) {
  1004. // consider vertex normals
  1005. if ( normalIndex && normalIndex.length > 0 ) {
  1006. // if the normalIndex field is not empty, then it is used to choose normals for each vertex of the IndexedFaceSet.
  1007. var triangulatedNormalIndex = triangulateFaceIndex( normalIndex, ccw );
  1008. normalAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedNormalIndex, normal, 3 );
  1009. } else {
  1010. // if the normalIndex field is empty, then the coordIndex field is used to choose normals from the Normal node
  1011. normalAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( normal, 3 ) );
  1012. }
  1013. } else {
  1014. // consider face normals
  1015. if ( normalIndex && normalIndex.length > 0 ) {
  1016. // if the normalIndex field is not empty, then they are used to choose one normal for each face of the IndexedFaceSet
  1017. var flattenFaceNormals = flattenData( normal, normalIndex );
  1018. var triangulatedFaceNormals = triangulateFaceData( flattenFaceNormals, coordIndex );
  1019. normalAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceNormals );
  1020. } else {
  1021. // if the normalIndex field is empty, then the normals are applied to each face of the IndexedFaceSet in order
  1022. var triangulatedFaceNormals = triangulateFaceData( normal, coordIndex );
  1023. normalAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceNormals );
  1024. }
  1025. }
  1026. } else {
  1027. // if the normal field is NULL, then the loader should automatically generate normals, using creaseAngle to determine if and how normals are smoothed across shared vertices
  1028. normalAttribute = computeNormalAttribute( triangulatedCoordIndex, coord, creaseAngle );
  1029. }
  1030. if ( texCoord ) {
  1031. // texture coordinates are always defined on vertex level
  1032. if ( texCoordIndex && texCoordIndex.length > 0 ) {
  1033. // if the texCoordIndex field is not empty, then it is used to choose texture coordinates for each vertex of the IndexedFaceSet.
  1034. var triangulatedTexCoordIndex = triangulateFaceIndex( texCoordIndex, ccw );
  1035. uvAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedTexCoordIndex, texCoord, 2 );
  1036. } else {
  1037. // if the texCoordIndex field is empty, then the coordIndex array is used to choose texture coordinates from the TextureCoordinate node
  1038. uvAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( texCoord, 2 ) );
  1039. }
  1040. }
  1041. var geometry = new THREE.BufferGeometry();
  1042. positionAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( coord, 3 ) );
  1043. geometry.setAttribute( 'position', positionAttribute );
  1044. geometry.setAttribute( 'normal', normalAttribute );
  1045. // optional attributes
  1046. if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute );
  1047. if ( uvAttribute ) geometry.setAttribute( 'uv', uvAttribute );
  1048. // "solid" influences the material so let's store it for later use
  1049. geometry._solid = solid;
  1050. geometry._type = 'mesh';
  1051. return geometry;
  1052. }
  1053. function buildIndexedLineSetNode( node ) {
  1054. var color, coord;
  1055. var colorIndex, coordIndex;
  1056. var colorPerVertex = true;
  1057. var fields = node.fields;
  1058. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  1059. var field = fields[ i ];
  1060. var fieldName = field.name;
  1061. var fieldValues = field.values;
  1062. switch ( fieldName ) {
  1063. case 'color':
  1064. var colorNode = fieldValues[ 0 ];
  1065. if ( colorNode !== null ) {
  1066. color = getNode( colorNode );
  1067. }
  1068. break;
  1069. case 'coord':
  1070. var coordNode = fieldValues[ 0 ];
  1071. if ( coordNode !== null ) {
  1072. coord = getNode( coordNode );
  1073. }
  1074. break;
  1075. case 'colorIndex':
  1076. colorIndex = fieldValues;
  1077. break;
  1078. case 'colorPerVertex':
  1079. colorPerVertex = fieldValues[ 0 ];
  1080. break;
  1081. case 'coordIndex':
  1082. coordIndex = fieldValues;
  1083. break;
  1084. default:
  1085. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  1086. break;
  1087. }
  1088. }
  1089. // build lines
  1090. var colorAttribute;
  1091. var expandedLineIndex = expandLineIndex( coordIndex ); // create an index for three.js's linesegment primitive
  1092. if ( color ) {
  1093. if ( colorPerVertex === true ) {
  1094. if ( colorIndex.length > 0 ) {
  1095. // if the colorIndex field is not empty, then one color is used for each polyline of the IndexedLineSet.
  1096. var expandedColorIndex = expandLineIndex( colorIndex ); // compute colors for each line segment (rendering primitve)
  1097. colorAttribute = computeAttributeFromIndexedData( expandedLineIndex, expandedColorIndex, color, 3 ); // compute data on vertex level
  1098. } else {
  1099. // if the colorIndex field is empty, then the colors are applied to each polyline of the IndexedLineSet in order.
  1100. colorAttribute = toNonIndexedAttribute( expandedLineIndex, new THREE.Float32BufferAttribute( color, 3 ) );
  1101. }
  1102. } else {
  1103. if ( colorIndex.length > 0 ) {
  1104. // if the colorIndex field is not empty, then colors are applied to each vertex of the IndexedLineSet
  1105. var flattenLineColors = flattenData( color, colorIndex ); // compute colors for each VRML primitve
  1106. var expandedLineColors = expandLineData( flattenLineColors, coordIndex ); // compute colors for each line segment (rendering primitve)
  1107. colorAttribute = computeAttributeFromLineData( expandedLineIndex, expandedLineColors ); // compute data on vertex level
  1108. } else {
  1109. // if the colorIndex field is empty, then the coordIndex field is used to choose colors from the Color node
  1110. var expandedLineColors = expandLineData( color, coordIndex ); // compute colors for each line segment (rendering primitve)
  1111. colorAttribute = computeAttributeFromLineData( expandedLineIndex, expandedLineColors ); // compute data on vertex level
  1112. }
  1113. }
  1114. }
  1115. //
  1116. var geometry = new THREE.BufferGeometry();
  1117. var positionAttribute = toNonIndexedAttribute( expandedLineIndex, new THREE.Float32BufferAttribute( coord, 3 ) );
  1118. geometry.setAttribute( 'position', positionAttribute );
  1119. if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute );
  1120. geometry._type = 'line';
  1121. return geometry;
  1122. }
  1123. function buildPointSetNode( node ) {
  1124. var geometry;
  1125. var color, coord;
  1126. var fields = node.fields;
  1127. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  1128. var field = fields[ i ];
  1129. var fieldName = field.name;
  1130. var fieldValues = field.values;
  1131. switch ( fieldName ) {
  1132. case 'color':
  1133. var colorNode = fieldValues[ 0 ];
  1134. if ( colorNode !== null ) {
  1135. color = getNode( colorNode );
  1136. }
  1137. break;
  1138. case 'coord':
  1139. var coordNode = fieldValues[ 0 ];
  1140. if ( coordNode !== null ) {
  1141. coord = getNode( coordNode );
  1142. }
  1143. break;
  1144. default:
  1145. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  1146. break;
  1147. }
  1148. }
  1149. var geometry = new THREE.BufferGeometry();
  1150. geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( coord, 3 ) );
  1151. if ( color ) geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( color, 3 ) );
  1152. geometry._type = 'points';
  1153. return geometry;
  1154. }
  1155. function buildBoxNode( node ) {
  1156. var size = new THREE.Vector3( 2, 2, 2 );
  1157. var fields = node.fields;
  1158. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  1159. var field = fields[ i ];
  1160. var fieldName = field.name;
  1161. var fieldValues = field.values;
  1162. switch ( fieldName ) {
  1163. case 'size':
  1164. size.x = fieldValues[ 0 ];
  1165. size.y = fieldValues[ 1 ];
  1166. size.z = fieldValues[ 2 ];
  1167. break;
  1168. default:
  1169. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  1170. break;
  1171. }
  1172. }
  1173. var geometry = new THREE.BoxBufferGeometry( size.x, size.y, size.z );
  1174. return geometry;
  1175. }
  1176. function buildConeNode( node ) {
  1177. var radius = 1, height = 2, openEnded = false;
  1178. var fields = node.fields;
  1179. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  1180. var field = fields[ i ];
  1181. var fieldName = field.name;
  1182. var fieldValues = field.values;
  1183. switch ( fieldName ) {
  1184. case 'bottom':
  1185. openEnded = ! fieldValues[ 0 ];
  1186. break;
  1187. case 'bottomRadius':
  1188. radius = fieldValues[ 0 ];
  1189. break;
  1190. case 'height':
  1191. height = fieldValues[ 0 ];
  1192. break;
  1193. case 'side':
  1194. // field not supported
  1195. break;
  1196. default:
  1197. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  1198. break;
  1199. }
  1200. }
  1201. var geometry = new THREE.ConeBufferGeometry( radius, height, 16, 1, openEnded );
  1202. return geometry;
  1203. }
  1204. function buildCylinderNode( node ) {
  1205. var radius = 1, height = 2;
  1206. var fields = node.fields;
  1207. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  1208. var field = fields[ i ];
  1209. var fieldName = field.name;
  1210. var fieldValues = field.values;
  1211. switch ( fieldName ) {
  1212. case 'bottom':
  1213. // field not supported
  1214. break;
  1215. case 'radius':
  1216. radius = fieldValues[ 0 ];
  1217. break;
  1218. case 'height':
  1219. height = fieldValues[ 0 ];
  1220. break;
  1221. case 'side':
  1222. // field not supported
  1223. break;
  1224. case 'top':
  1225. // field not supported
  1226. break;
  1227. default:
  1228. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  1229. break;
  1230. }
  1231. }
  1232. var geometry = new THREE.CylinderBufferGeometry( radius, radius, height, 16, 1 );
  1233. return geometry;
  1234. }
  1235. function buildSphereNode( node ) {
  1236. var radius = 1;
  1237. var fields = node.fields;
  1238. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  1239. var field = fields[ i ];
  1240. var fieldName = field.name;
  1241. var fieldValues = field.values;
  1242. switch ( fieldName ) {
  1243. case 'radius':
  1244. radius = fieldValues[ 0 ];
  1245. break;
  1246. default:
  1247. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  1248. break;
  1249. }
  1250. }
  1251. var geometry = new THREE.SphereBufferGeometry( radius, 16, 16 );
  1252. return geometry;
  1253. }
  1254. function buildElevationGridNode( node ) {
  1255. var color;
  1256. var normal;
  1257. var texCoord;
  1258. var height;
  1259. var colorPerVertex = true;
  1260. var normalPerVertex = true;
  1261. var solid = true;
  1262. var ccw = true;
  1263. var creaseAngle = 0;
  1264. var xDimension = 2;
  1265. var zDimension = 2;
  1266. var xSpacing = 1;
  1267. var zSpacing = 1;
  1268. var fields = node.fields;
  1269. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  1270. var field = fields[ i ];
  1271. var fieldName = field.name;
  1272. var fieldValues = field.values;
  1273. switch ( fieldName ) {
  1274. case 'color':
  1275. var colorNode = fieldValues[ 0 ];
  1276. if ( colorNode !== null ) {
  1277. color = getNode( colorNode );
  1278. }
  1279. break;
  1280. case 'normal':
  1281. var normalNode = fieldValues[ 0 ];
  1282. if ( normalNode !== null ) {
  1283. normal = getNode( normalNode );
  1284. }
  1285. break;
  1286. case 'texCoord':
  1287. var texCoordNode = fieldValues[ 0 ];
  1288. if ( texCoordNode !== null ) {
  1289. texCoord = getNode( texCoordNode );
  1290. }
  1291. break;
  1292. case 'height':
  1293. height = fieldValues;
  1294. break;
  1295. case 'ccw':
  1296. ccw = fieldValues[ 0 ];
  1297. break;
  1298. case 'colorPerVertex':
  1299. colorPerVertex = fieldValues[ 0 ];
  1300. break;
  1301. case 'creaseAngle':
  1302. creaseAngle = fieldValues[ 0 ];
  1303. break;
  1304. case 'normalPerVertex':
  1305. normalPerVertex = fieldValues[ 0 ];
  1306. break;
  1307. case 'solid':
  1308. solid = fieldValues[ 0 ];
  1309. break;
  1310. case 'xDimension':
  1311. xDimension = fieldValues[ 0 ];
  1312. break;
  1313. case 'xSpacing':
  1314. xSpacing = fieldValues[ 0 ];
  1315. break;
  1316. case 'zDimension':
  1317. zDimension = fieldValues[ 0 ];
  1318. break;
  1319. case 'zSpacing':
  1320. zSpacing = fieldValues[ 0 ];
  1321. break;
  1322. default:
  1323. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  1324. break;
  1325. }
  1326. }
  1327. // vertex data
  1328. var vertices = [];
  1329. var normals = [];
  1330. var colors = [];
  1331. var uvs = [];
  1332. for ( var i = 0; i < zDimension; i ++ ) {
  1333. for ( var j = 0; j < xDimension; j ++ ) {
  1334. // compute a row major index
  1335. var index = ( i * xDimension ) + j;
  1336. // vertices
  1337. var x = xSpacing * i;
  1338. var y = height[ index ];
  1339. var z = zSpacing * j;
  1340. vertices.push( x, y, z );
  1341. // colors
  1342. if ( color && colorPerVertex === true ) {
  1343. var r = color[ index * 3 + 0 ];
  1344. var g = color[ index * 3 + 1 ];
  1345. var b = color[ index * 3 + 2 ];
  1346. colors.push( r, g, b );
  1347. }
  1348. // normals
  1349. if ( normal && normalPerVertex === true ) {
  1350. var xn = normal[ index * 3 + 0 ];
  1351. var yn = normal[ index * 3 + 1 ];
  1352. var zn = normal[ index * 3 + 2 ];
  1353. normals.push( xn, yn, zn );
  1354. }
  1355. // uvs
  1356. if ( texCoord ) {
  1357. var s = texCoord[ index * 2 + 0 ];
  1358. var t = texCoord[ index * 2 + 1 ];
  1359. uvs.push( s, t );
  1360. } else {
  1361. uvs.push( i / ( xDimension - 1 ), j / ( zDimension - 1 ) );
  1362. }
  1363. }
  1364. }
  1365. // indices
  1366. var indices = [];
  1367. for ( var i = 0; i < xDimension - 1; i ++ ) {
  1368. for ( var j = 0; j < zDimension - 1; j ++ ) {
  1369. // from https://tecfa.unige.ch/guides/vrml/vrml97/spec/part1/nodesRef.html#ElevationGrid
  1370. var a = i + j * xDimension;
  1371. var b = i + ( j + 1 ) * xDimension;
  1372. var c = ( i + 1 ) + ( j + 1 ) * xDimension;
  1373. var d = ( i + 1 ) + j * xDimension;
  1374. // faces
  1375. if ( ccw === true ) {
  1376. indices.push( a, c, b );
  1377. indices.push( c, a, d );
  1378. } else {
  1379. indices.push( a, b, c );
  1380. indices.push( c, d, a );
  1381. }
  1382. }
  1383. }
  1384. //
  1385. var positionAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( vertices, 3 ) );
  1386. var uvAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( uvs, 2 ) );
  1387. var colorAttribute;
  1388. var normalAttribute;
  1389. // color attribute
  1390. if ( color ) {
  1391. if ( colorPerVertex === false ) {
  1392. for ( var i = 0; i < xDimension - 1; i ++ ) {
  1393. for ( var j = 0; j < zDimension - 1; j ++ ) {
  1394. var index = i + j * ( xDimension - 1 );
  1395. var r = color[ index * 3 + 0 ];
  1396. var g = color[ index * 3 + 1 ];
  1397. var b = color[ index * 3 + 2 ];
  1398. // one color per quad
  1399. colors.push( r, g, b ); colors.push( r, g, b ); colors.push( r, g, b );
  1400. colors.push( r, g, b ); colors.push( r, g, b ); colors.push( r, g, b );
  1401. }
  1402. }
  1403. colorAttribute = new THREE.Float32BufferAttribute( colors, 3 );
  1404. } else {
  1405. colorAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( colors, 3 ) );
  1406. }
  1407. }
  1408. // normal attribute
  1409. if ( normal ) {
  1410. if ( normalPerVertex === false ) {
  1411. for ( var i = 0; i < xDimension - 1; i ++ ) {
  1412. for ( var j = 0; j < zDimension - 1; j ++ ) {
  1413. var index = i + j * ( xDimension - 1 );
  1414. var xn = normal[ index * 3 + 0 ];
  1415. var yn = normal[ index * 3 + 1 ];
  1416. var zn = normal[ index * 3 + 2 ];
  1417. // one normal per quad
  1418. normals.push( xn, yn, zn ); normals.push( xn, yn, zn ); normals.push( xn, yn, zn );
  1419. normals.push( xn, yn, zn ); normals.push( xn, yn, zn ); normals.push( xn, yn, zn );
  1420. }
  1421. }
  1422. normalAttribute = new THREE.Float32BufferAttribute( normals, 3 );
  1423. } else {
  1424. normalAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( normals, 3 ) );
  1425. }
  1426. } else {
  1427. normalAttribute = computeNormalAttribute( indices, vertices, creaseAngle );
  1428. }
  1429. // build geometry
  1430. var geometry = new THREE.BufferGeometry();
  1431. geometry.setAttribute( 'position', positionAttribute );
  1432. geometry.setAttribute( 'normal', normalAttribute );
  1433. geometry.setAttribute( 'uv', uvAttribute );
  1434. if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute );
  1435. // "solid" influences the material so let's store it for later use
  1436. geometry._solid = solid;
  1437. geometry._type = 'mesh';
  1438. return geometry;
  1439. }
  1440. // helper functions
  1441. function resolveUSE( identifier ) {
  1442. var node = nodeMap[ identifier ];
  1443. var build = getNode( node );
  1444. // because the same 3D objects can have different transformations, it's necessary to clone them.
  1445. // materials can be influenced by the geometry (e.g. vertex normals). cloning is necessary to avoid
  1446. // any side effects
  1447. return ( build.isObject3D || build.isMaterial ) ? build.clone() : build;
  1448. }
  1449. function parseFieldChildren( children, owner ) {
  1450. for ( var i = 0, l = children.length; i < l; i ++ ) {
  1451. var object = getNode( children[ i ] );
  1452. if ( object instanceof THREE.Object3D ) owner.add( object );
  1453. }
  1454. }
  1455. function triangulateFaceIndex( index, ccw ) {
  1456. var indices = [];
  1457. // since face defintions can have more than three vertices, it's necessary to
  1458. // perform a simple triangulation
  1459. var start = 0;
  1460. for ( var i = 0, l = index.length; i < l; i ++ ) {
  1461. var i1 = index[ start ];
  1462. var i2 = index[ i + ( ccw ? 1 : 2 ) ];
  1463. var i3 = index[ i + ( ccw ? 2 : 1 ) ];
  1464. indices.push( i1, i2, i3 );
  1465. // an index of -1 indicates that the current face has ended and the next one begins
  1466. if ( index[ i + 3 ] === - 1 || i + 3 >= l ) {
  1467. i += 3;
  1468. start = i + 1;
  1469. }
  1470. }
  1471. return indices;
  1472. }
  1473. function triangulateFaceData( data, index ) {
  1474. var triangulatedData = [];
  1475. var start = 0;
  1476. for ( var i = 0, l = index.length; i < l; i ++ ) {
  1477. var stride = start * 3;
  1478. var x = data[ stride ];
  1479. var y = data[ stride + 1 ];
  1480. var z = data[ stride + 2 ];
  1481. triangulatedData.push( x, y, z );
  1482. // an index of -1 indicates that the current face has ended and the next one begins
  1483. if ( index[ i + 3 ] === - 1 || i + 3 >= l ) {
  1484. i += 3;
  1485. start ++;
  1486. }
  1487. }
  1488. return triangulatedData;
  1489. }
  1490. function flattenData( data, index ) {
  1491. var flattenData = [];
  1492. for ( var i = 0, l = index.length; i < l; i ++ ) {
  1493. var i1 = index[ i ];
  1494. var stride = i1 * 3;
  1495. var x = data[ stride ];
  1496. var y = data[ stride + 1 ];
  1497. var z = data[ stride + 2 ];
  1498. flattenData.push( x, y, z );
  1499. }
  1500. return flattenData;
  1501. }
  1502. function expandLineIndex( index ) {
  1503. var indices = [];
  1504. for ( var i = 0, l = index.length; i < l; i ++ ) {
  1505. var i1 = index[ i ];
  1506. var i2 = index[ i + 1 ];
  1507. indices.push( i1, i2 );
  1508. // an index of -1 indicates that the current line has ended and the next one begins
  1509. if ( index[ i + 2 ] === - 1 || i + 2 >= l ) {
  1510. i += 2;
  1511. }
  1512. }
  1513. return indices;
  1514. }
  1515. function expandLineData( data, index ) {
  1516. var triangulatedData = [];
  1517. var start = 0;
  1518. for ( var i = 0, l = index.length; i < l; i ++ ) {
  1519. var stride = start * 3;
  1520. var x = data[ stride ];
  1521. var y = data[ stride + 1 ];
  1522. var z = data[ stride + 2 ];
  1523. triangulatedData.push( x, y, z );
  1524. // an index of -1 indicates that the current line has ended and the next one begins
  1525. if ( index[ i + 2 ] === - 1 || i + 2 >= l ) {
  1526. i += 2;
  1527. start ++;
  1528. }
  1529. }
  1530. return triangulatedData;
  1531. }
  1532. var vA = new THREE.Vector3();
  1533. var vB = new THREE.Vector3();
  1534. var vC = new THREE.Vector3();
  1535. var uvA = new THREE.Vector2();
  1536. var uvB = new THREE.Vector2();
  1537. var uvC = new THREE.Vector2();
  1538. function computeAttributeFromIndexedData( coordIndex, index, data, itemSize ) {
  1539. var array = [];
  1540. // we use the coordIndex.length as delimiter since normalIndex must contain at least as many indices
  1541. for ( var i = 0, l = coordIndex.length; i < l; i += 3 ) {
  1542. var a = index[ i ];
  1543. var b = index[ i + 1 ];
  1544. var c = index[ i + 2 ];
  1545. if ( itemSize === 2 ) {
  1546. uvA.fromArray( data, a * itemSize );
  1547. uvB.fromArray( data, b * itemSize );
  1548. uvC.fromArray( data, c * itemSize );
  1549. array.push( uvA.x, uvA.y );
  1550. array.push( uvB.x, uvB.y );
  1551. array.push( uvC.x, uvC.y );
  1552. } else {
  1553. vA.fromArray( data, a * itemSize );
  1554. vB.fromArray( data, b * itemSize );
  1555. vC.fromArray( data, c * itemSize );
  1556. array.push( vA.x, vA.y, vA.z );
  1557. array.push( vB.x, vB.y, vB.z );
  1558. array.push( vC.x, vC.y, vC.z );
  1559. }
  1560. }
  1561. return new THREE.Float32BufferAttribute( array, itemSize );
  1562. }
  1563. function computeAttributeFromFaceData( index, faceData ) {
  1564. var array = [];
  1565. for ( var i = 0, j = 0, l = index.length; i < l; i += 3, j ++ ) {
  1566. vA.fromArray( faceData, j * 3 );
  1567. array.push( vA.x, vA.y, vA.z );
  1568. array.push( vA.x, vA.y, vA.z );
  1569. array.push( vA.x, vA.y, vA.z );
  1570. }
  1571. return new THREE.Float32BufferAttribute( array, 3 );
  1572. }
  1573. function computeAttributeFromLineData( index, lineData ) {
  1574. var array = [];
  1575. for ( var i = 0, j = 0, l = index.length; i < l; i += 2, j ++ ) {
  1576. vA.fromArray( lineData, j * 3 );
  1577. array.push( vA.x, vA.y, vA.z );
  1578. array.push( vA.x, vA.y, vA.z );
  1579. }
  1580. return new THREE.Float32BufferAttribute( array, 3 );
  1581. }
  1582. function toNonIndexedAttribute( indices, attribute ) {
  1583. var array = attribute.array;
  1584. var itemSize = attribute.itemSize;
  1585. var array2 = new array.constructor( indices.length * itemSize );
  1586. var index = 0, index2 = 0;
  1587. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  1588. index = indices[ i ] * itemSize;
  1589. for ( var j = 0; j < itemSize; j ++ ) {
  1590. array2[ index2 ++ ] = array[ index ++ ];
  1591. }
  1592. }
  1593. return new THREE.Float32BufferAttribute( array2, itemSize );
  1594. }
  1595. var ab = new THREE.Vector3();
  1596. var cb = new THREE.Vector3();
  1597. function computeNormalAttribute( index, coord, creaseAngle ) {
  1598. var faces = [];
  1599. var vertexNormals = {};
  1600. // prepare face and raw vertex normals
  1601. for ( var i = 0, l = index.length; i < l; i += 3 ) {
  1602. var a = index[ i ];
  1603. var b = index[ i + 1 ];
  1604. var c = index[ i + 2 ];
  1605. var face = new Face( a, b, c );
  1606. vA.fromArray( coord, a * 3 );
  1607. vB.fromArray( coord, b * 3 );
  1608. vC.fromArray( coord, c * 3 );
  1609. cb.subVectors( vC, vB );
  1610. ab.subVectors( vA, vB );
  1611. cb.cross( ab );
  1612. cb.normalize();
  1613. face.normal.copy( cb );
  1614. if ( vertexNormals[ a ] === undefined ) vertexNormals[ a ] = [];
  1615. if ( vertexNormals[ b ] === undefined ) vertexNormals[ b ] = [];
  1616. if ( vertexNormals[ c ] === undefined ) vertexNormals[ c ] = [];
  1617. vertexNormals[ a ].push( face.normal );
  1618. vertexNormals[ b ].push( face.normal );
  1619. vertexNormals[ c ].push( face.normal );
  1620. faces.push( face );
  1621. }
  1622. // compute vertex normals and build final geometry
  1623. var normals = [];
  1624. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  1625. var face = faces[ i ];
  1626. var nA = weightedNormal( vertexNormals[ face.a ], face.normal, creaseAngle );
  1627. var nB = weightedNormal( vertexNormals[ face.b ], face.normal, creaseAngle );
  1628. var nC = weightedNormal( vertexNormals[ face.c ], face.normal, creaseAngle );
  1629. vA.fromArray( coord, face.a * 3 );
  1630. vB.fromArray( coord, face.b * 3 );
  1631. vC.fromArray( coord, face.c * 3 );
  1632. normals.push( nA.x, nA.y, nA.z );
  1633. normals.push( nB.x, nB.y, nB.z );
  1634. normals.push( nC.x, nC.y, nC.z );
  1635. }
  1636. return new THREE.Float32BufferAttribute( normals, 3 );
  1637. }
  1638. function weightedNormal( normals, vector, creaseAngle ) {
  1639. var normal = new THREE.Vector3();
  1640. if ( creaseAngle === 0 ) {
  1641. normal.copy( vector );
  1642. } else {
  1643. for ( var i = 0, l = normals.length; i < l; i ++ ) {
  1644. if ( normals[ i ].angleTo( vector ) < creaseAngle ) {
  1645. normal.add( normals[ i ] );
  1646. }
  1647. }
  1648. }
  1649. return normal.normalize();
  1650. }
  1651. function toColorArray( colors ) {
  1652. var array = [];
  1653. for ( var i = 0, l = colors.length; i < l; i += 3 ) {
  1654. array.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  1655. }
  1656. return array;
  1657. }
  1658. /**
  1659. * Vertically paints the faces interpolating between the
  1660. * specified colors at the specified angels. This is used for the Background
  1661. * node, but could be applied to other nodes with multiple faces as well.
  1662. *
  1663. * When used with the Background node, default is directionIsDown is true if
  1664. * interpolating the skyColor down from the Zenith. When interpolationg up from
  1665. * the Nadir i.e. interpolating the groundColor, the directionIsDown is false.
  1666. *
  1667. * The first angle is never specified, it is the Zenith (0 rad). Angles are specified
  1668. * in radians. The geometry is thought a sphere, but could be anything. The color interpolation
  1669. * is linear along the Y axis in any case.
  1670. *
  1671. * You must specify one more color than you have angles at the beginning of the colors array.
  1672. * This is the color of the Zenith (the top of the shape).
  1673. *
  1674. * @param {BufferGeometry} geometry
  1675. * @param {number} radius
  1676. * @param {array} angles
  1677. * @param {array} colors
  1678. * @param {boolean} topDown - Whether to work top down or bottom up.
  1679. */
  1680. function paintFaces( geometry, radius, angles, colors, topDown ) {
  1681. // compute threshold values
  1682. var thresholds = [];
  1683. var startAngle = ( topDown === true ) ? 0 : Math.PI;
  1684. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  1685. var angle = ( i === 0 ) ? 0 : angles[ i - 1 ];
  1686. angle = ( topDown === true ) ? angle : ( startAngle - angle );
  1687. var point = new THREE.Vector3();
  1688. point.setFromSphericalCoords( radius, angle, 0 );
  1689. thresholds.push( point );
  1690. }
  1691. // generate vertex colors
  1692. var indices = geometry.index;
  1693. var positionAttribute = geometry.attributes.position;
  1694. var colorAttribute = new THREE.BufferAttribute( new Float32Array( geometry.attributes.position.count * 3 ), 3 );
  1695. var position = new THREE.Vector3();
  1696. var color = new THREE.Color();
  1697. for ( var i = 0; i < indices.count; i ++ ) {
  1698. var index = indices.getX( i );
  1699. position.fromBufferAttribute( positionAttribute, index );
  1700. var thresholdIndexA, thresholdIndexB;
  1701. var t = 1;
  1702. for ( var j = 1; j < thresholds.length; j ++ ) {
  1703. thresholdIndexA = j - 1;
  1704. thresholdIndexB = j;
  1705. var thresholdA = thresholds[ thresholdIndexA ];
  1706. var thresholdB = thresholds[ thresholdIndexB ];
  1707. if ( topDown === true ) {
  1708. // interpolation for sky color
  1709. if ( position.y <= thresholdA.y && position.y > thresholdB.y ) {
  1710. t = Math.abs( thresholdA.y - position.y ) / Math.abs( thresholdA.y - thresholdB.y );
  1711. break;
  1712. }
  1713. } else {
  1714. // interpolation for ground color
  1715. if ( position.y >= thresholdA.y && position.y < thresholdB.y ) {
  1716. t = Math.abs( thresholdA.y - position.y ) / Math.abs( thresholdA.y - thresholdB.y );
  1717. break;
  1718. }
  1719. }
  1720. }
  1721. var colorA = colors[ thresholdIndexA ];
  1722. var colorB = colors[ thresholdIndexB ];
  1723. color.copy( colorA ).lerp( colorB, t );
  1724. colorAttribute.setXYZ( index, color.r, color.g, color.b );
  1725. }
  1726. geometry.setAttribute( 'color', colorAttribute );
  1727. }
  1728. //
  1729. var textureLoader = new THREE.TextureLoader( this.manager );
  1730. textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  1731. // create JSON representing the tree structure of the VRML asset
  1732. var tree = generateVRMLTree( data );
  1733. // check version (only 2.0 is supported)
  1734. if ( tree.version.indexOf( 'V2.0' ) === - 1 ) {
  1735. throw Error( 'THREE.VRMLLexer: Version of VRML asset not supported.' );
  1736. }
  1737. // parse the tree structure to a three.js scene
  1738. var scene = parseTree( tree );
  1739. return scene;
  1740. }
  1741. } );
  1742. function VRMLLexer( tokens ) {
  1743. this.lexer = new chevrotain.Lexer( tokens );
  1744. }
  1745. VRMLLexer.prototype = {
  1746. constructor: VRMLLexer,
  1747. lex: function ( inputText ) {
  1748. var lexingResult = this.lexer.tokenize( inputText );
  1749. if ( lexingResult.errors.length > 0 ) {
  1750. console.error( lexingResult.errors );
  1751. throw Error( 'THREE.VRMLLexer: Lexing errors detected.' );
  1752. }
  1753. return lexingResult;
  1754. }
  1755. };
  1756. function VRMLParser( tokenVocabulary ) {
  1757. chevrotain.Parser.call( this, tokenVocabulary );
  1758. var $ = this;
  1759. var Version = tokenVocabulary[ 'Version' ];
  1760. var LCurly = tokenVocabulary[ 'LCurly' ];
  1761. var RCurly = tokenVocabulary[ 'RCurly' ];
  1762. var LSquare = tokenVocabulary[ 'LSquare' ];
  1763. var RSquare = tokenVocabulary[ 'RSquare' ];
  1764. var Identifier = tokenVocabulary[ 'Identifier' ];
  1765. var RouteIdentifier = tokenVocabulary[ 'RouteIdentifier' ];
  1766. var StringLiteral = tokenVocabulary[ 'StringLiteral' ];
  1767. var HexLiteral = tokenVocabulary[ 'HexLiteral' ];
  1768. var NumberLiteral = tokenVocabulary[ 'NumberLiteral' ];
  1769. var TrueLiteral = tokenVocabulary[ 'TrueLiteral' ];
  1770. var FalseLiteral = tokenVocabulary[ 'FalseLiteral' ];
  1771. var NullLiteral = tokenVocabulary[ 'NullLiteral' ];
  1772. var DEF = tokenVocabulary[ 'DEF' ];
  1773. var USE = tokenVocabulary[ 'USE' ];
  1774. var ROUTE = tokenVocabulary[ 'ROUTE' ];
  1775. var TO = tokenVocabulary[ 'TO' ];
  1776. var NodeName = tokenVocabulary[ 'NodeName' ];
  1777. $.RULE( 'vrml', function () {
  1778. $.SUBRULE( $.version );
  1779. $.AT_LEAST_ONE( function () {
  1780. $.SUBRULE( $.node );
  1781. } );
  1782. $.MANY( function () {
  1783. $.SUBRULE( $.route );
  1784. } );
  1785. } );
  1786. $.RULE( 'version', function () {
  1787. $.CONSUME( Version );
  1788. } );
  1789. $.RULE( 'node', function () {
  1790. $.OPTION( function () {
  1791. $.SUBRULE( $.def );
  1792. } );
  1793. $.CONSUME( NodeName );
  1794. $.CONSUME( LCurly );
  1795. $.MANY( function () {
  1796. $.SUBRULE( $.field );
  1797. } );
  1798. $.CONSUME( RCurly );
  1799. } );
  1800. $.RULE( 'field', function () {
  1801. $.CONSUME( Identifier );
  1802. $.OR2( [
  1803. { ALT: function () {
  1804. $.SUBRULE( $.singleFieldValue );
  1805. } },
  1806. { ALT: function () {
  1807. $.SUBRULE( $.multiFieldValue );
  1808. } }
  1809. ] );
  1810. } );
  1811. $.RULE( 'def', function () {
  1812. $.CONSUME( DEF );
  1813. $.CONSUME( Identifier );
  1814. } );
  1815. $.RULE( 'use', function () {
  1816. $.CONSUME( USE );
  1817. $.CONSUME( Identifier );
  1818. } );
  1819. $.RULE( 'singleFieldValue', function () {
  1820. $.AT_LEAST_ONE( function () {
  1821. $.OR( [
  1822. { ALT: function () {
  1823. $.SUBRULE( $.node );
  1824. } },
  1825. { ALT: function () {
  1826. $.SUBRULE( $.use );
  1827. } },
  1828. { ALT: function () {
  1829. $.CONSUME( StringLiteral );
  1830. } },
  1831. { ALT: function () {
  1832. $.CONSUME( HexLiteral );
  1833. } },
  1834. { ALT: function () {
  1835. $.CONSUME( NumberLiteral );
  1836. } },
  1837. { ALT: function () {
  1838. $.CONSUME( TrueLiteral );
  1839. } },
  1840. { ALT: function () {
  1841. $.CONSUME( FalseLiteral );
  1842. } },
  1843. { ALT: function () {
  1844. $.CONSUME( NullLiteral );
  1845. } }
  1846. ] );
  1847. } );
  1848. } );
  1849. $.RULE( 'multiFieldValue', function () {
  1850. $.CONSUME( LSquare );
  1851. $.MANY( function () {
  1852. $.OR( [
  1853. { ALT: function () {
  1854. $.SUBRULE( $.node );
  1855. } },
  1856. { ALT: function () {
  1857. $.SUBRULE( $.use );
  1858. } },
  1859. { ALT: function () {
  1860. $.CONSUME( StringLiteral );
  1861. } },
  1862. { ALT: function () {
  1863. $.CONSUME( HexLiteral );
  1864. } },
  1865. { ALT: function () {
  1866. $.CONSUME( NumberLiteral );
  1867. } },
  1868. { ALT: function () {
  1869. $.CONSUME( NullLiteral );
  1870. } }
  1871. ] );
  1872. } );
  1873. $.CONSUME( RSquare );
  1874. } );
  1875. $.RULE( 'route', function () {
  1876. $.CONSUME( ROUTE );
  1877. $.CONSUME( RouteIdentifier );
  1878. $.CONSUME( TO );
  1879. $.CONSUME2( RouteIdentifier );
  1880. } );
  1881. this.performSelfAnalysis();
  1882. }
  1883. VRMLParser.prototype = Object.create( chevrotain.Parser.prototype );
  1884. VRMLParser.prototype.constructor = VRMLParser;
  1885. function Face( a, b, c ) {
  1886. this.a = a;
  1887. this.b = b;
  1888. this.c = c;
  1889. this.normal = new THREE.Vector3();
  1890. }
  1891. var TEXTURE_TYPE = {
  1892. INTENSITY: 1,
  1893. INTENSITY_ALPHA: 2,
  1894. RGB: 3,
  1895. RGBA: 4
  1896. };
  1897. return VRMLLoader;
  1898. } )();