three.module.js 988 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090
  1. // Polyfills
  2. if ( Number.EPSILON === undefined ) {
  3. Number.EPSILON = Math.pow( 2, - 52 );
  4. }
  5. if ( Number.isInteger === undefined ) {
  6. // Missing in IE
  7. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  8. Number.isInteger = function ( value ) {
  9. return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
  10. };
  11. }
  12. //
  13. if ( Math.sign === undefined ) {
  14. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  15. Math.sign = function ( x ) {
  16. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  17. };
  18. }
  19. if ( Function.prototype.name === undefined ) {
  20. // Missing in IE
  21. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  22. Object.defineProperty( Function.prototype, 'name', {
  23. get: function () {
  24. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  25. }
  26. } );
  27. }
  28. if ( Object.assign === undefined ) {
  29. // Missing in IE
  30. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  31. ( function () {
  32. Object.assign = function ( target ) {
  33. 'use strict';
  34. if ( target === undefined || target === null ) {
  35. throw new TypeError( 'Cannot convert undefined or null to object' );
  36. }
  37. var output = Object( target );
  38. for ( var index = 1; index < arguments.length; index ++ ) {
  39. var source = arguments[ index ];
  40. if ( source !== undefined && source !== null ) {
  41. for ( var nextKey in source ) {
  42. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  43. output[ nextKey ] = source[ nextKey ];
  44. }
  45. }
  46. }
  47. }
  48. return output;
  49. };
  50. } )();
  51. }
  52. /**
  53. * https://github.com/mrdoob/eventdispatcher.js/
  54. */
  55. function EventDispatcher() {}
  56. Object.assign( EventDispatcher.prototype, {
  57. addEventListener: function ( type, listener ) {
  58. if ( this._listeners === undefined ) this._listeners = {};
  59. var listeners = this._listeners;
  60. if ( listeners[ type ] === undefined ) {
  61. listeners[ type ] = [];
  62. }
  63. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  64. listeners[ type ].push( listener );
  65. }
  66. },
  67. hasEventListener: function ( type, listener ) {
  68. if ( this._listeners === undefined ) return false;
  69. var listeners = this._listeners;
  70. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  71. },
  72. removeEventListener: function ( type, listener ) {
  73. if ( this._listeners === undefined ) return;
  74. var listeners = this._listeners;
  75. var listenerArray = listeners[ type ];
  76. if ( listenerArray !== undefined ) {
  77. var index = listenerArray.indexOf( listener );
  78. if ( index !== - 1 ) {
  79. listenerArray.splice( index, 1 );
  80. }
  81. }
  82. },
  83. dispatchEvent: function ( event ) {
  84. if ( this._listeners === undefined ) return;
  85. var listeners = this._listeners;
  86. var listenerArray = listeners[ event.type ];
  87. if ( listenerArray !== undefined ) {
  88. event.target = this;
  89. var array = listenerArray.slice( 0 );
  90. for ( var i = 0, l = array.length; i < l; i ++ ) {
  91. array[ i ].call( this, event );
  92. }
  93. }
  94. }
  95. } );
  96. var REVISION = '87dev';
  97. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  98. var CullFaceNone = 0;
  99. var CullFaceBack = 1;
  100. var CullFaceFront = 2;
  101. var CullFaceFrontBack = 3;
  102. var FrontFaceDirectionCW = 0;
  103. var FrontFaceDirectionCCW = 1;
  104. var BasicShadowMap = 0;
  105. var PCFShadowMap = 1;
  106. var PCFSoftShadowMap = 2;
  107. var FrontSide = 0;
  108. var BackSide = 1;
  109. var DoubleSide = 2;
  110. var FlatShading = 1;
  111. var SmoothShading = 2;
  112. var NoColors = 0;
  113. var FaceColors = 1;
  114. var VertexColors = 2;
  115. var NoBlending = 0;
  116. var NormalBlending = 1;
  117. var AdditiveBlending = 2;
  118. var SubtractiveBlending = 3;
  119. var MultiplyBlending = 4;
  120. var CustomBlending = 5;
  121. var AddEquation = 100;
  122. var SubtractEquation = 101;
  123. var ReverseSubtractEquation = 102;
  124. var MinEquation = 103;
  125. var MaxEquation = 104;
  126. var ZeroFactor = 200;
  127. var OneFactor = 201;
  128. var SrcColorFactor = 202;
  129. var OneMinusSrcColorFactor = 203;
  130. var SrcAlphaFactor = 204;
  131. var OneMinusSrcAlphaFactor = 205;
  132. var DstAlphaFactor = 206;
  133. var OneMinusDstAlphaFactor = 207;
  134. var DstColorFactor = 208;
  135. var OneMinusDstColorFactor = 209;
  136. var SrcAlphaSaturateFactor = 210;
  137. var NeverDepth = 0;
  138. var AlwaysDepth = 1;
  139. var LessDepth = 2;
  140. var LessEqualDepth = 3;
  141. var EqualDepth = 4;
  142. var GreaterEqualDepth = 5;
  143. var GreaterDepth = 6;
  144. var NotEqualDepth = 7;
  145. var MultiplyOperation = 0;
  146. var MixOperation = 1;
  147. var AddOperation = 2;
  148. var NoToneMapping = 0;
  149. var LinearToneMapping = 1;
  150. var ReinhardToneMapping = 2;
  151. var Uncharted2ToneMapping = 3;
  152. var CineonToneMapping = 4;
  153. var UVMapping = 300;
  154. var CubeReflectionMapping = 301;
  155. var CubeRefractionMapping = 302;
  156. var EquirectangularReflectionMapping = 303;
  157. var EquirectangularRefractionMapping = 304;
  158. var SphericalReflectionMapping = 305;
  159. var CubeUVReflectionMapping = 306;
  160. var CubeUVRefractionMapping = 307;
  161. var RepeatWrapping = 1000;
  162. var ClampToEdgeWrapping = 1001;
  163. var MirroredRepeatWrapping = 1002;
  164. var NearestFilter = 1003;
  165. var NearestMipMapNearestFilter = 1004;
  166. var NearestMipMapLinearFilter = 1005;
  167. var LinearFilter = 1006;
  168. var LinearMipMapNearestFilter = 1007;
  169. var LinearMipMapLinearFilter = 1008;
  170. var UnsignedByteType = 1009;
  171. var ByteType = 1010;
  172. var ShortType = 1011;
  173. var UnsignedShortType = 1012;
  174. var IntType = 1013;
  175. var UnsignedIntType = 1014;
  176. var FloatType = 1015;
  177. var HalfFloatType = 1016;
  178. var UnsignedShort4444Type = 1017;
  179. var UnsignedShort5551Type = 1018;
  180. var UnsignedShort565Type = 1019;
  181. var UnsignedInt248Type = 1020;
  182. var AlphaFormat = 1021;
  183. var RGBFormat = 1022;
  184. var RGBAFormat = 1023;
  185. var LuminanceFormat = 1024;
  186. var LuminanceAlphaFormat = 1025;
  187. var RGBEFormat = RGBAFormat;
  188. var DepthFormat = 1026;
  189. var DepthStencilFormat = 1027;
  190. var RGB_S3TC_DXT1_Format = 2001;
  191. var RGBA_S3TC_DXT1_Format = 2002;
  192. var RGBA_S3TC_DXT3_Format = 2003;
  193. var RGBA_S3TC_DXT5_Format = 2004;
  194. var RGB_PVRTC_4BPPV1_Format = 2100;
  195. var RGB_PVRTC_2BPPV1_Format = 2101;
  196. var RGBA_PVRTC_4BPPV1_Format = 2102;
  197. var RGBA_PVRTC_2BPPV1_Format = 2103;
  198. var RGB_ETC1_Format = 2151;
  199. var LoopOnce = 2200;
  200. var LoopRepeat = 2201;
  201. var LoopPingPong = 2202;
  202. var InterpolateDiscrete = 2300;
  203. var InterpolateLinear = 2301;
  204. var InterpolateSmooth = 2302;
  205. var ZeroCurvatureEnding = 2400;
  206. var ZeroSlopeEnding = 2401;
  207. var WrapAroundEnding = 2402;
  208. var TrianglesDrawMode = 0;
  209. var TriangleStripDrawMode = 1;
  210. var TriangleFanDrawMode = 2;
  211. var LinearEncoding = 3000;
  212. var sRGBEncoding = 3001;
  213. var GammaEncoding = 3007;
  214. var RGBEEncoding = 3002;
  215. var LogLuvEncoding = 3003;
  216. var RGBM7Encoding = 3004;
  217. var RGBM16Encoding = 3005;
  218. var RGBDEncoding = 3006;
  219. var BasicDepthPacking = 3200;
  220. var RGBADepthPacking = 3201;
  221. /**
  222. * @author alteredq / http://alteredqualia.com/
  223. * @author mrdoob / http://mrdoob.com/
  224. */
  225. var _Math = {
  226. DEG2RAD: Math.PI / 180,
  227. RAD2DEG: 180 / Math.PI,
  228. generateUUID: function () {
  229. // http://www.broofa.com/Tools/Math.uuid.htm
  230. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  231. var uuid = new Array( 36 );
  232. var rnd = 0, r;
  233. return function generateUUID() {
  234. for ( var i = 0; i < 36; i ++ ) {
  235. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  236. uuid[ i ] = '-';
  237. } else if ( i === 14 ) {
  238. uuid[ i ] = '4';
  239. } else {
  240. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  241. r = rnd & 0xf;
  242. rnd = rnd >> 4;
  243. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  244. }
  245. }
  246. return uuid.join( '' );
  247. };
  248. }(),
  249. clamp: function ( value, min, max ) {
  250. return Math.max( min, Math.min( max, value ) );
  251. },
  252. // compute euclidian modulo of m % n
  253. // https://en.wikipedia.org/wiki/Modulo_operation
  254. euclideanModulo: function ( n, m ) {
  255. return ( ( n % m ) + m ) % m;
  256. },
  257. // Linear mapping from range <a1, a2> to range <b1, b2>
  258. mapLinear: function ( x, a1, a2, b1, b2 ) {
  259. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  260. },
  261. // https://en.wikipedia.org/wiki/Linear_interpolation
  262. lerp: function ( x, y, t ) {
  263. return ( 1 - t ) * x + t * y;
  264. },
  265. // http://en.wikipedia.org/wiki/Smoothstep
  266. smoothstep: function ( x, min, max ) {
  267. if ( x <= min ) return 0;
  268. if ( x >= max ) return 1;
  269. x = ( x - min ) / ( max - min );
  270. return x * x * ( 3 - 2 * x );
  271. },
  272. smootherstep: function ( x, min, max ) {
  273. if ( x <= min ) return 0;
  274. if ( x >= max ) return 1;
  275. x = ( x - min ) / ( max - min );
  276. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  277. },
  278. // Random integer from <low, high> interval
  279. randInt: function ( low, high ) {
  280. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  281. },
  282. // Random float from <low, high> interval
  283. randFloat: function ( low, high ) {
  284. return low + Math.random() * ( high - low );
  285. },
  286. // Random float from <-range/2, range/2> interval
  287. randFloatSpread: function ( range ) {
  288. return range * ( 0.5 - Math.random() );
  289. },
  290. degToRad: function ( degrees ) {
  291. return degrees * _Math.DEG2RAD;
  292. },
  293. radToDeg: function ( radians ) {
  294. return radians * _Math.RAD2DEG;
  295. },
  296. isPowerOfTwo: function ( value ) {
  297. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  298. },
  299. nearestPowerOfTwo: function ( value ) {
  300. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  301. },
  302. nextPowerOfTwo: function ( value ) {
  303. value --;
  304. value |= value >> 1;
  305. value |= value >> 2;
  306. value |= value >> 4;
  307. value |= value >> 8;
  308. value |= value >> 16;
  309. value ++;
  310. return value;
  311. }
  312. };
  313. /**
  314. * @author mrdoob / http://mrdoob.com/
  315. * @author philogb / http://blog.thejit.org/
  316. * @author egraether / http://egraether.com/
  317. * @author zz85 / http://www.lab4games.net/zz85/blog
  318. */
  319. function Vector2( x, y ) {
  320. this.x = x || 0;
  321. this.y = y || 0;
  322. }
  323. Object.defineProperties( Vector2.prototype, {
  324. "width" : {
  325. get: function () {
  326. return this.x;
  327. },
  328. set: function ( value ) {
  329. this.x = value;
  330. }
  331. },
  332. "height" : {
  333. get: function () {
  334. return this.y;
  335. },
  336. set: function ( value ) {
  337. this.y = value;
  338. }
  339. }
  340. } );
  341. Object.assign( Vector2.prototype, {
  342. isVector2: true,
  343. set: function ( x, y ) {
  344. this.x = x;
  345. this.y = y;
  346. return this;
  347. },
  348. setScalar: function ( scalar ) {
  349. this.x = scalar;
  350. this.y = scalar;
  351. return this;
  352. },
  353. setX: function ( x ) {
  354. this.x = x;
  355. return this;
  356. },
  357. setY: function ( y ) {
  358. this.y = y;
  359. return this;
  360. },
  361. setComponent: function ( index, value ) {
  362. switch ( index ) {
  363. case 0: this.x = value; break;
  364. case 1: this.y = value; break;
  365. default: throw new Error( 'index is out of range: ' + index );
  366. }
  367. return this;
  368. },
  369. getComponent: function ( index ) {
  370. switch ( index ) {
  371. case 0: return this.x;
  372. case 1: return this.y;
  373. default: throw new Error( 'index is out of range: ' + index );
  374. }
  375. },
  376. clone: function () {
  377. return new this.constructor( this.x, this.y );
  378. },
  379. copy: function ( v ) {
  380. this.x = v.x;
  381. this.y = v.y;
  382. return this;
  383. },
  384. add: function ( v, w ) {
  385. if ( w !== undefined ) {
  386. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  387. return this.addVectors( v, w );
  388. }
  389. this.x += v.x;
  390. this.y += v.y;
  391. return this;
  392. },
  393. addScalar: function ( s ) {
  394. this.x += s;
  395. this.y += s;
  396. return this;
  397. },
  398. addVectors: function ( a, b ) {
  399. this.x = a.x + b.x;
  400. this.y = a.y + b.y;
  401. return this;
  402. },
  403. addScaledVector: function ( v, s ) {
  404. this.x += v.x * s;
  405. this.y += v.y * s;
  406. return this;
  407. },
  408. sub: function ( v, w ) {
  409. if ( w !== undefined ) {
  410. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  411. return this.subVectors( v, w );
  412. }
  413. this.x -= v.x;
  414. this.y -= v.y;
  415. return this;
  416. },
  417. subScalar: function ( s ) {
  418. this.x -= s;
  419. this.y -= s;
  420. return this;
  421. },
  422. subVectors: function ( a, b ) {
  423. this.x = a.x - b.x;
  424. this.y = a.y - b.y;
  425. return this;
  426. },
  427. multiply: function ( v ) {
  428. this.x *= v.x;
  429. this.y *= v.y;
  430. return this;
  431. },
  432. multiplyScalar: function ( scalar ) {
  433. this.x *= scalar;
  434. this.y *= scalar;
  435. return this;
  436. },
  437. divide: function ( v ) {
  438. this.x /= v.x;
  439. this.y /= v.y;
  440. return this;
  441. },
  442. divideScalar: function ( scalar ) {
  443. return this.multiplyScalar( 1 / scalar );
  444. },
  445. min: function ( v ) {
  446. this.x = Math.min( this.x, v.x );
  447. this.y = Math.min( this.y, v.y );
  448. return this;
  449. },
  450. max: function ( v ) {
  451. this.x = Math.max( this.x, v.x );
  452. this.y = Math.max( this.y, v.y );
  453. return this;
  454. },
  455. clamp: function ( min, max ) {
  456. // assumes min < max, componentwise
  457. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  458. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  459. return this;
  460. },
  461. clampScalar: function () {
  462. var min = new Vector2();
  463. var max = new Vector2();
  464. return function clampScalar( minVal, maxVal ) {
  465. min.set( minVal, minVal );
  466. max.set( maxVal, maxVal );
  467. return this.clamp( min, max );
  468. };
  469. }(),
  470. clampLength: function ( min, max ) {
  471. var length = this.length();
  472. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  473. },
  474. floor: function () {
  475. this.x = Math.floor( this.x );
  476. this.y = Math.floor( this.y );
  477. return this;
  478. },
  479. ceil: function () {
  480. this.x = Math.ceil( this.x );
  481. this.y = Math.ceil( this.y );
  482. return this;
  483. },
  484. round: function () {
  485. this.x = Math.round( this.x );
  486. this.y = Math.round( this.y );
  487. return this;
  488. },
  489. roundToZero: function () {
  490. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  491. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  492. return this;
  493. },
  494. negate: function () {
  495. this.x = - this.x;
  496. this.y = - this.y;
  497. return this;
  498. },
  499. dot: function ( v ) {
  500. return this.x * v.x + this.y * v.y;
  501. },
  502. lengthSq: function () {
  503. return this.x * this.x + this.y * this.y;
  504. },
  505. length: function () {
  506. return Math.sqrt( this.x * this.x + this.y * this.y );
  507. },
  508. lengthManhattan: function() {
  509. return Math.abs( this.x ) + Math.abs( this.y );
  510. },
  511. normalize: function () {
  512. return this.divideScalar( this.length() || 1 );
  513. },
  514. angle: function () {
  515. // computes the angle in radians with respect to the positive x-axis
  516. var angle = Math.atan2( this.y, this.x );
  517. if ( angle < 0 ) angle += 2 * Math.PI;
  518. return angle;
  519. },
  520. distanceTo: function ( v ) {
  521. return Math.sqrt( this.distanceToSquared( v ) );
  522. },
  523. distanceToSquared: function ( v ) {
  524. var dx = this.x - v.x, dy = this.y - v.y;
  525. return dx * dx + dy * dy;
  526. },
  527. distanceToManhattan: function ( v ) {
  528. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  529. },
  530. setLength: function ( length ) {
  531. return this.normalize().multiplyScalar( length );
  532. },
  533. lerp: function ( v, alpha ) {
  534. this.x += ( v.x - this.x ) * alpha;
  535. this.y += ( v.y - this.y ) * alpha;
  536. return this;
  537. },
  538. lerpVectors: function ( v1, v2, alpha ) {
  539. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  540. },
  541. equals: function ( v ) {
  542. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  543. },
  544. fromArray: function ( array, offset ) {
  545. if ( offset === undefined ) offset = 0;
  546. this.x = array[ offset ];
  547. this.y = array[ offset + 1 ];
  548. return this;
  549. },
  550. toArray: function ( array, offset ) {
  551. if ( array === undefined ) array = [];
  552. if ( offset === undefined ) offset = 0;
  553. array[ offset ] = this.x;
  554. array[ offset + 1 ] = this.y;
  555. return array;
  556. },
  557. fromBufferAttribute: function ( attribute, index, offset ) {
  558. if ( offset !== undefined ) {
  559. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  560. }
  561. this.x = attribute.getX( index );
  562. this.y = attribute.getY( index );
  563. return this;
  564. },
  565. rotateAround: function ( center, angle ) {
  566. var c = Math.cos( angle ), s = Math.sin( angle );
  567. var x = this.x - center.x;
  568. var y = this.y - center.y;
  569. this.x = x * c - y * s + center.x;
  570. this.y = x * s + y * c + center.y;
  571. return this;
  572. }
  573. } );
  574. /**
  575. * @author mrdoob / http://mrdoob.com/
  576. * @author alteredq / http://alteredqualia.com/
  577. * @author szimek / https://github.com/szimek/
  578. */
  579. var textureId = 0;
  580. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  581. Object.defineProperty( this, 'id', { value: textureId ++ } );
  582. this.uuid = _Math.generateUUID();
  583. this.name = '';
  584. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  585. this.mipmaps = [];
  586. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  587. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  588. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  589. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  590. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  591. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  592. this.format = format !== undefined ? format : RGBAFormat;
  593. this.type = type !== undefined ? type : UnsignedByteType;
  594. this.offset = new Vector2( 0, 0 );
  595. this.repeat = new Vector2( 1, 1 );
  596. this.generateMipmaps = true;
  597. this.premultiplyAlpha = false;
  598. this.flipY = true;
  599. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  600. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  601. //
  602. // Also changing the encoding after already used by a Material will not automatically make the Material
  603. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  604. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  605. this.version = 0;
  606. this.onUpdate = null;
  607. }
  608. Texture.DEFAULT_IMAGE = undefined;
  609. Texture.DEFAULT_MAPPING = UVMapping;
  610. Object.defineProperty( Texture.prototype, "needsUpdate", {
  611. set: function ( value ) {
  612. if ( value === true ) this.version ++;
  613. }
  614. } );
  615. Object.assign( Texture.prototype, EventDispatcher.prototype, {
  616. constructor: Texture,
  617. isTexture: true,
  618. clone: function () {
  619. return new this.constructor().copy( this );
  620. },
  621. copy: function ( source ) {
  622. this.name = source.name;
  623. this.image = source.image;
  624. this.mipmaps = source.mipmaps.slice( 0 );
  625. this.mapping = source.mapping;
  626. this.wrapS = source.wrapS;
  627. this.wrapT = source.wrapT;
  628. this.magFilter = source.magFilter;
  629. this.minFilter = source.minFilter;
  630. this.anisotropy = source.anisotropy;
  631. this.format = source.format;
  632. this.type = source.type;
  633. this.offset.copy( source.offset );
  634. this.repeat.copy( source.repeat );
  635. this.generateMipmaps = source.generateMipmaps;
  636. this.premultiplyAlpha = source.premultiplyAlpha;
  637. this.flipY = source.flipY;
  638. this.unpackAlignment = source.unpackAlignment;
  639. this.encoding = source.encoding;
  640. return this;
  641. },
  642. toJSON: function ( meta ) {
  643. if ( meta.textures[ this.uuid ] !== undefined ) {
  644. return meta.textures[ this.uuid ];
  645. }
  646. function getDataURL( image ) {
  647. var canvas;
  648. if ( image.toDataURL !== undefined ) {
  649. canvas = image;
  650. } else {
  651. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  652. canvas.width = image.width;
  653. canvas.height = image.height;
  654. var context = canvas.getContext( '2d' );
  655. if ( image instanceof ImageData ) {
  656. context.putImageData( image, 0, 0 );
  657. } else {
  658. context.drawImage( image, 0, 0, image.width, image.height );
  659. }
  660. }
  661. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  662. return canvas.toDataURL( 'image/jpeg', 0.6 );
  663. } else {
  664. return canvas.toDataURL( 'image/png' );
  665. }
  666. }
  667. var output = {
  668. metadata: {
  669. version: 4.5,
  670. type: 'Texture',
  671. generator: 'Texture.toJSON'
  672. },
  673. uuid: this.uuid,
  674. name: this.name,
  675. mapping: this.mapping,
  676. repeat: [ this.repeat.x, this.repeat.y ],
  677. offset: [ this.offset.x, this.offset.y ],
  678. wrap: [ this.wrapS, this.wrapT ],
  679. minFilter: this.minFilter,
  680. magFilter: this.magFilter,
  681. anisotropy: this.anisotropy,
  682. flipY: this.flipY
  683. };
  684. if ( this.image !== undefined ) {
  685. // TODO: Move to THREE.Image
  686. var image = this.image;
  687. if ( image.uuid === undefined ) {
  688. image.uuid = _Math.generateUUID(); // UGH
  689. }
  690. if ( meta.images[ image.uuid ] === undefined ) {
  691. meta.images[ image.uuid ] = {
  692. uuid: image.uuid,
  693. url: getDataURL( image )
  694. };
  695. }
  696. output.image = image.uuid;
  697. }
  698. meta.textures[ this.uuid ] = output;
  699. return output;
  700. },
  701. dispose: function () {
  702. this.dispatchEvent( { type: 'dispose' } );
  703. },
  704. transformUv: function ( uv ) {
  705. if ( this.mapping !== UVMapping ) return;
  706. uv.multiply( this.repeat );
  707. uv.add( this.offset );
  708. if ( uv.x < 0 || uv.x > 1 ) {
  709. switch ( this.wrapS ) {
  710. case RepeatWrapping:
  711. uv.x = uv.x - Math.floor( uv.x );
  712. break;
  713. case ClampToEdgeWrapping:
  714. uv.x = uv.x < 0 ? 0 : 1;
  715. break;
  716. case MirroredRepeatWrapping:
  717. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  718. uv.x = Math.ceil( uv.x ) - uv.x;
  719. } else {
  720. uv.x = uv.x - Math.floor( uv.x );
  721. }
  722. break;
  723. }
  724. }
  725. if ( uv.y < 0 || uv.y > 1 ) {
  726. switch ( this.wrapT ) {
  727. case RepeatWrapping:
  728. uv.y = uv.y - Math.floor( uv.y );
  729. break;
  730. case ClampToEdgeWrapping:
  731. uv.y = uv.y < 0 ? 0 : 1;
  732. break;
  733. case MirroredRepeatWrapping:
  734. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  735. uv.y = Math.ceil( uv.y ) - uv.y;
  736. } else {
  737. uv.y = uv.y - Math.floor( uv.y );
  738. }
  739. break;
  740. }
  741. }
  742. if ( this.flipY ) {
  743. uv.y = 1 - uv.y;
  744. }
  745. }
  746. } );
  747. /**
  748. * @author supereggbert / http://www.paulbrunt.co.uk/
  749. * @author philogb / http://blog.thejit.org/
  750. * @author mikael emtinger / http://gomo.se/
  751. * @author egraether / http://egraether.com/
  752. * @author WestLangley / http://github.com/WestLangley
  753. */
  754. function Vector4( x, y, z, w ) {
  755. this.x = x || 0;
  756. this.y = y || 0;
  757. this.z = z || 0;
  758. this.w = ( w !== undefined ) ? w : 1;
  759. }
  760. Object.assign( Vector4.prototype, {
  761. isVector4: true,
  762. set: function ( x, y, z, w ) {
  763. this.x = x;
  764. this.y = y;
  765. this.z = z;
  766. this.w = w;
  767. return this;
  768. },
  769. setScalar: function ( scalar ) {
  770. this.x = scalar;
  771. this.y = scalar;
  772. this.z = scalar;
  773. this.w = scalar;
  774. return this;
  775. },
  776. setX: function ( x ) {
  777. this.x = x;
  778. return this;
  779. },
  780. setY: function ( y ) {
  781. this.y = y;
  782. return this;
  783. },
  784. setZ: function ( z ) {
  785. this.z = z;
  786. return this;
  787. },
  788. setW: function ( w ) {
  789. this.w = w;
  790. return this;
  791. },
  792. setComponent: function ( index, value ) {
  793. switch ( index ) {
  794. case 0: this.x = value; break;
  795. case 1: this.y = value; break;
  796. case 2: this.z = value; break;
  797. case 3: this.w = value; break;
  798. default: throw new Error( 'index is out of range: ' + index );
  799. }
  800. return this;
  801. },
  802. getComponent: function ( index ) {
  803. switch ( index ) {
  804. case 0: return this.x;
  805. case 1: return this.y;
  806. case 2: return this.z;
  807. case 3: return this.w;
  808. default: throw new Error( 'index is out of range: ' + index );
  809. }
  810. },
  811. clone: function () {
  812. return new this.constructor( this.x, this.y, this.z, this.w );
  813. },
  814. copy: function ( v ) {
  815. this.x = v.x;
  816. this.y = v.y;
  817. this.z = v.z;
  818. this.w = ( v.w !== undefined ) ? v.w : 1;
  819. return this;
  820. },
  821. add: function ( v, w ) {
  822. if ( w !== undefined ) {
  823. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  824. return this.addVectors( v, w );
  825. }
  826. this.x += v.x;
  827. this.y += v.y;
  828. this.z += v.z;
  829. this.w += v.w;
  830. return this;
  831. },
  832. addScalar: function ( s ) {
  833. this.x += s;
  834. this.y += s;
  835. this.z += s;
  836. this.w += s;
  837. return this;
  838. },
  839. addVectors: function ( a, b ) {
  840. this.x = a.x + b.x;
  841. this.y = a.y + b.y;
  842. this.z = a.z + b.z;
  843. this.w = a.w + b.w;
  844. return this;
  845. },
  846. addScaledVector: function ( v, s ) {
  847. this.x += v.x * s;
  848. this.y += v.y * s;
  849. this.z += v.z * s;
  850. this.w += v.w * s;
  851. return this;
  852. },
  853. sub: function ( v, w ) {
  854. if ( w !== undefined ) {
  855. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  856. return this.subVectors( v, w );
  857. }
  858. this.x -= v.x;
  859. this.y -= v.y;
  860. this.z -= v.z;
  861. this.w -= v.w;
  862. return this;
  863. },
  864. subScalar: function ( s ) {
  865. this.x -= s;
  866. this.y -= s;
  867. this.z -= s;
  868. this.w -= s;
  869. return this;
  870. },
  871. subVectors: function ( a, b ) {
  872. this.x = a.x - b.x;
  873. this.y = a.y - b.y;
  874. this.z = a.z - b.z;
  875. this.w = a.w - b.w;
  876. return this;
  877. },
  878. multiplyScalar: function ( scalar ) {
  879. this.x *= scalar;
  880. this.y *= scalar;
  881. this.z *= scalar;
  882. this.w *= scalar;
  883. return this;
  884. },
  885. applyMatrix4: function ( m ) {
  886. var x = this.x, y = this.y, z = this.z, w = this.w;
  887. var e = m.elements;
  888. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  889. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  890. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  891. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  892. return this;
  893. },
  894. divideScalar: function ( scalar ) {
  895. return this.multiplyScalar( 1 / scalar );
  896. },
  897. setAxisAngleFromQuaternion: function ( q ) {
  898. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  899. // q is assumed to be normalized
  900. this.w = 2 * Math.acos( q.w );
  901. var s = Math.sqrt( 1 - q.w * q.w );
  902. if ( s < 0.0001 ) {
  903. this.x = 1;
  904. this.y = 0;
  905. this.z = 0;
  906. } else {
  907. this.x = q.x / s;
  908. this.y = q.y / s;
  909. this.z = q.z / s;
  910. }
  911. return this;
  912. },
  913. setAxisAngleFromRotationMatrix: function ( m ) {
  914. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  915. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  916. var angle, x, y, z, // variables for result
  917. epsilon = 0.01, // margin to allow for rounding errors
  918. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  919. te = m.elements,
  920. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  921. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  922. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  923. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  924. ( Math.abs( m13 - m31 ) < epsilon ) &&
  925. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  926. // singularity found
  927. // first check for identity matrix which must have +1 for all terms
  928. // in leading diagonal and zero in other terms
  929. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  930. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  931. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  932. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  933. // this singularity is identity matrix so angle = 0
  934. this.set( 1, 0, 0, 0 );
  935. return this; // zero angle, arbitrary axis
  936. }
  937. // otherwise this singularity is angle = 180
  938. angle = Math.PI;
  939. var xx = ( m11 + 1 ) / 2;
  940. var yy = ( m22 + 1 ) / 2;
  941. var zz = ( m33 + 1 ) / 2;
  942. var xy = ( m12 + m21 ) / 4;
  943. var xz = ( m13 + m31 ) / 4;
  944. var yz = ( m23 + m32 ) / 4;
  945. if ( ( xx > yy ) && ( xx > zz ) ) {
  946. // m11 is the largest diagonal term
  947. if ( xx < epsilon ) {
  948. x = 0;
  949. y = 0.707106781;
  950. z = 0.707106781;
  951. } else {
  952. x = Math.sqrt( xx );
  953. y = xy / x;
  954. z = xz / x;
  955. }
  956. } else if ( yy > zz ) {
  957. // m22 is the largest diagonal term
  958. if ( yy < epsilon ) {
  959. x = 0.707106781;
  960. y = 0;
  961. z = 0.707106781;
  962. } else {
  963. y = Math.sqrt( yy );
  964. x = xy / y;
  965. z = yz / y;
  966. }
  967. } else {
  968. // m33 is the largest diagonal term so base result on this
  969. if ( zz < epsilon ) {
  970. x = 0.707106781;
  971. y = 0.707106781;
  972. z = 0;
  973. } else {
  974. z = Math.sqrt( zz );
  975. x = xz / z;
  976. y = yz / z;
  977. }
  978. }
  979. this.set( x, y, z, angle );
  980. return this; // return 180 deg rotation
  981. }
  982. // as we have reached here there are no singularities so we can handle normally
  983. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  984. ( m13 - m31 ) * ( m13 - m31 ) +
  985. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  986. if ( Math.abs( s ) < 0.001 ) s = 1;
  987. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  988. // caught by singularity test above, but I've left it in just in case
  989. this.x = ( m32 - m23 ) / s;
  990. this.y = ( m13 - m31 ) / s;
  991. this.z = ( m21 - m12 ) / s;
  992. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  993. return this;
  994. },
  995. min: function ( v ) {
  996. this.x = Math.min( this.x, v.x );
  997. this.y = Math.min( this.y, v.y );
  998. this.z = Math.min( this.z, v.z );
  999. this.w = Math.min( this.w, v.w );
  1000. return this;
  1001. },
  1002. max: function ( v ) {
  1003. this.x = Math.max( this.x, v.x );
  1004. this.y = Math.max( this.y, v.y );
  1005. this.z = Math.max( this.z, v.z );
  1006. this.w = Math.max( this.w, v.w );
  1007. return this;
  1008. },
  1009. clamp: function ( min, max ) {
  1010. // assumes min < max, componentwise
  1011. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1012. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1013. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1014. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1015. return this;
  1016. },
  1017. clampScalar: function () {
  1018. var min, max;
  1019. return function clampScalar( minVal, maxVal ) {
  1020. if ( min === undefined ) {
  1021. min = new Vector4();
  1022. max = new Vector4();
  1023. }
  1024. min.set( minVal, minVal, minVal, minVal );
  1025. max.set( maxVal, maxVal, maxVal, maxVal );
  1026. return this.clamp( min, max );
  1027. };
  1028. }(),
  1029. clampLength: function ( min, max ) {
  1030. var length = this.length();
  1031. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1032. },
  1033. floor: function () {
  1034. this.x = Math.floor( this.x );
  1035. this.y = Math.floor( this.y );
  1036. this.z = Math.floor( this.z );
  1037. this.w = Math.floor( this.w );
  1038. return this;
  1039. },
  1040. ceil: function () {
  1041. this.x = Math.ceil( this.x );
  1042. this.y = Math.ceil( this.y );
  1043. this.z = Math.ceil( this.z );
  1044. this.w = Math.ceil( this.w );
  1045. return this;
  1046. },
  1047. round: function () {
  1048. this.x = Math.round( this.x );
  1049. this.y = Math.round( this.y );
  1050. this.z = Math.round( this.z );
  1051. this.w = Math.round( this.w );
  1052. return this;
  1053. },
  1054. roundToZero: function () {
  1055. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1056. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1057. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1058. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1059. return this;
  1060. },
  1061. negate: function () {
  1062. this.x = - this.x;
  1063. this.y = - this.y;
  1064. this.z = - this.z;
  1065. this.w = - this.w;
  1066. return this;
  1067. },
  1068. dot: function ( v ) {
  1069. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1070. },
  1071. lengthSq: function () {
  1072. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1073. },
  1074. length: function () {
  1075. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1076. },
  1077. lengthManhattan: function () {
  1078. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1079. },
  1080. normalize: function () {
  1081. return this.divideScalar( this.length() || 1 );
  1082. },
  1083. setLength: function ( length ) {
  1084. return this.normalize().multiplyScalar( length );
  1085. },
  1086. lerp: function ( v, alpha ) {
  1087. this.x += ( v.x - this.x ) * alpha;
  1088. this.y += ( v.y - this.y ) * alpha;
  1089. this.z += ( v.z - this.z ) * alpha;
  1090. this.w += ( v.w - this.w ) * alpha;
  1091. return this;
  1092. },
  1093. lerpVectors: function ( v1, v2, alpha ) {
  1094. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1095. },
  1096. equals: function ( v ) {
  1097. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1098. },
  1099. fromArray: function ( array, offset ) {
  1100. if ( offset === undefined ) offset = 0;
  1101. this.x = array[ offset ];
  1102. this.y = array[ offset + 1 ];
  1103. this.z = array[ offset + 2 ];
  1104. this.w = array[ offset + 3 ];
  1105. return this;
  1106. },
  1107. toArray: function ( array, offset ) {
  1108. if ( array === undefined ) array = [];
  1109. if ( offset === undefined ) offset = 0;
  1110. array[ offset ] = this.x;
  1111. array[ offset + 1 ] = this.y;
  1112. array[ offset + 2 ] = this.z;
  1113. array[ offset + 3 ] = this.w;
  1114. return array;
  1115. },
  1116. fromBufferAttribute: function ( attribute, index, offset ) {
  1117. if ( offset !== undefined ) {
  1118. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  1119. }
  1120. this.x = attribute.getX( index );
  1121. this.y = attribute.getY( index );
  1122. this.z = attribute.getZ( index );
  1123. this.w = attribute.getW( index );
  1124. return this;
  1125. }
  1126. } );
  1127. /**
  1128. * @author szimek / https://github.com/szimek/
  1129. * @author alteredq / http://alteredqualia.com/
  1130. * @author Marius Kintel / https://github.com/kintel
  1131. */
  1132. /*
  1133. In options, we can specify:
  1134. * Texture parameters for an auto-generated target texture
  1135. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1136. */
  1137. function WebGLRenderTarget( width, height, options ) {
  1138. this.uuid = _Math.generateUUID();
  1139. this.width = width;
  1140. this.height = height;
  1141. this.scissor = new Vector4( 0, 0, width, height );
  1142. this.scissorTest = false;
  1143. this.viewport = new Vector4( 0, 0, width, height );
  1144. options = options || {};
  1145. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  1146. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1147. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1148. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  1149. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1150. }
  1151. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, {
  1152. isWebGLRenderTarget: true,
  1153. setSize: function ( width, height ) {
  1154. if ( this.width !== width || this.height !== height ) {
  1155. this.width = width;
  1156. this.height = height;
  1157. this.dispose();
  1158. }
  1159. this.viewport.set( 0, 0, width, height );
  1160. this.scissor.set( 0, 0, width, height );
  1161. },
  1162. clone: function () {
  1163. return new this.constructor().copy( this );
  1164. },
  1165. copy: function ( source ) {
  1166. this.width = source.width;
  1167. this.height = source.height;
  1168. this.viewport.copy( source.viewport );
  1169. this.texture = source.texture.clone();
  1170. this.depthBuffer = source.depthBuffer;
  1171. this.stencilBuffer = source.stencilBuffer;
  1172. this.depthTexture = source.depthTexture;
  1173. return this;
  1174. },
  1175. dispose: function () {
  1176. this.dispatchEvent( { type: 'dispose' } );
  1177. }
  1178. } );
  1179. /**
  1180. * @author alteredq / http://alteredqualia.com
  1181. */
  1182. function WebGLRenderTargetCube( width, height, options ) {
  1183. WebGLRenderTarget.call( this, width, height, options );
  1184. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  1185. this.activeMipMapLevel = 0;
  1186. }
  1187. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  1188. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  1189. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  1190. /**
  1191. * @author mikael emtinger / http://gomo.se/
  1192. * @author alteredq / http://alteredqualia.com/
  1193. * @author WestLangley / http://github.com/WestLangley
  1194. * @author bhouston / http://clara.io
  1195. */
  1196. function Quaternion( x, y, z, w ) {
  1197. this._x = x || 0;
  1198. this._y = y || 0;
  1199. this._z = z || 0;
  1200. this._w = ( w !== undefined ) ? w : 1;
  1201. }
  1202. Object.assign( Quaternion, {
  1203. slerp: function ( qa, qb, qm, t ) {
  1204. return qm.copy( qa ).slerp( qb, t );
  1205. },
  1206. slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1207. // fuzz-free, array-based Quaternion SLERP operation
  1208. var x0 = src0[ srcOffset0 + 0 ],
  1209. y0 = src0[ srcOffset0 + 1 ],
  1210. z0 = src0[ srcOffset0 + 2 ],
  1211. w0 = src0[ srcOffset0 + 3 ],
  1212. x1 = src1[ srcOffset1 + 0 ],
  1213. y1 = src1[ srcOffset1 + 1 ],
  1214. z1 = src1[ srcOffset1 + 2 ],
  1215. w1 = src1[ srcOffset1 + 3 ];
  1216. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1217. var s = 1 - t,
  1218. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1219. dir = ( cos >= 0 ? 1 : - 1 ),
  1220. sqrSin = 1 - cos * cos;
  1221. // Skip the Slerp for tiny steps to avoid numeric problems:
  1222. if ( sqrSin > Number.EPSILON ) {
  1223. var sin = Math.sqrt( sqrSin ),
  1224. len = Math.atan2( sin, cos * dir );
  1225. s = Math.sin( s * len ) / sin;
  1226. t = Math.sin( t * len ) / sin;
  1227. }
  1228. var tDir = t * dir;
  1229. x0 = x0 * s + x1 * tDir;
  1230. y0 = y0 * s + y1 * tDir;
  1231. z0 = z0 * s + z1 * tDir;
  1232. w0 = w0 * s + w1 * tDir;
  1233. // Normalize in case we just did a lerp:
  1234. if ( s === 1 - t ) {
  1235. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1236. x0 *= f;
  1237. y0 *= f;
  1238. z0 *= f;
  1239. w0 *= f;
  1240. }
  1241. }
  1242. dst[ dstOffset ] = x0;
  1243. dst[ dstOffset + 1 ] = y0;
  1244. dst[ dstOffset + 2 ] = z0;
  1245. dst[ dstOffset + 3 ] = w0;
  1246. }
  1247. } );
  1248. Object.defineProperties( Quaternion.prototype, {
  1249. x: {
  1250. get: function () {
  1251. return this._x;
  1252. },
  1253. set: function ( value ) {
  1254. this._x = value;
  1255. this.onChangeCallback();
  1256. }
  1257. },
  1258. y: {
  1259. get: function () {
  1260. return this._y;
  1261. },
  1262. set: function ( value ) {
  1263. this._y = value;
  1264. this.onChangeCallback();
  1265. }
  1266. },
  1267. z: {
  1268. get: function () {
  1269. return this._z;
  1270. },
  1271. set: function ( value ) {
  1272. this._z = value;
  1273. this.onChangeCallback();
  1274. }
  1275. },
  1276. w: {
  1277. get: function () {
  1278. return this._w;
  1279. },
  1280. set: function ( value ) {
  1281. this._w = value;
  1282. this.onChangeCallback();
  1283. }
  1284. }
  1285. } );
  1286. Object.assign( Quaternion.prototype, {
  1287. set: function ( x, y, z, w ) {
  1288. this._x = x;
  1289. this._y = y;
  1290. this._z = z;
  1291. this._w = w;
  1292. this.onChangeCallback();
  1293. return this;
  1294. },
  1295. clone: function () {
  1296. return new this.constructor( this._x, this._y, this._z, this._w );
  1297. },
  1298. copy: function ( quaternion ) {
  1299. this._x = quaternion.x;
  1300. this._y = quaternion.y;
  1301. this._z = quaternion.z;
  1302. this._w = quaternion.w;
  1303. this.onChangeCallback();
  1304. return this;
  1305. },
  1306. setFromEuler: function ( euler, update ) {
  1307. if ( ! ( euler && euler.isEuler ) ) {
  1308. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1309. }
  1310. var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
  1311. // http://www.mathworks.com/matlabcentral/fileexchange/
  1312. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1313. // content/SpinCalc.m
  1314. var cos = Math.cos;
  1315. var sin = Math.sin;
  1316. var c1 = cos( x / 2 );
  1317. var c2 = cos( y / 2 );
  1318. var c3 = cos( z / 2 );
  1319. var s1 = sin( x / 2 );
  1320. var s2 = sin( y / 2 );
  1321. var s3 = sin( z / 2 );
  1322. if ( order === 'XYZ' ) {
  1323. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1324. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1325. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1326. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1327. } else if ( order === 'YXZ' ) {
  1328. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1329. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1330. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1331. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1332. } else if ( order === 'ZXY' ) {
  1333. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1334. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1335. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1336. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1337. } else if ( order === 'ZYX' ) {
  1338. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1339. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1340. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1341. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1342. } else if ( order === 'YZX' ) {
  1343. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1344. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1345. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1346. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1347. } else if ( order === 'XZY' ) {
  1348. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1349. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1350. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1351. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1352. }
  1353. if ( update !== false ) this.onChangeCallback();
  1354. return this;
  1355. },
  1356. setFromAxisAngle: function ( axis, angle ) {
  1357. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1358. // assumes axis is normalized
  1359. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  1360. this._x = axis.x * s;
  1361. this._y = axis.y * s;
  1362. this._z = axis.z * s;
  1363. this._w = Math.cos( halfAngle );
  1364. this.onChangeCallback();
  1365. return this;
  1366. },
  1367. setFromRotationMatrix: function ( m ) {
  1368. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1369. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1370. var te = m.elements,
  1371. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1372. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1373. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1374. trace = m11 + m22 + m33,
  1375. s;
  1376. if ( trace > 0 ) {
  1377. s = 0.5 / Math.sqrt( trace + 1.0 );
  1378. this._w = 0.25 / s;
  1379. this._x = ( m32 - m23 ) * s;
  1380. this._y = ( m13 - m31 ) * s;
  1381. this._z = ( m21 - m12 ) * s;
  1382. } else if ( m11 > m22 && m11 > m33 ) {
  1383. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1384. this._w = ( m32 - m23 ) / s;
  1385. this._x = 0.25 * s;
  1386. this._y = ( m12 + m21 ) / s;
  1387. this._z = ( m13 + m31 ) / s;
  1388. } else if ( m22 > m33 ) {
  1389. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1390. this._w = ( m13 - m31 ) / s;
  1391. this._x = ( m12 + m21 ) / s;
  1392. this._y = 0.25 * s;
  1393. this._z = ( m23 + m32 ) / s;
  1394. } else {
  1395. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1396. this._w = ( m21 - m12 ) / s;
  1397. this._x = ( m13 + m31 ) / s;
  1398. this._y = ( m23 + m32 ) / s;
  1399. this._z = 0.25 * s;
  1400. }
  1401. this.onChangeCallback();
  1402. return this;
  1403. },
  1404. setFromUnitVectors: function () {
  1405. // assumes direction vectors vFrom and vTo are normalized
  1406. var v1 = new Vector3();
  1407. var r;
  1408. var EPS = 0.000001;
  1409. return function setFromUnitVectors( vFrom, vTo ) {
  1410. if ( v1 === undefined ) v1 = new Vector3();
  1411. r = vFrom.dot( vTo ) + 1;
  1412. if ( r < EPS ) {
  1413. r = 0;
  1414. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1415. v1.set( - vFrom.y, vFrom.x, 0 );
  1416. } else {
  1417. v1.set( 0, - vFrom.z, vFrom.y );
  1418. }
  1419. } else {
  1420. v1.crossVectors( vFrom, vTo );
  1421. }
  1422. this._x = v1.x;
  1423. this._y = v1.y;
  1424. this._z = v1.z;
  1425. this._w = r;
  1426. return this.normalize();
  1427. };
  1428. }(),
  1429. inverse: function () {
  1430. return this.conjugate().normalize();
  1431. },
  1432. conjugate: function () {
  1433. this._x *= - 1;
  1434. this._y *= - 1;
  1435. this._z *= - 1;
  1436. this.onChangeCallback();
  1437. return this;
  1438. },
  1439. dot: function ( v ) {
  1440. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1441. },
  1442. lengthSq: function () {
  1443. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1444. },
  1445. length: function () {
  1446. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1447. },
  1448. normalize: function () {
  1449. var l = this.length();
  1450. if ( l === 0 ) {
  1451. this._x = 0;
  1452. this._y = 0;
  1453. this._z = 0;
  1454. this._w = 1;
  1455. } else {
  1456. l = 1 / l;
  1457. this._x = this._x * l;
  1458. this._y = this._y * l;
  1459. this._z = this._z * l;
  1460. this._w = this._w * l;
  1461. }
  1462. this.onChangeCallback();
  1463. return this;
  1464. },
  1465. multiply: function ( q, p ) {
  1466. if ( p !== undefined ) {
  1467. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1468. return this.multiplyQuaternions( q, p );
  1469. }
  1470. return this.multiplyQuaternions( this, q );
  1471. },
  1472. premultiply: function ( q ) {
  1473. return this.multiplyQuaternions( q, this );
  1474. },
  1475. multiplyQuaternions: function ( a, b ) {
  1476. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1477. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1478. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1479. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1480. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1481. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1482. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1483. this.onChangeCallback();
  1484. return this;
  1485. },
  1486. slerp: function ( qb, t ) {
  1487. if ( t === 0 ) return this;
  1488. if ( t === 1 ) return this.copy( qb );
  1489. var x = this._x, y = this._y, z = this._z, w = this._w;
  1490. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1491. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1492. if ( cosHalfTheta < 0 ) {
  1493. this._w = - qb._w;
  1494. this._x = - qb._x;
  1495. this._y = - qb._y;
  1496. this._z = - qb._z;
  1497. cosHalfTheta = - cosHalfTheta;
  1498. } else {
  1499. this.copy( qb );
  1500. }
  1501. if ( cosHalfTheta >= 1.0 ) {
  1502. this._w = w;
  1503. this._x = x;
  1504. this._y = y;
  1505. this._z = z;
  1506. return this;
  1507. }
  1508. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  1509. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  1510. this._w = 0.5 * ( w + this._w );
  1511. this._x = 0.5 * ( x + this._x );
  1512. this._y = 0.5 * ( y + this._y );
  1513. this._z = 0.5 * ( z + this._z );
  1514. return this;
  1515. }
  1516. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1517. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1518. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1519. this._w = ( w * ratioA + this._w * ratioB );
  1520. this._x = ( x * ratioA + this._x * ratioB );
  1521. this._y = ( y * ratioA + this._y * ratioB );
  1522. this._z = ( z * ratioA + this._z * ratioB );
  1523. this.onChangeCallback();
  1524. return this;
  1525. },
  1526. equals: function ( quaternion ) {
  1527. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1528. },
  1529. fromArray: function ( array, offset ) {
  1530. if ( offset === undefined ) offset = 0;
  1531. this._x = array[ offset ];
  1532. this._y = array[ offset + 1 ];
  1533. this._z = array[ offset + 2 ];
  1534. this._w = array[ offset + 3 ];
  1535. this.onChangeCallback();
  1536. return this;
  1537. },
  1538. toArray: function ( array, offset ) {
  1539. if ( array === undefined ) array = [];
  1540. if ( offset === undefined ) offset = 0;
  1541. array[ offset ] = this._x;
  1542. array[ offset + 1 ] = this._y;
  1543. array[ offset + 2 ] = this._z;
  1544. array[ offset + 3 ] = this._w;
  1545. return array;
  1546. },
  1547. onChange: function ( callback ) {
  1548. this.onChangeCallback = callback;
  1549. return this;
  1550. },
  1551. onChangeCallback: function () {}
  1552. } );
  1553. /**
  1554. * @author mrdoob / http://mrdoob.com/
  1555. * @author kile / http://kile.stravaganza.org/
  1556. * @author philogb / http://blog.thejit.org/
  1557. * @author mikael emtinger / http://gomo.se/
  1558. * @author egraether / http://egraether.com/
  1559. * @author WestLangley / http://github.com/WestLangley
  1560. */
  1561. function Vector3( x, y, z ) {
  1562. this.x = x || 0;
  1563. this.y = y || 0;
  1564. this.z = z || 0;
  1565. }
  1566. Object.assign( Vector3.prototype, {
  1567. isVector3: true,
  1568. set: function ( x, y, z ) {
  1569. this.x = x;
  1570. this.y = y;
  1571. this.z = z;
  1572. return this;
  1573. },
  1574. setScalar: function ( scalar ) {
  1575. this.x = scalar;
  1576. this.y = scalar;
  1577. this.z = scalar;
  1578. return this;
  1579. },
  1580. setX: function ( x ) {
  1581. this.x = x;
  1582. return this;
  1583. },
  1584. setY: function ( y ) {
  1585. this.y = y;
  1586. return this;
  1587. },
  1588. setZ: function ( z ) {
  1589. this.z = z;
  1590. return this;
  1591. },
  1592. setComponent: function ( index, value ) {
  1593. switch ( index ) {
  1594. case 0: this.x = value; break;
  1595. case 1: this.y = value; break;
  1596. case 2: this.z = value; break;
  1597. default: throw new Error( 'index is out of range: ' + index );
  1598. }
  1599. return this;
  1600. },
  1601. getComponent: function ( index ) {
  1602. switch ( index ) {
  1603. case 0: return this.x;
  1604. case 1: return this.y;
  1605. case 2: return this.z;
  1606. default: throw new Error( 'index is out of range: ' + index );
  1607. }
  1608. },
  1609. clone: function () {
  1610. return new this.constructor( this.x, this.y, this.z );
  1611. },
  1612. copy: function ( v ) {
  1613. this.x = v.x;
  1614. this.y = v.y;
  1615. this.z = v.z;
  1616. return this;
  1617. },
  1618. add: function ( v, w ) {
  1619. if ( w !== undefined ) {
  1620. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1621. return this.addVectors( v, w );
  1622. }
  1623. this.x += v.x;
  1624. this.y += v.y;
  1625. this.z += v.z;
  1626. return this;
  1627. },
  1628. addScalar: function ( s ) {
  1629. this.x += s;
  1630. this.y += s;
  1631. this.z += s;
  1632. return this;
  1633. },
  1634. addVectors: function ( a, b ) {
  1635. this.x = a.x + b.x;
  1636. this.y = a.y + b.y;
  1637. this.z = a.z + b.z;
  1638. return this;
  1639. },
  1640. addScaledVector: function ( v, s ) {
  1641. this.x += v.x * s;
  1642. this.y += v.y * s;
  1643. this.z += v.z * s;
  1644. return this;
  1645. },
  1646. sub: function ( v, w ) {
  1647. if ( w !== undefined ) {
  1648. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1649. return this.subVectors( v, w );
  1650. }
  1651. this.x -= v.x;
  1652. this.y -= v.y;
  1653. this.z -= v.z;
  1654. return this;
  1655. },
  1656. subScalar: function ( s ) {
  1657. this.x -= s;
  1658. this.y -= s;
  1659. this.z -= s;
  1660. return this;
  1661. },
  1662. subVectors: function ( a, b ) {
  1663. this.x = a.x - b.x;
  1664. this.y = a.y - b.y;
  1665. this.z = a.z - b.z;
  1666. return this;
  1667. },
  1668. multiply: function ( v, w ) {
  1669. if ( w !== undefined ) {
  1670. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1671. return this.multiplyVectors( v, w );
  1672. }
  1673. this.x *= v.x;
  1674. this.y *= v.y;
  1675. this.z *= v.z;
  1676. return this;
  1677. },
  1678. multiplyScalar: function ( scalar ) {
  1679. this.x *= scalar;
  1680. this.y *= scalar;
  1681. this.z *= scalar;
  1682. return this;
  1683. },
  1684. multiplyVectors: function ( a, b ) {
  1685. this.x = a.x * b.x;
  1686. this.y = a.y * b.y;
  1687. this.z = a.z * b.z;
  1688. return this;
  1689. },
  1690. applyEuler: function () {
  1691. var quaternion = new Quaternion();
  1692. return function applyEuler( euler ) {
  1693. if ( ! ( euler && euler.isEuler ) ) {
  1694. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1695. }
  1696. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1697. };
  1698. }(),
  1699. applyAxisAngle: function () {
  1700. var quaternion = new Quaternion();
  1701. return function applyAxisAngle( axis, angle ) {
  1702. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1703. };
  1704. }(),
  1705. applyMatrix3: function ( m ) {
  1706. var x = this.x, y = this.y, z = this.z;
  1707. var e = m.elements;
  1708. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1709. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1710. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1711. return this;
  1712. },
  1713. applyMatrix4: function ( m ) {
  1714. var x = this.x, y = this.y, z = this.z;
  1715. var e = m.elements;
  1716. var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  1717. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  1718. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  1719. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  1720. return this;
  1721. },
  1722. applyQuaternion: function ( q ) {
  1723. var x = this.x, y = this.y, z = this.z;
  1724. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1725. // calculate quat * vector
  1726. var ix = qw * x + qy * z - qz * y;
  1727. var iy = qw * y + qz * x - qx * z;
  1728. var iz = qw * z + qx * y - qy * x;
  1729. var iw = - qx * x - qy * y - qz * z;
  1730. // calculate result * inverse quat
  1731. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1732. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1733. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1734. return this;
  1735. },
  1736. project: function () {
  1737. var matrix = new Matrix4();
  1738. return function project( camera ) {
  1739. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1740. return this.applyMatrix4( matrix );
  1741. };
  1742. }(),
  1743. unproject: function () {
  1744. var matrix = new Matrix4();
  1745. return function unproject( camera ) {
  1746. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1747. return this.applyMatrix4( matrix );
  1748. };
  1749. }(),
  1750. transformDirection: function ( m ) {
  1751. // input: THREE.Matrix4 affine matrix
  1752. // vector interpreted as a direction
  1753. var x = this.x, y = this.y, z = this.z;
  1754. var e = m.elements;
  1755. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1756. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1757. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1758. return this.normalize();
  1759. },
  1760. divide: function ( v ) {
  1761. this.x /= v.x;
  1762. this.y /= v.y;
  1763. this.z /= v.z;
  1764. return this;
  1765. },
  1766. divideScalar: function ( scalar ) {
  1767. return this.multiplyScalar( 1 / scalar );
  1768. },
  1769. min: function ( v ) {
  1770. this.x = Math.min( this.x, v.x );
  1771. this.y = Math.min( this.y, v.y );
  1772. this.z = Math.min( this.z, v.z );
  1773. return this;
  1774. },
  1775. max: function ( v ) {
  1776. this.x = Math.max( this.x, v.x );
  1777. this.y = Math.max( this.y, v.y );
  1778. this.z = Math.max( this.z, v.z );
  1779. return this;
  1780. },
  1781. clamp: function ( min, max ) {
  1782. // assumes min < max, componentwise
  1783. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1784. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1785. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1786. return this;
  1787. },
  1788. clampScalar: function () {
  1789. var min = new Vector3();
  1790. var max = new Vector3();
  1791. return function clampScalar( minVal, maxVal ) {
  1792. min.set( minVal, minVal, minVal );
  1793. max.set( maxVal, maxVal, maxVal );
  1794. return this.clamp( min, max );
  1795. };
  1796. }(),
  1797. clampLength: function ( min, max ) {
  1798. var length = this.length();
  1799. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1800. },
  1801. floor: function () {
  1802. this.x = Math.floor( this.x );
  1803. this.y = Math.floor( this.y );
  1804. this.z = Math.floor( this.z );
  1805. return this;
  1806. },
  1807. ceil: function () {
  1808. this.x = Math.ceil( this.x );
  1809. this.y = Math.ceil( this.y );
  1810. this.z = Math.ceil( this.z );
  1811. return this;
  1812. },
  1813. round: function () {
  1814. this.x = Math.round( this.x );
  1815. this.y = Math.round( this.y );
  1816. this.z = Math.round( this.z );
  1817. return this;
  1818. },
  1819. roundToZero: function () {
  1820. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1821. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1822. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1823. return this;
  1824. },
  1825. negate: function () {
  1826. this.x = - this.x;
  1827. this.y = - this.y;
  1828. this.z = - this.z;
  1829. return this;
  1830. },
  1831. dot: function ( v ) {
  1832. return this.x * v.x + this.y * v.y + this.z * v.z;
  1833. },
  1834. // TODO lengthSquared?
  1835. lengthSq: function () {
  1836. return this.x * this.x + this.y * this.y + this.z * this.z;
  1837. },
  1838. length: function () {
  1839. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1840. },
  1841. lengthManhattan: function () {
  1842. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1843. },
  1844. normalize: function () {
  1845. return this.divideScalar( this.length() || 1 );
  1846. },
  1847. setLength: function ( length ) {
  1848. return this.normalize().multiplyScalar( length );
  1849. },
  1850. lerp: function ( v, alpha ) {
  1851. this.x += ( v.x - this.x ) * alpha;
  1852. this.y += ( v.y - this.y ) * alpha;
  1853. this.z += ( v.z - this.z ) * alpha;
  1854. return this;
  1855. },
  1856. lerpVectors: function ( v1, v2, alpha ) {
  1857. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1858. },
  1859. cross: function ( v, w ) {
  1860. if ( w !== undefined ) {
  1861. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1862. return this.crossVectors( v, w );
  1863. }
  1864. var x = this.x, y = this.y, z = this.z;
  1865. this.x = y * v.z - z * v.y;
  1866. this.y = z * v.x - x * v.z;
  1867. this.z = x * v.y - y * v.x;
  1868. return this;
  1869. },
  1870. crossVectors: function ( a, b ) {
  1871. var ax = a.x, ay = a.y, az = a.z;
  1872. var bx = b.x, by = b.y, bz = b.z;
  1873. this.x = ay * bz - az * by;
  1874. this.y = az * bx - ax * bz;
  1875. this.z = ax * by - ay * bx;
  1876. return this;
  1877. },
  1878. projectOnVector: function ( vector ) {
  1879. var scalar = vector.dot( this ) / vector.lengthSq();
  1880. return this.copy( vector ).multiplyScalar( scalar );
  1881. },
  1882. projectOnPlane: function () {
  1883. var v1 = new Vector3();
  1884. return function projectOnPlane( planeNormal ) {
  1885. v1.copy( this ).projectOnVector( planeNormal );
  1886. return this.sub( v1 );
  1887. };
  1888. }(),
  1889. reflect: function () {
  1890. // reflect incident vector off plane orthogonal to normal
  1891. // normal is assumed to have unit length
  1892. var v1 = new Vector3();
  1893. return function reflect( normal ) {
  1894. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1895. };
  1896. }(),
  1897. angleTo: function ( v ) {
  1898. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1899. // clamp, to handle numerical problems
  1900. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  1901. },
  1902. distanceTo: function ( v ) {
  1903. return Math.sqrt( this.distanceToSquared( v ) );
  1904. },
  1905. distanceToSquared: function ( v ) {
  1906. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  1907. return dx * dx + dy * dy + dz * dz;
  1908. },
  1909. distanceToManhattan: function ( v ) {
  1910. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  1911. },
  1912. setFromSpherical: function ( s ) {
  1913. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  1914. this.x = sinPhiRadius * Math.sin( s.theta );
  1915. this.y = Math.cos( s.phi ) * s.radius;
  1916. this.z = sinPhiRadius * Math.cos( s.theta );
  1917. return this;
  1918. },
  1919. setFromCylindrical: function ( c ) {
  1920. this.x = c.radius * Math.sin( c.theta );
  1921. this.y = c.y;
  1922. this.z = c.radius * Math.cos( c.theta );
  1923. return this;
  1924. },
  1925. setFromMatrixPosition: function ( m ) {
  1926. var e = m.elements;
  1927. this.x = e[ 12 ];
  1928. this.y = e[ 13 ];
  1929. this.z = e[ 14 ];
  1930. return this;
  1931. },
  1932. setFromMatrixScale: function ( m ) {
  1933. var sx = this.setFromMatrixColumn( m, 0 ).length();
  1934. var sy = this.setFromMatrixColumn( m, 1 ).length();
  1935. var sz = this.setFromMatrixColumn( m, 2 ).length();
  1936. this.x = sx;
  1937. this.y = sy;
  1938. this.z = sz;
  1939. return this;
  1940. },
  1941. setFromMatrixColumn: function ( m, index ) {
  1942. return this.fromArray( m.elements, index * 4 );
  1943. },
  1944. equals: function ( v ) {
  1945. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1946. },
  1947. fromArray: function ( array, offset ) {
  1948. if ( offset === undefined ) offset = 0;
  1949. this.x = array[ offset ];
  1950. this.y = array[ offset + 1 ];
  1951. this.z = array[ offset + 2 ];
  1952. return this;
  1953. },
  1954. toArray: function ( array, offset ) {
  1955. if ( array === undefined ) array = [];
  1956. if ( offset === undefined ) offset = 0;
  1957. array[ offset ] = this.x;
  1958. array[ offset + 1 ] = this.y;
  1959. array[ offset + 2 ] = this.z;
  1960. return array;
  1961. },
  1962. fromBufferAttribute: function ( attribute, index, offset ) {
  1963. if ( offset !== undefined ) {
  1964. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  1965. }
  1966. this.x = attribute.getX( index );
  1967. this.y = attribute.getY( index );
  1968. this.z = attribute.getZ( index );
  1969. return this;
  1970. }
  1971. } );
  1972. /**
  1973. * @author mrdoob / http://mrdoob.com/
  1974. * @author supereggbert / http://www.paulbrunt.co.uk/
  1975. * @author philogb / http://blog.thejit.org/
  1976. * @author jordi_ros / http://plattsoft.com
  1977. * @author D1plo1d / http://github.com/D1plo1d
  1978. * @author alteredq / http://alteredqualia.com/
  1979. * @author mikael emtinger / http://gomo.se/
  1980. * @author timknip / http://www.floorplanner.com/
  1981. * @author bhouston / http://clara.io
  1982. * @author WestLangley / http://github.com/WestLangley
  1983. */
  1984. function Matrix4() {
  1985. this.elements = [
  1986. 1, 0, 0, 0,
  1987. 0, 1, 0, 0,
  1988. 0, 0, 1, 0,
  1989. 0, 0, 0, 1
  1990. ];
  1991. if ( arguments.length > 0 ) {
  1992. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  1993. }
  1994. }
  1995. Object.assign( Matrix4.prototype, {
  1996. isMatrix4: true,
  1997. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1998. var te = this.elements;
  1999. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2000. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2001. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2002. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2003. return this;
  2004. },
  2005. identity: function () {
  2006. this.set(
  2007. 1, 0, 0, 0,
  2008. 0, 1, 0, 0,
  2009. 0, 0, 1, 0,
  2010. 0, 0, 0, 1
  2011. );
  2012. return this;
  2013. },
  2014. clone: function () {
  2015. return new Matrix4().fromArray( this.elements );
  2016. },
  2017. copy: function ( m ) {
  2018. var te = this.elements;
  2019. var me = m.elements;
  2020. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  2021. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  2022. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  2023. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  2024. return this;
  2025. },
  2026. copyPosition: function ( m ) {
  2027. var te = this.elements, me = m.elements;
  2028. te[ 12 ] = me[ 12 ];
  2029. te[ 13 ] = me[ 13 ];
  2030. te[ 14 ] = me[ 14 ];
  2031. return this;
  2032. },
  2033. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2034. xAxis.setFromMatrixColumn( this, 0 );
  2035. yAxis.setFromMatrixColumn( this, 1 );
  2036. zAxis.setFromMatrixColumn( this, 2 );
  2037. return this;
  2038. },
  2039. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2040. this.set(
  2041. xAxis.x, yAxis.x, zAxis.x, 0,
  2042. xAxis.y, yAxis.y, zAxis.y, 0,
  2043. xAxis.z, yAxis.z, zAxis.z, 0,
  2044. 0, 0, 0, 1
  2045. );
  2046. return this;
  2047. },
  2048. extractRotation: function () {
  2049. var v1 = new Vector3();
  2050. return function extractRotation( m ) {
  2051. var te = this.elements;
  2052. var me = m.elements;
  2053. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  2054. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  2055. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  2056. te[ 0 ] = me[ 0 ] * scaleX;
  2057. te[ 1 ] = me[ 1 ] * scaleX;
  2058. te[ 2 ] = me[ 2 ] * scaleX;
  2059. te[ 4 ] = me[ 4 ] * scaleY;
  2060. te[ 5 ] = me[ 5 ] * scaleY;
  2061. te[ 6 ] = me[ 6 ] * scaleY;
  2062. te[ 8 ] = me[ 8 ] * scaleZ;
  2063. te[ 9 ] = me[ 9 ] * scaleZ;
  2064. te[ 10 ] = me[ 10 ] * scaleZ;
  2065. return this;
  2066. };
  2067. }(),
  2068. makeRotationFromEuler: function ( euler ) {
  2069. if ( ! ( euler && euler.isEuler ) ) {
  2070. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2071. }
  2072. var te = this.elements;
  2073. var x = euler.x, y = euler.y, z = euler.z;
  2074. var a = Math.cos( x ), b = Math.sin( x );
  2075. var c = Math.cos( y ), d = Math.sin( y );
  2076. var e = Math.cos( z ), f = Math.sin( z );
  2077. if ( euler.order === 'XYZ' ) {
  2078. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2079. te[ 0 ] = c * e;
  2080. te[ 4 ] = - c * f;
  2081. te[ 8 ] = d;
  2082. te[ 1 ] = af + be * d;
  2083. te[ 5 ] = ae - bf * d;
  2084. te[ 9 ] = - b * c;
  2085. te[ 2 ] = bf - ae * d;
  2086. te[ 6 ] = be + af * d;
  2087. te[ 10 ] = a * c;
  2088. } else if ( euler.order === 'YXZ' ) {
  2089. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2090. te[ 0 ] = ce + df * b;
  2091. te[ 4 ] = de * b - cf;
  2092. te[ 8 ] = a * d;
  2093. te[ 1 ] = a * f;
  2094. te[ 5 ] = a * e;
  2095. te[ 9 ] = - b;
  2096. te[ 2 ] = cf * b - de;
  2097. te[ 6 ] = df + ce * b;
  2098. te[ 10 ] = a * c;
  2099. } else if ( euler.order === 'ZXY' ) {
  2100. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2101. te[ 0 ] = ce - df * b;
  2102. te[ 4 ] = - a * f;
  2103. te[ 8 ] = de + cf * b;
  2104. te[ 1 ] = cf + de * b;
  2105. te[ 5 ] = a * e;
  2106. te[ 9 ] = df - ce * b;
  2107. te[ 2 ] = - a * d;
  2108. te[ 6 ] = b;
  2109. te[ 10 ] = a * c;
  2110. } else if ( euler.order === 'ZYX' ) {
  2111. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2112. te[ 0 ] = c * e;
  2113. te[ 4 ] = be * d - af;
  2114. te[ 8 ] = ae * d + bf;
  2115. te[ 1 ] = c * f;
  2116. te[ 5 ] = bf * d + ae;
  2117. te[ 9 ] = af * d - be;
  2118. te[ 2 ] = - d;
  2119. te[ 6 ] = b * c;
  2120. te[ 10 ] = a * c;
  2121. } else if ( euler.order === 'YZX' ) {
  2122. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2123. te[ 0 ] = c * e;
  2124. te[ 4 ] = bd - ac * f;
  2125. te[ 8 ] = bc * f + ad;
  2126. te[ 1 ] = f;
  2127. te[ 5 ] = a * e;
  2128. te[ 9 ] = - b * e;
  2129. te[ 2 ] = - d * e;
  2130. te[ 6 ] = ad * f + bc;
  2131. te[ 10 ] = ac - bd * f;
  2132. } else if ( euler.order === 'XZY' ) {
  2133. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2134. te[ 0 ] = c * e;
  2135. te[ 4 ] = - f;
  2136. te[ 8 ] = d * e;
  2137. te[ 1 ] = ac * f + bd;
  2138. te[ 5 ] = a * e;
  2139. te[ 9 ] = ad * f - bc;
  2140. te[ 2 ] = bc * f - ad;
  2141. te[ 6 ] = b * e;
  2142. te[ 10 ] = bd * f + ac;
  2143. }
  2144. // last column
  2145. te[ 3 ] = 0;
  2146. te[ 7 ] = 0;
  2147. te[ 11 ] = 0;
  2148. // bottom row
  2149. te[ 12 ] = 0;
  2150. te[ 13 ] = 0;
  2151. te[ 14 ] = 0;
  2152. te[ 15 ] = 1;
  2153. return this;
  2154. },
  2155. makeRotationFromQuaternion: function ( q ) {
  2156. var te = this.elements;
  2157. var x = q._x, y = q._y, z = q._z, w = q._w;
  2158. var x2 = x + x, y2 = y + y, z2 = z + z;
  2159. var xx = x * x2, xy = x * y2, xz = x * z2;
  2160. var yy = y * y2, yz = y * z2, zz = z * z2;
  2161. var wx = w * x2, wy = w * y2, wz = w * z2;
  2162. te[ 0 ] = 1 - ( yy + zz );
  2163. te[ 4 ] = xy - wz;
  2164. te[ 8 ] = xz + wy;
  2165. te[ 1 ] = xy + wz;
  2166. te[ 5 ] = 1 - ( xx + zz );
  2167. te[ 9 ] = yz - wx;
  2168. te[ 2 ] = xz - wy;
  2169. te[ 6 ] = yz + wx;
  2170. te[ 10 ] = 1 - ( xx + yy );
  2171. // last column
  2172. te[ 3 ] = 0;
  2173. te[ 7 ] = 0;
  2174. te[ 11 ] = 0;
  2175. // bottom row
  2176. te[ 12 ] = 0;
  2177. te[ 13 ] = 0;
  2178. te[ 14 ] = 0;
  2179. te[ 15 ] = 1;
  2180. return this;
  2181. },
  2182. lookAt: function () {
  2183. var x = new Vector3();
  2184. var y = new Vector3();
  2185. var z = new Vector3();
  2186. return function lookAt( eye, target, up ) {
  2187. var te = this.elements;
  2188. z.subVectors( eye, target );
  2189. if ( z.lengthSq() === 0 ) {
  2190. // eye and target are in the same position
  2191. z.z = 1;
  2192. }
  2193. z.normalize();
  2194. x.crossVectors( up, z );
  2195. if ( x.lengthSq() === 0 ) {
  2196. // up and z are parallel
  2197. if ( Math.abs( up.z ) === 1 ) {
  2198. z.x += 0.0001;
  2199. } else {
  2200. z.z += 0.0001;
  2201. }
  2202. z.normalize();
  2203. x.crossVectors( up, z );
  2204. }
  2205. x.normalize();
  2206. y.crossVectors( z, x );
  2207. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2208. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2209. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2210. return this;
  2211. };
  2212. }(),
  2213. multiply: function ( m, n ) {
  2214. if ( n !== undefined ) {
  2215. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2216. return this.multiplyMatrices( m, n );
  2217. }
  2218. return this.multiplyMatrices( this, m );
  2219. },
  2220. premultiply: function ( m ) {
  2221. return this.multiplyMatrices( m, this );
  2222. },
  2223. multiplyMatrices: function ( a, b ) {
  2224. var ae = a.elements;
  2225. var be = b.elements;
  2226. var te = this.elements;
  2227. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2228. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2229. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2230. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2231. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2232. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2233. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2234. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2235. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2236. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2237. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2238. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2239. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2240. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2241. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2242. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2243. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2244. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2245. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2246. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2247. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2248. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2249. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2250. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2251. return this;
  2252. },
  2253. multiplyScalar: function ( s ) {
  2254. var te = this.elements;
  2255. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2256. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2257. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2258. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2259. return this;
  2260. },
  2261. applyToBufferAttribute: function () {
  2262. var v1 = new Vector3();
  2263. return function applyToBufferAttribute( attribute ) {
  2264. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  2265. v1.x = attribute.getX( i );
  2266. v1.y = attribute.getY( i );
  2267. v1.z = attribute.getZ( i );
  2268. v1.applyMatrix4( this );
  2269. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  2270. }
  2271. return attribute;
  2272. };
  2273. }(),
  2274. determinant: function () {
  2275. var te = this.elements;
  2276. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2277. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2278. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2279. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2280. //TODO: make this more efficient
  2281. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2282. return (
  2283. n41 * (
  2284. + n14 * n23 * n32
  2285. - n13 * n24 * n32
  2286. - n14 * n22 * n33
  2287. + n12 * n24 * n33
  2288. + n13 * n22 * n34
  2289. - n12 * n23 * n34
  2290. ) +
  2291. n42 * (
  2292. + n11 * n23 * n34
  2293. - n11 * n24 * n33
  2294. + n14 * n21 * n33
  2295. - n13 * n21 * n34
  2296. + n13 * n24 * n31
  2297. - n14 * n23 * n31
  2298. ) +
  2299. n43 * (
  2300. + n11 * n24 * n32
  2301. - n11 * n22 * n34
  2302. - n14 * n21 * n32
  2303. + n12 * n21 * n34
  2304. + n14 * n22 * n31
  2305. - n12 * n24 * n31
  2306. ) +
  2307. n44 * (
  2308. - n13 * n22 * n31
  2309. - n11 * n23 * n32
  2310. + n11 * n22 * n33
  2311. + n13 * n21 * n32
  2312. - n12 * n21 * n33
  2313. + n12 * n23 * n31
  2314. )
  2315. );
  2316. },
  2317. transpose: function () {
  2318. var te = this.elements;
  2319. var tmp;
  2320. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  2321. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  2322. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  2323. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  2324. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  2325. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  2326. return this;
  2327. },
  2328. setPosition: function ( v ) {
  2329. var te = this.elements;
  2330. te[ 12 ] = v.x;
  2331. te[ 13 ] = v.y;
  2332. te[ 14 ] = v.z;
  2333. return this;
  2334. },
  2335. getInverse: function ( m, throwOnDegenerate ) {
  2336. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2337. var te = this.elements,
  2338. me = m.elements,
  2339. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  2340. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  2341. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  2342. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  2343. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  2344. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  2345. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  2346. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  2347. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  2348. if ( det === 0 ) {
  2349. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  2350. if ( throwOnDegenerate === true ) {
  2351. throw new Error( msg );
  2352. } else {
  2353. console.warn( msg );
  2354. }
  2355. return this.identity();
  2356. }
  2357. var detInv = 1 / det;
  2358. te[ 0 ] = t11 * detInv;
  2359. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  2360. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  2361. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  2362. te[ 4 ] = t12 * detInv;
  2363. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  2364. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  2365. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  2366. te[ 8 ] = t13 * detInv;
  2367. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  2368. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  2369. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  2370. te[ 12 ] = t14 * detInv;
  2371. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  2372. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  2373. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  2374. return this;
  2375. },
  2376. scale: function ( v ) {
  2377. var te = this.elements;
  2378. var x = v.x, y = v.y, z = v.z;
  2379. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  2380. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  2381. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  2382. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  2383. return this;
  2384. },
  2385. getMaxScaleOnAxis: function () {
  2386. var te = this.elements;
  2387. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  2388. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  2389. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  2390. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  2391. },
  2392. makeTranslation: function ( x, y, z ) {
  2393. this.set(
  2394. 1, 0, 0, x,
  2395. 0, 1, 0, y,
  2396. 0, 0, 1, z,
  2397. 0, 0, 0, 1
  2398. );
  2399. return this;
  2400. },
  2401. makeRotationX: function ( theta ) {
  2402. var c = Math.cos( theta ), s = Math.sin( theta );
  2403. this.set(
  2404. 1, 0, 0, 0,
  2405. 0, c, - s, 0,
  2406. 0, s, c, 0,
  2407. 0, 0, 0, 1
  2408. );
  2409. return this;
  2410. },
  2411. makeRotationY: function ( theta ) {
  2412. var c = Math.cos( theta ), s = Math.sin( theta );
  2413. this.set(
  2414. c, 0, s, 0,
  2415. 0, 1, 0, 0,
  2416. - s, 0, c, 0,
  2417. 0, 0, 0, 1
  2418. );
  2419. return this;
  2420. },
  2421. makeRotationZ: function ( theta ) {
  2422. var c = Math.cos( theta ), s = Math.sin( theta );
  2423. this.set(
  2424. c, - s, 0, 0,
  2425. s, c, 0, 0,
  2426. 0, 0, 1, 0,
  2427. 0, 0, 0, 1
  2428. );
  2429. return this;
  2430. },
  2431. makeRotationAxis: function ( axis, angle ) {
  2432. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2433. var c = Math.cos( angle );
  2434. var s = Math.sin( angle );
  2435. var t = 1 - c;
  2436. var x = axis.x, y = axis.y, z = axis.z;
  2437. var tx = t * x, ty = t * y;
  2438. this.set(
  2439. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2440. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2441. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2442. 0, 0, 0, 1
  2443. );
  2444. return this;
  2445. },
  2446. makeScale: function ( x, y, z ) {
  2447. this.set(
  2448. x, 0, 0, 0,
  2449. 0, y, 0, 0,
  2450. 0, 0, z, 0,
  2451. 0, 0, 0, 1
  2452. );
  2453. return this;
  2454. },
  2455. makeShear: function ( x, y, z ) {
  2456. this.set(
  2457. 1, y, z, 0,
  2458. x, 1, z, 0,
  2459. x, y, 1, 0,
  2460. 0, 0, 0, 1
  2461. );
  2462. return this;
  2463. },
  2464. compose: function ( position, quaternion, scale ) {
  2465. this.makeRotationFromQuaternion( quaternion );
  2466. this.scale( scale );
  2467. this.setPosition( position );
  2468. return this;
  2469. },
  2470. decompose: function () {
  2471. var vector = new Vector3();
  2472. var matrix = new Matrix4();
  2473. return function decompose( position, quaternion, scale ) {
  2474. var te = this.elements;
  2475. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  2476. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  2477. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  2478. // if determine is negative, we need to invert one scale
  2479. var det = this.determinant();
  2480. if ( det < 0 ) sx = - sx;
  2481. position.x = te[ 12 ];
  2482. position.y = te[ 13 ];
  2483. position.z = te[ 14 ];
  2484. // scale the rotation part
  2485. matrix.copy( this );
  2486. var invSX = 1 / sx;
  2487. var invSY = 1 / sy;
  2488. var invSZ = 1 / sz;
  2489. matrix.elements[ 0 ] *= invSX;
  2490. matrix.elements[ 1 ] *= invSX;
  2491. matrix.elements[ 2 ] *= invSX;
  2492. matrix.elements[ 4 ] *= invSY;
  2493. matrix.elements[ 5 ] *= invSY;
  2494. matrix.elements[ 6 ] *= invSY;
  2495. matrix.elements[ 8 ] *= invSZ;
  2496. matrix.elements[ 9 ] *= invSZ;
  2497. matrix.elements[ 10 ] *= invSZ;
  2498. quaternion.setFromRotationMatrix( matrix );
  2499. scale.x = sx;
  2500. scale.y = sy;
  2501. scale.z = sz;
  2502. return this;
  2503. };
  2504. }(),
  2505. makePerspective: function ( left, right, top, bottom, near, far ) {
  2506. if ( far === undefined ) {
  2507. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  2508. }
  2509. var te = this.elements;
  2510. var x = 2 * near / ( right - left );
  2511. var y = 2 * near / ( top - bottom );
  2512. var a = ( right + left ) / ( right - left );
  2513. var b = ( top + bottom ) / ( top - bottom );
  2514. var c = - ( far + near ) / ( far - near );
  2515. var d = - 2 * far * near / ( far - near );
  2516. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  2517. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  2518. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  2519. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  2520. return this;
  2521. },
  2522. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2523. var te = this.elements;
  2524. var w = 1.0 / ( right - left );
  2525. var h = 1.0 / ( top - bottom );
  2526. var p = 1.0 / ( far - near );
  2527. var x = ( right + left ) * w;
  2528. var y = ( top + bottom ) * h;
  2529. var z = ( far + near ) * p;
  2530. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  2531. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  2532. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  2533. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  2534. return this;
  2535. },
  2536. equals: function ( matrix ) {
  2537. var te = this.elements;
  2538. var me = matrix.elements;
  2539. for ( var i = 0; i < 16; i ++ ) {
  2540. if ( te[ i ] !== me[ i ] ) return false;
  2541. }
  2542. return true;
  2543. },
  2544. fromArray: function ( array, offset ) {
  2545. if ( offset === undefined ) offset = 0;
  2546. for ( var i = 0; i < 16; i ++ ) {
  2547. this.elements[ i ] = array[ i + offset ];
  2548. }
  2549. return this;
  2550. },
  2551. toArray: function ( array, offset ) {
  2552. if ( array === undefined ) array = [];
  2553. if ( offset === undefined ) offset = 0;
  2554. var te = this.elements;
  2555. array[ offset ] = te[ 0 ];
  2556. array[ offset + 1 ] = te[ 1 ];
  2557. array[ offset + 2 ] = te[ 2 ];
  2558. array[ offset + 3 ] = te[ 3 ];
  2559. array[ offset + 4 ] = te[ 4 ];
  2560. array[ offset + 5 ] = te[ 5 ];
  2561. array[ offset + 6 ] = te[ 6 ];
  2562. array[ offset + 7 ] = te[ 7 ];
  2563. array[ offset + 8 ] = te[ 8 ];
  2564. array[ offset + 9 ] = te[ 9 ];
  2565. array[ offset + 10 ] = te[ 10 ];
  2566. array[ offset + 11 ] = te[ 11 ];
  2567. array[ offset + 12 ] = te[ 12 ];
  2568. array[ offset + 13 ] = te[ 13 ];
  2569. array[ offset + 14 ] = te[ 14 ];
  2570. array[ offset + 15 ] = te[ 15 ];
  2571. return array;
  2572. }
  2573. } );
  2574. /**
  2575. * @author alteredq / http://alteredqualia.com/
  2576. */
  2577. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  2578. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2579. this.image = { data: data, width: width, height: height };
  2580. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  2581. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  2582. this.generateMipmaps = false;
  2583. this.flipY = false;
  2584. this.unpackAlignment = 1;
  2585. }
  2586. DataTexture.prototype = Object.create( Texture.prototype );
  2587. DataTexture.prototype.constructor = DataTexture;
  2588. DataTexture.prototype.isDataTexture = true;
  2589. /**
  2590. * @author mrdoob / http://mrdoob.com/
  2591. */
  2592. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  2593. images = images !== undefined ? images : [];
  2594. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  2595. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2596. this.flipY = false;
  2597. }
  2598. CubeTexture.prototype = Object.create( Texture.prototype );
  2599. CubeTexture.prototype.constructor = CubeTexture;
  2600. CubeTexture.prototype.isCubeTexture = true;
  2601. Object.defineProperty( CubeTexture.prototype, 'images', {
  2602. get: function () {
  2603. return this.image;
  2604. },
  2605. set: function ( value ) {
  2606. this.image = value;
  2607. }
  2608. } );
  2609. /**
  2610. * @author tschw
  2611. *
  2612. * Uniforms of a program.
  2613. * Those form a tree structure with a special top-level container for the root,
  2614. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  2615. *
  2616. *
  2617. * Properties of inner nodes including the top-level container:
  2618. *
  2619. * .seq - array of nested uniforms
  2620. * .map - nested uniforms by name
  2621. *
  2622. *
  2623. * Methods of all nodes except the top-level container:
  2624. *
  2625. * .setValue( gl, value, [renderer] )
  2626. *
  2627. * uploads a uniform value(s)
  2628. * the 'renderer' parameter is needed for sampler uniforms
  2629. *
  2630. *
  2631. * Static methods of the top-level container (renderer factorizations):
  2632. *
  2633. * .upload( gl, seq, values, renderer )
  2634. *
  2635. * sets uniforms in 'seq' to 'values[id].value'
  2636. *
  2637. * .seqWithValue( seq, values ) : filteredSeq
  2638. *
  2639. * filters 'seq' entries with corresponding entry in values
  2640. *
  2641. *
  2642. * Methods of the top-level container (renderer factorizations):
  2643. *
  2644. * .setValue( gl, name, value )
  2645. *
  2646. * sets uniform with name 'name' to 'value'
  2647. *
  2648. * .set( gl, obj, prop )
  2649. *
  2650. * sets uniform from object and property with same name than uniform
  2651. *
  2652. * .setOptional( gl, obj, prop )
  2653. *
  2654. * like .set for an optional property of the object
  2655. *
  2656. */
  2657. var emptyTexture = new Texture();
  2658. var emptyCubeTexture = new CubeTexture();
  2659. // --- Base for inner nodes (including the root) ---
  2660. function UniformContainer() {
  2661. this.seq = [];
  2662. this.map = {};
  2663. }
  2664. // --- Utilities ---
  2665. // Array Caches (provide typed arrays for temporary by size)
  2666. var arrayCacheF32 = [];
  2667. var arrayCacheI32 = [];
  2668. // Float32Array caches used for uploading Matrix uniforms
  2669. var mat4array = new Float32Array( 16 );
  2670. var mat3array = new Float32Array( 9 );
  2671. // Flattening for arrays of vectors and matrices
  2672. function flatten( array, nBlocks, blockSize ) {
  2673. var firstElem = array[ 0 ];
  2674. if ( firstElem <= 0 || firstElem > 0 ) return array;
  2675. // unoptimized: ! isNaN( firstElem )
  2676. // see http://jacksondunstan.com/articles/983
  2677. var n = nBlocks * blockSize,
  2678. r = arrayCacheF32[ n ];
  2679. if ( r === undefined ) {
  2680. r = new Float32Array( n );
  2681. arrayCacheF32[ n ] = r;
  2682. }
  2683. if ( nBlocks !== 0 ) {
  2684. firstElem.toArray( r, 0 );
  2685. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  2686. offset += blockSize;
  2687. array[ i ].toArray( r, offset );
  2688. }
  2689. }
  2690. return r;
  2691. }
  2692. // Texture unit allocation
  2693. function allocTexUnits( renderer, n ) {
  2694. var r = arrayCacheI32[ n ];
  2695. if ( r === undefined ) {
  2696. r = new Int32Array( n );
  2697. arrayCacheI32[ n ] = r;
  2698. }
  2699. for ( var i = 0; i !== n; ++ i )
  2700. r[ i ] = renderer.allocTextureUnit();
  2701. return r;
  2702. }
  2703. // --- Setters ---
  2704. // Note: Defining these methods externally, because they come in a bunch
  2705. // and this way their names minify.
  2706. // Single scalar
  2707. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  2708. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  2709. // Single float vector (from flat array or THREE.VectorN)
  2710. function setValue2fv( gl, v ) {
  2711. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  2712. else gl.uniform2f( this.addr, v.x, v.y );
  2713. }
  2714. function setValue3fv( gl, v ) {
  2715. if ( v.x !== undefined )
  2716. gl.uniform3f( this.addr, v.x, v.y, v.z );
  2717. else if ( v.r !== undefined )
  2718. gl.uniform3f( this.addr, v.r, v.g, v.b );
  2719. else
  2720. gl.uniform3fv( this.addr, v );
  2721. }
  2722. function setValue4fv( gl, v ) {
  2723. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  2724. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  2725. }
  2726. // Single matrix (from flat array or MatrixN)
  2727. function setValue2fm( gl, v ) {
  2728. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  2729. }
  2730. function setValue3fm( gl, v ) {
  2731. if ( v.elements === undefined ) {
  2732. gl.uniformMatrix3fv( this.addr, false, v );
  2733. } else {
  2734. mat3array.set( v.elements );
  2735. gl.uniformMatrix3fv( this.addr, false, mat3array );
  2736. }
  2737. }
  2738. function setValue4fm( gl, v ) {
  2739. if ( v.elements === undefined ) {
  2740. gl.uniformMatrix4fv( this.addr, false, v );
  2741. } else {
  2742. mat4array.set( v.elements );
  2743. gl.uniformMatrix4fv( this.addr, false, mat4array );
  2744. }
  2745. }
  2746. // Single texture (2D / Cube)
  2747. function setValueT1( gl, v, renderer ) {
  2748. var unit = renderer.allocTextureUnit();
  2749. gl.uniform1i( this.addr, unit );
  2750. renderer.setTexture2D( v || emptyTexture, unit );
  2751. }
  2752. function setValueT6( gl, v, renderer ) {
  2753. var unit = renderer.allocTextureUnit();
  2754. gl.uniform1i( this.addr, unit );
  2755. renderer.setTextureCube( v || emptyCubeTexture, unit );
  2756. }
  2757. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  2758. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  2759. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  2760. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  2761. // Helper to pick the right setter for the singular case
  2762. function getSingularSetter( type ) {
  2763. switch ( type ) {
  2764. case 0x1406: return setValue1f; // FLOAT
  2765. case 0x8b50: return setValue2fv; // _VEC2
  2766. case 0x8b51: return setValue3fv; // _VEC3
  2767. case 0x8b52: return setValue4fv; // _VEC4
  2768. case 0x8b5a: return setValue2fm; // _MAT2
  2769. case 0x8b5b: return setValue3fm; // _MAT3
  2770. case 0x8b5c: return setValue4fm; // _MAT4
  2771. case 0x8b5e: case 0x8d66: return setValueT1; // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  2772. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  2773. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  2774. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2775. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2776. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2777. }
  2778. }
  2779. // Array of scalars
  2780. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  2781. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  2782. // Array of vectors (flat or from THREE classes)
  2783. function setValueV2a( gl, v ) {
  2784. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  2785. }
  2786. function setValueV3a( gl, v ) {
  2787. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  2788. }
  2789. function setValueV4a( gl, v ) {
  2790. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  2791. }
  2792. // Array of matrices (flat or from THREE clases)
  2793. function setValueM2a( gl, v ) {
  2794. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  2795. }
  2796. function setValueM3a( gl, v ) {
  2797. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  2798. }
  2799. function setValueM4a( gl, v ) {
  2800. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  2801. }
  2802. // Array of textures (2D / Cube)
  2803. function setValueT1a( gl, v, renderer ) {
  2804. var n = v.length,
  2805. units = allocTexUnits( renderer, n );
  2806. gl.uniform1iv( this.addr, units );
  2807. for ( var i = 0; i !== n; ++ i ) {
  2808. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  2809. }
  2810. }
  2811. function setValueT6a( gl, v, renderer ) {
  2812. var n = v.length,
  2813. units = allocTexUnits( renderer, n );
  2814. gl.uniform1iv( this.addr, units );
  2815. for ( var i = 0; i !== n; ++ i ) {
  2816. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  2817. }
  2818. }
  2819. // Helper to pick the right setter for a pure (bottom-level) array
  2820. function getPureArraySetter( type ) {
  2821. switch ( type ) {
  2822. case 0x1406: return setValue1fv; // FLOAT
  2823. case 0x8b50: return setValueV2a; // _VEC2
  2824. case 0x8b51: return setValueV3a; // _VEC3
  2825. case 0x8b52: return setValueV4a; // _VEC4
  2826. case 0x8b5a: return setValueM2a; // _MAT2
  2827. case 0x8b5b: return setValueM3a; // _MAT3
  2828. case 0x8b5c: return setValueM4a; // _MAT4
  2829. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  2830. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  2831. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  2832. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2833. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2834. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2835. }
  2836. }
  2837. // --- Uniform Classes ---
  2838. function SingleUniform( id, activeInfo, addr ) {
  2839. this.id = id;
  2840. this.addr = addr;
  2841. this.setValue = getSingularSetter( activeInfo.type );
  2842. // this.path = activeInfo.name; // DEBUG
  2843. }
  2844. function PureArrayUniform( id, activeInfo, addr ) {
  2845. this.id = id;
  2846. this.addr = addr;
  2847. this.size = activeInfo.size;
  2848. this.setValue = getPureArraySetter( activeInfo.type );
  2849. // this.path = activeInfo.name; // DEBUG
  2850. }
  2851. function StructuredUniform( id ) {
  2852. this.id = id;
  2853. UniformContainer.call( this ); // mix-in
  2854. }
  2855. StructuredUniform.prototype.setValue = function ( gl, value ) {
  2856. // Note: Don't need an extra 'renderer' parameter, since samplers
  2857. // are not allowed in structured uniforms.
  2858. var seq = this.seq;
  2859. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2860. var u = seq[ i ];
  2861. u.setValue( gl, value[ u.id ] );
  2862. }
  2863. };
  2864. // --- Top-level ---
  2865. // Parser - builds up the property tree from the path strings
  2866. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  2867. // extracts
  2868. // - the identifier (member name or array index)
  2869. // - followed by an optional right bracket (found when array index)
  2870. // - followed by an optional left bracket or dot (type of subscript)
  2871. //
  2872. // Note: These portions can be read in a non-overlapping fashion and
  2873. // allow straightforward parsing of the hierarchy that WebGL encodes
  2874. // in the uniform names.
  2875. function addUniform( container, uniformObject ) {
  2876. container.seq.push( uniformObject );
  2877. container.map[ uniformObject.id ] = uniformObject;
  2878. }
  2879. function parseUniform( activeInfo, addr, container ) {
  2880. var path = activeInfo.name,
  2881. pathLength = path.length;
  2882. // reset RegExp object, because of the early exit of a previous run
  2883. RePathPart.lastIndex = 0;
  2884. for ( ; ; ) {
  2885. var match = RePathPart.exec( path ),
  2886. matchEnd = RePathPart.lastIndex,
  2887. id = match[ 1 ],
  2888. idIsIndex = match[ 2 ] === ']',
  2889. subscript = match[ 3 ];
  2890. if ( idIsIndex ) id = id | 0; // convert to integer
  2891. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  2892. // bare name or "pure" bottom-level array "[0]" suffix
  2893. addUniform( container, subscript === undefined ?
  2894. new SingleUniform( id, activeInfo, addr ) :
  2895. new PureArrayUniform( id, activeInfo, addr ) );
  2896. break;
  2897. } else {
  2898. // step into inner node / create it in case it doesn't exist
  2899. var map = container.map, next = map[ id ];
  2900. if ( next === undefined ) {
  2901. next = new StructuredUniform( id );
  2902. addUniform( container, next );
  2903. }
  2904. container = next;
  2905. }
  2906. }
  2907. }
  2908. // Root Container
  2909. function WebGLUniforms( gl, program, renderer ) {
  2910. UniformContainer.call( this );
  2911. this.renderer = renderer;
  2912. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  2913. for ( var i = 0; i < n; ++ i ) {
  2914. var info = gl.getActiveUniform( program, i ),
  2915. path = info.name,
  2916. addr = gl.getUniformLocation( program, path );
  2917. parseUniform( info, addr, this );
  2918. }
  2919. }
  2920. WebGLUniforms.prototype.setValue = function ( gl, name, value ) {
  2921. var u = this.map[ name ];
  2922. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  2923. };
  2924. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  2925. var v = object[ name ];
  2926. if ( v !== undefined ) this.setValue( gl, name, v );
  2927. };
  2928. // Static interface
  2929. WebGLUniforms.upload = function ( gl, seq, values, renderer ) {
  2930. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2931. var u = seq[ i ],
  2932. v = values[ u.id ];
  2933. if ( v.needsUpdate !== false ) {
  2934. // note: always updating when .needsUpdate is undefined
  2935. u.setValue( gl, v.value, renderer );
  2936. }
  2937. }
  2938. };
  2939. WebGLUniforms.seqWithValue = function ( seq, values ) {
  2940. var r = [];
  2941. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2942. var u = seq[ i ];
  2943. if ( u.id in values ) r.push( u );
  2944. }
  2945. return r;
  2946. };
  2947. /**
  2948. * @author mrdoob / http://mrdoob.com/
  2949. */
  2950. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  2951. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  2952. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  2953. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  2954. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  2955. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  2956. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  2957. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  2958. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  2959. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  2960. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  2961. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  2962. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  2963. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  2964. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  2965. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  2966. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  2967. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  2968. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  2969. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  2970. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  2971. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  2972. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  2973. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  2974. function Color( r, g, b ) {
  2975. if ( g === undefined && b === undefined ) {
  2976. // r is THREE.Color, hex or string
  2977. return this.set( r );
  2978. }
  2979. return this.setRGB( r, g, b );
  2980. }
  2981. Object.assign( Color.prototype, {
  2982. isColor: true,
  2983. r: 1, g: 1, b: 1,
  2984. set: function ( value ) {
  2985. if ( value && value.isColor ) {
  2986. this.copy( value );
  2987. } else if ( typeof value === 'number' ) {
  2988. this.setHex( value );
  2989. } else if ( typeof value === 'string' ) {
  2990. this.setStyle( value );
  2991. }
  2992. return this;
  2993. },
  2994. setScalar: function ( scalar ) {
  2995. this.r = scalar;
  2996. this.g = scalar;
  2997. this.b = scalar;
  2998. return this;
  2999. },
  3000. setHex: function ( hex ) {
  3001. hex = Math.floor( hex );
  3002. this.r = ( hex >> 16 & 255 ) / 255;
  3003. this.g = ( hex >> 8 & 255 ) / 255;
  3004. this.b = ( hex & 255 ) / 255;
  3005. return this;
  3006. },
  3007. setRGB: function ( r, g, b ) {
  3008. this.r = r;
  3009. this.g = g;
  3010. this.b = b;
  3011. return this;
  3012. },
  3013. setHSL: function () {
  3014. function hue2rgb( p, q, t ) {
  3015. if ( t < 0 ) t += 1;
  3016. if ( t > 1 ) t -= 1;
  3017. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  3018. if ( t < 1 / 2 ) return q;
  3019. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  3020. return p;
  3021. }
  3022. return function setHSL( h, s, l ) {
  3023. // h,s,l ranges are in 0.0 - 1.0
  3024. h = _Math.euclideanModulo( h, 1 );
  3025. s = _Math.clamp( s, 0, 1 );
  3026. l = _Math.clamp( l, 0, 1 );
  3027. if ( s === 0 ) {
  3028. this.r = this.g = this.b = l;
  3029. } else {
  3030. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  3031. var q = ( 2 * l ) - p;
  3032. this.r = hue2rgb( q, p, h + 1 / 3 );
  3033. this.g = hue2rgb( q, p, h );
  3034. this.b = hue2rgb( q, p, h - 1 / 3 );
  3035. }
  3036. return this;
  3037. };
  3038. }(),
  3039. setStyle: function ( style ) {
  3040. function handleAlpha( string ) {
  3041. if ( string === undefined ) return;
  3042. if ( parseFloat( string ) < 1 ) {
  3043. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  3044. }
  3045. }
  3046. var m;
  3047. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  3048. // rgb / hsl
  3049. var color;
  3050. var name = m[ 1 ];
  3051. var components = m[ 2 ];
  3052. switch ( name ) {
  3053. case 'rgb':
  3054. case 'rgba':
  3055. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3056. // rgb(255,0,0) rgba(255,0,0,0.5)
  3057. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  3058. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  3059. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  3060. handleAlpha( color[ 5 ] );
  3061. return this;
  3062. }
  3063. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3064. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  3065. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  3066. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  3067. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  3068. handleAlpha( color[ 5 ] );
  3069. return this;
  3070. }
  3071. break;
  3072. case 'hsl':
  3073. case 'hsla':
  3074. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3075. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  3076. var h = parseFloat( color[ 1 ] ) / 360;
  3077. var s = parseInt( color[ 2 ], 10 ) / 100;
  3078. var l = parseInt( color[ 3 ], 10 ) / 100;
  3079. handleAlpha( color[ 5 ] );
  3080. return this.setHSL( h, s, l );
  3081. }
  3082. break;
  3083. }
  3084. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  3085. // hex color
  3086. var hex = m[ 1 ];
  3087. var size = hex.length;
  3088. if ( size === 3 ) {
  3089. // #ff0
  3090. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  3091. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  3092. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  3093. return this;
  3094. } else if ( size === 6 ) {
  3095. // #ff0000
  3096. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  3097. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  3098. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  3099. return this;
  3100. }
  3101. }
  3102. if ( style && style.length > 0 ) {
  3103. // color keywords
  3104. var hex = ColorKeywords[ style ];
  3105. if ( hex !== undefined ) {
  3106. // red
  3107. this.setHex( hex );
  3108. } else {
  3109. // unknown color
  3110. console.warn( 'THREE.Color: Unknown color ' + style );
  3111. }
  3112. }
  3113. return this;
  3114. },
  3115. clone: function () {
  3116. return new this.constructor( this.r, this.g, this.b );
  3117. },
  3118. copy: function ( color ) {
  3119. this.r = color.r;
  3120. this.g = color.g;
  3121. this.b = color.b;
  3122. return this;
  3123. },
  3124. copyGammaToLinear: function ( color, gammaFactor ) {
  3125. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3126. this.r = Math.pow( color.r, gammaFactor );
  3127. this.g = Math.pow( color.g, gammaFactor );
  3128. this.b = Math.pow( color.b, gammaFactor );
  3129. return this;
  3130. },
  3131. copyLinearToGamma: function ( color, gammaFactor ) {
  3132. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3133. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  3134. this.r = Math.pow( color.r, safeInverse );
  3135. this.g = Math.pow( color.g, safeInverse );
  3136. this.b = Math.pow( color.b, safeInverse );
  3137. return this;
  3138. },
  3139. convertGammaToLinear: function () {
  3140. var r = this.r, g = this.g, b = this.b;
  3141. this.r = r * r;
  3142. this.g = g * g;
  3143. this.b = b * b;
  3144. return this;
  3145. },
  3146. convertLinearToGamma: function () {
  3147. this.r = Math.sqrt( this.r );
  3148. this.g = Math.sqrt( this.g );
  3149. this.b = Math.sqrt( this.b );
  3150. return this;
  3151. },
  3152. getHex: function () {
  3153. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  3154. },
  3155. getHexString: function () {
  3156. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  3157. },
  3158. getHSL: function ( optionalTarget ) {
  3159. // h,s,l ranges are in 0.0 - 1.0
  3160. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  3161. var r = this.r, g = this.g, b = this.b;
  3162. var max = Math.max( r, g, b );
  3163. var min = Math.min( r, g, b );
  3164. var hue, saturation;
  3165. var lightness = ( min + max ) / 2.0;
  3166. if ( min === max ) {
  3167. hue = 0;
  3168. saturation = 0;
  3169. } else {
  3170. var delta = max - min;
  3171. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  3172. switch ( max ) {
  3173. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  3174. case g: hue = ( b - r ) / delta + 2; break;
  3175. case b: hue = ( r - g ) / delta + 4; break;
  3176. }
  3177. hue /= 6;
  3178. }
  3179. hsl.h = hue;
  3180. hsl.s = saturation;
  3181. hsl.l = lightness;
  3182. return hsl;
  3183. },
  3184. getStyle: function () {
  3185. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  3186. },
  3187. offsetHSL: function ( h, s, l ) {
  3188. var hsl = this.getHSL();
  3189. hsl.h += h; hsl.s += s; hsl.l += l;
  3190. this.setHSL( hsl.h, hsl.s, hsl.l );
  3191. return this;
  3192. },
  3193. add: function ( color ) {
  3194. this.r += color.r;
  3195. this.g += color.g;
  3196. this.b += color.b;
  3197. return this;
  3198. },
  3199. addColors: function ( color1, color2 ) {
  3200. this.r = color1.r + color2.r;
  3201. this.g = color1.g + color2.g;
  3202. this.b = color1.b + color2.b;
  3203. return this;
  3204. },
  3205. addScalar: function ( s ) {
  3206. this.r += s;
  3207. this.g += s;
  3208. this.b += s;
  3209. return this;
  3210. },
  3211. sub: function( color ) {
  3212. this.r = Math.max( 0, this.r - color.r );
  3213. this.g = Math.max( 0, this.g - color.g );
  3214. this.b = Math.max( 0, this.b - color.b );
  3215. return this;
  3216. },
  3217. multiply: function ( color ) {
  3218. this.r *= color.r;
  3219. this.g *= color.g;
  3220. this.b *= color.b;
  3221. return this;
  3222. },
  3223. multiplyScalar: function ( s ) {
  3224. this.r *= s;
  3225. this.g *= s;
  3226. this.b *= s;
  3227. return this;
  3228. },
  3229. lerp: function ( color, alpha ) {
  3230. this.r += ( color.r - this.r ) * alpha;
  3231. this.g += ( color.g - this.g ) * alpha;
  3232. this.b += ( color.b - this.b ) * alpha;
  3233. return this;
  3234. },
  3235. equals: function ( c ) {
  3236. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  3237. },
  3238. fromArray: function ( array, offset ) {
  3239. if ( offset === undefined ) offset = 0;
  3240. this.r = array[ offset ];
  3241. this.g = array[ offset + 1 ];
  3242. this.b = array[ offset + 2 ];
  3243. return this;
  3244. },
  3245. toArray: function ( array, offset ) {
  3246. if ( array === undefined ) array = [];
  3247. if ( offset === undefined ) offset = 0;
  3248. array[ offset ] = this.r;
  3249. array[ offset + 1 ] = this.g;
  3250. array[ offset + 2 ] = this.b;
  3251. return array;
  3252. },
  3253. toJSON: function () {
  3254. return this.getHex();
  3255. }
  3256. } );
  3257. /**
  3258. * Uniforms library for shared webgl shaders
  3259. */
  3260. var UniformsLib = {
  3261. common: {
  3262. diffuse: { value: new Color( 0xeeeeee ) },
  3263. opacity: { value: 1.0 },
  3264. map: { value: null },
  3265. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) },
  3266. alphaMap: { value: null },
  3267. },
  3268. specularmap: {
  3269. specularMap: { value: null },
  3270. },
  3271. envmap: {
  3272. envMap: { value: null },
  3273. flipEnvMap: { value: - 1 },
  3274. reflectivity: { value: 1.0 },
  3275. refractionRatio: { value: 0.98 }
  3276. },
  3277. aomap: {
  3278. aoMap: { value: null },
  3279. aoMapIntensity: { value: 1 }
  3280. },
  3281. lightmap: {
  3282. lightMap: { value: null },
  3283. lightMapIntensity: { value: 1 }
  3284. },
  3285. emissivemap: {
  3286. emissiveMap: { value: null }
  3287. },
  3288. bumpmap: {
  3289. bumpMap: { value: null },
  3290. bumpScale: { value: 1 }
  3291. },
  3292. normalmap: {
  3293. normalMap: { value: null },
  3294. normalScale: { value: new Vector2( 1, 1 ) }
  3295. },
  3296. displacementmap: {
  3297. displacementMap: { value: null },
  3298. displacementScale: { value: 1 },
  3299. displacementBias: { value: 0 }
  3300. },
  3301. roughnessmap: {
  3302. roughnessMap: { value: null }
  3303. },
  3304. metalnessmap: {
  3305. metalnessMap: { value: null }
  3306. },
  3307. gradientmap: {
  3308. gradientMap: { value: null }
  3309. },
  3310. fog: {
  3311. fogDensity: { value: 0.00025 },
  3312. fogNear: { value: 1 },
  3313. fogFar: { value: 2000 },
  3314. fogColor: { value: new Color( 0xffffff ) }
  3315. },
  3316. lights: {
  3317. ambientLightColor: { value: [] },
  3318. directionalLights: { value: [], properties: {
  3319. direction: {},
  3320. color: {},
  3321. shadow: {},
  3322. shadowBias: {},
  3323. shadowRadius: {},
  3324. shadowMapSize: {}
  3325. } },
  3326. directionalShadowMap: { value: [] },
  3327. directionalShadowMatrix: { value: [] },
  3328. spotLights: { value: [], properties: {
  3329. color: {},
  3330. position: {},
  3331. direction: {},
  3332. distance: {},
  3333. coneCos: {},
  3334. penumbraCos: {},
  3335. decay: {},
  3336. shadow: {},
  3337. shadowBias: {},
  3338. shadowRadius: {},
  3339. shadowMapSize: {}
  3340. } },
  3341. spotShadowMap: { value: [] },
  3342. spotShadowMatrix: { value: [] },
  3343. pointLights: { value: [], properties: {
  3344. color: {},
  3345. position: {},
  3346. decay: {},
  3347. distance: {},
  3348. shadow: {},
  3349. shadowBias: {},
  3350. shadowRadius: {},
  3351. shadowMapSize: {},
  3352. shadowCameraNear: {},
  3353. shadowCameraFar: {}
  3354. } },
  3355. pointShadowMap: { value: [] },
  3356. pointShadowMatrix: { value: [] },
  3357. hemisphereLights: { value: [], properties: {
  3358. direction: {},
  3359. skyColor: {},
  3360. groundColor: {}
  3361. } },
  3362. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  3363. rectAreaLights: { value: [], properties: {
  3364. color: {},
  3365. position: {},
  3366. width: {},
  3367. height: {}
  3368. } }
  3369. },
  3370. points: {
  3371. diffuse: { value: new Color( 0xeeeeee ) },
  3372. opacity: { value: 1.0 },
  3373. size: { value: 1.0 },
  3374. scale: { value: 1.0 },
  3375. map: { value: null },
  3376. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }
  3377. }
  3378. };
  3379. /**
  3380. * Uniform Utilities
  3381. */
  3382. var UniformsUtils = {
  3383. merge: function ( uniforms ) {
  3384. var merged = {};
  3385. for ( var u = 0; u < uniforms.length; u ++ ) {
  3386. var tmp = this.clone( uniforms[ u ] );
  3387. for ( var p in tmp ) {
  3388. merged[ p ] = tmp[ p ];
  3389. }
  3390. }
  3391. return merged;
  3392. },
  3393. clone: function ( uniforms_src ) {
  3394. var uniforms_dst = {};
  3395. for ( var u in uniforms_src ) {
  3396. uniforms_dst[ u ] = {};
  3397. for ( var p in uniforms_src[ u ] ) {
  3398. var parameter_src = uniforms_src[ u ][ p ];
  3399. if ( parameter_src && ( parameter_src.isColor ||
  3400. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  3401. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  3402. parameter_src.isTexture ) ) {
  3403. uniforms_dst[ u ][ p ] = parameter_src.clone();
  3404. } else if ( Array.isArray( parameter_src ) ) {
  3405. uniforms_dst[ u ][ p ] = parameter_src.slice();
  3406. } else {
  3407. uniforms_dst[ u ][ p ] = parameter_src;
  3408. }
  3409. }
  3410. }
  3411. return uniforms_dst;
  3412. }
  3413. };
  3414. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  3415. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  3416. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  3417. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n";
  3418. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  3419. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  3420. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  3421. var bsdfs = "float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t}\n\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.86267 + (0.49788 + 0.01436 * y ) * y;\n\tfloat b = 3.45068 + (4.18814 + y) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = (x > 0.0) ? v : 0.5 * inversesqrt( 1.0 - x * x ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tvec3 result = vec3( LTC_ClippedSphereFormFactor( vectorFormFactor ) );\n\treturn result;\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n";
  3422. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n";
  3423. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t\t\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\t\tvec4 plane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t\n\t#endif\n#endif\n";
  3424. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n";
  3425. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  3426. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  3427. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  3428. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  3429. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  3430. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  3431. var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transpose( const in mat3 v ) {\n\tmat3 tmp;\n\ttmp[0] = vec3(v[0].x, v[1].x, v[2].x);\n\ttmp[1] = vec3(v[0].y, v[1].y, v[2].y);\n\ttmp[2] = vec3(v[0].z, v[1].z, v[2].z);\n\treturn tmp;\n}\n";
  3432. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n";
  3433. var defaultnormal_vertex = "vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n";
  3434. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  3435. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  3436. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n";
  3437. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  3438. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  3439. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = min( floor( D ) / 255.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n\tXp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract(Le);\n\tvResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n\treturn vec4( max(vRGB, 0.0), 1.0 );\n}\n";
  3440. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n";
  3441. var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n";
  3442. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n";
  3443. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n";
  3444. var fog_vertex = "\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif";
  3445. var fog_pars_vertex = "#ifdef USE_FOG\n varying float fogDepth;\n#endif\n";
  3446. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n";
  3447. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif\n";
  3448. var gradientmap_pars_fragment = "#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif\n";
  3449. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  3450. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  3451. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n";
  3452. var lights_pars = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltcMat;\tuniform sampler2D ltcMag;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n";
  3453. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  3454. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n";
  3455. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n";
  3456. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos - halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos + halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos + halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos - halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tfloat norm = texture2D( ltcMag, uv ).a;\n\t\tvec4 t = texture2D( ltcMat, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( 1, 0, t.y ),\n\t\t\tvec3( 0, t.z, 0 ),\n\t\t\tvec3( t.w, 0, t.x )\n\t\t);\n\t\treflectedLight.directSpecular += lightColor * material.specularColor * norm * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n";
  3457. var lights_template = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n";
  3458. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  3459. var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n";
  3460. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif";
  3461. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n";
  3462. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  3463. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  3464. var map_particle_fragment = "#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n";
  3465. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  3466. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n";
  3467. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  3468. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n";
  3469. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  3470. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n";
  3471. var normal_fragment = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n";
  3472. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n";
  3473. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n";
  3474. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  3475. var project_vertex = "vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;\n";
  3476. var dithering_fragment = "#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n";
  3477. var dithering_pars_fragment = "#if defined( DITHERING )\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif\n";
  3478. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n";
  3479. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  3480. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n";
  3481. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n";
  3482. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n";
  3483. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n";
  3484. var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  3485. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n";
  3486. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif\n";
  3487. var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n";
  3488. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  3489. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  3490. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  3491. var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n";
  3492. var uv_pars_fragment = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif";
  3493. var uv_pars_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n#endif\n";
  3494. var uv_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif";
  3495. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  3496. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  3497. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  3498. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n";
  3499. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n";
  3500. var cube_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  3501. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n";
  3502. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  3503. var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}\n";
  3504. var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}\n";
  3505. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n";
  3506. var equirect_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  3507. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3508. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}\n";
  3509. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3510. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}\n";
  3511. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";
  3512. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  3513. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";
  3514. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  3515. var meshphysical_frag = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";
  3516. var meshphysical_vert = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  3517. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n";
  3518. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n";
  3519. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3520. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  3521. var shadow_frag = "uniform float opacity;\n#include <common>\n#include <packing>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n";
  3522. var shadow_vert = "#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3523. var ShaderChunk = {
  3524. alphamap_fragment: alphamap_fragment,
  3525. alphamap_pars_fragment: alphamap_pars_fragment,
  3526. alphatest_fragment: alphatest_fragment,
  3527. aomap_fragment: aomap_fragment,
  3528. aomap_pars_fragment: aomap_pars_fragment,
  3529. begin_vertex: begin_vertex,
  3530. beginnormal_vertex: beginnormal_vertex,
  3531. bsdfs: bsdfs,
  3532. bumpmap_pars_fragment: bumpmap_pars_fragment,
  3533. clipping_planes_fragment: clipping_planes_fragment,
  3534. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  3535. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  3536. clipping_planes_vertex: clipping_planes_vertex,
  3537. color_fragment: color_fragment,
  3538. color_pars_fragment: color_pars_fragment,
  3539. color_pars_vertex: color_pars_vertex,
  3540. color_vertex: color_vertex,
  3541. common: common,
  3542. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  3543. defaultnormal_vertex: defaultnormal_vertex,
  3544. displacementmap_pars_vertex: displacementmap_pars_vertex,
  3545. displacementmap_vertex: displacementmap_vertex,
  3546. emissivemap_fragment: emissivemap_fragment,
  3547. emissivemap_pars_fragment: emissivemap_pars_fragment,
  3548. encodings_fragment: encodings_fragment,
  3549. encodings_pars_fragment: encodings_pars_fragment,
  3550. envmap_fragment: envmap_fragment,
  3551. envmap_pars_fragment: envmap_pars_fragment,
  3552. envmap_pars_vertex: envmap_pars_vertex,
  3553. envmap_vertex: envmap_vertex,
  3554. fog_vertex: fog_vertex,
  3555. fog_pars_vertex: fog_pars_vertex,
  3556. fog_fragment: fog_fragment,
  3557. fog_pars_fragment: fog_pars_fragment,
  3558. gradientmap_pars_fragment: gradientmap_pars_fragment,
  3559. lightmap_fragment: lightmap_fragment,
  3560. lightmap_pars_fragment: lightmap_pars_fragment,
  3561. lights_lambert_vertex: lights_lambert_vertex,
  3562. lights_pars: lights_pars,
  3563. lights_phong_fragment: lights_phong_fragment,
  3564. lights_phong_pars_fragment: lights_phong_pars_fragment,
  3565. lights_physical_fragment: lights_physical_fragment,
  3566. lights_physical_pars_fragment: lights_physical_pars_fragment,
  3567. lights_template: lights_template,
  3568. logdepthbuf_fragment: logdepthbuf_fragment,
  3569. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  3570. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  3571. logdepthbuf_vertex: logdepthbuf_vertex,
  3572. map_fragment: map_fragment,
  3573. map_pars_fragment: map_pars_fragment,
  3574. map_particle_fragment: map_particle_fragment,
  3575. map_particle_pars_fragment: map_particle_pars_fragment,
  3576. metalnessmap_fragment: metalnessmap_fragment,
  3577. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  3578. morphnormal_vertex: morphnormal_vertex,
  3579. morphtarget_pars_vertex: morphtarget_pars_vertex,
  3580. morphtarget_vertex: morphtarget_vertex,
  3581. normal_fragment: normal_fragment,
  3582. normalmap_pars_fragment: normalmap_pars_fragment,
  3583. packing: packing,
  3584. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  3585. project_vertex: project_vertex,
  3586. dithering_fragment: dithering_fragment,
  3587. dithering_pars_fragment: dithering_pars_fragment,
  3588. roughnessmap_fragment: roughnessmap_fragment,
  3589. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  3590. shadowmap_pars_fragment: shadowmap_pars_fragment,
  3591. shadowmap_pars_vertex: shadowmap_pars_vertex,
  3592. shadowmap_vertex: shadowmap_vertex,
  3593. shadowmask_pars_fragment: shadowmask_pars_fragment,
  3594. skinbase_vertex: skinbase_vertex,
  3595. skinning_pars_vertex: skinning_pars_vertex,
  3596. skinning_vertex: skinning_vertex,
  3597. skinnormal_vertex: skinnormal_vertex,
  3598. specularmap_fragment: specularmap_fragment,
  3599. specularmap_pars_fragment: specularmap_pars_fragment,
  3600. tonemapping_fragment: tonemapping_fragment,
  3601. tonemapping_pars_fragment: tonemapping_pars_fragment,
  3602. uv_pars_fragment: uv_pars_fragment,
  3603. uv_pars_vertex: uv_pars_vertex,
  3604. uv_vertex: uv_vertex,
  3605. uv2_pars_fragment: uv2_pars_fragment,
  3606. uv2_pars_vertex: uv2_pars_vertex,
  3607. uv2_vertex: uv2_vertex,
  3608. worldpos_vertex: worldpos_vertex,
  3609. cube_frag: cube_frag,
  3610. cube_vert: cube_vert,
  3611. depth_frag: depth_frag,
  3612. depth_vert: depth_vert,
  3613. distanceRGBA_frag: distanceRGBA_frag,
  3614. distanceRGBA_vert: distanceRGBA_vert,
  3615. equirect_frag: equirect_frag,
  3616. equirect_vert: equirect_vert,
  3617. linedashed_frag: linedashed_frag,
  3618. linedashed_vert: linedashed_vert,
  3619. meshbasic_frag: meshbasic_frag,
  3620. meshbasic_vert: meshbasic_vert,
  3621. meshlambert_frag: meshlambert_frag,
  3622. meshlambert_vert: meshlambert_vert,
  3623. meshphong_frag: meshphong_frag,
  3624. meshphong_vert: meshphong_vert,
  3625. meshphysical_frag: meshphysical_frag,
  3626. meshphysical_vert: meshphysical_vert,
  3627. normal_frag: normal_frag,
  3628. normal_vert: normal_vert,
  3629. points_frag: points_frag,
  3630. points_vert: points_vert,
  3631. shadow_frag: shadow_frag,
  3632. shadow_vert: shadow_vert
  3633. };
  3634. /**
  3635. * @author alteredq / http://alteredqualia.com/
  3636. * @author mrdoob / http://mrdoob.com/
  3637. * @author mikael emtinger / http://gomo.se/
  3638. */
  3639. var ShaderLib = {
  3640. basic: {
  3641. uniforms: UniformsUtils.merge( [
  3642. UniformsLib.common,
  3643. UniformsLib.specularmap,
  3644. UniformsLib.envmap,
  3645. UniformsLib.aomap,
  3646. UniformsLib.lightmap,
  3647. UniformsLib.fog
  3648. ] ),
  3649. vertexShader: ShaderChunk.meshbasic_vert,
  3650. fragmentShader: ShaderChunk.meshbasic_frag
  3651. },
  3652. lambert: {
  3653. uniforms: UniformsUtils.merge( [
  3654. UniformsLib.common,
  3655. UniformsLib.specularmap,
  3656. UniformsLib.envmap,
  3657. UniformsLib.aomap,
  3658. UniformsLib.lightmap,
  3659. UniformsLib.emissivemap,
  3660. UniformsLib.fog,
  3661. UniformsLib.lights,
  3662. {
  3663. emissive: { value: new Color( 0x000000 ) }
  3664. }
  3665. ] ),
  3666. vertexShader: ShaderChunk.meshlambert_vert,
  3667. fragmentShader: ShaderChunk.meshlambert_frag
  3668. },
  3669. phong: {
  3670. uniforms: UniformsUtils.merge( [
  3671. UniformsLib.common,
  3672. UniformsLib.specularmap,
  3673. UniformsLib.envmap,
  3674. UniformsLib.aomap,
  3675. UniformsLib.lightmap,
  3676. UniformsLib.emissivemap,
  3677. UniformsLib.bumpmap,
  3678. UniformsLib.normalmap,
  3679. UniformsLib.displacementmap,
  3680. UniformsLib.gradientmap,
  3681. UniformsLib.fog,
  3682. UniformsLib.lights,
  3683. {
  3684. emissive: { value: new Color( 0x000000 ) },
  3685. specular: { value: new Color( 0x111111 ) },
  3686. shininess: { value: 30 }
  3687. }
  3688. ] ),
  3689. vertexShader: ShaderChunk.meshphong_vert,
  3690. fragmentShader: ShaderChunk.meshphong_frag
  3691. },
  3692. standard: {
  3693. uniforms: UniformsUtils.merge( [
  3694. UniformsLib.common,
  3695. UniformsLib.envmap,
  3696. UniformsLib.aomap,
  3697. UniformsLib.lightmap,
  3698. UniformsLib.emissivemap,
  3699. UniformsLib.bumpmap,
  3700. UniformsLib.normalmap,
  3701. UniformsLib.displacementmap,
  3702. UniformsLib.roughnessmap,
  3703. UniformsLib.metalnessmap,
  3704. UniformsLib.fog,
  3705. UniformsLib.lights,
  3706. {
  3707. emissive: { value: new Color( 0x000000 ) },
  3708. roughness: { value: 0.5 },
  3709. metalness: { value: 0.5 },
  3710. envMapIntensity: { value: 1 } // temporary
  3711. }
  3712. ] ),
  3713. vertexShader: ShaderChunk.meshphysical_vert,
  3714. fragmentShader: ShaderChunk.meshphysical_frag
  3715. },
  3716. points: {
  3717. uniforms: UniformsUtils.merge( [
  3718. UniformsLib.points,
  3719. UniformsLib.fog
  3720. ] ),
  3721. vertexShader: ShaderChunk.points_vert,
  3722. fragmentShader: ShaderChunk.points_frag
  3723. },
  3724. dashed: {
  3725. uniforms: UniformsUtils.merge( [
  3726. UniformsLib.common,
  3727. UniformsLib.fog,
  3728. {
  3729. scale: { value: 1 },
  3730. dashSize: { value: 1 },
  3731. totalSize: { value: 2 }
  3732. }
  3733. ] ),
  3734. vertexShader: ShaderChunk.linedashed_vert,
  3735. fragmentShader: ShaderChunk.linedashed_frag
  3736. },
  3737. depth: {
  3738. uniforms: UniformsUtils.merge( [
  3739. UniformsLib.common,
  3740. UniformsLib.displacementmap
  3741. ] ),
  3742. vertexShader: ShaderChunk.depth_vert,
  3743. fragmentShader: ShaderChunk.depth_frag
  3744. },
  3745. normal: {
  3746. uniforms: UniformsUtils.merge( [
  3747. UniformsLib.common,
  3748. UniformsLib.bumpmap,
  3749. UniformsLib.normalmap,
  3750. UniformsLib.displacementmap,
  3751. {
  3752. opacity: { value: 1.0 }
  3753. }
  3754. ] ),
  3755. vertexShader: ShaderChunk.normal_vert,
  3756. fragmentShader: ShaderChunk.normal_frag
  3757. },
  3758. /* -------------------------------------------------------------------------
  3759. // Cube map shader
  3760. ------------------------------------------------------------------------- */
  3761. cube: {
  3762. uniforms: {
  3763. tCube: { value: null },
  3764. tFlip: { value: - 1 },
  3765. opacity: { value: 1.0 }
  3766. },
  3767. vertexShader: ShaderChunk.cube_vert,
  3768. fragmentShader: ShaderChunk.cube_frag
  3769. },
  3770. equirect: {
  3771. uniforms: {
  3772. tEquirect: { value: null },
  3773. },
  3774. vertexShader: ShaderChunk.equirect_vert,
  3775. fragmentShader: ShaderChunk.equirect_frag
  3776. },
  3777. distanceRGBA: {
  3778. uniforms: UniformsUtils.merge( [
  3779. UniformsLib.common,
  3780. UniformsLib.displacementmap,
  3781. {
  3782. referencePosition: { value: new Vector3() },
  3783. nearDistance: { value: 1 },
  3784. farDistance: { value: 1000 }
  3785. }
  3786. ] ),
  3787. vertexShader: ShaderChunk.distanceRGBA_vert,
  3788. fragmentShader: ShaderChunk.distanceRGBA_frag
  3789. }
  3790. };
  3791. ShaderLib.physical = {
  3792. uniforms: UniformsUtils.merge( [
  3793. ShaderLib.standard.uniforms,
  3794. {
  3795. clearCoat: { value: 0 },
  3796. clearCoatRoughness: { value: 0 }
  3797. }
  3798. ] ),
  3799. vertexShader: ShaderChunk.meshphysical_vert,
  3800. fragmentShader: ShaderChunk.meshphysical_frag
  3801. };
  3802. /**
  3803. * @author bhouston / http://clara.io
  3804. */
  3805. function Box2( min, max ) {
  3806. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  3807. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  3808. }
  3809. Object.assign( Box2.prototype, {
  3810. set: function ( min, max ) {
  3811. this.min.copy( min );
  3812. this.max.copy( max );
  3813. return this;
  3814. },
  3815. setFromPoints: function ( points ) {
  3816. this.makeEmpty();
  3817. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3818. this.expandByPoint( points[ i ] );
  3819. }
  3820. return this;
  3821. },
  3822. setFromCenterAndSize: function () {
  3823. var v1 = new Vector2();
  3824. return function setFromCenterAndSize( center, size ) {
  3825. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  3826. this.min.copy( center ).sub( halfSize );
  3827. this.max.copy( center ).add( halfSize );
  3828. return this;
  3829. };
  3830. }(),
  3831. clone: function () {
  3832. return new this.constructor().copy( this );
  3833. },
  3834. copy: function ( box ) {
  3835. this.min.copy( box.min );
  3836. this.max.copy( box.max );
  3837. return this;
  3838. },
  3839. makeEmpty: function () {
  3840. this.min.x = this.min.y = + Infinity;
  3841. this.max.x = this.max.y = - Infinity;
  3842. return this;
  3843. },
  3844. isEmpty: function () {
  3845. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3846. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  3847. },
  3848. getCenter: function ( optionalTarget ) {
  3849. var result = optionalTarget || new Vector2();
  3850. return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3851. },
  3852. getSize: function ( optionalTarget ) {
  3853. var result = optionalTarget || new Vector2();
  3854. return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min );
  3855. },
  3856. expandByPoint: function ( point ) {
  3857. this.min.min( point );
  3858. this.max.max( point );
  3859. return this;
  3860. },
  3861. expandByVector: function ( vector ) {
  3862. this.min.sub( vector );
  3863. this.max.add( vector );
  3864. return this;
  3865. },
  3866. expandByScalar: function ( scalar ) {
  3867. this.min.addScalar( - scalar );
  3868. this.max.addScalar( scalar );
  3869. return this;
  3870. },
  3871. containsPoint: function ( point ) {
  3872. return point.x < this.min.x || point.x > this.max.x ||
  3873. point.y < this.min.y || point.y > this.max.y ? false : true;
  3874. },
  3875. containsBox: function ( box ) {
  3876. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3877. this.min.y <= box.min.y && box.max.y <= this.max.y;
  3878. },
  3879. getParameter: function ( point, optionalTarget ) {
  3880. // This can potentially have a divide by zero if the box
  3881. // has a size dimension of 0.
  3882. var result = optionalTarget || new Vector2();
  3883. return result.set(
  3884. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3885. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  3886. );
  3887. },
  3888. intersectsBox: function ( box ) {
  3889. // using 4 splitting planes to rule out intersections
  3890. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3891. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  3892. },
  3893. clampPoint: function ( point, optionalTarget ) {
  3894. var result = optionalTarget || new Vector2();
  3895. return result.copy( point ).clamp( this.min, this.max );
  3896. },
  3897. distanceToPoint: function () {
  3898. var v1 = new Vector2();
  3899. return function distanceToPoint( point ) {
  3900. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  3901. return clampedPoint.sub( point ).length();
  3902. };
  3903. }(),
  3904. intersect: function ( box ) {
  3905. this.min.max( box.min );
  3906. this.max.min( box.max );
  3907. return this;
  3908. },
  3909. union: function ( box ) {
  3910. this.min.min( box.min );
  3911. this.max.max( box.max );
  3912. return this;
  3913. },
  3914. translate: function ( offset ) {
  3915. this.min.add( offset );
  3916. this.max.add( offset );
  3917. return this;
  3918. },
  3919. equals: function ( box ) {
  3920. return box.min.equals( this.min ) && box.max.equals( this.max );
  3921. }
  3922. } );
  3923. /**
  3924. * @author mikael emtinger / http://gomo.se/
  3925. * @author alteredq / http://alteredqualia.com/
  3926. */
  3927. function WebGLFlareRenderer( renderer, gl, state, textures, capabilities ) {
  3928. var vertexBuffer, elementBuffer;
  3929. var shader, program, attributes, uniforms;
  3930. var tempTexture, occlusionTexture;
  3931. function init() {
  3932. var vertices = new Float32Array( [
  3933. - 1, - 1, 0, 0,
  3934. 1, - 1, 1, 0,
  3935. 1, 1, 1, 1,
  3936. - 1, 1, 0, 1
  3937. ] );
  3938. var faces = new Uint16Array( [
  3939. 0, 1, 2,
  3940. 0, 2, 3
  3941. ] );
  3942. // buffers
  3943. vertexBuffer = gl.createBuffer();
  3944. elementBuffer = gl.createBuffer();
  3945. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  3946. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  3947. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  3948. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  3949. // textures
  3950. tempTexture = gl.createTexture();
  3951. occlusionTexture = gl.createTexture();
  3952. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  3953. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  3954. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3955. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3956. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3957. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3958. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  3959. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  3960. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3961. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3962. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3963. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3964. shader = {
  3965. vertexShader: [
  3966. "uniform lowp int renderType;",
  3967. "uniform vec3 screenPosition;",
  3968. "uniform vec2 scale;",
  3969. "uniform float rotation;",
  3970. "uniform sampler2D occlusionMap;",
  3971. "attribute vec2 position;",
  3972. "attribute vec2 uv;",
  3973. "varying vec2 vUV;",
  3974. "varying float vVisibility;",
  3975. "void main() {",
  3976. "vUV = uv;",
  3977. "vec2 pos = position;",
  3978. "if ( renderType == 2 ) {",
  3979. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  3980. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  3981. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  3982. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  3983. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  3984. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  3985. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  3986. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  3987. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  3988. "vVisibility = visibility.r / 9.0;",
  3989. "vVisibility *= 1.0 - visibility.g / 9.0;",
  3990. "vVisibility *= visibility.b / 9.0;",
  3991. "vVisibility *= 1.0 - visibility.a / 9.0;",
  3992. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  3993. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  3994. "}",
  3995. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  3996. "}"
  3997. ].join( "\n" ),
  3998. fragmentShader: [
  3999. "uniform lowp int renderType;",
  4000. "uniform sampler2D map;",
  4001. "uniform float opacity;",
  4002. "uniform vec3 color;",
  4003. "varying vec2 vUV;",
  4004. "varying float vVisibility;",
  4005. "void main() {",
  4006. // pink square
  4007. "if ( renderType == 0 ) {",
  4008. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  4009. // restore
  4010. "} else if ( renderType == 1 ) {",
  4011. "gl_FragColor = texture2D( map, vUV );",
  4012. // flare
  4013. "} else {",
  4014. "vec4 texture = texture2D( map, vUV );",
  4015. "texture.a *= opacity * vVisibility;",
  4016. "gl_FragColor = texture;",
  4017. "gl_FragColor.rgb *= color;",
  4018. "}",
  4019. "}"
  4020. ].join( "\n" )
  4021. };
  4022. program = createProgram( shader );
  4023. attributes = {
  4024. vertex: gl.getAttribLocation ( program, "position" ),
  4025. uv: gl.getAttribLocation ( program, "uv" )
  4026. };
  4027. uniforms = {
  4028. renderType: gl.getUniformLocation( program, "renderType" ),
  4029. map: gl.getUniformLocation( program, "map" ),
  4030. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  4031. opacity: gl.getUniformLocation( program, "opacity" ),
  4032. color: gl.getUniformLocation( program, "color" ),
  4033. scale: gl.getUniformLocation( program, "scale" ),
  4034. rotation: gl.getUniformLocation( program, "rotation" ),
  4035. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  4036. };
  4037. }
  4038. /*
  4039. * Render lens flares
  4040. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  4041. * reads these back and calculates occlusion.
  4042. */
  4043. this.render = function ( flares, scene, camera, viewport ) {
  4044. if ( flares.length === 0 ) return;
  4045. var tempPosition = new Vector3();
  4046. var invAspect = viewport.w / viewport.z,
  4047. halfViewportWidth = viewport.z * 0.5,
  4048. halfViewportHeight = viewport.w * 0.5;
  4049. var size = 16 / viewport.w,
  4050. scale = new Vector2( size * invAspect, size );
  4051. var screenPosition = new Vector3( 1, 1, 0 ),
  4052. screenPositionPixels = new Vector2( 1, 1 );
  4053. var validArea = new Box2();
  4054. validArea.min.set( viewport.x, viewport.y );
  4055. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  4056. if ( program === undefined ) {
  4057. init();
  4058. }
  4059. state.useProgram( program );
  4060. state.initAttributes();
  4061. state.enableAttribute( attributes.vertex );
  4062. state.enableAttribute( attributes.uv );
  4063. state.disableUnusedAttributes();
  4064. // loop through all lens flares to update their occlusion and positions
  4065. // setup gl and common used attribs/uniforms
  4066. gl.uniform1i( uniforms.occlusionMap, 0 );
  4067. gl.uniform1i( uniforms.map, 1 );
  4068. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4069. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  4070. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4071. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4072. state.disable( gl.CULL_FACE );
  4073. state.buffers.depth.setMask( false );
  4074. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  4075. size = 16 / viewport.w;
  4076. scale.set( size * invAspect, size );
  4077. // calc object screen position
  4078. var flare = flares[ i ];
  4079. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  4080. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  4081. tempPosition.applyMatrix4( camera.projectionMatrix );
  4082. // setup arrays for gl programs
  4083. screenPosition.copy( tempPosition );
  4084. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  4085. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  4086. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  4087. // screen cull
  4088. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  4089. // save current RGB to temp texture
  4090. state.activeTexture( gl.TEXTURE0 );
  4091. state.bindTexture( gl.TEXTURE_2D, null );
  4092. state.activeTexture( gl.TEXTURE1 );
  4093. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4094. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4095. // render pink quad
  4096. gl.uniform1i( uniforms.renderType, 0 );
  4097. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4098. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4099. state.disable( gl.BLEND );
  4100. state.enable( gl.DEPTH_TEST );
  4101. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4102. // copy result to occlusionMap
  4103. state.activeTexture( gl.TEXTURE0 );
  4104. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  4105. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4106. // restore graphics
  4107. gl.uniform1i( uniforms.renderType, 1 );
  4108. state.disable( gl.DEPTH_TEST );
  4109. state.activeTexture( gl.TEXTURE1 );
  4110. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4111. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4112. // update object positions
  4113. flare.positionScreen.copy( screenPosition );
  4114. if ( flare.customUpdateCallback ) {
  4115. flare.customUpdateCallback( flare );
  4116. } else {
  4117. flare.updateLensFlares();
  4118. }
  4119. // render flares
  4120. gl.uniform1i( uniforms.renderType, 2 );
  4121. state.enable( gl.BLEND );
  4122. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  4123. var sprite = flare.lensFlares[ j ];
  4124. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  4125. screenPosition.x = sprite.x;
  4126. screenPosition.y = sprite.y;
  4127. screenPosition.z = sprite.z;
  4128. size = sprite.size * sprite.scale / viewport.w;
  4129. scale.x = size * invAspect;
  4130. scale.y = size;
  4131. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4132. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4133. gl.uniform1f( uniforms.rotation, sprite.rotation );
  4134. gl.uniform1f( uniforms.opacity, sprite.opacity );
  4135. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  4136. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  4137. textures.setTexture2D( sprite.texture, 1 );
  4138. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4139. }
  4140. }
  4141. }
  4142. }
  4143. // restore gl
  4144. state.enable( gl.CULL_FACE );
  4145. state.enable( gl.DEPTH_TEST );
  4146. state.buffers.depth.setMask( true );
  4147. state.reset();
  4148. };
  4149. function createProgram( shader ) {
  4150. var program = gl.createProgram();
  4151. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4152. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4153. var prefix = "precision " + capabilities.precision + " float;\n";
  4154. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  4155. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  4156. gl.compileShader( fragmentShader );
  4157. gl.compileShader( vertexShader );
  4158. gl.attachShader( program, fragmentShader );
  4159. gl.attachShader( program, vertexShader );
  4160. gl.linkProgram( program );
  4161. return program;
  4162. }
  4163. }
  4164. /**
  4165. * @author mrdoob / http://mrdoob.com/
  4166. */
  4167. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  4168. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  4169. this.needsUpdate = true;
  4170. }
  4171. CanvasTexture.prototype = Object.create( Texture.prototype );
  4172. CanvasTexture.prototype.constructor = CanvasTexture;
  4173. /**
  4174. * @author mikael emtinger / http://gomo.se/
  4175. * @author alteredq / http://alteredqualia.com/
  4176. */
  4177. function WebGLSpriteRenderer( renderer, gl, state, textures, capabilities ) {
  4178. var vertexBuffer, elementBuffer;
  4179. var program, attributes, uniforms;
  4180. var texture;
  4181. // decompose matrixWorld
  4182. var spritePosition = new Vector3();
  4183. var spriteRotation = new Quaternion();
  4184. var spriteScale = new Vector3();
  4185. function init() {
  4186. var vertices = new Float32Array( [
  4187. - 0.5, - 0.5, 0, 0,
  4188. 0.5, - 0.5, 1, 0,
  4189. 0.5, 0.5, 1, 1,
  4190. - 0.5, 0.5, 0, 1
  4191. ] );
  4192. var faces = new Uint16Array( [
  4193. 0, 1, 2,
  4194. 0, 2, 3
  4195. ] );
  4196. vertexBuffer = gl.createBuffer();
  4197. elementBuffer = gl.createBuffer();
  4198. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4199. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  4200. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4201. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  4202. program = createProgram();
  4203. attributes = {
  4204. position: gl.getAttribLocation ( program, 'position' ),
  4205. uv: gl.getAttribLocation ( program, 'uv' )
  4206. };
  4207. uniforms = {
  4208. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  4209. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  4210. rotation: gl.getUniformLocation( program, 'rotation' ),
  4211. scale: gl.getUniformLocation( program, 'scale' ),
  4212. color: gl.getUniformLocation( program, 'color' ),
  4213. map: gl.getUniformLocation( program, 'map' ),
  4214. opacity: gl.getUniformLocation( program, 'opacity' ),
  4215. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  4216. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  4217. fogType: gl.getUniformLocation( program, 'fogType' ),
  4218. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  4219. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  4220. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  4221. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  4222. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  4223. };
  4224. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  4225. canvas.width = 8;
  4226. canvas.height = 8;
  4227. var context = canvas.getContext( '2d' );
  4228. context.fillStyle = 'white';
  4229. context.fillRect( 0, 0, 8, 8 );
  4230. texture = new CanvasTexture( canvas );
  4231. }
  4232. this.render = function ( sprites, scene, camera ) {
  4233. if ( sprites.length === 0 ) return;
  4234. // setup gl
  4235. if ( program === undefined ) {
  4236. init();
  4237. }
  4238. state.useProgram( program );
  4239. state.initAttributes();
  4240. state.enableAttribute( attributes.position );
  4241. state.enableAttribute( attributes.uv );
  4242. state.disableUnusedAttributes();
  4243. state.disable( gl.CULL_FACE );
  4244. state.enable( gl.BLEND );
  4245. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4246. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  4247. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4248. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4249. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  4250. state.activeTexture( gl.TEXTURE0 );
  4251. gl.uniform1i( uniforms.map, 0 );
  4252. var oldFogType = 0;
  4253. var sceneFogType = 0;
  4254. var fog = scene.fog;
  4255. if ( fog ) {
  4256. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  4257. if ( fog.isFog ) {
  4258. gl.uniform1f( uniforms.fogNear, fog.near );
  4259. gl.uniform1f( uniforms.fogFar, fog.far );
  4260. gl.uniform1i( uniforms.fogType, 1 );
  4261. oldFogType = 1;
  4262. sceneFogType = 1;
  4263. } else if ( fog.isFogExp2 ) {
  4264. gl.uniform1f( uniforms.fogDensity, fog.density );
  4265. gl.uniform1i( uniforms.fogType, 2 );
  4266. oldFogType = 2;
  4267. sceneFogType = 2;
  4268. }
  4269. } else {
  4270. gl.uniform1i( uniforms.fogType, 0 );
  4271. oldFogType = 0;
  4272. sceneFogType = 0;
  4273. }
  4274. // update positions and sort
  4275. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4276. var sprite = sprites[ i ];
  4277. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  4278. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  4279. }
  4280. sprites.sort( painterSortStable );
  4281. // render all sprites
  4282. var scale = [];
  4283. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4284. var sprite = sprites[ i ];
  4285. var material = sprite.material;
  4286. if ( material.visible === false ) continue;
  4287. sprite.onBeforeRender( renderer, scene, camera, undefined, material, undefined );
  4288. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  4289. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  4290. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  4291. scale[ 0 ] = spriteScale.x;
  4292. scale[ 1 ] = spriteScale.y;
  4293. var fogType = 0;
  4294. if ( scene.fog && material.fog ) {
  4295. fogType = sceneFogType;
  4296. }
  4297. if ( oldFogType !== fogType ) {
  4298. gl.uniform1i( uniforms.fogType, fogType );
  4299. oldFogType = fogType;
  4300. }
  4301. if ( material.map !== null ) {
  4302. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  4303. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  4304. } else {
  4305. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  4306. gl.uniform2f( uniforms.uvScale, 1, 1 );
  4307. }
  4308. gl.uniform1f( uniforms.opacity, material.opacity );
  4309. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  4310. gl.uniform1f( uniforms.rotation, material.rotation );
  4311. gl.uniform2fv( uniforms.scale, scale );
  4312. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  4313. state.buffers.depth.setTest( material.depthTest );
  4314. state.buffers.depth.setMask( material.depthWrite );
  4315. textures.setTexture2D( material.map || texture, 0 );
  4316. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4317. sprite.onAfterRender( renderer, scene, camera, undefined, material, undefined );
  4318. }
  4319. // restore gl
  4320. state.enable( gl.CULL_FACE );
  4321. state.reset();
  4322. };
  4323. function createProgram() {
  4324. var program = gl.createProgram();
  4325. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4326. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4327. gl.shaderSource( vertexShader, [
  4328. 'precision ' + capabilities.precision + ' float;',
  4329. '#define SHADER_NAME ' + 'SpriteMaterial',
  4330. 'uniform mat4 modelViewMatrix;',
  4331. 'uniform mat4 projectionMatrix;',
  4332. 'uniform float rotation;',
  4333. 'uniform vec2 scale;',
  4334. 'uniform vec2 uvOffset;',
  4335. 'uniform vec2 uvScale;',
  4336. 'attribute vec2 position;',
  4337. 'attribute vec2 uv;',
  4338. 'varying vec2 vUV;',
  4339. 'void main() {',
  4340. 'vUV = uvOffset + uv * uvScale;',
  4341. 'vec2 alignedPosition = position * scale;',
  4342. 'vec2 rotatedPosition;',
  4343. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  4344. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  4345. 'vec4 finalPosition;',
  4346. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  4347. 'finalPosition.xy += rotatedPosition;',
  4348. 'finalPosition = projectionMatrix * finalPosition;',
  4349. 'gl_Position = finalPosition;',
  4350. '}'
  4351. ].join( '\n' ) );
  4352. gl.shaderSource( fragmentShader, [
  4353. 'precision ' + capabilities.precision + ' float;',
  4354. '#define SHADER_NAME ' + 'SpriteMaterial',
  4355. 'uniform vec3 color;',
  4356. 'uniform sampler2D map;',
  4357. 'uniform float opacity;',
  4358. 'uniform int fogType;',
  4359. 'uniform vec3 fogColor;',
  4360. 'uniform float fogDensity;',
  4361. 'uniform float fogNear;',
  4362. 'uniform float fogFar;',
  4363. 'uniform float alphaTest;',
  4364. 'varying vec2 vUV;',
  4365. 'void main() {',
  4366. 'vec4 texture = texture2D( map, vUV );',
  4367. 'if ( texture.a < alphaTest ) discard;',
  4368. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  4369. 'if ( fogType > 0 ) {',
  4370. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  4371. 'float fogFactor = 0.0;',
  4372. 'if ( fogType == 1 ) {',
  4373. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  4374. '} else {',
  4375. 'const float LOG2 = 1.442695;',
  4376. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  4377. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  4378. '}',
  4379. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  4380. '}',
  4381. '}'
  4382. ].join( '\n' ) );
  4383. gl.compileShader( vertexShader );
  4384. gl.compileShader( fragmentShader );
  4385. gl.attachShader( program, vertexShader );
  4386. gl.attachShader( program, fragmentShader );
  4387. gl.linkProgram( program );
  4388. return program;
  4389. }
  4390. function painterSortStable( a, b ) {
  4391. if ( a.renderOrder !== b.renderOrder ) {
  4392. return a.renderOrder - b.renderOrder;
  4393. } else if ( a.z !== b.z ) {
  4394. return b.z - a.z;
  4395. } else {
  4396. return b.id - a.id;
  4397. }
  4398. }
  4399. }
  4400. /**
  4401. * @author mrdoob / http://mrdoob.com/
  4402. * @author alteredq / http://alteredqualia.com/
  4403. */
  4404. var materialId = 0;
  4405. function Material() {
  4406. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4407. this.uuid = _Math.generateUUID();
  4408. this.name = '';
  4409. this.type = 'Material';
  4410. this.fog = true;
  4411. this.lights = true;
  4412. this.blending = NormalBlending;
  4413. this.side = FrontSide;
  4414. this.flatShading = false;
  4415. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  4416. this.opacity = 1;
  4417. this.transparent = false;
  4418. this.blendSrc = SrcAlphaFactor;
  4419. this.blendDst = OneMinusSrcAlphaFactor;
  4420. this.blendEquation = AddEquation;
  4421. this.blendSrcAlpha = null;
  4422. this.blendDstAlpha = null;
  4423. this.blendEquationAlpha = null;
  4424. this.depthFunc = LessEqualDepth;
  4425. this.depthTest = true;
  4426. this.depthWrite = true;
  4427. this.clippingPlanes = null;
  4428. this.clipIntersection = false;
  4429. this.clipShadows = false;
  4430. this.colorWrite = true;
  4431. this.precision = null; // override the renderer's default precision for this material
  4432. this.polygonOffset = false;
  4433. this.polygonOffsetFactor = 0;
  4434. this.polygonOffsetUnits = 0;
  4435. this.dithering = false;
  4436. this.alphaTest = 0;
  4437. this.premultipliedAlpha = false;
  4438. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  4439. this.visible = true;
  4440. this.needsUpdate = true;
  4441. }
  4442. Object.assign( Material.prototype, EventDispatcher.prototype, {
  4443. isMaterial: true,
  4444. onBeforeCompile: function () {},
  4445. setValues: function ( values ) {
  4446. if ( values === undefined ) return;
  4447. for ( var key in values ) {
  4448. var newValue = values[ key ];
  4449. if ( newValue === undefined ) {
  4450. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  4451. continue;
  4452. }
  4453. // for backward compatability if shading is set in the constructor
  4454. if ( key === 'shading' ) {
  4455. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  4456. this.flatShading = ( newValue === FlatShading ) ? true : false;
  4457. continue;
  4458. }
  4459. var currentValue = this[ key ];
  4460. if ( currentValue === undefined ) {
  4461. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  4462. continue;
  4463. }
  4464. if ( currentValue && currentValue.isColor ) {
  4465. currentValue.set( newValue );
  4466. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4467. currentValue.copy( newValue );
  4468. } else if ( key === 'overdraw' ) {
  4469. // ensure overdraw is backwards-compatible with legacy boolean type
  4470. this[ key ] = Number( newValue );
  4471. } else {
  4472. this[ key ] = newValue;
  4473. }
  4474. }
  4475. },
  4476. toJSON: function ( meta ) {
  4477. var isRoot = meta === undefined;
  4478. if ( isRoot ) {
  4479. meta = {
  4480. textures: {},
  4481. images: {}
  4482. };
  4483. }
  4484. var data = {
  4485. metadata: {
  4486. version: 4.5,
  4487. type: 'Material',
  4488. generator: 'Material.toJSON'
  4489. }
  4490. };
  4491. // standard Material serialization
  4492. data.uuid = this.uuid;
  4493. data.type = this.type;
  4494. if ( this.name !== '' ) data.name = this.name;
  4495. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4496. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4497. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4498. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4499. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4500. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4501. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  4502. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  4503. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4504. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4505. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4506. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4507. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4508. data.bumpScale = this.bumpScale;
  4509. }
  4510. if ( this.normalMap && this.normalMap.isTexture ) {
  4511. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4512. data.normalScale = this.normalScale.toArray();
  4513. }
  4514. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4515. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4516. data.displacementScale = this.displacementScale;
  4517. data.displacementBias = this.displacementBias;
  4518. }
  4519. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4520. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4521. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4522. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4523. if ( this.envMap && this.envMap.isTexture ) {
  4524. data.envMap = this.envMap.toJSON( meta ).uuid;
  4525. data.reflectivity = this.reflectivity; // Scale behind envMap
  4526. }
  4527. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4528. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4529. }
  4530. if ( this.size !== undefined ) data.size = this.size;
  4531. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4532. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4533. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  4534. if ( this.side !== FrontSide ) data.side = this.side;
  4535. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  4536. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4537. if ( this.transparent === true ) data.transparent = this.transparent;
  4538. data.depthFunc = this.depthFunc;
  4539. data.depthTest = this.depthTest;
  4540. data.depthWrite = this.depthWrite;
  4541. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4542. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4543. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4544. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4545. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4546. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4547. data.skinning = this.skinning;
  4548. data.morphTargets = this.morphTargets;
  4549. data.dithering = this.dithering;
  4550. // TODO: Copied from Object3D.toJSON
  4551. function extractFromCache( cache ) {
  4552. var values = [];
  4553. for ( var key in cache ) {
  4554. var data = cache[ key ];
  4555. delete data.metadata;
  4556. values.push( data );
  4557. }
  4558. return values;
  4559. }
  4560. if ( isRoot ) {
  4561. var textures = extractFromCache( meta.textures );
  4562. var images = extractFromCache( meta.images );
  4563. if ( textures.length > 0 ) data.textures = textures;
  4564. if ( images.length > 0 ) data.images = images;
  4565. }
  4566. return data;
  4567. },
  4568. clone: function () {
  4569. return new this.constructor().copy( this );
  4570. },
  4571. copy: function ( source ) {
  4572. this.name = source.name;
  4573. this.fog = source.fog;
  4574. this.lights = source.lights;
  4575. this.blending = source.blending;
  4576. this.side = source.side;
  4577. this.flatShading = source.flatShading;
  4578. this.vertexColors = source.vertexColors;
  4579. this.opacity = source.opacity;
  4580. this.transparent = source.transparent;
  4581. this.blendSrc = source.blendSrc;
  4582. this.blendDst = source.blendDst;
  4583. this.blendEquation = source.blendEquation;
  4584. this.blendSrcAlpha = source.blendSrcAlpha;
  4585. this.blendDstAlpha = source.blendDstAlpha;
  4586. this.blendEquationAlpha = source.blendEquationAlpha;
  4587. this.depthFunc = source.depthFunc;
  4588. this.depthTest = source.depthTest;
  4589. this.depthWrite = source.depthWrite;
  4590. this.colorWrite = source.colorWrite;
  4591. this.precision = source.precision;
  4592. this.polygonOffset = source.polygonOffset;
  4593. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4594. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4595. this.dithering = source.dithering;
  4596. this.alphaTest = source.alphaTest;
  4597. this.premultipliedAlpha = source.premultipliedAlpha;
  4598. this.overdraw = source.overdraw;
  4599. this.visible = source.visible;
  4600. this.clipShadows = source.clipShadows;
  4601. this.clipIntersection = source.clipIntersection;
  4602. var srcPlanes = source.clippingPlanes,
  4603. dstPlanes = null;
  4604. if ( srcPlanes !== null ) {
  4605. var n = srcPlanes.length;
  4606. dstPlanes = new Array( n );
  4607. for ( var i = 0; i !== n; ++ i )
  4608. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4609. }
  4610. this.clippingPlanes = dstPlanes;
  4611. return this;
  4612. },
  4613. dispose: function () {
  4614. this.dispatchEvent( { type: 'dispose' } );
  4615. }
  4616. } );
  4617. /**
  4618. * @author alteredq / http://alteredqualia.com/
  4619. *
  4620. * parameters = {
  4621. * defines: { "label" : "value" },
  4622. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  4623. *
  4624. * fragmentShader: <string>,
  4625. * vertexShader: <string>,
  4626. *
  4627. * wireframe: <boolean>,
  4628. * wireframeLinewidth: <float>,
  4629. *
  4630. * lights: <bool>,
  4631. *
  4632. * skinning: <bool>,
  4633. * morphTargets: <bool>,
  4634. * morphNormals: <bool>
  4635. * }
  4636. */
  4637. function ShaderMaterial( parameters ) {
  4638. Material.call( this );
  4639. this.type = 'ShaderMaterial';
  4640. this.defines = {};
  4641. this.uniforms = {};
  4642. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  4643. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  4644. this.linewidth = 1;
  4645. this.wireframe = false;
  4646. this.wireframeLinewidth = 1;
  4647. this.fog = false; // set to use scene fog
  4648. this.lights = false; // set to use scene lights
  4649. this.clipping = false; // set to use user-defined clipping planes
  4650. this.skinning = false; // set to use skinning attribute streams
  4651. this.morphTargets = false; // set to use morph targets
  4652. this.morphNormals = false; // set to use morph normals
  4653. this.extensions = {
  4654. derivatives: false, // set to use derivatives
  4655. fragDepth: false, // set to use fragment depth values
  4656. drawBuffers: false, // set to use draw buffers
  4657. shaderTextureLOD: false // set to use shader texture LOD
  4658. };
  4659. // When rendered geometry doesn't include these attributes but the material does,
  4660. // use these default values in WebGL. This avoids errors when buffer data is missing.
  4661. this.defaultAttributeValues = {
  4662. 'color': [ 1, 1, 1 ],
  4663. 'uv': [ 0, 0 ],
  4664. 'uv2': [ 0, 0 ]
  4665. };
  4666. this.index0AttributeName = undefined;
  4667. if ( parameters !== undefined ) {
  4668. if ( parameters.attributes !== undefined ) {
  4669. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  4670. }
  4671. this.setValues( parameters );
  4672. }
  4673. }
  4674. ShaderMaterial.prototype = Object.create( Material.prototype );
  4675. ShaderMaterial.prototype.constructor = ShaderMaterial;
  4676. ShaderMaterial.prototype.isShaderMaterial = true;
  4677. ShaderMaterial.prototype.copy = function ( source ) {
  4678. Material.prototype.copy.call( this, source );
  4679. this.fragmentShader = source.fragmentShader;
  4680. this.vertexShader = source.vertexShader;
  4681. this.uniforms = UniformsUtils.clone( source.uniforms );
  4682. this.defines = source.defines;
  4683. this.wireframe = source.wireframe;
  4684. this.wireframeLinewidth = source.wireframeLinewidth;
  4685. this.lights = source.lights;
  4686. this.clipping = source.clipping;
  4687. this.skinning = source.skinning;
  4688. this.morphTargets = source.morphTargets;
  4689. this.morphNormals = source.morphNormals;
  4690. this.extensions = source.extensions;
  4691. return this;
  4692. };
  4693. ShaderMaterial.prototype.toJSON = function ( meta ) {
  4694. var data = Material.prototype.toJSON.call( this, meta );
  4695. data.uniforms = this.uniforms;
  4696. data.vertexShader = this.vertexShader;
  4697. data.fragmentShader = this.fragmentShader;
  4698. return data;
  4699. };
  4700. /**
  4701. * @author mrdoob / http://mrdoob.com/
  4702. * @author alteredq / http://alteredqualia.com/
  4703. * @author bhouston / https://clara.io
  4704. * @author WestLangley / http://github.com/WestLangley
  4705. *
  4706. * parameters = {
  4707. *
  4708. * opacity: <float>,
  4709. *
  4710. * map: new THREE.Texture( <Image> ),
  4711. *
  4712. * alphaMap: new THREE.Texture( <Image> ),
  4713. *
  4714. * displacementMap: new THREE.Texture( <Image> ),
  4715. * displacementScale: <float>,
  4716. * displacementBias: <float>,
  4717. *
  4718. * wireframe: <boolean>,
  4719. * wireframeLinewidth: <float>
  4720. * }
  4721. */
  4722. function MeshDepthMaterial( parameters ) {
  4723. Material.call( this );
  4724. this.type = 'MeshDepthMaterial';
  4725. this.depthPacking = BasicDepthPacking;
  4726. this.skinning = false;
  4727. this.morphTargets = false;
  4728. this.map = null;
  4729. this.alphaMap = null;
  4730. this.displacementMap = null;
  4731. this.displacementScale = 1;
  4732. this.displacementBias = 0;
  4733. this.wireframe = false;
  4734. this.wireframeLinewidth = 1;
  4735. this.fog = false;
  4736. this.lights = false;
  4737. this.setValues( parameters );
  4738. }
  4739. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  4740. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  4741. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  4742. MeshDepthMaterial.prototype.copy = function ( source ) {
  4743. Material.prototype.copy.call( this, source );
  4744. this.depthPacking = source.depthPacking;
  4745. this.skinning = source.skinning;
  4746. this.morphTargets = source.morphTargets;
  4747. this.map = source.map;
  4748. this.alphaMap = source.alphaMap;
  4749. this.displacementMap = source.displacementMap;
  4750. this.displacementScale = source.displacementScale;
  4751. this.displacementBias = source.displacementBias;
  4752. this.wireframe = source.wireframe;
  4753. this.wireframeLinewidth = source.wireframeLinewidth;
  4754. return this;
  4755. };
  4756. /**
  4757. * @author WestLangley / http://github.com/WestLangley
  4758. *
  4759. * parameters = {
  4760. *
  4761. * referencePosition: <float>,
  4762. * nearDistance: <float>,
  4763. * farDistance: <float>,
  4764. *
  4765. * skinning: <bool>,
  4766. * morphTargets: <bool>,
  4767. *
  4768. * map: new THREE.Texture( <Image> ),
  4769. *
  4770. * alphaMap: new THREE.Texture( <Image> ),
  4771. *
  4772. * displacementMap: new THREE.Texture( <Image> ),
  4773. * displacementScale: <float>,
  4774. * displacementBias: <float>
  4775. *
  4776. * }
  4777. */
  4778. function MeshDistanceMaterial( parameters ) {
  4779. Material.call( this );
  4780. this.type = 'MeshDistanceMaterial';
  4781. this.referencePosition = new Vector3();
  4782. this.nearDistance = 1;
  4783. this.farDistance = 1000;
  4784. this.skinning = false;
  4785. this.morphTargets = false;
  4786. this.map = null;
  4787. this.alphaMap = null;
  4788. this.displacementMap = null;
  4789. this.displacementScale = 1;
  4790. this.displacementBias = 0;
  4791. this.fog = false;
  4792. this.lights = false;
  4793. this.setValues( parameters );
  4794. }
  4795. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  4796. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  4797. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  4798. MeshDistanceMaterial.prototype.copy = function ( source ) {
  4799. Material.prototype.copy.call( this, source );
  4800. this.referencePosition.copy( source.referencePosition );
  4801. this.nearDistance = source.nearDistance;
  4802. this.farDistance = source.farDistance;
  4803. this.skinning = source.skinning;
  4804. this.morphTargets = source.morphTargets;
  4805. this.map = source.map;
  4806. this.alphaMap = source.alphaMap;
  4807. this.displacementMap = source.displacementMap;
  4808. this.displacementScale = source.displacementScale;
  4809. this.displacementBias = source.displacementBias;
  4810. return this;
  4811. };
  4812. /**
  4813. * @author bhouston / http://clara.io
  4814. * @author WestLangley / http://github.com/WestLangley
  4815. */
  4816. function Box3( min, max ) {
  4817. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  4818. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  4819. }
  4820. Object.assign( Box3.prototype, {
  4821. isBox3: true,
  4822. set: function ( min, max ) {
  4823. this.min.copy( min );
  4824. this.max.copy( max );
  4825. return this;
  4826. },
  4827. setFromArray: function ( array ) {
  4828. var minX = + Infinity;
  4829. var minY = + Infinity;
  4830. var minZ = + Infinity;
  4831. var maxX = - Infinity;
  4832. var maxY = - Infinity;
  4833. var maxZ = - Infinity;
  4834. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  4835. var x = array[ i ];
  4836. var y = array[ i + 1 ];
  4837. var z = array[ i + 2 ];
  4838. if ( x < minX ) minX = x;
  4839. if ( y < minY ) minY = y;
  4840. if ( z < minZ ) minZ = z;
  4841. if ( x > maxX ) maxX = x;
  4842. if ( y > maxY ) maxY = y;
  4843. if ( z > maxZ ) maxZ = z;
  4844. }
  4845. this.min.set( minX, minY, minZ );
  4846. this.max.set( maxX, maxY, maxZ );
  4847. return this;
  4848. },
  4849. setFromBufferAttribute: function ( attribute ) {
  4850. var minX = + Infinity;
  4851. var minY = + Infinity;
  4852. var minZ = + Infinity;
  4853. var maxX = - Infinity;
  4854. var maxY = - Infinity;
  4855. var maxZ = - Infinity;
  4856. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  4857. var x = attribute.getX( i );
  4858. var y = attribute.getY( i );
  4859. var z = attribute.getZ( i );
  4860. if ( x < minX ) minX = x;
  4861. if ( y < minY ) minY = y;
  4862. if ( z < minZ ) minZ = z;
  4863. if ( x > maxX ) maxX = x;
  4864. if ( y > maxY ) maxY = y;
  4865. if ( z > maxZ ) maxZ = z;
  4866. }
  4867. this.min.set( minX, minY, minZ );
  4868. this.max.set( maxX, maxY, maxZ );
  4869. return this;
  4870. },
  4871. setFromPoints: function ( points ) {
  4872. this.makeEmpty();
  4873. for ( var i = 0, il = points.length; i < il; i ++ ) {
  4874. this.expandByPoint( points[ i ] );
  4875. }
  4876. return this;
  4877. },
  4878. setFromCenterAndSize: function () {
  4879. var v1 = new Vector3();
  4880. return function setFromCenterAndSize( center, size ) {
  4881. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  4882. this.min.copy( center ).sub( halfSize );
  4883. this.max.copy( center ).add( halfSize );
  4884. return this;
  4885. };
  4886. }(),
  4887. setFromObject: function ( object ) {
  4888. this.makeEmpty();
  4889. return this.expandByObject( object );
  4890. },
  4891. clone: function () {
  4892. return new this.constructor().copy( this );
  4893. },
  4894. copy: function ( box ) {
  4895. this.min.copy( box.min );
  4896. this.max.copy( box.max );
  4897. return this;
  4898. },
  4899. makeEmpty: function () {
  4900. this.min.x = this.min.y = this.min.z = + Infinity;
  4901. this.max.x = this.max.y = this.max.z = - Infinity;
  4902. return this;
  4903. },
  4904. isEmpty: function () {
  4905. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4906. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  4907. },
  4908. getCenter: function ( optionalTarget ) {
  4909. var result = optionalTarget || new Vector3();
  4910. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  4911. },
  4912. getSize: function ( optionalTarget ) {
  4913. var result = optionalTarget || new Vector3();
  4914. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  4915. },
  4916. expandByPoint: function ( point ) {
  4917. this.min.min( point );
  4918. this.max.max( point );
  4919. return this;
  4920. },
  4921. expandByVector: function ( vector ) {
  4922. this.min.sub( vector );
  4923. this.max.add( vector );
  4924. return this;
  4925. },
  4926. expandByScalar: function ( scalar ) {
  4927. this.min.addScalar( - scalar );
  4928. this.max.addScalar( scalar );
  4929. return this;
  4930. },
  4931. expandByObject: function () {
  4932. // Computes the world-axis-aligned bounding box of an object (including its children),
  4933. // accounting for both the object's, and children's, world transforms
  4934. var v1 = new Vector3();
  4935. return function expandByObject( object ) {
  4936. var scope = this;
  4937. object.updateMatrixWorld( true );
  4938. object.traverse( function ( node ) {
  4939. var i, l;
  4940. var geometry = node.geometry;
  4941. if ( geometry !== undefined ) {
  4942. if ( geometry.isGeometry ) {
  4943. var vertices = geometry.vertices;
  4944. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  4945. v1.copy( vertices[ i ] );
  4946. v1.applyMatrix4( node.matrixWorld );
  4947. scope.expandByPoint( v1 );
  4948. }
  4949. } else if ( geometry.isBufferGeometry ) {
  4950. var attribute = geometry.attributes.position;
  4951. if ( attribute !== undefined ) {
  4952. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  4953. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  4954. scope.expandByPoint( v1 );
  4955. }
  4956. }
  4957. }
  4958. }
  4959. } );
  4960. return this;
  4961. };
  4962. }(),
  4963. containsPoint: function ( point ) {
  4964. return point.x < this.min.x || point.x > this.max.x ||
  4965. point.y < this.min.y || point.y > this.max.y ||
  4966. point.z < this.min.z || point.z > this.max.z ? false : true;
  4967. },
  4968. containsBox: function ( box ) {
  4969. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  4970. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  4971. this.min.z <= box.min.z && box.max.z <= this.max.z;
  4972. },
  4973. getParameter: function ( point, optionalTarget ) {
  4974. // This can potentially have a divide by zero if the box
  4975. // has a size dimension of 0.
  4976. var result = optionalTarget || new Vector3();
  4977. return result.set(
  4978. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  4979. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  4980. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  4981. );
  4982. },
  4983. intersectsBox: function ( box ) {
  4984. // using 6 splitting planes to rule out intersections.
  4985. return box.max.x < this.min.x || box.min.x > this.max.x ||
  4986. box.max.y < this.min.y || box.min.y > this.max.y ||
  4987. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  4988. },
  4989. intersectsSphere: ( function () {
  4990. var closestPoint = new Vector3();
  4991. return function intersectsSphere( sphere ) {
  4992. // Find the point on the AABB closest to the sphere center.
  4993. this.clampPoint( sphere.center, closestPoint );
  4994. // If that point is inside the sphere, the AABB and sphere intersect.
  4995. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  4996. };
  4997. } )(),
  4998. intersectsPlane: function ( plane ) {
  4999. // We compute the minimum and maximum dot product values. If those values
  5000. // are on the same side (back or front) of the plane, then there is no intersection.
  5001. var min, max;
  5002. if ( plane.normal.x > 0 ) {
  5003. min = plane.normal.x * this.min.x;
  5004. max = plane.normal.x * this.max.x;
  5005. } else {
  5006. min = plane.normal.x * this.max.x;
  5007. max = plane.normal.x * this.min.x;
  5008. }
  5009. if ( plane.normal.y > 0 ) {
  5010. min += plane.normal.y * this.min.y;
  5011. max += plane.normal.y * this.max.y;
  5012. } else {
  5013. min += plane.normal.y * this.max.y;
  5014. max += plane.normal.y * this.min.y;
  5015. }
  5016. if ( plane.normal.z > 0 ) {
  5017. min += plane.normal.z * this.min.z;
  5018. max += plane.normal.z * this.max.z;
  5019. } else {
  5020. min += plane.normal.z * this.max.z;
  5021. max += plane.normal.z * this.min.z;
  5022. }
  5023. return ( min <= plane.constant && max >= plane.constant );
  5024. },
  5025. clampPoint: function ( point, optionalTarget ) {
  5026. var result = optionalTarget || new Vector3();
  5027. return result.copy( point ).clamp( this.min, this.max );
  5028. },
  5029. distanceToPoint: function () {
  5030. var v1 = new Vector3();
  5031. return function distanceToPoint( point ) {
  5032. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  5033. return clampedPoint.sub( point ).length();
  5034. };
  5035. }(),
  5036. getBoundingSphere: function () {
  5037. var v1 = new Vector3();
  5038. return function getBoundingSphere( optionalTarget ) {
  5039. var result = optionalTarget || new Sphere();
  5040. this.getCenter( result.center );
  5041. result.radius = this.getSize( v1 ).length() * 0.5;
  5042. return result;
  5043. };
  5044. }(),
  5045. intersect: function ( box ) {
  5046. this.min.max( box.min );
  5047. this.max.min( box.max );
  5048. // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
  5049. if( this.isEmpty() ) this.makeEmpty();
  5050. return this;
  5051. },
  5052. union: function ( box ) {
  5053. this.min.min( box.min );
  5054. this.max.max( box.max );
  5055. return this;
  5056. },
  5057. applyMatrix4: function () {
  5058. var points = [
  5059. new Vector3(),
  5060. new Vector3(),
  5061. new Vector3(),
  5062. new Vector3(),
  5063. new Vector3(),
  5064. new Vector3(),
  5065. new Vector3(),
  5066. new Vector3()
  5067. ];
  5068. return function applyMatrix4( matrix ) {
  5069. // transform of empty box is an empty box.
  5070. if( this.isEmpty() ) return this;
  5071. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5072. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  5073. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  5074. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  5075. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  5076. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  5077. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  5078. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  5079. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  5080. this.setFromPoints( points );
  5081. return this;
  5082. };
  5083. }(),
  5084. translate: function ( offset ) {
  5085. this.min.add( offset );
  5086. this.max.add( offset );
  5087. return this;
  5088. },
  5089. equals: function ( box ) {
  5090. return box.min.equals( this.min ) && box.max.equals( this.max );
  5091. }
  5092. } );
  5093. /**
  5094. * @author bhouston / http://clara.io
  5095. * @author mrdoob / http://mrdoob.com/
  5096. */
  5097. function Sphere( center, radius ) {
  5098. this.center = ( center !== undefined ) ? center : new Vector3();
  5099. this.radius = ( radius !== undefined ) ? radius : 0;
  5100. }
  5101. Object.assign( Sphere.prototype, {
  5102. set: function ( center, radius ) {
  5103. this.center.copy( center );
  5104. this.radius = radius;
  5105. return this;
  5106. },
  5107. setFromPoints: function () {
  5108. var box = new Box3();
  5109. return function setFromPoints( points, optionalCenter ) {
  5110. var center = this.center;
  5111. if ( optionalCenter !== undefined ) {
  5112. center.copy( optionalCenter );
  5113. } else {
  5114. box.setFromPoints( points ).getCenter( center );
  5115. }
  5116. var maxRadiusSq = 0;
  5117. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5118. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5119. }
  5120. this.radius = Math.sqrt( maxRadiusSq );
  5121. return this;
  5122. };
  5123. }(),
  5124. clone: function () {
  5125. return new this.constructor().copy( this );
  5126. },
  5127. copy: function ( sphere ) {
  5128. this.center.copy( sphere.center );
  5129. this.radius = sphere.radius;
  5130. return this;
  5131. },
  5132. empty: function () {
  5133. return ( this.radius <= 0 );
  5134. },
  5135. containsPoint: function ( point ) {
  5136. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5137. },
  5138. distanceToPoint: function ( point ) {
  5139. return ( point.distanceTo( this.center ) - this.radius );
  5140. },
  5141. intersectsSphere: function ( sphere ) {
  5142. var radiusSum = this.radius + sphere.radius;
  5143. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5144. },
  5145. intersectsBox: function ( box ) {
  5146. return box.intersectsSphere( this );
  5147. },
  5148. intersectsPlane: function ( plane ) {
  5149. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  5150. },
  5151. clampPoint: function ( point, optionalTarget ) {
  5152. var deltaLengthSq = this.center.distanceToSquared( point );
  5153. var result = optionalTarget || new Vector3();
  5154. result.copy( point );
  5155. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5156. result.sub( this.center ).normalize();
  5157. result.multiplyScalar( this.radius ).add( this.center );
  5158. }
  5159. return result;
  5160. },
  5161. getBoundingBox: function ( optionalTarget ) {
  5162. var box = optionalTarget || new Box3();
  5163. box.set( this.center, this.center );
  5164. box.expandByScalar( this.radius );
  5165. return box;
  5166. },
  5167. applyMatrix4: function ( matrix ) {
  5168. this.center.applyMatrix4( matrix );
  5169. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5170. return this;
  5171. },
  5172. translate: function ( offset ) {
  5173. this.center.add( offset );
  5174. return this;
  5175. },
  5176. equals: function ( sphere ) {
  5177. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  5178. }
  5179. } );
  5180. /**
  5181. * @author alteredq / http://alteredqualia.com/
  5182. * @author WestLangley / http://github.com/WestLangley
  5183. * @author bhouston / http://clara.io
  5184. * @author tschw
  5185. */
  5186. function Matrix3() {
  5187. this.elements = [
  5188. 1, 0, 0,
  5189. 0, 1, 0,
  5190. 0, 0, 1
  5191. ];
  5192. if ( arguments.length > 0 ) {
  5193. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  5194. }
  5195. }
  5196. Object.assign( Matrix3.prototype, {
  5197. isMatrix3: true,
  5198. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  5199. var te = this.elements;
  5200. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  5201. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  5202. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  5203. return this;
  5204. },
  5205. identity: function () {
  5206. this.set(
  5207. 1, 0, 0,
  5208. 0, 1, 0,
  5209. 0, 0, 1
  5210. );
  5211. return this;
  5212. },
  5213. clone: function () {
  5214. return new this.constructor().fromArray( this.elements );
  5215. },
  5216. copy: function ( m ) {
  5217. var te = this.elements;
  5218. var me = m.elements;
  5219. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  5220. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  5221. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  5222. return this;
  5223. },
  5224. setFromMatrix4: function ( m ) {
  5225. var me = m.elements;
  5226. this.set(
  5227. me[ 0 ], me[ 4 ], me[ 8 ],
  5228. me[ 1 ], me[ 5 ], me[ 9 ],
  5229. me[ 2 ], me[ 6 ], me[ 10 ]
  5230. );
  5231. return this;
  5232. },
  5233. applyToBufferAttribute: function () {
  5234. var v1 = new Vector3();
  5235. return function applyToBufferAttribute( attribute ) {
  5236. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  5237. v1.x = attribute.getX( i );
  5238. v1.y = attribute.getY( i );
  5239. v1.z = attribute.getZ( i );
  5240. v1.applyMatrix3( this );
  5241. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  5242. }
  5243. return attribute;
  5244. };
  5245. }(),
  5246. multiply: function ( m ) {
  5247. return this.multiplyMatrices( this, m );
  5248. },
  5249. premultiply: function ( m ) {
  5250. return this.multiplyMatrices( m, this );
  5251. },
  5252. multiplyMatrices: function ( a, b ) {
  5253. var ae = a.elements;
  5254. var be = b.elements;
  5255. var te = this.elements;
  5256. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  5257. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  5258. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  5259. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  5260. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  5261. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  5262. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  5263. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  5264. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  5265. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  5266. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  5267. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  5268. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  5269. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  5270. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  5271. return this;
  5272. },
  5273. multiplyScalar: function ( s ) {
  5274. var te = this.elements;
  5275. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  5276. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  5277. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  5278. return this;
  5279. },
  5280. determinant: function () {
  5281. var te = this.elements;
  5282. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  5283. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  5284. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  5285. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  5286. },
  5287. getInverse: function ( matrix, throwOnDegenerate ) {
  5288. if ( matrix && matrix.isMatrix4 ) {
  5289. console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." );
  5290. }
  5291. var me = matrix.elements,
  5292. te = this.elements,
  5293. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  5294. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  5295. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  5296. t11 = n33 * n22 - n32 * n23,
  5297. t12 = n32 * n13 - n33 * n12,
  5298. t13 = n23 * n12 - n22 * n13,
  5299. det = n11 * t11 + n21 * t12 + n31 * t13;
  5300. if ( det === 0 ) {
  5301. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  5302. if ( throwOnDegenerate === true ) {
  5303. throw new Error( msg );
  5304. } else {
  5305. console.warn( msg );
  5306. }
  5307. return this.identity();
  5308. }
  5309. var detInv = 1 / det;
  5310. te[ 0 ] = t11 * detInv;
  5311. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  5312. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  5313. te[ 3 ] = t12 * detInv;
  5314. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  5315. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  5316. te[ 6 ] = t13 * detInv;
  5317. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  5318. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  5319. return this;
  5320. },
  5321. transpose: function () {
  5322. var tmp, m = this.elements;
  5323. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  5324. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  5325. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  5326. return this;
  5327. },
  5328. getNormalMatrix: function ( matrix4 ) {
  5329. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  5330. },
  5331. transposeIntoArray: function ( r ) {
  5332. var m = this.elements;
  5333. r[ 0 ] = m[ 0 ];
  5334. r[ 1 ] = m[ 3 ];
  5335. r[ 2 ] = m[ 6 ];
  5336. r[ 3 ] = m[ 1 ];
  5337. r[ 4 ] = m[ 4 ];
  5338. r[ 5 ] = m[ 7 ];
  5339. r[ 6 ] = m[ 2 ];
  5340. r[ 7 ] = m[ 5 ];
  5341. r[ 8 ] = m[ 8 ];
  5342. return this;
  5343. },
  5344. equals: function ( matrix ) {
  5345. var te = this.elements;
  5346. var me = matrix.elements;
  5347. for ( var i = 0; i < 9; i ++ ) {
  5348. if ( te[ i ] !== me[ i ] ) return false;
  5349. }
  5350. return true;
  5351. },
  5352. fromArray: function ( array, offset ) {
  5353. if ( offset === undefined ) offset = 0;
  5354. for ( var i = 0; i < 9; i ++ ) {
  5355. this.elements[ i ] = array[ i + offset ];
  5356. }
  5357. return this;
  5358. },
  5359. toArray: function ( array, offset ) {
  5360. if ( array === undefined ) array = [];
  5361. if ( offset === undefined ) offset = 0;
  5362. var te = this.elements;
  5363. array[ offset ] = te[ 0 ];
  5364. array[ offset + 1 ] = te[ 1 ];
  5365. array[ offset + 2 ] = te[ 2 ];
  5366. array[ offset + 3 ] = te[ 3 ];
  5367. array[ offset + 4 ] = te[ 4 ];
  5368. array[ offset + 5 ] = te[ 5 ];
  5369. array[ offset + 6 ] = te[ 6 ];
  5370. array[ offset + 7 ] = te[ 7 ];
  5371. array[ offset + 8 ] = te[ 8 ];
  5372. return array;
  5373. }
  5374. } );
  5375. /**
  5376. * @author bhouston / http://clara.io
  5377. */
  5378. function Plane( normal, constant ) {
  5379. // normal is assumed to be normalized
  5380. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  5381. this.constant = ( constant !== undefined ) ? constant : 0;
  5382. }
  5383. Object.assign( Plane.prototype, {
  5384. set: function ( normal, constant ) {
  5385. this.normal.copy( normal );
  5386. this.constant = constant;
  5387. return this;
  5388. },
  5389. setComponents: function ( x, y, z, w ) {
  5390. this.normal.set( x, y, z );
  5391. this.constant = w;
  5392. return this;
  5393. },
  5394. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  5395. this.normal.copy( normal );
  5396. this.constant = - point.dot( this.normal );
  5397. return this;
  5398. },
  5399. setFromCoplanarPoints: function () {
  5400. var v1 = new Vector3();
  5401. var v2 = new Vector3();
  5402. return function setFromCoplanarPoints( a, b, c ) {
  5403. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  5404. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5405. this.setFromNormalAndCoplanarPoint( normal, a );
  5406. return this;
  5407. };
  5408. }(),
  5409. clone: function () {
  5410. return new this.constructor().copy( this );
  5411. },
  5412. copy: function ( plane ) {
  5413. this.normal.copy( plane.normal );
  5414. this.constant = plane.constant;
  5415. return this;
  5416. },
  5417. normalize: function () {
  5418. // Note: will lead to a divide by zero if the plane is invalid.
  5419. var inverseNormalLength = 1.0 / this.normal.length();
  5420. this.normal.multiplyScalar( inverseNormalLength );
  5421. this.constant *= inverseNormalLength;
  5422. return this;
  5423. },
  5424. negate: function () {
  5425. this.constant *= - 1;
  5426. this.normal.negate();
  5427. return this;
  5428. },
  5429. distanceToPoint: function ( point ) {
  5430. return this.normal.dot( point ) + this.constant;
  5431. },
  5432. distanceToSphere: function ( sphere ) {
  5433. return this.distanceToPoint( sphere.center ) - sphere.radius;
  5434. },
  5435. projectPoint: function ( point, optionalTarget ) {
  5436. var result = optionalTarget || new Vector3();
  5437. return result.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  5438. },
  5439. intersectLine: function () {
  5440. var v1 = new Vector3();
  5441. return function intersectLine( line, optionalTarget ) {
  5442. var result = optionalTarget || new Vector3();
  5443. var direction = line.delta( v1 );
  5444. var denominator = this.normal.dot( direction );
  5445. if ( denominator === 0 ) {
  5446. // line is coplanar, return origin
  5447. if ( this.distanceToPoint( line.start ) === 0 ) {
  5448. return result.copy( line.start );
  5449. }
  5450. // Unsure if this is the correct method to handle this case.
  5451. return undefined;
  5452. }
  5453. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  5454. if ( t < 0 || t > 1 ) {
  5455. return undefined;
  5456. }
  5457. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  5458. };
  5459. }(),
  5460. intersectsLine: function ( line ) {
  5461. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5462. var startSign = this.distanceToPoint( line.start );
  5463. var endSign = this.distanceToPoint( line.end );
  5464. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  5465. },
  5466. intersectsBox: function ( box ) {
  5467. return box.intersectsPlane( this );
  5468. },
  5469. intersectsSphere: function ( sphere ) {
  5470. return sphere.intersectsPlane( this );
  5471. },
  5472. coplanarPoint: function ( optionalTarget ) {
  5473. var result = optionalTarget || new Vector3();
  5474. return result.copy( this.normal ).multiplyScalar( - this.constant );
  5475. },
  5476. applyMatrix4: function () {
  5477. var v1 = new Vector3();
  5478. var m1 = new Matrix3();
  5479. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  5480. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  5481. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  5482. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  5483. this.constant = - referencePoint.dot( normal );
  5484. return this;
  5485. };
  5486. }(),
  5487. translate: function ( offset ) {
  5488. this.constant -= offset.dot( this.normal );
  5489. return this;
  5490. },
  5491. equals: function ( plane ) {
  5492. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  5493. }
  5494. } );
  5495. /**
  5496. * @author mrdoob / http://mrdoob.com/
  5497. * @author alteredq / http://alteredqualia.com/
  5498. * @author bhouston / http://clara.io
  5499. */
  5500. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  5501. this.planes = [
  5502. ( p0 !== undefined ) ? p0 : new Plane(),
  5503. ( p1 !== undefined ) ? p1 : new Plane(),
  5504. ( p2 !== undefined ) ? p2 : new Plane(),
  5505. ( p3 !== undefined ) ? p3 : new Plane(),
  5506. ( p4 !== undefined ) ? p4 : new Plane(),
  5507. ( p5 !== undefined ) ? p5 : new Plane()
  5508. ];
  5509. }
  5510. Object.assign( Frustum.prototype, {
  5511. set: function ( p0, p1, p2, p3, p4, p5 ) {
  5512. var planes = this.planes;
  5513. planes[ 0 ].copy( p0 );
  5514. planes[ 1 ].copy( p1 );
  5515. planes[ 2 ].copy( p2 );
  5516. planes[ 3 ].copy( p3 );
  5517. planes[ 4 ].copy( p4 );
  5518. planes[ 5 ].copy( p5 );
  5519. return this;
  5520. },
  5521. clone: function () {
  5522. return new this.constructor().copy( this );
  5523. },
  5524. copy: function ( frustum ) {
  5525. var planes = this.planes;
  5526. for ( var i = 0; i < 6; i ++ ) {
  5527. planes[ i ].copy( frustum.planes[ i ] );
  5528. }
  5529. return this;
  5530. },
  5531. setFromMatrix: function ( m ) {
  5532. var planes = this.planes;
  5533. var me = m.elements;
  5534. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  5535. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  5536. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  5537. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  5538. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  5539. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  5540. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  5541. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  5542. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  5543. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  5544. return this;
  5545. },
  5546. intersectsObject: function () {
  5547. var sphere = new Sphere();
  5548. return function intersectsObject( object ) {
  5549. var geometry = object.geometry;
  5550. if ( geometry.boundingSphere === null )
  5551. geometry.computeBoundingSphere();
  5552. sphere.copy( geometry.boundingSphere )
  5553. .applyMatrix4( object.matrixWorld );
  5554. return this.intersectsSphere( sphere );
  5555. };
  5556. }(),
  5557. intersectsSprite: function () {
  5558. var sphere = new Sphere();
  5559. return function intersectsSprite( sprite ) {
  5560. sphere.center.set( 0, 0, 0 );
  5561. sphere.radius = 0.7071067811865476;
  5562. sphere.applyMatrix4( sprite.matrixWorld );
  5563. return this.intersectsSphere( sphere );
  5564. };
  5565. }(),
  5566. intersectsSphere: function ( sphere ) {
  5567. var planes = this.planes;
  5568. var center = sphere.center;
  5569. var negRadius = - sphere.radius;
  5570. for ( var i = 0; i < 6; i ++ ) {
  5571. var distance = planes[ i ].distanceToPoint( center );
  5572. if ( distance < negRadius ) {
  5573. return false;
  5574. }
  5575. }
  5576. return true;
  5577. },
  5578. intersectsBox: function () {
  5579. var p1 = new Vector3(),
  5580. p2 = new Vector3();
  5581. return function intersectsBox( box ) {
  5582. var planes = this.planes;
  5583. for ( var i = 0; i < 6; i ++ ) {
  5584. var plane = planes[ i ];
  5585. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  5586. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  5587. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  5588. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  5589. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  5590. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  5591. var d1 = plane.distanceToPoint( p1 );
  5592. var d2 = plane.distanceToPoint( p2 );
  5593. // if both outside plane, no intersection
  5594. if ( d1 < 0 && d2 < 0 ) {
  5595. return false;
  5596. }
  5597. }
  5598. return true;
  5599. };
  5600. }(),
  5601. containsPoint: function ( point ) {
  5602. var planes = this.planes;
  5603. for ( var i = 0; i < 6; i ++ ) {
  5604. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  5605. return false;
  5606. }
  5607. }
  5608. return true;
  5609. }
  5610. } );
  5611. /**
  5612. * @author alteredq / http://alteredqualia.com/
  5613. * @author mrdoob / http://mrdoob.com/
  5614. */
  5615. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  5616. var _frustum = new Frustum(),
  5617. _projScreenMatrix = new Matrix4(),
  5618. _shadowMapSize = new Vector2(),
  5619. _maxShadowMapSize = new Vector2( maxTextureSize, maxTextureSize ),
  5620. _lookTarget = new Vector3(),
  5621. _lightPositionWorld = new Vector3(),
  5622. _MorphingFlag = 1,
  5623. _SkinningFlag = 2,
  5624. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  5625. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  5626. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  5627. _materialCache = {};
  5628. var cubeDirections = [
  5629. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  5630. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  5631. ];
  5632. var cubeUps = [
  5633. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  5634. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  5635. ];
  5636. var cube2DViewPorts = [
  5637. new Vector4(), new Vector4(), new Vector4(),
  5638. new Vector4(), new Vector4(), new Vector4()
  5639. ];
  5640. // init
  5641. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  5642. var useMorphing = ( i & _MorphingFlag ) !== 0;
  5643. var useSkinning = ( i & _SkinningFlag ) !== 0;
  5644. var depthMaterial = new MeshDepthMaterial( {
  5645. depthPacking: RGBADepthPacking,
  5646. morphTargets: useMorphing,
  5647. skinning: useSkinning
  5648. } );
  5649. _depthMaterials[ i ] = depthMaterial;
  5650. //
  5651. var distanceMaterial = new MeshDistanceMaterial( {
  5652. morphTargets: useMorphing,
  5653. skinning: useSkinning
  5654. } );
  5655. _distanceMaterials[ i ] = distanceMaterial;
  5656. }
  5657. //
  5658. var scope = this;
  5659. this.enabled = false;
  5660. this.autoUpdate = true;
  5661. this.needsUpdate = false;
  5662. this.type = PCFShadowMap;
  5663. this.renderReverseSided = true;
  5664. this.renderSingleSided = true;
  5665. this.render = function ( lights, scene, camera ) {
  5666. if ( scope.enabled === false ) return;
  5667. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  5668. if ( lights.length === 0 ) return;
  5669. // TODO Clean up (needed in case of contextlost)
  5670. var _gl = _renderer.context;
  5671. var _state = _renderer.state;
  5672. // Set GL state for depth map.
  5673. _state.disable( _gl.BLEND );
  5674. _state.buffers.color.setClear( 1, 1, 1, 1 );
  5675. _state.buffers.depth.setTest( true );
  5676. _state.setScissorTest( false );
  5677. // render depth map
  5678. var faceCount;
  5679. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  5680. var light = lights[ i ];
  5681. var shadow = light.shadow;
  5682. var isPointLight = light && light.isPointLight;
  5683. if ( shadow === undefined ) {
  5684. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  5685. continue;
  5686. }
  5687. var shadowCamera = shadow.camera;
  5688. _shadowMapSize.copy( shadow.mapSize );
  5689. _shadowMapSize.min( _maxShadowMapSize );
  5690. if ( isPointLight ) {
  5691. var vpWidth = _shadowMapSize.x;
  5692. var vpHeight = _shadowMapSize.y;
  5693. // These viewports map a cube-map onto a 2D texture with the
  5694. // following orientation:
  5695. //
  5696. // xzXZ
  5697. // y Y
  5698. //
  5699. // X - Positive x direction
  5700. // x - Negative x direction
  5701. // Y - Positive y direction
  5702. // y - Negative y direction
  5703. // Z - Positive z direction
  5704. // z - Negative z direction
  5705. // positive X
  5706. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  5707. // negative X
  5708. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  5709. // positive Z
  5710. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  5711. // negative Z
  5712. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  5713. // positive Y
  5714. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  5715. // negative Y
  5716. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  5717. _shadowMapSize.x *= 4.0;
  5718. _shadowMapSize.y *= 2.0;
  5719. }
  5720. if ( shadow.map === null ) {
  5721. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  5722. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  5723. shadow.map.texture.name = light.name + ".shadowMap";
  5724. shadowCamera.updateProjectionMatrix();
  5725. }
  5726. if ( shadow.isSpotLightShadow ) {
  5727. shadow.update( light );
  5728. }
  5729. var shadowMap = shadow.map;
  5730. var shadowMatrix = shadow.matrix;
  5731. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  5732. shadowCamera.position.copy( _lightPositionWorld );
  5733. if ( isPointLight ) {
  5734. faceCount = 6;
  5735. // for point lights we set the shadow matrix to be a translation-only matrix
  5736. // equal to inverse of the light's position
  5737. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  5738. } else {
  5739. faceCount = 1;
  5740. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  5741. shadowCamera.lookAt( _lookTarget );
  5742. shadowCamera.updateMatrixWorld();
  5743. // compute shadow matrix
  5744. shadowMatrix.set(
  5745. 0.5, 0.0, 0.0, 0.5,
  5746. 0.0, 0.5, 0.0, 0.5,
  5747. 0.0, 0.0, 0.5, 0.5,
  5748. 0.0, 0.0, 0.0, 1.0
  5749. );
  5750. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  5751. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  5752. }
  5753. _renderer.setRenderTarget( shadowMap );
  5754. _renderer.clear();
  5755. // render shadow map for each cube face (if omni-directional) or
  5756. // run a single pass if not
  5757. for ( var face = 0; face < faceCount; face ++ ) {
  5758. if ( isPointLight ) {
  5759. _lookTarget.copy( shadowCamera.position );
  5760. _lookTarget.add( cubeDirections[ face ] );
  5761. shadowCamera.up.copy( cubeUps[ face ] );
  5762. shadowCamera.lookAt( _lookTarget );
  5763. shadowCamera.updateMatrixWorld();
  5764. var vpDimensions = cube2DViewPorts[ face ];
  5765. _state.viewport( vpDimensions );
  5766. }
  5767. // update camera matrices and frustum
  5768. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  5769. _frustum.setFromMatrix( _projScreenMatrix );
  5770. // set object matrices & frustum culling
  5771. renderObject( scene, camera, shadowCamera, isPointLight );
  5772. }
  5773. }
  5774. scope.needsUpdate = false;
  5775. };
  5776. function getDepthMaterial( object, material, isPointLight, lightPositionWorld, shadowCameraNear, shadowCameraFar ) {
  5777. var geometry = object.geometry;
  5778. var result = null;
  5779. var materialVariants = _depthMaterials;
  5780. var customMaterial = object.customDepthMaterial;
  5781. if ( isPointLight ) {
  5782. materialVariants = _distanceMaterials;
  5783. customMaterial = object.customDistanceMaterial;
  5784. }
  5785. if ( ! customMaterial ) {
  5786. var useMorphing = false;
  5787. if ( material.morphTargets ) {
  5788. if ( geometry && geometry.isBufferGeometry ) {
  5789. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  5790. } else if ( geometry && geometry.isGeometry ) {
  5791. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  5792. }
  5793. }
  5794. if ( object.isSkinnedMesh && material.skinning === false ) {
  5795. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  5796. }
  5797. var useSkinning = object.isSkinnedMesh && material.skinning;
  5798. var variantIndex = 0;
  5799. if ( useMorphing ) variantIndex |= _MorphingFlag;
  5800. if ( useSkinning ) variantIndex |= _SkinningFlag;
  5801. result = materialVariants[ variantIndex ];
  5802. } else {
  5803. result = customMaterial;
  5804. }
  5805. if ( _renderer.localClippingEnabled &&
  5806. material.clipShadows === true &&
  5807. material.clippingPlanes.length !== 0 ) {
  5808. // in this case we need a unique material instance reflecting the
  5809. // appropriate state
  5810. var keyA = result.uuid, keyB = material.uuid;
  5811. var materialsForVariant = _materialCache[ keyA ];
  5812. if ( materialsForVariant === undefined ) {
  5813. materialsForVariant = {};
  5814. _materialCache[ keyA ] = materialsForVariant;
  5815. }
  5816. var cachedMaterial = materialsForVariant[ keyB ];
  5817. if ( cachedMaterial === undefined ) {
  5818. cachedMaterial = result.clone();
  5819. materialsForVariant[ keyB ] = cachedMaterial;
  5820. }
  5821. result = cachedMaterial;
  5822. }
  5823. result.visible = material.visible;
  5824. result.wireframe = material.wireframe;
  5825. var side = material.side;
  5826. if ( scope.renderSingleSided && side == DoubleSide ) {
  5827. side = FrontSide;
  5828. }
  5829. if ( scope.renderReverseSided ) {
  5830. if ( side === FrontSide ) side = BackSide;
  5831. else if ( side === BackSide ) side = FrontSide;
  5832. }
  5833. result.side = side;
  5834. result.clipShadows = material.clipShadows;
  5835. result.clippingPlanes = material.clippingPlanes;
  5836. result.clipIntersection = material.clipIntersection;
  5837. result.wireframeLinewidth = material.wireframeLinewidth;
  5838. result.linewidth = material.linewidth;
  5839. if ( isPointLight && result.isMeshDistanceMaterial ) {
  5840. result.referencePosition.copy( lightPositionWorld );
  5841. result.nearDistance = shadowCameraNear;
  5842. result.farDistance = shadowCameraFar;
  5843. }
  5844. return result;
  5845. }
  5846. function renderObject( object, camera, shadowCamera, isPointLight ) {
  5847. if ( object.visible === false ) return;
  5848. var visible = object.layers.test( camera.layers );
  5849. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  5850. if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  5851. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  5852. var geometry = _objects.update( object );
  5853. var material = object.material;
  5854. if ( Array.isArray( material ) ) {
  5855. var groups = geometry.groups;
  5856. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  5857. var group = groups[ k ];
  5858. var groupMaterial = material[ group.materialIndex ];
  5859. if ( groupMaterial && groupMaterial.visible ) {
  5860. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  5861. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  5862. }
  5863. }
  5864. } else if ( material.visible ) {
  5865. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  5866. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  5867. }
  5868. }
  5869. }
  5870. var children = object.children;
  5871. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5872. renderObject( children[ i ], camera, shadowCamera, isPointLight );
  5873. }
  5874. }
  5875. }
  5876. /**
  5877. * @author mrdoob / http://mrdoob.com/
  5878. */
  5879. function WebGLAttributes( gl ) {
  5880. var buffers = {};
  5881. function createBuffer( attribute, bufferType ) {
  5882. var array = attribute.array;
  5883. var usage = attribute.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  5884. var buffer = gl.createBuffer();
  5885. gl.bindBuffer( bufferType, buffer );
  5886. gl.bufferData( bufferType, array, usage );
  5887. attribute.onUploadCallback();
  5888. var type = gl.FLOAT;
  5889. if ( array instanceof Float32Array ) {
  5890. type = gl.FLOAT;
  5891. } else if ( array instanceof Float64Array ) {
  5892. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  5893. } else if ( array instanceof Uint16Array ) {
  5894. type = gl.UNSIGNED_SHORT;
  5895. } else if ( array instanceof Int16Array ) {
  5896. type = gl.SHORT;
  5897. } else if ( array instanceof Uint32Array ) {
  5898. type = gl.UNSIGNED_INT;
  5899. } else if ( array instanceof Int32Array ) {
  5900. type = gl.INT;
  5901. } else if ( array instanceof Int8Array ) {
  5902. type = gl.BYTE;
  5903. } else if ( array instanceof Uint8Array ) {
  5904. type = gl.UNSIGNED_BYTE;
  5905. }
  5906. return {
  5907. buffer: buffer,
  5908. type: type,
  5909. bytesPerElement: array.BYTES_PER_ELEMENT,
  5910. version: attribute.version
  5911. };
  5912. }
  5913. function updateBuffer( buffer, attribute, bufferType ) {
  5914. var array = attribute.array;
  5915. var updateRange = attribute.updateRange;
  5916. gl.bindBuffer( bufferType, buffer );
  5917. if ( attribute.dynamic === false ) {
  5918. gl.bufferData( bufferType, array, gl.STATIC_DRAW );
  5919. } else if ( updateRange.count === - 1 ) {
  5920. // Not using update ranges
  5921. gl.bufferSubData( bufferType, 0, array );
  5922. } else if ( updateRange.count === 0 ) {
  5923. console.error( 'THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.' );
  5924. } else {
  5925. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  5926. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  5927. updateRange.count = -1; // reset range
  5928. }
  5929. }
  5930. //
  5931. function get( attribute ) {
  5932. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  5933. return buffers[ attribute.uuid ];
  5934. }
  5935. function remove( attribute ) {
  5936. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  5937. var data = buffers[ attribute.uuid ];
  5938. if ( data ) {
  5939. gl.deleteBuffer( data.buffer );
  5940. delete buffers[ attribute.uuid ];
  5941. }
  5942. }
  5943. function update( attribute, bufferType ) {
  5944. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  5945. var data = buffers[ attribute.uuid ];
  5946. if ( data === undefined ) {
  5947. buffers[ attribute.uuid ] = createBuffer( attribute, bufferType );
  5948. } else if ( data.version < attribute.version ) {
  5949. updateBuffer( data.buffer, attribute, bufferType );
  5950. data.version = attribute.version;
  5951. }
  5952. }
  5953. return {
  5954. get: get,
  5955. remove: remove,
  5956. update: update
  5957. };
  5958. }
  5959. /**
  5960. * @author mrdoob / http://mrdoob.com/
  5961. * @author WestLangley / http://github.com/WestLangley
  5962. * @author bhouston / http://clara.io
  5963. */
  5964. function Euler( x, y, z, order ) {
  5965. this._x = x || 0;
  5966. this._y = y || 0;
  5967. this._z = z || 0;
  5968. this._order = order || Euler.DefaultOrder;
  5969. }
  5970. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  5971. Euler.DefaultOrder = 'XYZ';
  5972. Object.defineProperties( Euler.prototype, {
  5973. x: {
  5974. get: function () {
  5975. return this._x;
  5976. },
  5977. set: function ( value ) {
  5978. this._x = value;
  5979. this.onChangeCallback();
  5980. }
  5981. },
  5982. y: {
  5983. get: function () {
  5984. return this._y;
  5985. },
  5986. set: function ( value ) {
  5987. this._y = value;
  5988. this.onChangeCallback();
  5989. }
  5990. },
  5991. z: {
  5992. get: function () {
  5993. return this._z;
  5994. },
  5995. set: function ( value ) {
  5996. this._z = value;
  5997. this.onChangeCallback();
  5998. }
  5999. },
  6000. order: {
  6001. get: function () {
  6002. return this._order;
  6003. },
  6004. set: function ( value ) {
  6005. this._order = value;
  6006. this.onChangeCallback();
  6007. }
  6008. }
  6009. } );
  6010. Object.assign( Euler.prototype, {
  6011. isEuler: true,
  6012. set: function ( x, y, z, order ) {
  6013. this._x = x;
  6014. this._y = y;
  6015. this._z = z;
  6016. this._order = order || this._order;
  6017. this.onChangeCallback();
  6018. return this;
  6019. },
  6020. clone: function () {
  6021. return new this.constructor( this._x, this._y, this._z, this._order );
  6022. },
  6023. copy: function ( euler ) {
  6024. this._x = euler._x;
  6025. this._y = euler._y;
  6026. this._z = euler._z;
  6027. this._order = euler._order;
  6028. this.onChangeCallback();
  6029. return this;
  6030. },
  6031. setFromRotationMatrix: function ( m, order, update ) {
  6032. var clamp = _Math.clamp;
  6033. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6034. var te = m.elements;
  6035. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  6036. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  6037. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6038. order = order || this._order;
  6039. if ( order === 'XYZ' ) {
  6040. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  6041. if ( Math.abs( m13 ) < 0.99999 ) {
  6042. this._x = Math.atan2( - m23, m33 );
  6043. this._z = Math.atan2( - m12, m11 );
  6044. } else {
  6045. this._x = Math.atan2( m32, m22 );
  6046. this._z = 0;
  6047. }
  6048. } else if ( order === 'YXZ' ) {
  6049. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  6050. if ( Math.abs( m23 ) < 0.99999 ) {
  6051. this._y = Math.atan2( m13, m33 );
  6052. this._z = Math.atan2( m21, m22 );
  6053. } else {
  6054. this._y = Math.atan2( - m31, m11 );
  6055. this._z = 0;
  6056. }
  6057. } else if ( order === 'ZXY' ) {
  6058. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  6059. if ( Math.abs( m32 ) < 0.99999 ) {
  6060. this._y = Math.atan2( - m31, m33 );
  6061. this._z = Math.atan2( - m12, m22 );
  6062. } else {
  6063. this._y = 0;
  6064. this._z = Math.atan2( m21, m11 );
  6065. }
  6066. } else if ( order === 'ZYX' ) {
  6067. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  6068. if ( Math.abs( m31 ) < 0.99999 ) {
  6069. this._x = Math.atan2( m32, m33 );
  6070. this._z = Math.atan2( m21, m11 );
  6071. } else {
  6072. this._x = 0;
  6073. this._z = Math.atan2( - m12, m22 );
  6074. }
  6075. } else if ( order === 'YZX' ) {
  6076. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  6077. if ( Math.abs( m21 ) < 0.99999 ) {
  6078. this._x = Math.atan2( - m23, m22 );
  6079. this._y = Math.atan2( - m31, m11 );
  6080. } else {
  6081. this._x = 0;
  6082. this._y = Math.atan2( m13, m33 );
  6083. }
  6084. } else if ( order === 'XZY' ) {
  6085. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  6086. if ( Math.abs( m12 ) < 0.99999 ) {
  6087. this._x = Math.atan2( m32, m22 );
  6088. this._y = Math.atan2( m13, m11 );
  6089. } else {
  6090. this._x = Math.atan2( - m23, m33 );
  6091. this._y = 0;
  6092. }
  6093. } else {
  6094. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  6095. }
  6096. this._order = order;
  6097. if ( update !== false ) this.onChangeCallback();
  6098. return this;
  6099. },
  6100. setFromQuaternion: function () {
  6101. var matrix = new Matrix4();
  6102. return function setFromQuaternion( q, order, update ) {
  6103. matrix.makeRotationFromQuaternion( q );
  6104. return this.setFromRotationMatrix( matrix, order, update );
  6105. };
  6106. }(),
  6107. setFromVector3: function ( v, order ) {
  6108. return this.set( v.x, v.y, v.z, order || this._order );
  6109. },
  6110. reorder: function () {
  6111. // WARNING: this discards revolution information -bhouston
  6112. var q = new Quaternion();
  6113. return function reorder( newOrder ) {
  6114. q.setFromEuler( this );
  6115. return this.setFromQuaternion( q, newOrder );
  6116. };
  6117. }(),
  6118. equals: function ( euler ) {
  6119. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  6120. },
  6121. fromArray: function ( array ) {
  6122. this._x = array[ 0 ];
  6123. this._y = array[ 1 ];
  6124. this._z = array[ 2 ];
  6125. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  6126. this.onChangeCallback();
  6127. return this;
  6128. },
  6129. toArray: function ( array, offset ) {
  6130. if ( array === undefined ) array = [];
  6131. if ( offset === undefined ) offset = 0;
  6132. array[ offset ] = this._x;
  6133. array[ offset + 1 ] = this._y;
  6134. array[ offset + 2 ] = this._z;
  6135. array[ offset + 3 ] = this._order;
  6136. return array;
  6137. },
  6138. toVector3: function ( optionalResult ) {
  6139. if ( optionalResult ) {
  6140. return optionalResult.set( this._x, this._y, this._z );
  6141. } else {
  6142. return new Vector3( this._x, this._y, this._z );
  6143. }
  6144. },
  6145. onChange: function ( callback ) {
  6146. this.onChangeCallback = callback;
  6147. return this;
  6148. },
  6149. onChangeCallback: function () {}
  6150. } );
  6151. /**
  6152. * @author mrdoob / http://mrdoob.com/
  6153. */
  6154. function Layers() {
  6155. this.mask = 1 | 0;
  6156. }
  6157. Object.assign( Layers.prototype, {
  6158. set: function ( channel ) {
  6159. this.mask = 1 << channel | 0;
  6160. },
  6161. enable: function ( channel ) {
  6162. this.mask |= 1 << channel | 0;
  6163. },
  6164. toggle: function ( channel ) {
  6165. this.mask ^= 1 << channel | 0;
  6166. },
  6167. disable: function ( channel ) {
  6168. this.mask &= ~ ( 1 << channel | 0 );
  6169. },
  6170. test: function ( layers ) {
  6171. return ( this.mask & layers.mask ) !== 0;
  6172. }
  6173. } );
  6174. /**
  6175. * @author mrdoob / http://mrdoob.com/
  6176. * @author mikael emtinger / http://gomo.se/
  6177. * @author alteredq / http://alteredqualia.com/
  6178. * @author WestLangley / http://github.com/WestLangley
  6179. * @author elephantatwork / www.elephantatwork.ch
  6180. */
  6181. var object3DId = 0;
  6182. function Object3D() {
  6183. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  6184. this.uuid = _Math.generateUUID();
  6185. this.name = '';
  6186. this.type = 'Object3D';
  6187. this.parent = null;
  6188. this.children = [];
  6189. this.up = Object3D.DefaultUp.clone();
  6190. var position = new Vector3();
  6191. var rotation = new Euler();
  6192. var quaternion = new Quaternion();
  6193. var scale = new Vector3( 1, 1, 1 );
  6194. function onRotationChange() {
  6195. quaternion.setFromEuler( rotation, false );
  6196. }
  6197. function onQuaternionChange() {
  6198. rotation.setFromQuaternion( quaternion, undefined, false );
  6199. }
  6200. rotation.onChange( onRotationChange );
  6201. quaternion.onChange( onQuaternionChange );
  6202. Object.defineProperties( this, {
  6203. position: {
  6204. enumerable: true,
  6205. value: position
  6206. },
  6207. rotation: {
  6208. enumerable: true,
  6209. value: rotation
  6210. },
  6211. quaternion: {
  6212. enumerable: true,
  6213. value: quaternion
  6214. },
  6215. scale: {
  6216. enumerable: true,
  6217. value: scale
  6218. },
  6219. modelViewMatrix: {
  6220. value: new Matrix4()
  6221. },
  6222. normalMatrix: {
  6223. value: new Matrix3()
  6224. }
  6225. } );
  6226. this.matrix = new Matrix4();
  6227. this.matrixWorld = new Matrix4();
  6228. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  6229. this.matrixWorldNeedsUpdate = false;
  6230. this.layers = new Layers();
  6231. this.visible = true;
  6232. this.castShadow = false;
  6233. this.receiveShadow = false;
  6234. this.frustumCulled = true;
  6235. this.renderOrder = 0;
  6236. this.userData = {};
  6237. }
  6238. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  6239. Object3D.DefaultMatrixAutoUpdate = true;
  6240. Object.assign( Object3D.prototype, EventDispatcher.prototype, {
  6241. isObject3D: true,
  6242. onBeforeRender: function () {},
  6243. onAfterRender: function () {},
  6244. applyMatrix: function ( matrix ) {
  6245. this.matrix.multiplyMatrices( matrix, this.matrix );
  6246. this.matrix.decompose( this.position, this.quaternion, this.scale );
  6247. },
  6248. applyQuaternion: function ( q ) {
  6249. this.quaternion.premultiply( q );
  6250. return this;
  6251. },
  6252. setRotationFromAxisAngle: function ( axis, angle ) {
  6253. // assumes axis is normalized
  6254. this.quaternion.setFromAxisAngle( axis, angle );
  6255. },
  6256. setRotationFromEuler: function ( euler ) {
  6257. this.quaternion.setFromEuler( euler, true );
  6258. },
  6259. setRotationFromMatrix: function ( m ) {
  6260. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6261. this.quaternion.setFromRotationMatrix( m );
  6262. },
  6263. setRotationFromQuaternion: function ( q ) {
  6264. // assumes q is normalized
  6265. this.quaternion.copy( q );
  6266. },
  6267. rotateOnAxis: function () {
  6268. // rotate object on axis in object space
  6269. // axis is assumed to be normalized
  6270. var q1 = new Quaternion();
  6271. return function rotateOnAxis( axis, angle ) {
  6272. q1.setFromAxisAngle( axis, angle );
  6273. this.quaternion.multiply( q1 );
  6274. return this;
  6275. };
  6276. }(),
  6277. rotateX: function () {
  6278. var v1 = new Vector3( 1, 0, 0 );
  6279. return function rotateX( angle ) {
  6280. return this.rotateOnAxis( v1, angle );
  6281. };
  6282. }(),
  6283. rotateY: function () {
  6284. var v1 = new Vector3( 0, 1, 0 );
  6285. return function rotateY( angle ) {
  6286. return this.rotateOnAxis( v1, angle );
  6287. };
  6288. }(),
  6289. rotateZ: function () {
  6290. var v1 = new Vector3( 0, 0, 1 );
  6291. return function rotateZ( angle ) {
  6292. return this.rotateOnAxis( v1, angle );
  6293. };
  6294. }(),
  6295. translateOnAxis: function () {
  6296. // translate object by distance along axis in object space
  6297. // axis is assumed to be normalized
  6298. var v1 = new Vector3();
  6299. return function translateOnAxis( axis, distance ) {
  6300. v1.copy( axis ).applyQuaternion( this.quaternion );
  6301. this.position.add( v1.multiplyScalar( distance ) );
  6302. return this;
  6303. };
  6304. }(),
  6305. translateX: function () {
  6306. var v1 = new Vector3( 1, 0, 0 );
  6307. return function translateX( distance ) {
  6308. return this.translateOnAxis( v1, distance );
  6309. };
  6310. }(),
  6311. translateY: function () {
  6312. var v1 = new Vector3( 0, 1, 0 );
  6313. return function translateY( distance ) {
  6314. return this.translateOnAxis( v1, distance );
  6315. };
  6316. }(),
  6317. translateZ: function () {
  6318. var v1 = new Vector3( 0, 0, 1 );
  6319. return function translateZ( distance ) {
  6320. return this.translateOnAxis( v1, distance );
  6321. };
  6322. }(),
  6323. localToWorld: function ( vector ) {
  6324. return vector.applyMatrix4( this.matrixWorld );
  6325. },
  6326. worldToLocal: function () {
  6327. var m1 = new Matrix4();
  6328. return function worldToLocal( vector ) {
  6329. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  6330. };
  6331. }(),
  6332. lookAt: function () {
  6333. // This method does not support objects with rotated and/or translated parent(s)
  6334. var m1 = new Matrix4();
  6335. return function lookAt( vector ) {
  6336. if ( this.isCamera ) {
  6337. m1.lookAt( this.position, vector, this.up );
  6338. } else {
  6339. m1.lookAt( vector, this.position, this.up );
  6340. }
  6341. this.quaternion.setFromRotationMatrix( m1 );
  6342. };
  6343. }(),
  6344. add: function ( object ) {
  6345. if ( arguments.length > 1 ) {
  6346. for ( var i = 0; i < arguments.length; i ++ ) {
  6347. this.add( arguments[ i ] );
  6348. }
  6349. return this;
  6350. }
  6351. if ( object === this ) {
  6352. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  6353. return this;
  6354. }
  6355. if ( ( object && object.isObject3D ) ) {
  6356. if ( object.parent !== null ) {
  6357. object.parent.remove( object );
  6358. }
  6359. object.parent = this;
  6360. object.dispatchEvent( { type: 'added' } );
  6361. this.children.push( object );
  6362. } else {
  6363. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  6364. }
  6365. return this;
  6366. },
  6367. remove: function ( object ) {
  6368. if ( arguments.length > 1 ) {
  6369. for ( var i = 0; i < arguments.length; i ++ ) {
  6370. this.remove( arguments[ i ] );
  6371. }
  6372. return this;
  6373. }
  6374. var index = this.children.indexOf( object );
  6375. if ( index !== - 1 ) {
  6376. object.parent = null;
  6377. object.dispatchEvent( { type: 'removed' } );
  6378. this.children.splice( index, 1 );
  6379. }
  6380. return this;
  6381. },
  6382. getObjectById: function ( id ) {
  6383. return this.getObjectByProperty( 'id', id );
  6384. },
  6385. getObjectByName: function ( name ) {
  6386. return this.getObjectByProperty( 'name', name );
  6387. },
  6388. getObjectByProperty: function ( name, value ) {
  6389. if ( this[ name ] === value ) return this;
  6390. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6391. var child = this.children[ i ];
  6392. var object = child.getObjectByProperty( name, value );
  6393. if ( object !== undefined ) {
  6394. return object;
  6395. }
  6396. }
  6397. return undefined;
  6398. },
  6399. getWorldPosition: function ( optionalTarget ) {
  6400. var result = optionalTarget || new Vector3();
  6401. this.updateMatrixWorld( true );
  6402. return result.setFromMatrixPosition( this.matrixWorld );
  6403. },
  6404. getWorldQuaternion: function () {
  6405. var position = new Vector3();
  6406. var scale = new Vector3();
  6407. return function getWorldQuaternion( optionalTarget ) {
  6408. var result = optionalTarget || new Quaternion();
  6409. this.updateMatrixWorld( true );
  6410. this.matrixWorld.decompose( position, result, scale );
  6411. return result;
  6412. };
  6413. }(),
  6414. getWorldRotation: function () {
  6415. var quaternion = new Quaternion();
  6416. return function getWorldRotation( optionalTarget ) {
  6417. var result = optionalTarget || new Euler();
  6418. this.getWorldQuaternion( quaternion );
  6419. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  6420. };
  6421. }(),
  6422. getWorldScale: function () {
  6423. var position = new Vector3();
  6424. var quaternion = new Quaternion();
  6425. return function getWorldScale( optionalTarget ) {
  6426. var result = optionalTarget || new Vector3();
  6427. this.updateMatrixWorld( true );
  6428. this.matrixWorld.decompose( position, quaternion, result );
  6429. return result;
  6430. };
  6431. }(),
  6432. getWorldDirection: function () {
  6433. var quaternion = new Quaternion();
  6434. return function getWorldDirection( optionalTarget ) {
  6435. var result = optionalTarget || new Vector3();
  6436. this.getWorldQuaternion( quaternion );
  6437. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  6438. };
  6439. }(),
  6440. raycast: function () {},
  6441. traverse: function ( callback ) {
  6442. callback( this );
  6443. var children = this.children;
  6444. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6445. children[ i ].traverse( callback );
  6446. }
  6447. },
  6448. traverseVisible: function ( callback ) {
  6449. if ( this.visible === false ) return;
  6450. callback( this );
  6451. var children = this.children;
  6452. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6453. children[ i ].traverseVisible( callback );
  6454. }
  6455. },
  6456. traverseAncestors: function ( callback ) {
  6457. var parent = this.parent;
  6458. if ( parent !== null ) {
  6459. callback( parent );
  6460. parent.traverseAncestors( callback );
  6461. }
  6462. },
  6463. updateMatrix: function () {
  6464. this.matrix.compose( this.position, this.quaternion, this.scale );
  6465. this.matrixWorldNeedsUpdate = true;
  6466. },
  6467. updateMatrixWorld: function ( force ) {
  6468. if ( this.matrixAutoUpdate ) this.updateMatrix();
  6469. if ( this.matrixWorldNeedsUpdate || force ) {
  6470. if ( this.parent === null ) {
  6471. this.matrixWorld.copy( this.matrix );
  6472. } else {
  6473. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  6474. }
  6475. this.matrixWorldNeedsUpdate = false;
  6476. force = true;
  6477. }
  6478. // update children
  6479. var children = this.children;
  6480. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6481. children[ i ].updateMatrixWorld( force );
  6482. }
  6483. },
  6484. toJSON: function ( meta ) {
  6485. // meta is '' when called from JSON.stringify
  6486. var isRootObject = ( meta === undefined || meta === '' );
  6487. var output = {};
  6488. // meta is a hash used to collect geometries, materials.
  6489. // not providing it implies that this is the root object
  6490. // being serialized.
  6491. if ( isRootObject ) {
  6492. // initialize meta obj
  6493. meta = {
  6494. geometries: {},
  6495. materials: {},
  6496. textures: {},
  6497. images: {}
  6498. };
  6499. output.metadata = {
  6500. version: 4.5,
  6501. type: 'Object',
  6502. generator: 'Object3D.toJSON'
  6503. };
  6504. }
  6505. // standard Object3D serialization
  6506. var object = {};
  6507. object.uuid = this.uuid;
  6508. object.type = this.type;
  6509. if ( this.name !== '' ) object.name = this.name;
  6510. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  6511. if ( this.castShadow === true ) object.castShadow = true;
  6512. if ( this.receiveShadow === true ) object.receiveShadow = true;
  6513. if ( this.visible === false ) object.visible = false;
  6514. object.matrix = this.matrix.toArray();
  6515. //
  6516. function serialize( library, element ) {
  6517. if ( library[ element.uuid ] === undefined ) {
  6518. library[ element.uuid ] = element.toJSON( meta );
  6519. }
  6520. return element.uuid;
  6521. }
  6522. if ( this.geometry !== undefined ) {
  6523. object.geometry = serialize( meta.geometries, this.geometry );
  6524. }
  6525. if ( this.material !== undefined ) {
  6526. if ( Array.isArray( this.material ) ) {
  6527. var uuids = [];
  6528. for ( var i = 0, l = this.material.length; i < l; i ++ ) {
  6529. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  6530. }
  6531. object.material = uuids;
  6532. } else {
  6533. object.material = serialize( meta.materials, this.material );
  6534. }
  6535. }
  6536. //
  6537. if ( this.children.length > 0 ) {
  6538. object.children = [];
  6539. for ( var i = 0; i < this.children.length; i ++ ) {
  6540. object.children.push( this.children[ i ].toJSON( meta ).object );
  6541. }
  6542. }
  6543. if ( isRootObject ) {
  6544. var geometries = extractFromCache( meta.geometries );
  6545. var materials = extractFromCache( meta.materials );
  6546. var textures = extractFromCache( meta.textures );
  6547. var images = extractFromCache( meta.images );
  6548. if ( geometries.length > 0 ) output.geometries = geometries;
  6549. if ( materials.length > 0 ) output.materials = materials;
  6550. if ( textures.length > 0 ) output.textures = textures;
  6551. if ( images.length > 0 ) output.images = images;
  6552. }
  6553. output.object = object;
  6554. return output;
  6555. // extract data from the cache hash
  6556. // remove metadata on each item
  6557. // and return as array
  6558. function extractFromCache( cache ) {
  6559. var values = [];
  6560. for ( var key in cache ) {
  6561. var data = cache[ key ];
  6562. delete data.metadata;
  6563. values.push( data );
  6564. }
  6565. return values;
  6566. }
  6567. },
  6568. clone: function ( recursive ) {
  6569. return new this.constructor().copy( this, recursive );
  6570. },
  6571. copy: function ( source, recursive ) {
  6572. if ( recursive === undefined ) recursive = true;
  6573. this.name = source.name;
  6574. this.up.copy( source.up );
  6575. this.position.copy( source.position );
  6576. this.quaternion.copy( source.quaternion );
  6577. this.scale.copy( source.scale );
  6578. this.matrix.copy( source.matrix );
  6579. this.matrixWorld.copy( source.matrixWorld );
  6580. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6581. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  6582. this.layers.mask = source.layers.mask;
  6583. this.visible = source.visible;
  6584. this.castShadow = source.castShadow;
  6585. this.receiveShadow = source.receiveShadow;
  6586. this.frustumCulled = source.frustumCulled;
  6587. this.renderOrder = source.renderOrder;
  6588. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6589. if ( recursive === true ) {
  6590. for ( var i = 0; i < source.children.length; i ++ ) {
  6591. var child = source.children[ i ];
  6592. this.add( child.clone() );
  6593. }
  6594. }
  6595. return this;
  6596. }
  6597. } );
  6598. /**
  6599. * @author mrdoob / http://mrdoob.com/
  6600. * @author mikael emtinger / http://gomo.se/
  6601. * @author WestLangley / http://github.com/WestLangley
  6602. */
  6603. function Camera() {
  6604. Object3D.call( this );
  6605. this.type = 'Camera';
  6606. this.matrixWorldInverse = new Matrix4();
  6607. this.projectionMatrix = new Matrix4();
  6608. }
  6609. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  6610. constructor: Camera,
  6611. isCamera: true,
  6612. copy: function ( source, recursive ) {
  6613. Object3D.prototype.copy.call( this, source, recursive );
  6614. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6615. this.projectionMatrix.copy( source.projectionMatrix );
  6616. return this;
  6617. },
  6618. getWorldDirection: function () {
  6619. var quaternion = new Quaternion();
  6620. return function getWorldDirection( optionalTarget ) {
  6621. var result = optionalTarget || new Vector3();
  6622. this.getWorldQuaternion( quaternion );
  6623. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  6624. };
  6625. }(),
  6626. updateMatrixWorld: function ( force ) {
  6627. Object3D.prototype.updateMatrixWorld.call( this, force );
  6628. this.matrixWorldInverse.getInverse( this.matrixWorld );
  6629. },
  6630. clone: function () {
  6631. return new this.constructor().copy( this );
  6632. }
  6633. } );
  6634. /**
  6635. * @author alteredq / http://alteredqualia.com/
  6636. * @author arose / http://github.com/arose
  6637. */
  6638. function OrthographicCamera( left, right, top, bottom, near, far ) {
  6639. Camera.call( this );
  6640. this.type = 'OrthographicCamera';
  6641. this.zoom = 1;
  6642. this.view = null;
  6643. this.left = left;
  6644. this.right = right;
  6645. this.top = top;
  6646. this.bottom = bottom;
  6647. this.near = ( near !== undefined ) ? near : 0.1;
  6648. this.far = ( far !== undefined ) ? far : 2000;
  6649. this.updateProjectionMatrix();
  6650. }
  6651. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  6652. constructor: OrthographicCamera,
  6653. isOrthographicCamera: true,
  6654. copy: function ( source, recursive ) {
  6655. Camera.prototype.copy.call( this, source, recursive );
  6656. this.left = source.left;
  6657. this.right = source.right;
  6658. this.top = source.top;
  6659. this.bottom = source.bottom;
  6660. this.near = source.near;
  6661. this.far = source.far;
  6662. this.zoom = source.zoom;
  6663. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6664. return this;
  6665. },
  6666. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  6667. this.view = {
  6668. fullWidth: fullWidth,
  6669. fullHeight: fullHeight,
  6670. offsetX: x,
  6671. offsetY: y,
  6672. width: width,
  6673. height: height
  6674. };
  6675. this.updateProjectionMatrix();
  6676. },
  6677. clearViewOffset: function() {
  6678. this.view = null;
  6679. this.updateProjectionMatrix();
  6680. },
  6681. updateProjectionMatrix: function () {
  6682. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  6683. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  6684. var cx = ( this.right + this.left ) / 2;
  6685. var cy = ( this.top + this.bottom ) / 2;
  6686. var left = cx - dx;
  6687. var right = cx + dx;
  6688. var top = cy + dy;
  6689. var bottom = cy - dy;
  6690. if ( this.view !== null ) {
  6691. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  6692. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  6693. var scaleW = ( this.right - this.left ) / this.view.width;
  6694. var scaleH = ( this.top - this.bottom ) / this.view.height;
  6695. left += scaleW * ( this.view.offsetX / zoomW );
  6696. right = left + scaleW * ( this.view.width / zoomW );
  6697. top -= scaleH * ( this.view.offsetY / zoomH );
  6698. bottom = top - scaleH * ( this.view.height / zoomH );
  6699. }
  6700. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  6701. },
  6702. toJSON: function ( meta ) {
  6703. var data = Object3D.prototype.toJSON.call( this, meta );
  6704. data.object.zoom = this.zoom;
  6705. data.object.left = this.left;
  6706. data.object.right = this.right;
  6707. data.object.top = this.top;
  6708. data.object.bottom = this.bottom;
  6709. data.object.near = this.near;
  6710. data.object.far = this.far;
  6711. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  6712. return data;
  6713. }
  6714. } );
  6715. /**
  6716. * @author mrdoob / http://mrdoob.com/
  6717. * @author greggman / http://games.greggman.com/
  6718. * @author zz85 / http://www.lab4games.net/zz85/blog
  6719. * @author tschw
  6720. */
  6721. function PerspectiveCamera( fov, aspect, near, far ) {
  6722. Camera.call( this );
  6723. this.type = 'PerspectiveCamera';
  6724. this.fov = fov !== undefined ? fov : 50;
  6725. this.zoom = 1;
  6726. this.near = near !== undefined ? near : 0.1;
  6727. this.far = far !== undefined ? far : 2000;
  6728. this.focus = 10;
  6729. this.aspect = aspect !== undefined ? aspect : 1;
  6730. this.view = null;
  6731. this.filmGauge = 35; // width of the film (default in millimeters)
  6732. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  6733. this.updateProjectionMatrix();
  6734. }
  6735. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  6736. constructor: PerspectiveCamera,
  6737. isPerspectiveCamera: true,
  6738. copy: function ( source, recursive ) {
  6739. Camera.prototype.copy.call( this, source, recursive );
  6740. this.fov = source.fov;
  6741. this.zoom = source.zoom;
  6742. this.near = source.near;
  6743. this.far = source.far;
  6744. this.focus = source.focus;
  6745. this.aspect = source.aspect;
  6746. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6747. this.filmGauge = source.filmGauge;
  6748. this.filmOffset = source.filmOffset;
  6749. return this;
  6750. },
  6751. /**
  6752. * Sets the FOV by focal length in respect to the current .filmGauge.
  6753. *
  6754. * The default film gauge is 35, so that the focal length can be specified for
  6755. * a 35mm (full frame) camera.
  6756. *
  6757. * Values for focal length and film gauge must have the same unit.
  6758. */
  6759. setFocalLength: function ( focalLength ) {
  6760. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  6761. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  6762. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  6763. this.updateProjectionMatrix();
  6764. },
  6765. /**
  6766. * Calculates the focal length from the current .fov and .filmGauge.
  6767. */
  6768. getFocalLength: function () {
  6769. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  6770. return 0.5 * this.getFilmHeight() / vExtentSlope;
  6771. },
  6772. getEffectiveFOV: function () {
  6773. return _Math.RAD2DEG * 2 * Math.atan(
  6774. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  6775. },
  6776. getFilmWidth: function () {
  6777. // film not completely covered in portrait format (aspect < 1)
  6778. return this.filmGauge * Math.min( this.aspect, 1 );
  6779. },
  6780. getFilmHeight: function () {
  6781. // film not completely covered in landscape format (aspect > 1)
  6782. return this.filmGauge / Math.max( this.aspect, 1 );
  6783. },
  6784. /**
  6785. * Sets an offset in a larger frustum. This is useful for multi-window or
  6786. * multi-monitor/multi-machine setups.
  6787. *
  6788. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6789. * the monitors are in grid like this
  6790. *
  6791. * +---+---+---+
  6792. * | A | B | C |
  6793. * +---+---+---+
  6794. * | D | E | F |
  6795. * +---+---+---+
  6796. *
  6797. * then for each monitor you would call it like this
  6798. *
  6799. * var w = 1920;
  6800. * var h = 1080;
  6801. * var fullWidth = w * 3;
  6802. * var fullHeight = h * 2;
  6803. *
  6804. * --A--
  6805. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6806. * --B--
  6807. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6808. * --C--
  6809. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6810. * --D--
  6811. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6812. * --E--
  6813. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6814. * --F--
  6815. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6816. *
  6817. * Note there is no reason monitors have to be the same size or in a grid.
  6818. */
  6819. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  6820. this.aspect = fullWidth / fullHeight;
  6821. this.view = {
  6822. fullWidth: fullWidth,
  6823. fullHeight: fullHeight,
  6824. offsetX: x,
  6825. offsetY: y,
  6826. width: width,
  6827. height: height
  6828. };
  6829. this.updateProjectionMatrix();
  6830. },
  6831. clearViewOffset: function () {
  6832. this.view = null;
  6833. this.updateProjectionMatrix();
  6834. },
  6835. updateProjectionMatrix: function () {
  6836. var near = this.near,
  6837. top = near * Math.tan(
  6838. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  6839. height = 2 * top,
  6840. width = this.aspect * height,
  6841. left = - 0.5 * width,
  6842. view = this.view;
  6843. if ( view !== null ) {
  6844. var fullWidth = view.fullWidth,
  6845. fullHeight = view.fullHeight;
  6846. left += view.offsetX * width / fullWidth;
  6847. top -= view.offsetY * height / fullHeight;
  6848. width *= view.width / fullWidth;
  6849. height *= view.height / fullHeight;
  6850. }
  6851. var skew = this.filmOffset;
  6852. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  6853. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  6854. },
  6855. toJSON: function ( meta ) {
  6856. var data = Object3D.prototype.toJSON.call( this, meta );
  6857. data.object.fov = this.fov;
  6858. data.object.zoom = this.zoom;
  6859. data.object.near = this.near;
  6860. data.object.far = this.far;
  6861. data.object.focus = this.focus;
  6862. data.object.aspect = this.aspect;
  6863. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  6864. data.object.filmGauge = this.filmGauge;
  6865. data.object.filmOffset = this.filmOffset;
  6866. return data;
  6867. }
  6868. } );
  6869. /**
  6870. * @author mrdoob / http://mrdoob.com/
  6871. * @author alteredq / http://alteredqualia.com/
  6872. */
  6873. function Face3( a, b, c, normal, color, materialIndex ) {
  6874. this.a = a;
  6875. this.b = b;
  6876. this.c = c;
  6877. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  6878. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  6879. this.color = ( color && color.isColor ) ? color : new Color();
  6880. this.vertexColors = Array.isArray( color ) ? color : [];
  6881. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6882. }
  6883. Object.assign( Face3.prototype, {
  6884. clone: function () {
  6885. return new this.constructor().copy( this );
  6886. },
  6887. copy: function ( source ) {
  6888. this.a = source.a;
  6889. this.b = source.b;
  6890. this.c = source.c;
  6891. this.normal.copy( source.normal );
  6892. this.color.copy( source.color );
  6893. this.materialIndex = source.materialIndex;
  6894. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  6895. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  6896. }
  6897. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  6898. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  6899. }
  6900. return this;
  6901. }
  6902. } );
  6903. /**
  6904. * @author mrdoob / http://mrdoob.com/
  6905. * @author kile / http://kile.stravaganza.org/
  6906. * @author alteredq / http://alteredqualia.com/
  6907. * @author mikael emtinger / http://gomo.se/
  6908. * @author zz85 / http://www.lab4games.net/zz85/blog
  6909. * @author bhouston / http://clara.io
  6910. */
  6911. var count = 0;
  6912. function GeometryIdCount() { return count++; }
  6913. function Geometry() {
  6914. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  6915. this.uuid = _Math.generateUUID();
  6916. this.name = '';
  6917. this.type = 'Geometry';
  6918. this.vertices = [];
  6919. this.colors = [];
  6920. this.faces = [];
  6921. this.faceVertexUvs = [[]];
  6922. this.morphTargets = [];
  6923. this.morphNormals = [];
  6924. this.skinWeights = [];
  6925. this.skinIndices = [];
  6926. this.lineDistances = [];
  6927. this.boundingBox = null;
  6928. this.boundingSphere = null;
  6929. // update flags
  6930. this.elementsNeedUpdate = false;
  6931. this.verticesNeedUpdate = false;
  6932. this.uvsNeedUpdate = false;
  6933. this.normalsNeedUpdate = false;
  6934. this.colorsNeedUpdate = false;
  6935. this.lineDistancesNeedUpdate = false;
  6936. this.groupsNeedUpdate = false;
  6937. }
  6938. Object.assign( Geometry.prototype, EventDispatcher.prototype, {
  6939. isGeometry: true,
  6940. applyMatrix: function ( matrix ) {
  6941. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6942. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  6943. var vertex = this.vertices[ i ];
  6944. vertex.applyMatrix4( matrix );
  6945. }
  6946. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  6947. var face = this.faces[ i ];
  6948. face.normal.applyMatrix3( normalMatrix ).normalize();
  6949. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  6950. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  6951. }
  6952. }
  6953. if ( this.boundingBox !== null ) {
  6954. this.computeBoundingBox();
  6955. }
  6956. if ( this.boundingSphere !== null ) {
  6957. this.computeBoundingSphere();
  6958. }
  6959. this.verticesNeedUpdate = true;
  6960. this.normalsNeedUpdate = true;
  6961. return this;
  6962. },
  6963. rotateX: function () {
  6964. // rotate geometry around world x-axis
  6965. var m1 = new Matrix4();
  6966. return function rotateX( angle ) {
  6967. m1.makeRotationX( angle );
  6968. this.applyMatrix( m1 );
  6969. return this;
  6970. };
  6971. }(),
  6972. rotateY: function () {
  6973. // rotate geometry around world y-axis
  6974. var m1 = new Matrix4();
  6975. return function rotateY( angle ) {
  6976. m1.makeRotationY( angle );
  6977. this.applyMatrix( m1 );
  6978. return this;
  6979. };
  6980. }(),
  6981. rotateZ: function () {
  6982. // rotate geometry around world z-axis
  6983. var m1 = new Matrix4();
  6984. return function rotateZ( angle ) {
  6985. m1.makeRotationZ( angle );
  6986. this.applyMatrix( m1 );
  6987. return this;
  6988. };
  6989. }(),
  6990. translate: function () {
  6991. // translate geometry
  6992. var m1 = new Matrix4();
  6993. return function translate( x, y, z ) {
  6994. m1.makeTranslation( x, y, z );
  6995. this.applyMatrix( m1 );
  6996. return this;
  6997. };
  6998. }(),
  6999. scale: function () {
  7000. // scale geometry
  7001. var m1 = new Matrix4();
  7002. return function scale( x, y, z ) {
  7003. m1.makeScale( x, y, z );
  7004. this.applyMatrix( m1 );
  7005. return this;
  7006. };
  7007. }(),
  7008. lookAt: function () {
  7009. var obj = new Object3D();
  7010. return function lookAt( vector ) {
  7011. obj.lookAt( vector );
  7012. obj.updateMatrix();
  7013. this.applyMatrix( obj.matrix );
  7014. };
  7015. }(),
  7016. fromBufferGeometry: function ( geometry ) {
  7017. var scope = this;
  7018. var indices = geometry.index !== null ? geometry.index.array : undefined;
  7019. var attributes = geometry.attributes;
  7020. var positions = attributes.position.array;
  7021. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  7022. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  7023. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  7024. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  7025. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  7026. var tempNormals = [];
  7027. var tempUVs = [];
  7028. var tempUVs2 = [];
  7029. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  7030. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  7031. if ( normals !== undefined ) {
  7032. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  7033. }
  7034. if ( colors !== undefined ) {
  7035. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  7036. }
  7037. if ( uvs !== undefined ) {
  7038. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  7039. }
  7040. if ( uvs2 !== undefined ) {
  7041. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  7042. }
  7043. }
  7044. function addFace( a, b, c, materialIndex ) {
  7045. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  7046. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  7047. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  7048. scope.faces.push( face );
  7049. if ( uvs !== undefined ) {
  7050. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  7051. }
  7052. if ( uvs2 !== undefined ) {
  7053. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  7054. }
  7055. }
  7056. var groups = geometry.groups;
  7057. if ( groups.length > 0 ) {
  7058. for ( var i = 0; i < groups.length; i ++ ) {
  7059. var group = groups[ i ];
  7060. var start = group.start;
  7061. var count = group.count;
  7062. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  7063. if ( indices !== undefined ) {
  7064. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  7065. } else {
  7066. addFace( j, j + 1, j + 2, group.materialIndex );
  7067. }
  7068. }
  7069. }
  7070. } else {
  7071. if ( indices !== undefined ) {
  7072. for ( var i = 0; i < indices.length; i += 3 ) {
  7073. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  7074. }
  7075. } else {
  7076. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  7077. addFace( i, i + 1, i + 2 );
  7078. }
  7079. }
  7080. }
  7081. this.computeFaceNormals();
  7082. if ( geometry.boundingBox !== null ) {
  7083. this.boundingBox = geometry.boundingBox.clone();
  7084. }
  7085. if ( geometry.boundingSphere !== null ) {
  7086. this.boundingSphere = geometry.boundingSphere.clone();
  7087. }
  7088. return this;
  7089. },
  7090. center: function () {
  7091. this.computeBoundingBox();
  7092. var offset = this.boundingBox.getCenter().negate();
  7093. this.translate( offset.x, offset.y, offset.z );
  7094. return offset;
  7095. },
  7096. normalize: function () {
  7097. this.computeBoundingSphere();
  7098. var center = this.boundingSphere.center;
  7099. var radius = this.boundingSphere.radius;
  7100. var s = radius === 0 ? 1 : 1.0 / radius;
  7101. var matrix = new Matrix4();
  7102. matrix.set(
  7103. s, 0, 0, - s * center.x,
  7104. 0, s, 0, - s * center.y,
  7105. 0, 0, s, - s * center.z,
  7106. 0, 0, 0, 1
  7107. );
  7108. this.applyMatrix( matrix );
  7109. return this;
  7110. },
  7111. computeFaceNormals: function () {
  7112. var cb = new Vector3(), ab = new Vector3();
  7113. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7114. var face = this.faces[ f ];
  7115. var vA = this.vertices[ face.a ];
  7116. var vB = this.vertices[ face.b ];
  7117. var vC = this.vertices[ face.c ];
  7118. cb.subVectors( vC, vB );
  7119. ab.subVectors( vA, vB );
  7120. cb.cross( ab );
  7121. cb.normalize();
  7122. face.normal.copy( cb );
  7123. }
  7124. },
  7125. computeVertexNormals: function ( areaWeighted ) {
  7126. if ( areaWeighted === undefined ) areaWeighted = true;
  7127. var v, vl, f, fl, face, vertices;
  7128. vertices = new Array( this.vertices.length );
  7129. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7130. vertices[ v ] = new Vector3();
  7131. }
  7132. if ( areaWeighted ) {
  7133. // vertex normals weighted by triangle areas
  7134. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7135. var vA, vB, vC;
  7136. var cb = new Vector3(), ab = new Vector3();
  7137. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7138. face = this.faces[ f ];
  7139. vA = this.vertices[ face.a ];
  7140. vB = this.vertices[ face.b ];
  7141. vC = this.vertices[ face.c ];
  7142. cb.subVectors( vC, vB );
  7143. ab.subVectors( vA, vB );
  7144. cb.cross( ab );
  7145. vertices[ face.a ].add( cb );
  7146. vertices[ face.b ].add( cb );
  7147. vertices[ face.c ].add( cb );
  7148. }
  7149. } else {
  7150. this.computeFaceNormals();
  7151. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7152. face = this.faces[ f ];
  7153. vertices[ face.a ].add( face.normal );
  7154. vertices[ face.b ].add( face.normal );
  7155. vertices[ face.c ].add( face.normal );
  7156. }
  7157. }
  7158. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7159. vertices[ v ].normalize();
  7160. }
  7161. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7162. face = this.faces[ f ];
  7163. var vertexNormals = face.vertexNormals;
  7164. if ( vertexNormals.length === 3 ) {
  7165. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  7166. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  7167. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  7168. } else {
  7169. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  7170. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  7171. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  7172. }
  7173. }
  7174. if ( this.faces.length > 0 ) {
  7175. this.normalsNeedUpdate = true;
  7176. }
  7177. },
  7178. computeFlatVertexNormals: function () {
  7179. var f, fl, face;
  7180. this.computeFaceNormals();
  7181. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7182. face = this.faces[ f ];
  7183. var vertexNormals = face.vertexNormals;
  7184. if ( vertexNormals.length === 3 ) {
  7185. vertexNormals[ 0 ].copy( face.normal );
  7186. vertexNormals[ 1 ].copy( face.normal );
  7187. vertexNormals[ 2 ].copy( face.normal );
  7188. } else {
  7189. vertexNormals[ 0 ] = face.normal.clone();
  7190. vertexNormals[ 1 ] = face.normal.clone();
  7191. vertexNormals[ 2 ] = face.normal.clone();
  7192. }
  7193. }
  7194. if ( this.faces.length > 0 ) {
  7195. this.normalsNeedUpdate = true;
  7196. }
  7197. },
  7198. computeMorphNormals: function () {
  7199. var i, il, f, fl, face;
  7200. // save original normals
  7201. // - create temp variables on first access
  7202. // otherwise just copy (for faster repeated calls)
  7203. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7204. face = this.faces[ f ];
  7205. if ( ! face.__originalFaceNormal ) {
  7206. face.__originalFaceNormal = face.normal.clone();
  7207. } else {
  7208. face.__originalFaceNormal.copy( face.normal );
  7209. }
  7210. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  7211. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  7212. if ( ! face.__originalVertexNormals[ i ] ) {
  7213. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  7214. } else {
  7215. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  7216. }
  7217. }
  7218. }
  7219. // use temp geometry to compute face and vertex normals for each morph
  7220. var tmpGeo = new Geometry();
  7221. tmpGeo.faces = this.faces;
  7222. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  7223. // create on first access
  7224. if ( ! this.morphNormals[ i ] ) {
  7225. this.morphNormals[ i ] = {};
  7226. this.morphNormals[ i ].faceNormals = [];
  7227. this.morphNormals[ i ].vertexNormals = [];
  7228. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  7229. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  7230. var faceNormal, vertexNormals;
  7231. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7232. faceNormal = new Vector3();
  7233. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  7234. dstNormalsFace.push( faceNormal );
  7235. dstNormalsVertex.push( vertexNormals );
  7236. }
  7237. }
  7238. var morphNormals = this.morphNormals[ i ];
  7239. // set vertices to morph target
  7240. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  7241. // compute morph normals
  7242. tmpGeo.computeFaceNormals();
  7243. tmpGeo.computeVertexNormals();
  7244. // store morph normals
  7245. var faceNormal, vertexNormals;
  7246. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7247. face = this.faces[ f ];
  7248. faceNormal = morphNormals.faceNormals[ f ];
  7249. vertexNormals = morphNormals.vertexNormals[ f ];
  7250. faceNormal.copy( face.normal );
  7251. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  7252. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  7253. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  7254. }
  7255. }
  7256. // restore original normals
  7257. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7258. face = this.faces[ f ];
  7259. face.normal = face.__originalFaceNormal;
  7260. face.vertexNormals = face.__originalVertexNormals;
  7261. }
  7262. },
  7263. computeLineDistances: function () {
  7264. var d = 0;
  7265. var vertices = this.vertices;
  7266. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  7267. if ( i > 0 ) {
  7268. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  7269. }
  7270. this.lineDistances[ i ] = d;
  7271. }
  7272. },
  7273. computeBoundingBox: function () {
  7274. if ( this.boundingBox === null ) {
  7275. this.boundingBox = new Box3();
  7276. }
  7277. this.boundingBox.setFromPoints( this.vertices );
  7278. },
  7279. computeBoundingSphere: function () {
  7280. if ( this.boundingSphere === null ) {
  7281. this.boundingSphere = new Sphere();
  7282. }
  7283. this.boundingSphere.setFromPoints( this.vertices );
  7284. },
  7285. merge: function ( geometry, matrix, materialIndexOffset ) {
  7286. if ( ! ( geometry && geometry.isGeometry ) ) {
  7287. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  7288. return;
  7289. }
  7290. var normalMatrix,
  7291. vertexOffset = this.vertices.length,
  7292. vertices1 = this.vertices,
  7293. vertices2 = geometry.vertices,
  7294. faces1 = this.faces,
  7295. faces2 = geometry.faces,
  7296. uvs1 = this.faceVertexUvs[ 0 ],
  7297. uvs2 = geometry.faceVertexUvs[ 0 ],
  7298. colors1 = this.colors,
  7299. colors2 = geometry.colors;
  7300. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  7301. if ( matrix !== undefined ) {
  7302. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7303. }
  7304. // vertices
  7305. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  7306. var vertex = vertices2[ i ];
  7307. var vertexCopy = vertex.clone();
  7308. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  7309. vertices1.push( vertexCopy );
  7310. }
  7311. // colors
  7312. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  7313. colors1.push( colors2[ i ].clone() );
  7314. }
  7315. // faces
  7316. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  7317. var face = faces2[ i ], faceCopy, normal, color,
  7318. faceVertexNormals = face.vertexNormals,
  7319. faceVertexColors = face.vertexColors;
  7320. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  7321. faceCopy.normal.copy( face.normal );
  7322. if ( normalMatrix !== undefined ) {
  7323. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  7324. }
  7325. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  7326. normal = faceVertexNormals[ j ].clone();
  7327. if ( normalMatrix !== undefined ) {
  7328. normal.applyMatrix3( normalMatrix ).normalize();
  7329. }
  7330. faceCopy.vertexNormals.push( normal );
  7331. }
  7332. faceCopy.color.copy( face.color );
  7333. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  7334. color = faceVertexColors[ j ];
  7335. faceCopy.vertexColors.push( color.clone() );
  7336. }
  7337. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  7338. faces1.push( faceCopy );
  7339. }
  7340. // uvs
  7341. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  7342. var uv = uvs2[ i ], uvCopy = [];
  7343. if ( uv === undefined ) {
  7344. continue;
  7345. }
  7346. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  7347. uvCopy.push( uv[ j ].clone() );
  7348. }
  7349. uvs1.push( uvCopy );
  7350. }
  7351. },
  7352. mergeMesh: function ( mesh ) {
  7353. if ( ! ( mesh && mesh.isMesh ) ) {
  7354. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  7355. return;
  7356. }
  7357. mesh.matrixAutoUpdate && mesh.updateMatrix();
  7358. this.merge( mesh.geometry, mesh.matrix );
  7359. },
  7360. /*
  7361. * Checks for duplicate vertices with hashmap.
  7362. * Duplicated vertices are removed
  7363. * and faces' vertices are updated.
  7364. */
  7365. mergeVertices: function () {
  7366. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  7367. var unique = [], changes = [];
  7368. var v, key;
  7369. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  7370. var precision = Math.pow( 10, precisionPoints );
  7371. var i, il, face;
  7372. var indices, j, jl;
  7373. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  7374. v = this.vertices[ i ];
  7375. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  7376. if ( verticesMap[ key ] === undefined ) {
  7377. verticesMap[ key ] = i;
  7378. unique.push( this.vertices[ i ] );
  7379. changes[ i ] = unique.length - 1;
  7380. } else {
  7381. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  7382. changes[ i ] = changes[ verticesMap[ key ] ];
  7383. }
  7384. }
  7385. // if faces are completely degenerate after merging vertices, we
  7386. // have to remove them from the geometry.
  7387. var faceIndicesToRemove = [];
  7388. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  7389. face = this.faces[ i ];
  7390. face.a = changes[ face.a ];
  7391. face.b = changes[ face.b ];
  7392. face.c = changes[ face.c ];
  7393. indices = [ face.a, face.b, face.c ];
  7394. // if any duplicate vertices are found in a Face3
  7395. // we have to remove the face as nothing can be saved
  7396. for ( var n = 0; n < 3; n ++ ) {
  7397. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  7398. faceIndicesToRemove.push( i );
  7399. break;
  7400. }
  7401. }
  7402. }
  7403. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  7404. var idx = faceIndicesToRemove[ i ];
  7405. this.faces.splice( idx, 1 );
  7406. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  7407. this.faceVertexUvs[ j ].splice( idx, 1 );
  7408. }
  7409. }
  7410. // Use unique set of vertices
  7411. var diff = this.vertices.length - unique.length;
  7412. this.vertices = unique;
  7413. return diff;
  7414. },
  7415. sortFacesByMaterialIndex: function () {
  7416. var faces = this.faces;
  7417. var length = faces.length;
  7418. // tag faces
  7419. for ( var i = 0; i < length; i ++ ) {
  7420. faces[ i ]._id = i;
  7421. }
  7422. // sort faces
  7423. function materialIndexSort( a, b ) {
  7424. return a.materialIndex - b.materialIndex;
  7425. }
  7426. faces.sort( materialIndexSort );
  7427. // sort uvs
  7428. var uvs1 = this.faceVertexUvs[ 0 ];
  7429. var uvs2 = this.faceVertexUvs[ 1 ];
  7430. var newUvs1, newUvs2;
  7431. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  7432. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  7433. for ( var i = 0; i < length; i ++ ) {
  7434. var id = faces[ i ]._id;
  7435. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  7436. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  7437. }
  7438. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  7439. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  7440. },
  7441. toJSON: function () {
  7442. var data = {
  7443. metadata: {
  7444. version: 4.5,
  7445. type: 'Geometry',
  7446. generator: 'Geometry.toJSON'
  7447. }
  7448. };
  7449. // standard Geometry serialization
  7450. data.uuid = this.uuid;
  7451. data.type = this.type;
  7452. if ( this.name !== '' ) data.name = this.name;
  7453. if ( this.parameters !== undefined ) {
  7454. var parameters = this.parameters;
  7455. for ( var key in parameters ) {
  7456. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7457. }
  7458. return data;
  7459. }
  7460. var vertices = [];
  7461. for ( var i = 0; i < this.vertices.length; i ++ ) {
  7462. var vertex = this.vertices[ i ];
  7463. vertices.push( vertex.x, vertex.y, vertex.z );
  7464. }
  7465. var faces = [];
  7466. var normals = [];
  7467. var normalsHash = {};
  7468. var colors = [];
  7469. var colorsHash = {};
  7470. var uvs = [];
  7471. var uvsHash = {};
  7472. for ( var i = 0; i < this.faces.length; i ++ ) {
  7473. var face = this.faces[ i ];
  7474. var hasMaterial = true;
  7475. var hasFaceUv = false; // deprecated
  7476. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  7477. var hasFaceNormal = face.normal.length() > 0;
  7478. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  7479. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  7480. var hasFaceVertexColor = face.vertexColors.length > 0;
  7481. var faceType = 0;
  7482. faceType = setBit( faceType, 0, 0 ); // isQuad
  7483. faceType = setBit( faceType, 1, hasMaterial );
  7484. faceType = setBit( faceType, 2, hasFaceUv );
  7485. faceType = setBit( faceType, 3, hasFaceVertexUv );
  7486. faceType = setBit( faceType, 4, hasFaceNormal );
  7487. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  7488. faceType = setBit( faceType, 6, hasFaceColor );
  7489. faceType = setBit( faceType, 7, hasFaceVertexColor );
  7490. faces.push( faceType );
  7491. faces.push( face.a, face.b, face.c );
  7492. faces.push( face.materialIndex );
  7493. if ( hasFaceVertexUv ) {
  7494. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  7495. faces.push(
  7496. getUvIndex( faceVertexUvs[ 0 ] ),
  7497. getUvIndex( faceVertexUvs[ 1 ] ),
  7498. getUvIndex( faceVertexUvs[ 2 ] )
  7499. );
  7500. }
  7501. if ( hasFaceNormal ) {
  7502. faces.push( getNormalIndex( face.normal ) );
  7503. }
  7504. if ( hasFaceVertexNormal ) {
  7505. var vertexNormals = face.vertexNormals;
  7506. faces.push(
  7507. getNormalIndex( vertexNormals[ 0 ] ),
  7508. getNormalIndex( vertexNormals[ 1 ] ),
  7509. getNormalIndex( vertexNormals[ 2 ] )
  7510. );
  7511. }
  7512. if ( hasFaceColor ) {
  7513. faces.push( getColorIndex( face.color ) );
  7514. }
  7515. if ( hasFaceVertexColor ) {
  7516. var vertexColors = face.vertexColors;
  7517. faces.push(
  7518. getColorIndex( vertexColors[ 0 ] ),
  7519. getColorIndex( vertexColors[ 1 ] ),
  7520. getColorIndex( vertexColors[ 2 ] )
  7521. );
  7522. }
  7523. }
  7524. function setBit( value, position, enabled ) {
  7525. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  7526. }
  7527. function getNormalIndex( normal ) {
  7528. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  7529. if ( normalsHash[ hash ] !== undefined ) {
  7530. return normalsHash[ hash ];
  7531. }
  7532. normalsHash[ hash ] = normals.length / 3;
  7533. normals.push( normal.x, normal.y, normal.z );
  7534. return normalsHash[ hash ];
  7535. }
  7536. function getColorIndex( color ) {
  7537. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  7538. if ( colorsHash[ hash ] !== undefined ) {
  7539. return colorsHash[ hash ];
  7540. }
  7541. colorsHash[ hash ] = colors.length;
  7542. colors.push( color.getHex() );
  7543. return colorsHash[ hash ];
  7544. }
  7545. function getUvIndex( uv ) {
  7546. var hash = uv.x.toString() + uv.y.toString();
  7547. if ( uvsHash[ hash ] !== undefined ) {
  7548. return uvsHash[ hash ];
  7549. }
  7550. uvsHash[ hash ] = uvs.length / 2;
  7551. uvs.push( uv.x, uv.y );
  7552. return uvsHash[ hash ];
  7553. }
  7554. data.data = {};
  7555. data.data.vertices = vertices;
  7556. data.data.normals = normals;
  7557. if ( colors.length > 0 ) data.data.colors = colors;
  7558. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  7559. data.data.faces = faces;
  7560. return data;
  7561. },
  7562. clone: function () {
  7563. /*
  7564. // Handle primitives
  7565. var parameters = this.parameters;
  7566. if ( parameters !== undefined ) {
  7567. var values = [];
  7568. for ( var key in parameters ) {
  7569. values.push( parameters[ key ] );
  7570. }
  7571. var geometry = Object.create( this.constructor.prototype );
  7572. this.constructor.apply( geometry, values );
  7573. return geometry;
  7574. }
  7575. return new this.constructor().copy( this );
  7576. */
  7577. return new Geometry().copy( this );
  7578. },
  7579. copy: function ( source ) {
  7580. var i, il, j, jl, k, kl;
  7581. // reset
  7582. this.vertices = [];
  7583. this.colors = [];
  7584. this.faces = [];
  7585. this.faceVertexUvs = [[]];
  7586. this.morphTargets = [];
  7587. this.morphNormals = [];
  7588. this.skinWeights = [];
  7589. this.skinIndices = [];
  7590. this.lineDistances = [];
  7591. this.boundingBox = null;
  7592. this.boundingSphere = null;
  7593. // name
  7594. this.name = source.name;
  7595. // vertices
  7596. var vertices = source.vertices;
  7597. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  7598. this.vertices.push( vertices[ i ].clone() );
  7599. }
  7600. // colors
  7601. var colors = source.colors;
  7602. for ( i = 0, il = colors.length; i < il; i ++ ) {
  7603. this.colors.push( colors[ i ].clone() );
  7604. }
  7605. // faces
  7606. var faces = source.faces;
  7607. for ( i = 0, il = faces.length; i < il; i ++ ) {
  7608. this.faces.push( faces[ i ].clone() );
  7609. }
  7610. // face vertex uvs
  7611. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  7612. var faceVertexUvs = source.faceVertexUvs[ i ];
  7613. if ( this.faceVertexUvs[ i ] === undefined ) {
  7614. this.faceVertexUvs[ i ] = [];
  7615. }
  7616. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  7617. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  7618. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  7619. var uv = uvs[ k ];
  7620. uvsCopy.push( uv.clone() );
  7621. }
  7622. this.faceVertexUvs[ i ].push( uvsCopy );
  7623. }
  7624. }
  7625. // morph targets
  7626. var morphTargets = source.morphTargets;
  7627. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  7628. var morphTarget = {};
  7629. morphTarget.name = morphTargets[ i ].name;
  7630. // vertices
  7631. if ( morphTargets[ i ].vertices !== undefined ) {
  7632. morphTarget.vertices = [];
  7633. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  7634. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  7635. }
  7636. }
  7637. // normals
  7638. if ( morphTargets[ i ].normals !== undefined ) {
  7639. morphTarget.normals = [];
  7640. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  7641. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  7642. }
  7643. }
  7644. this.morphTargets.push( morphTarget );
  7645. }
  7646. // morph normals
  7647. var morphNormals = source.morphNormals;
  7648. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  7649. var morphNormal = {};
  7650. // vertex normals
  7651. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  7652. morphNormal.vertexNormals = [];
  7653. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  7654. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  7655. var destVertexNormal = {};
  7656. destVertexNormal.a = srcVertexNormal.a.clone();
  7657. destVertexNormal.b = srcVertexNormal.b.clone();
  7658. destVertexNormal.c = srcVertexNormal.c.clone();
  7659. morphNormal.vertexNormals.push( destVertexNormal );
  7660. }
  7661. }
  7662. // face normals
  7663. if ( morphNormals[ i ].faceNormals !== undefined ) {
  7664. morphNormal.faceNormals = [];
  7665. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  7666. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  7667. }
  7668. }
  7669. this.morphNormals.push( morphNormal );
  7670. }
  7671. // skin weights
  7672. var skinWeights = source.skinWeights;
  7673. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  7674. this.skinWeights.push( skinWeights[ i ].clone() );
  7675. }
  7676. // skin indices
  7677. var skinIndices = source.skinIndices;
  7678. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  7679. this.skinIndices.push( skinIndices[ i ].clone() );
  7680. }
  7681. // line distances
  7682. var lineDistances = source.lineDistances;
  7683. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  7684. this.lineDistances.push( lineDistances[ i ] );
  7685. }
  7686. // bounding box
  7687. var boundingBox = source.boundingBox;
  7688. if ( boundingBox !== null ) {
  7689. this.boundingBox = boundingBox.clone();
  7690. }
  7691. // bounding sphere
  7692. var boundingSphere = source.boundingSphere;
  7693. if ( boundingSphere !== null ) {
  7694. this.boundingSphere = boundingSphere.clone();
  7695. }
  7696. // update flags
  7697. this.elementsNeedUpdate = source.elementsNeedUpdate;
  7698. this.verticesNeedUpdate = source.verticesNeedUpdate;
  7699. this.uvsNeedUpdate = source.uvsNeedUpdate;
  7700. this.normalsNeedUpdate = source.normalsNeedUpdate;
  7701. this.colorsNeedUpdate = source.colorsNeedUpdate;
  7702. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  7703. this.groupsNeedUpdate = source.groupsNeedUpdate;
  7704. return this;
  7705. },
  7706. dispose: function () {
  7707. this.dispatchEvent( { type: 'dispose' } );
  7708. }
  7709. } );
  7710. /**
  7711. * @author mrdoob / http://mrdoob.com/
  7712. */
  7713. function BufferAttribute( array, itemSize, normalized ) {
  7714. if ( Array.isArray( array ) ) {
  7715. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7716. }
  7717. this.uuid = _Math.generateUUID();
  7718. this.name = '';
  7719. this.array = array;
  7720. this.itemSize = itemSize;
  7721. this.count = array !== undefined ? array.length / itemSize : 0;
  7722. this.normalized = normalized === true;
  7723. this.dynamic = false;
  7724. this.updateRange = { offset: 0, count: - 1 };
  7725. this.onUploadCallback = function () {};
  7726. this.version = 0;
  7727. }
  7728. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  7729. set: function ( value ) {
  7730. if ( value === true ) this.version ++;
  7731. }
  7732. } );
  7733. Object.assign( BufferAttribute.prototype, {
  7734. isBufferAttribute: true,
  7735. setArray: function ( array ) {
  7736. if ( Array.isArray( array ) ) {
  7737. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7738. }
  7739. this.count = array !== undefined ? array.length / this.itemSize : 0;
  7740. this.array = array;
  7741. },
  7742. setDynamic: function ( value ) {
  7743. this.dynamic = value;
  7744. return this;
  7745. },
  7746. copy: function ( source ) {
  7747. this.array = new source.array.constructor( source.array );
  7748. this.itemSize = source.itemSize;
  7749. this.count = source.count;
  7750. this.normalized = source.normalized;
  7751. this.dynamic = source.dynamic;
  7752. return this;
  7753. },
  7754. copyAt: function ( index1, attribute, index2 ) {
  7755. index1 *= this.itemSize;
  7756. index2 *= attribute.itemSize;
  7757. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  7758. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7759. }
  7760. return this;
  7761. },
  7762. copyArray: function ( array ) {
  7763. this.array.set( array );
  7764. return this;
  7765. },
  7766. copyColorsArray: function ( colors ) {
  7767. var array = this.array, offset = 0;
  7768. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  7769. var color = colors[ i ];
  7770. if ( color === undefined ) {
  7771. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  7772. color = new Color();
  7773. }
  7774. array[ offset ++ ] = color.r;
  7775. array[ offset ++ ] = color.g;
  7776. array[ offset ++ ] = color.b;
  7777. }
  7778. return this;
  7779. },
  7780. copyIndicesArray: function ( indices ) {
  7781. var array = this.array, offset = 0;
  7782. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  7783. var index = indices[ i ];
  7784. array[ offset ++ ] = index.a;
  7785. array[ offset ++ ] = index.b;
  7786. array[ offset ++ ] = index.c;
  7787. }
  7788. return this;
  7789. },
  7790. copyVector2sArray: function ( vectors ) {
  7791. var array = this.array, offset = 0;
  7792. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7793. var vector = vectors[ i ];
  7794. if ( vector === undefined ) {
  7795. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  7796. vector = new Vector2();
  7797. }
  7798. array[ offset ++ ] = vector.x;
  7799. array[ offset ++ ] = vector.y;
  7800. }
  7801. return this;
  7802. },
  7803. copyVector3sArray: function ( vectors ) {
  7804. var array = this.array, offset = 0;
  7805. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7806. var vector = vectors[ i ];
  7807. if ( vector === undefined ) {
  7808. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  7809. vector = new Vector3();
  7810. }
  7811. array[ offset ++ ] = vector.x;
  7812. array[ offset ++ ] = vector.y;
  7813. array[ offset ++ ] = vector.z;
  7814. }
  7815. return this;
  7816. },
  7817. copyVector4sArray: function ( vectors ) {
  7818. var array = this.array, offset = 0;
  7819. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7820. var vector = vectors[ i ];
  7821. if ( vector === undefined ) {
  7822. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  7823. vector = new Vector4();
  7824. }
  7825. array[ offset ++ ] = vector.x;
  7826. array[ offset ++ ] = vector.y;
  7827. array[ offset ++ ] = vector.z;
  7828. array[ offset ++ ] = vector.w;
  7829. }
  7830. return this;
  7831. },
  7832. set: function ( value, offset ) {
  7833. if ( offset === undefined ) offset = 0;
  7834. this.array.set( value, offset );
  7835. return this;
  7836. },
  7837. getX: function ( index ) {
  7838. return this.array[ index * this.itemSize ];
  7839. },
  7840. setX: function ( index, x ) {
  7841. this.array[ index * this.itemSize ] = x;
  7842. return this;
  7843. },
  7844. getY: function ( index ) {
  7845. return this.array[ index * this.itemSize + 1 ];
  7846. },
  7847. setY: function ( index, y ) {
  7848. this.array[ index * this.itemSize + 1 ] = y;
  7849. return this;
  7850. },
  7851. getZ: function ( index ) {
  7852. return this.array[ index * this.itemSize + 2 ];
  7853. },
  7854. setZ: function ( index, z ) {
  7855. this.array[ index * this.itemSize + 2 ] = z;
  7856. return this;
  7857. },
  7858. getW: function ( index ) {
  7859. return this.array[ index * this.itemSize + 3 ];
  7860. },
  7861. setW: function ( index, w ) {
  7862. this.array[ index * this.itemSize + 3 ] = w;
  7863. return this;
  7864. },
  7865. setXY: function ( index, x, y ) {
  7866. index *= this.itemSize;
  7867. this.array[ index + 0 ] = x;
  7868. this.array[ index + 1 ] = y;
  7869. return this;
  7870. },
  7871. setXYZ: function ( index, x, y, z ) {
  7872. index *= this.itemSize;
  7873. this.array[ index + 0 ] = x;
  7874. this.array[ index + 1 ] = y;
  7875. this.array[ index + 2 ] = z;
  7876. return this;
  7877. },
  7878. setXYZW: function ( index, x, y, z, w ) {
  7879. index *= this.itemSize;
  7880. this.array[ index + 0 ] = x;
  7881. this.array[ index + 1 ] = y;
  7882. this.array[ index + 2 ] = z;
  7883. this.array[ index + 3 ] = w;
  7884. return this;
  7885. },
  7886. onUpload: function ( callback ) {
  7887. this.onUploadCallback = callback;
  7888. return this;
  7889. },
  7890. clone: function () {
  7891. return new this.constructor( this.array, this.itemSize ).copy( this );
  7892. }
  7893. } );
  7894. //
  7895. function Int8BufferAttribute( array, itemSize ) {
  7896. BufferAttribute.call( this, new Int8Array( array ), itemSize );
  7897. }
  7898. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7899. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7900. function Uint8BufferAttribute( array, itemSize ) {
  7901. BufferAttribute.call( this, new Uint8Array( array ), itemSize );
  7902. }
  7903. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7904. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7905. function Uint8ClampedBufferAttribute( array, itemSize ) {
  7906. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize );
  7907. }
  7908. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7909. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7910. function Int16BufferAttribute( array, itemSize ) {
  7911. BufferAttribute.call( this, new Int16Array( array ), itemSize );
  7912. }
  7913. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7914. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7915. function Uint16BufferAttribute( array, itemSize ) {
  7916. BufferAttribute.call( this, new Uint16Array( array ), itemSize );
  7917. }
  7918. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7919. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7920. function Int32BufferAttribute( array, itemSize ) {
  7921. BufferAttribute.call( this, new Int32Array( array ), itemSize );
  7922. }
  7923. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7924. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7925. function Uint32BufferAttribute( array, itemSize ) {
  7926. BufferAttribute.call( this, new Uint32Array( array ), itemSize );
  7927. }
  7928. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7929. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7930. function Float32BufferAttribute( array, itemSize ) {
  7931. BufferAttribute.call( this, new Float32Array( array ), itemSize );
  7932. }
  7933. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7934. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  7935. function Float64BufferAttribute( array, itemSize ) {
  7936. BufferAttribute.call( this, new Float64Array( array ), itemSize );
  7937. }
  7938. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7939. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  7940. /**
  7941. * @author mrdoob / http://mrdoob.com/
  7942. */
  7943. function DirectGeometry() {
  7944. this.indices = [];
  7945. this.vertices = [];
  7946. this.normals = [];
  7947. this.colors = [];
  7948. this.uvs = [];
  7949. this.uvs2 = [];
  7950. this.groups = [];
  7951. this.morphTargets = {};
  7952. this.skinWeights = [];
  7953. this.skinIndices = [];
  7954. // this.lineDistances = [];
  7955. this.boundingBox = null;
  7956. this.boundingSphere = null;
  7957. // update flags
  7958. this.verticesNeedUpdate = false;
  7959. this.normalsNeedUpdate = false;
  7960. this.colorsNeedUpdate = false;
  7961. this.uvsNeedUpdate = false;
  7962. this.groupsNeedUpdate = false;
  7963. }
  7964. Object.assign( DirectGeometry.prototype, {
  7965. computeGroups: function ( geometry ) {
  7966. var group;
  7967. var groups = [];
  7968. var materialIndex = undefined;
  7969. var faces = geometry.faces;
  7970. for ( var i = 0; i < faces.length; i ++ ) {
  7971. var face = faces[ i ];
  7972. // materials
  7973. if ( face.materialIndex !== materialIndex ) {
  7974. materialIndex = face.materialIndex;
  7975. if ( group !== undefined ) {
  7976. group.count = ( i * 3 ) - group.start;
  7977. groups.push( group );
  7978. }
  7979. group = {
  7980. start: i * 3,
  7981. materialIndex: materialIndex
  7982. };
  7983. }
  7984. }
  7985. if ( group !== undefined ) {
  7986. group.count = ( i * 3 ) - group.start;
  7987. groups.push( group );
  7988. }
  7989. this.groups = groups;
  7990. },
  7991. fromGeometry: function ( geometry ) {
  7992. var faces = geometry.faces;
  7993. var vertices = geometry.vertices;
  7994. var faceVertexUvs = geometry.faceVertexUvs;
  7995. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  7996. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  7997. // morphs
  7998. var morphTargets = geometry.morphTargets;
  7999. var morphTargetsLength = morphTargets.length;
  8000. var morphTargetsPosition;
  8001. if ( morphTargetsLength > 0 ) {
  8002. morphTargetsPosition = [];
  8003. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  8004. morphTargetsPosition[ i ] = [];
  8005. }
  8006. this.morphTargets.position = morphTargetsPosition;
  8007. }
  8008. var morphNormals = geometry.morphNormals;
  8009. var morphNormalsLength = morphNormals.length;
  8010. var morphTargetsNormal;
  8011. if ( morphNormalsLength > 0 ) {
  8012. morphTargetsNormal = [];
  8013. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  8014. morphTargetsNormal[ i ] = [];
  8015. }
  8016. this.morphTargets.normal = morphTargetsNormal;
  8017. }
  8018. // skins
  8019. var skinIndices = geometry.skinIndices;
  8020. var skinWeights = geometry.skinWeights;
  8021. var hasSkinIndices = skinIndices.length === vertices.length;
  8022. var hasSkinWeights = skinWeights.length === vertices.length;
  8023. //
  8024. for ( var i = 0; i < faces.length; i ++ ) {
  8025. var face = faces[ i ];
  8026. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  8027. var vertexNormals = face.vertexNormals;
  8028. if ( vertexNormals.length === 3 ) {
  8029. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  8030. } else {
  8031. var normal = face.normal;
  8032. this.normals.push( normal, normal, normal );
  8033. }
  8034. var vertexColors = face.vertexColors;
  8035. if ( vertexColors.length === 3 ) {
  8036. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  8037. } else {
  8038. var color = face.color;
  8039. this.colors.push( color, color, color );
  8040. }
  8041. if ( hasFaceVertexUv === true ) {
  8042. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  8043. if ( vertexUvs !== undefined ) {
  8044. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  8045. } else {
  8046. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  8047. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  8048. }
  8049. }
  8050. if ( hasFaceVertexUv2 === true ) {
  8051. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  8052. if ( vertexUvs !== undefined ) {
  8053. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  8054. } else {
  8055. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  8056. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  8057. }
  8058. }
  8059. // morphs
  8060. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  8061. var morphTarget = morphTargets[ j ].vertices;
  8062. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  8063. }
  8064. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  8065. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  8066. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  8067. }
  8068. // skins
  8069. if ( hasSkinIndices ) {
  8070. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  8071. }
  8072. if ( hasSkinWeights ) {
  8073. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  8074. }
  8075. }
  8076. this.computeGroups( geometry );
  8077. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  8078. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  8079. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  8080. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  8081. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  8082. return this;
  8083. }
  8084. } );
  8085. /**
  8086. * @author mrdoob / http://mrdoob.com/
  8087. */
  8088. function arrayMax( array ) {
  8089. if ( array.length === 0 ) return - Infinity;
  8090. var max = array[ 0 ];
  8091. for ( var i = 1, l = array.length; i < l; ++ i ) {
  8092. if ( array[ i ] > max ) max = array[ i ];
  8093. }
  8094. return max;
  8095. }
  8096. /**
  8097. * @author alteredq / http://alteredqualia.com/
  8098. * @author mrdoob / http://mrdoob.com/
  8099. */
  8100. function BufferGeometry() {
  8101. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  8102. this.uuid = _Math.generateUUID();
  8103. this.name = '';
  8104. this.type = 'BufferGeometry';
  8105. this.index = null;
  8106. this.attributes = {};
  8107. this.morphAttributes = {};
  8108. this.groups = [];
  8109. this.boundingBox = null;
  8110. this.boundingSphere = null;
  8111. this.drawRange = { start: 0, count: Infinity };
  8112. }
  8113. BufferGeometry.MaxIndex = 65535;
  8114. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, {
  8115. isBufferGeometry: true,
  8116. getIndex: function () {
  8117. return this.index;
  8118. },
  8119. setIndex: function ( index ) {
  8120. if ( Array.isArray( index ) ) {
  8121. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  8122. } else {
  8123. this.index = index;
  8124. }
  8125. },
  8126. addAttribute: function ( name, attribute ) {
  8127. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  8128. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  8129. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  8130. return;
  8131. }
  8132. if ( name === 'index' ) {
  8133. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  8134. this.setIndex( attribute );
  8135. return;
  8136. }
  8137. this.attributes[ name ] = attribute;
  8138. return this;
  8139. },
  8140. getAttribute: function ( name ) {
  8141. return this.attributes[ name ];
  8142. },
  8143. removeAttribute: function ( name ) {
  8144. delete this.attributes[ name ];
  8145. return this;
  8146. },
  8147. addGroup: function ( start, count, materialIndex ) {
  8148. this.groups.push( {
  8149. start: start,
  8150. count: count,
  8151. materialIndex: materialIndex !== undefined ? materialIndex : 0
  8152. } );
  8153. },
  8154. clearGroups: function () {
  8155. this.groups = [];
  8156. },
  8157. setDrawRange: function ( start, count ) {
  8158. this.drawRange.start = start;
  8159. this.drawRange.count = count;
  8160. },
  8161. applyMatrix: function ( matrix ) {
  8162. var position = this.attributes.position;
  8163. if ( position !== undefined ) {
  8164. matrix.applyToBufferAttribute( position );
  8165. position.needsUpdate = true;
  8166. }
  8167. var normal = this.attributes.normal;
  8168. if ( normal !== undefined ) {
  8169. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8170. normalMatrix.applyToBufferAttribute( normal );
  8171. normal.needsUpdate = true;
  8172. }
  8173. if ( this.boundingBox !== null ) {
  8174. this.computeBoundingBox();
  8175. }
  8176. if ( this.boundingSphere !== null ) {
  8177. this.computeBoundingSphere();
  8178. }
  8179. return this;
  8180. },
  8181. rotateX: function () {
  8182. // rotate geometry around world x-axis
  8183. var m1 = new Matrix4();
  8184. return function rotateX( angle ) {
  8185. m1.makeRotationX( angle );
  8186. this.applyMatrix( m1 );
  8187. return this;
  8188. };
  8189. }(),
  8190. rotateY: function () {
  8191. // rotate geometry around world y-axis
  8192. var m1 = new Matrix4();
  8193. return function rotateY( angle ) {
  8194. m1.makeRotationY( angle );
  8195. this.applyMatrix( m1 );
  8196. return this;
  8197. };
  8198. }(),
  8199. rotateZ: function () {
  8200. // rotate geometry around world z-axis
  8201. var m1 = new Matrix4();
  8202. return function rotateZ( angle ) {
  8203. m1.makeRotationZ( angle );
  8204. this.applyMatrix( m1 );
  8205. return this;
  8206. };
  8207. }(),
  8208. translate: function () {
  8209. // translate geometry
  8210. var m1 = new Matrix4();
  8211. return function translate( x, y, z ) {
  8212. m1.makeTranslation( x, y, z );
  8213. this.applyMatrix( m1 );
  8214. return this;
  8215. };
  8216. }(),
  8217. scale: function () {
  8218. // scale geometry
  8219. var m1 = new Matrix4();
  8220. return function scale( x, y, z ) {
  8221. m1.makeScale( x, y, z );
  8222. this.applyMatrix( m1 );
  8223. return this;
  8224. };
  8225. }(),
  8226. lookAt: function () {
  8227. var obj = new Object3D();
  8228. return function lookAt( vector ) {
  8229. obj.lookAt( vector );
  8230. obj.updateMatrix();
  8231. this.applyMatrix( obj.matrix );
  8232. };
  8233. }(),
  8234. center: function () {
  8235. this.computeBoundingBox();
  8236. var offset = this.boundingBox.getCenter().negate();
  8237. this.translate( offset.x, offset.y, offset.z );
  8238. return offset;
  8239. },
  8240. setFromObject: function ( object ) {
  8241. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  8242. var geometry = object.geometry;
  8243. if ( object.isPoints || object.isLine ) {
  8244. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  8245. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  8246. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  8247. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  8248. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  8249. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  8250. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  8251. }
  8252. if ( geometry.boundingSphere !== null ) {
  8253. this.boundingSphere = geometry.boundingSphere.clone();
  8254. }
  8255. if ( geometry.boundingBox !== null ) {
  8256. this.boundingBox = geometry.boundingBox.clone();
  8257. }
  8258. } else if ( object.isMesh ) {
  8259. if ( geometry && geometry.isGeometry ) {
  8260. this.fromGeometry( geometry );
  8261. }
  8262. }
  8263. return this;
  8264. },
  8265. updateFromObject: function ( object ) {
  8266. var geometry = object.geometry;
  8267. if ( object.isMesh ) {
  8268. var direct = geometry.__directGeometry;
  8269. if ( geometry.elementsNeedUpdate === true ) {
  8270. direct = undefined;
  8271. geometry.elementsNeedUpdate = false;
  8272. }
  8273. if ( direct === undefined ) {
  8274. return this.fromGeometry( geometry );
  8275. }
  8276. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  8277. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  8278. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  8279. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  8280. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  8281. geometry.verticesNeedUpdate = false;
  8282. geometry.normalsNeedUpdate = false;
  8283. geometry.colorsNeedUpdate = false;
  8284. geometry.uvsNeedUpdate = false;
  8285. geometry.groupsNeedUpdate = false;
  8286. geometry = direct;
  8287. }
  8288. var attribute;
  8289. if ( geometry.verticesNeedUpdate === true ) {
  8290. attribute = this.attributes.position;
  8291. if ( attribute !== undefined ) {
  8292. attribute.copyVector3sArray( geometry.vertices );
  8293. attribute.needsUpdate = true;
  8294. }
  8295. geometry.verticesNeedUpdate = false;
  8296. }
  8297. if ( geometry.normalsNeedUpdate === true ) {
  8298. attribute = this.attributes.normal;
  8299. if ( attribute !== undefined ) {
  8300. attribute.copyVector3sArray( geometry.normals );
  8301. attribute.needsUpdate = true;
  8302. }
  8303. geometry.normalsNeedUpdate = false;
  8304. }
  8305. if ( geometry.colorsNeedUpdate === true ) {
  8306. attribute = this.attributes.color;
  8307. if ( attribute !== undefined ) {
  8308. attribute.copyColorsArray( geometry.colors );
  8309. attribute.needsUpdate = true;
  8310. }
  8311. geometry.colorsNeedUpdate = false;
  8312. }
  8313. if ( geometry.uvsNeedUpdate ) {
  8314. attribute = this.attributes.uv;
  8315. if ( attribute !== undefined ) {
  8316. attribute.copyVector2sArray( geometry.uvs );
  8317. attribute.needsUpdate = true;
  8318. }
  8319. geometry.uvsNeedUpdate = false;
  8320. }
  8321. if ( geometry.lineDistancesNeedUpdate ) {
  8322. attribute = this.attributes.lineDistance;
  8323. if ( attribute !== undefined ) {
  8324. attribute.copyArray( geometry.lineDistances );
  8325. attribute.needsUpdate = true;
  8326. }
  8327. geometry.lineDistancesNeedUpdate = false;
  8328. }
  8329. if ( geometry.groupsNeedUpdate ) {
  8330. geometry.computeGroups( object.geometry );
  8331. this.groups = geometry.groups;
  8332. geometry.groupsNeedUpdate = false;
  8333. }
  8334. return this;
  8335. },
  8336. fromGeometry: function ( geometry ) {
  8337. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  8338. return this.fromDirectGeometry( geometry.__directGeometry );
  8339. },
  8340. fromDirectGeometry: function ( geometry ) {
  8341. var positions = new Float32Array( geometry.vertices.length * 3 );
  8342. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  8343. if ( geometry.normals.length > 0 ) {
  8344. var normals = new Float32Array( geometry.normals.length * 3 );
  8345. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  8346. }
  8347. if ( geometry.colors.length > 0 ) {
  8348. var colors = new Float32Array( geometry.colors.length * 3 );
  8349. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  8350. }
  8351. if ( geometry.uvs.length > 0 ) {
  8352. var uvs = new Float32Array( geometry.uvs.length * 2 );
  8353. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  8354. }
  8355. if ( geometry.uvs2.length > 0 ) {
  8356. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  8357. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  8358. }
  8359. if ( geometry.indices.length > 0 ) {
  8360. var TypeArray = arrayMax( geometry.indices ) > 65535 ? Uint32Array : Uint16Array;
  8361. var indices = new TypeArray( geometry.indices.length * 3 );
  8362. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  8363. }
  8364. // groups
  8365. this.groups = geometry.groups;
  8366. // morphs
  8367. for ( var name in geometry.morphTargets ) {
  8368. var array = [];
  8369. var morphTargets = geometry.morphTargets[ name ];
  8370. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  8371. var morphTarget = morphTargets[ i ];
  8372. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  8373. array.push( attribute.copyVector3sArray( morphTarget ) );
  8374. }
  8375. this.morphAttributes[ name ] = array;
  8376. }
  8377. // skinning
  8378. if ( geometry.skinIndices.length > 0 ) {
  8379. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  8380. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  8381. }
  8382. if ( geometry.skinWeights.length > 0 ) {
  8383. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  8384. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  8385. }
  8386. //
  8387. if ( geometry.boundingSphere !== null ) {
  8388. this.boundingSphere = geometry.boundingSphere.clone();
  8389. }
  8390. if ( geometry.boundingBox !== null ) {
  8391. this.boundingBox = geometry.boundingBox.clone();
  8392. }
  8393. return this;
  8394. },
  8395. computeBoundingBox: function () {
  8396. if ( this.boundingBox === null ) {
  8397. this.boundingBox = new Box3();
  8398. }
  8399. var position = this.attributes.position;
  8400. if ( position !== undefined ) {
  8401. this.boundingBox.setFromBufferAttribute( position );
  8402. } else {
  8403. this.boundingBox.makeEmpty();
  8404. }
  8405. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  8406. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  8407. }
  8408. },
  8409. computeBoundingSphere: function () {
  8410. var box = new Box3();
  8411. var vector = new Vector3();
  8412. return function computeBoundingSphere() {
  8413. if ( this.boundingSphere === null ) {
  8414. this.boundingSphere = new Sphere();
  8415. }
  8416. var position = this.attributes.position;
  8417. if ( position ) {
  8418. var center = this.boundingSphere.center;
  8419. box.setFromBufferAttribute( position );
  8420. box.getCenter( center );
  8421. // hoping to find a boundingSphere with a radius smaller than the
  8422. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  8423. var maxRadiusSq = 0;
  8424. for ( var i = 0, il = position.count; i < il; i ++ ) {
  8425. vector.x = position.getX( i );
  8426. vector.y = position.getY( i );
  8427. vector.z = position.getZ( i );
  8428. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  8429. }
  8430. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  8431. if ( isNaN( this.boundingSphere.radius ) ) {
  8432. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  8433. }
  8434. }
  8435. };
  8436. }(),
  8437. computeFaceNormals: function () {
  8438. // backwards compatibility
  8439. },
  8440. computeVertexNormals: function () {
  8441. var index = this.index;
  8442. var attributes = this.attributes;
  8443. var groups = this.groups;
  8444. if ( attributes.position ) {
  8445. var positions = attributes.position.array;
  8446. if ( attributes.normal === undefined ) {
  8447. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  8448. } else {
  8449. // reset existing normals to zero
  8450. var array = attributes.normal.array;
  8451. for ( var i = 0, il = array.length; i < il; i ++ ) {
  8452. array[ i ] = 0;
  8453. }
  8454. }
  8455. var normals = attributes.normal.array;
  8456. var vA, vB, vC;
  8457. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  8458. var cb = new Vector3(), ab = new Vector3();
  8459. // indexed elements
  8460. if ( index ) {
  8461. var indices = index.array;
  8462. if ( groups.length === 0 ) {
  8463. this.addGroup( 0, indices.length );
  8464. }
  8465. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  8466. var group = groups[ j ];
  8467. var start = group.start;
  8468. var count = group.count;
  8469. for ( var i = start, il = start + count; i < il; i += 3 ) {
  8470. vA = indices[ i + 0 ] * 3;
  8471. vB = indices[ i + 1 ] * 3;
  8472. vC = indices[ i + 2 ] * 3;
  8473. pA.fromArray( positions, vA );
  8474. pB.fromArray( positions, vB );
  8475. pC.fromArray( positions, vC );
  8476. cb.subVectors( pC, pB );
  8477. ab.subVectors( pA, pB );
  8478. cb.cross( ab );
  8479. normals[ vA ] += cb.x;
  8480. normals[ vA + 1 ] += cb.y;
  8481. normals[ vA + 2 ] += cb.z;
  8482. normals[ vB ] += cb.x;
  8483. normals[ vB + 1 ] += cb.y;
  8484. normals[ vB + 2 ] += cb.z;
  8485. normals[ vC ] += cb.x;
  8486. normals[ vC + 1 ] += cb.y;
  8487. normals[ vC + 2 ] += cb.z;
  8488. }
  8489. }
  8490. } else {
  8491. // non-indexed elements (unconnected triangle soup)
  8492. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  8493. pA.fromArray( positions, i );
  8494. pB.fromArray( positions, i + 3 );
  8495. pC.fromArray( positions, i + 6 );
  8496. cb.subVectors( pC, pB );
  8497. ab.subVectors( pA, pB );
  8498. cb.cross( ab );
  8499. normals[ i ] = cb.x;
  8500. normals[ i + 1 ] = cb.y;
  8501. normals[ i + 2 ] = cb.z;
  8502. normals[ i + 3 ] = cb.x;
  8503. normals[ i + 4 ] = cb.y;
  8504. normals[ i + 5 ] = cb.z;
  8505. normals[ i + 6 ] = cb.x;
  8506. normals[ i + 7 ] = cb.y;
  8507. normals[ i + 8 ] = cb.z;
  8508. }
  8509. }
  8510. this.normalizeNormals();
  8511. attributes.normal.needsUpdate = true;
  8512. }
  8513. },
  8514. merge: function ( geometry, offset ) {
  8515. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  8516. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  8517. return;
  8518. }
  8519. if ( offset === undefined ) offset = 0;
  8520. var attributes = this.attributes;
  8521. for ( var key in attributes ) {
  8522. if ( geometry.attributes[ key ] === undefined ) continue;
  8523. var attribute1 = attributes[ key ];
  8524. var attributeArray1 = attribute1.array;
  8525. var attribute2 = geometry.attributes[ key ];
  8526. var attributeArray2 = attribute2.array;
  8527. var attributeSize = attribute2.itemSize;
  8528. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  8529. attributeArray1[ j ] = attributeArray2[ i ];
  8530. }
  8531. }
  8532. return this;
  8533. },
  8534. normalizeNormals: function () {
  8535. var vector = new Vector3();
  8536. return function normalizeNormals() {
  8537. var normals = this.attributes.normal;
  8538. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  8539. vector.x = normals.getX( i );
  8540. vector.y = normals.getY( i );
  8541. vector.z = normals.getZ( i );
  8542. vector.normalize();
  8543. normals.setXYZ( i, vector.x, vector.y, vector.z );
  8544. }
  8545. };
  8546. }(),
  8547. toNonIndexed: function () {
  8548. if ( this.index === null ) {
  8549. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  8550. return this;
  8551. }
  8552. var geometry2 = new BufferGeometry();
  8553. var indices = this.index.array;
  8554. var attributes = this.attributes;
  8555. for ( var name in attributes ) {
  8556. var attribute = attributes[ name ];
  8557. var array = attribute.array;
  8558. var itemSize = attribute.itemSize;
  8559. var array2 = new array.constructor( indices.length * itemSize );
  8560. var index = 0, index2 = 0;
  8561. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  8562. index = indices[ i ] * itemSize;
  8563. for ( var j = 0; j < itemSize; j ++ ) {
  8564. array2[ index2 ++ ] = array[ index ++ ];
  8565. }
  8566. }
  8567. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  8568. }
  8569. return geometry2;
  8570. },
  8571. toJSON: function () {
  8572. var data = {
  8573. metadata: {
  8574. version: 4.5,
  8575. type: 'BufferGeometry',
  8576. generator: 'BufferGeometry.toJSON'
  8577. }
  8578. };
  8579. // standard BufferGeometry serialization
  8580. data.uuid = this.uuid;
  8581. data.type = this.type;
  8582. if ( this.name !== '' ) data.name = this.name;
  8583. if ( this.parameters !== undefined ) {
  8584. var parameters = this.parameters;
  8585. for ( var key in parameters ) {
  8586. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8587. }
  8588. return data;
  8589. }
  8590. data.data = { attributes: {} };
  8591. var index = this.index;
  8592. if ( index !== null ) {
  8593. var array = Array.prototype.slice.call( index.array );
  8594. data.data.index = {
  8595. type: index.array.constructor.name,
  8596. array: array
  8597. };
  8598. }
  8599. var attributes = this.attributes;
  8600. for ( var key in attributes ) {
  8601. var attribute = attributes[ key ];
  8602. var array = Array.prototype.slice.call( attribute.array );
  8603. data.data.attributes[ key ] = {
  8604. itemSize: attribute.itemSize,
  8605. type: attribute.array.constructor.name,
  8606. array: array,
  8607. normalized: attribute.normalized
  8608. };
  8609. }
  8610. var groups = this.groups;
  8611. if ( groups.length > 0 ) {
  8612. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  8613. }
  8614. var boundingSphere = this.boundingSphere;
  8615. if ( boundingSphere !== null ) {
  8616. data.data.boundingSphere = {
  8617. center: boundingSphere.center.toArray(),
  8618. radius: boundingSphere.radius
  8619. };
  8620. }
  8621. return data;
  8622. },
  8623. clone: function () {
  8624. /*
  8625. // Handle primitives
  8626. var parameters = this.parameters;
  8627. if ( parameters !== undefined ) {
  8628. var values = [];
  8629. for ( var key in parameters ) {
  8630. values.push( parameters[ key ] );
  8631. }
  8632. var geometry = Object.create( this.constructor.prototype );
  8633. this.constructor.apply( geometry, values );
  8634. return geometry;
  8635. }
  8636. return new this.constructor().copy( this );
  8637. */
  8638. return new BufferGeometry().copy( this );
  8639. },
  8640. copy: function ( source ) {
  8641. var name, i, l;
  8642. // reset
  8643. this.index = null;
  8644. this.attributes = {};
  8645. this.morphAttributes = {};
  8646. this.groups = [];
  8647. this.boundingBox = null;
  8648. this.boundingSphere = null;
  8649. // name
  8650. this.name = source.name;
  8651. // index
  8652. var index = source.index;
  8653. if ( index !== null ) {
  8654. this.setIndex( index.clone() );
  8655. }
  8656. // attributes
  8657. var attributes = source.attributes;
  8658. for ( name in attributes ) {
  8659. var attribute = attributes[ name ];
  8660. this.addAttribute( name, attribute.clone() );
  8661. }
  8662. // morph attributes
  8663. var morphAttributes = source.morphAttributes;
  8664. for ( name in morphAttributes ) {
  8665. var array = [];
  8666. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  8667. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  8668. array.push( morphAttribute[ i ].clone() );
  8669. }
  8670. this.morphAttributes[ name ] = array;
  8671. }
  8672. // groups
  8673. var groups = source.groups;
  8674. for ( i = 0, l = groups.length; i < l; i ++ ) {
  8675. var group = groups[ i ];
  8676. this.addGroup( group.start, group.count, group.materialIndex );
  8677. }
  8678. // bounding box
  8679. var boundingBox = source.boundingBox;
  8680. if ( boundingBox !== null ) {
  8681. this.boundingBox = boundingBox.clone();
  8682. }
  8683. // bounding sphere
  8684. var boundingSphere = source.boundingSphere;
  8685. if ( boundingSphere !== null ) {
  8686. this.boundingSphere = boundingSphere.clone();
  8687. }
  8688. // draw range
  8689. this.drawRange.start = source.drawRange.start;
  8690. this.drawRange.count = source.drawRange.count;
  8691. return this;
  8692. },
  8693. dispose: function () {
  8694. this.dispatchEvent( { type: 'dispose' } );
  8695. }
  8696. } );
  8697. /**
  8698. * @author mrdoob / http://mrdoob.com/
  8699. * @author Mugen87 / https://github.com/Mugen87
  8700. */
  8701. // BoxGeometry
  8702. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  8703. Geometry.call( this );
  8704. this.type = 'BoxGeometry';
  8705. this.parameters = {
  8706. width: width,
  8707. height: height,
  8708. depth: depth,
  8709. widthSegments: widthSegments,
  8710. heightSegments: heightSegments,
  8711. depthSegments: depthSegments
  8712. };
  8713. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  8714. this.mergeVertices();
  8715. }
  8716. BoxGeometry.prototype = Object.create( Geometry.prototype );
  8717. BoxGeometry.prototype.constructor = BoxGeometry;
  8718. // BoxBufferGeometry
  8719. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  8720. BufferGeometry.call( this );
  8721. this.type = 'BoxBufferGeometry';
  8722. this.parameters = {
  8723. width: width,
  8724. height: height,
  8725. depth: depth,
  8726. widthSegments: widthSegments,
  8727. heightSegments: heightSegments,
  8728. depthSegments: depthSegments
  8729. };
  8730. var scope = this;
  8731. // segments
  8732. widthSegments = Math.floor( widthSegments ) || 1;
  8733. heightSegments = Math.floor( heightSegments ) || 1;
  8734. depthSegments = Math.floor( depthSegments ) || 1;
  8735. // buffers
  8736. var indices = [];
  8737. var vertices = [];
  8738. var normals = [];
  8739. var uvs = [];
  8740. // helper variables
  8741. var numberOfVertices = 0;
  8742. var groupStart = 0;
  8743. // build each side of the box geometry
  8744. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  8745. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  8746. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  8747. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  8748. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  8749. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  8750. // build geometry
  8751. this.setIndex( indices );
  8752. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8753. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8754. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8755. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  8756. var segmentWidth = width / gridX;
  8757. var segmentHeight = height / gridY;
  8758. var widthHalf = width / 2;
  8759. var heightHalf = height / 2;
  8760. var depthHalf = depth / 2;
  8761. var gridX1 = gridX + 1;
  8762. var gridY1 = gridY + 1;
  8763. var vertexCounter = 0;
  8764. var groupCount = 0;
  8765. var ix, iy;
  8766. var vector = new Vector3();
  8767. // generate vertices, normals and uvs
  8768. for ( iy = 0; iy < gridY1; iy ++ ) {
  8769. var y = iy * segmentHeight - heightHalf;
  8770. for ( ix = 0; ix < gridX1; ix ++ ) {
  8771. var x = ix * segmentWidth - widthHalf;
  8772. // set values to correct vector component
  8773. vector[ u ] = x * udir;
  8774. vector[ v ] = y * vdir;
  8775. vector[ w ] = depthHalf;
  8776. // now apply vector to vertex buffer
  8777. vertices.push( vector.x, vector.y, vector.z );
  8778. // set values to correct vector component
  8779. vector[ u ] = 0;
  8780. vector[ v ] = 0;
  8781. vector[ w ] = depth > 0 ? 1 : - 1;
  8782. // now apply vector to normal buffer
  8783. normals.push( vector.x, vector.y, vector.z );
  8784. // uvs
  8785. uvs.push( ix / gridX );
  8786. uvs.push( 1 - ( iy / gridY ) );
  8787. // counters
  8788. vertexCounter += 1;
  8789. }
  8790. }
  8791. // indices
  8792. // 1. you need three indices to draw a single face
  8793. // 2. a single segment consists of two faces
  8794. // 3. so we need to generate six (2*3) indices per segment
  8795. for ( iy = 0; iy < gridY; iy ++ ) {
  8796. for ( ix = 0; ix < gridX; ix ++ ) {
  8797. var a = numberOfVertices + ix + gridX1 * iy;
  8798. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  8799. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  8800. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  8801. // faces
  8802. indices.push( a, b, d );
  8803. indices.push( b, c, d );
  8804. // increase counter
  8805. groupCount += 6;
  8806. }
  8807. }
  8808. // add a group to the geometry. this will ensure multi material support
  8809. scope.addGroup( groupStart, groupCount, materialIndex );
  8810. // calculate new start value for groups
  8811. groupStart += groupCount;
  8812. // update total number of vertices
  8813. numberOfVertices += vertexCounter;
  8814. }
  8815. }
  8816. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  8817. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  8818. /**
  8819. * @author mrdoob / http://mrdoob.com/
  8820. * @author Mugen87 / https://github.com/Mugen87
  8821. */
  8822. // PlaneGeometry
  8823. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  8824. Geometry.call( this );
  8825. this.type = 'PlaneGeometry';
  8826. this.parameters = {
  8827. width: width,
  8828. height: height,
  8829. widthSegments: widthSegments,
  8830. heightSegments: heightSegments
  8831. };
  8832. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  8833. this.mergeVertices();
  8834. }
  8835. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  8836. PlaneGeometry.prototype.constructor = PlaneGeometry;
  8837. // PlaneBufferGeometry
  8838. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  8839. BufferGeometry.call( this );
  8840. this.type = 'PlaneBufferGeometry';
  8841. this.parameters = {
  8842. width: width,
  8843. height: height,
  8844. widthSegments: widthSegments,
  8845. heightSegments: heightSegments
  8846. };
  8847. var width_half = width / 2;
  8848. var height_half = height / 2;
  8849. var gridX = Math.floor( widthSegments ) || 1;
  8850. var gridY = Math.floor( heightSegments ) || 1;
  8851. var gridX1 = gridX + 1;
  8852. var gridY1 = gridY + 1;
  8853. var segment_width = width / gridX;
  8854. var segment_height = height / gridY;
  8855. var ix, iy;
  8856. // buffers
  8857. var indices = [];
  8858. var vertices = [];
  8859. var normals = [];
  8860. var uvs = [];
  8861. // generate vertices, normals and uvs
  8862. for ( iy = 0; iy < gridY1; iy ++ ) {
  8863. var y = iy * segment_height - height_half;
  8864. for ( ix = 0; ix < gridX1; ix ++ ) {
  8865. var x = ix * segment_width - width_half;
  8866. vertices.push( x, - y, 0 );
  8867. normals.push( 0, 0, 1 );
  8868. uvs.push( ix / gridX );
  8869. uvs.push( 1 - ( iy / gridY ) );
  8870. }
  8871. }
  8872. // indices
  8873. for ( iy = 0; iy < gridY; iy ++ ) {
  8874. for ( ix = 0; ix < gridX; ix ++ ) {
  8875. var a = ix + gridX1 * iy;
  8876. var b = ix + gridX1 * ( iy + 1 );
  8877. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8878. var d = ( ix + 1 ) + gridX1 * iy;
  8879. // faces
  8880. indices.push( a, b, d );
  8881. indices.push( b, c, d );
  8882. }
  8883. }
  8884. // build geometry
  8885. this.setIndex( indices );
  8886. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8887. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8888. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8889. }
  8890. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  8891. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  8892. /**
  8893. * @author mrdoob / http://mrdoob.com/
  8894. * @author alteredq / http://alteredqualia.com/
  8895. *
  8896. * parameters = {
  8897. * color: <hex>,
  8898. * opacity: <float>,
  8899. * map: new THREE.Texture( <Image> ),
  8900. *
  8901. * lightMap: new THREE.Texture( <Image> ),
  8902. * lightMapIntensity: <float>
  8903. *
  8904. * aoMap: new THREE.Texture( <Image> ),
  8905. * aoMapIntensity: <float>
  8906. *
  8907. * specularMap: new THREE.Texture( <Image> ),
  8908. *
  8909. * alphaMap: new THREE.Texture( <Image> ),
  8910. *
  8911. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8912. * combine: THREE.Multiply,
  8913. * reflectivity: <float>,
  8914. * refractionRatio: <float>,
  8915. *
  8916. * depthTest: <bool>,
  8917. * depthWrite: <bool>,
  8918. *
  8919. * wireframe: <boolean>,
  8920. * wireframeLinewidth: <float>,
  8921. *
  8922. * skinning: <bool>,
  8923. * morphTargets: <bool>
  8924. * }
  8925. */
  8926. function MeshBasicMaterial( parameters ) {
  8927. Material.call( this );
  8928. this.type = 'MeshBasicMaterial';
  8929. this.color = new Color( 0xffffff ); // emissive
  8930. this.map = null;
  8931. this.lightMap = null;
  8932. this.lightMapIntensity = 1.0;
  8933. this.aoMap = null;
  8934. this.aoMapIntensity = 1.0;
  8935. this.specularMap = null;
  8936. this.alphaMap = null;
  8937. this.envMap = null;
  8938. this.combine = MultiplyOperation;
  8939. this.reflectivity = 1;
  8940. this.refractionRatio = 0.98;
  8941. this.wireframe = false;
  8942. this.wireframeLinewidth = 1;
  8943. this.wireframeLinecap = 'round';
  8944. this.wireframeLinejoin = 'round';
  8945. this.skinning = false;
  8946. this.morphTargets = false;
  8947. this.lights = false;
  8948. this.setValues( parameters );
  8949. }
  8950. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  8951. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  8952. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  8953. MeshBasicMaterial.prototype.copy = function ( source ) {
  8954. Material.prototype.copy.call( this, source );
  8955. this.color.copy( source.color );
  8956. this.map = source.map;
  8957. this.lightMap = source.lightMap;
  8958. this.lightMapIntensity = source.lightMapIntensity;
  8959. this.aoMap = source.aoMap;
  8960. this.aoMapIntensity = source.aoMapIntensity;
  8961. this.specularMap = source.specularMap;
  8962. this.alphaMap = source.alphaMap;
  8963. this.envMap = source.envMap;
  8964. this.combine = source.combine;
  8965. this.reflectivity = source.reflectivity;
  8966. this.refractionRatio = source.refractionRatio;
  8967. this.wireframe = source.wireframe;
  8968. this.wireframeLinewidth = source.wireframeLinewidth;
  8969. this.wireframeLinecap = source.wireframeLinecap;
  8970. this.wireframeLinejoin = source.wireframeLinejoin;
  8971. this.skinning = source.skinning;
  8972. this.morphTargets = source.morphTargets;
  8973. return this;
  8974. };
  8975. /**
  8976. * @author bhouston / http://clara.io
  8977. */
  8978. function Ray( origin, direction ) {
  8979. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  8980. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  8981. }
  8982. Object.assign( Ray.prototype, {
  8983. set: function ( origin, direction ) {
  8984. this.origin.copy( origin );
  8985. this.direction.copy( direction );
  8986. return this;
  8987. },
  8988. clone: function () {
  8989. return new this.constructor().copy( this );
  8990. },
  8991. copy: function ( ray ) {
  8992. this.origin.copy( ray.origin );
  8993. this.direction.copy( ray.direction );
  8994. return this;
  8995. },
  8996. at: function ( t, optionalTarget ) {
  8997. var result = optionalTarget || new Vector3();
  8998. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  8999. },
  9000. lookAt: function ( v ) {
  9001. this.direction.copy( v ).sub( this.origin ).normalize();
  9002. return this;
  9003. },
  9004. recast: function () {
  9005. var v1 = new Vector3();
  9006. return function recast( t ) {
  9007. this.origin.copy( this.at( t, v1 ) );
  9008. return this;
  9009. };
  9010. }(),
  9011. closestPointToPoint: function ( point, optionalTarget ) {
  9012. var result = optionalTarget || new Vector3();
  9013. result.subVectors( point, this.origin );
  9014. var directionDistance = result.dot( this.direction );
  9015. if ( directionDistance < 0 ) {
  9016. return result.copy( this.origin );
  9017. }
  9018. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  9019. },
  9020. distanceToPoint: function ( point ) {
  9021. return Math.sqrt( this.distanceSqToPoint( point ) );
  9022. },
  9023. distanceSqToPoint: function () {
  9024. var v1 = new Vector3();
  9025. return function distanceSqToPoint( point ) {
  9026. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  9027. // point behind the ray
  9028. if ( directionDistance < 0 ) {
  9029. return this.origin.distanceToSquared( point );
  9030. }
  9031. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  9032. return v1.distanceToSquared( point );
  9033. };
  9034. }(),
  9035. distanceSqToSegment: function () {
  9036. var segCenter = new Vector3();
  9037. var segDir = new Vector3();
  9038. var diff = new Vector3();
  9039. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  9040. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  9041. // It returns the min distance between the ray and the segment
  9042. // defined by v0 and v1
  9043. // It can also set two optional targets :
  9044. // - The closest point on the ray
  9045. // - The closest point on the segment
  9046. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  9047. segDir.copy( v1 ).sub( v0 ).normalize();
  9048. diff.copy( this.origin ).sub( segCenter );
  9049. var segExtent = v0.distanceTo( v1 ) * 0.5;
  9050. var a01 = - this.direction.dot( segDir );
  9051. var b0 = diff.dot( this.direction );
  9052. var b1 = - diff.dot( segDir );
  9053. var c = diff.lengthSq();
  9054. var det = Math.abs( 1 - a01 * a01 );
  9055. var s0, s1, sqrDist, extDet;
  9056. if ( det > 0 ) {
  9057. // The ray and segment are not parallel.
  9058. s0 = a01 * b1 - b0;
  9059. s1 = a01 * b0 - b1;
  9060. extDet = segExtent * det;
  9061. if ( s0 >= 0 ) {
  9062. if ( s1 >= - extDet ) {
  9063. if ( s1 <= extDet ) {
  9064. // region 0
  9065. // Minimum at interior points of ray and segment.
  9066. var invDet = 1 / det;
  9067. s0 *= invDet;
  9068. s1 *= invDet;
  9069. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  9070. } else {
  9071. // region 1
  9072. s1 = segExtent;
  9073. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9074. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9075. }
  9076. } else {
  9077. // region 5
  9078. s1 = - segExtent;
  9079. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9080. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9081. }
  9082. } else {
  9083. if ( s1 <= - extDet ) {
  9084. // region 4
  9085. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  9086. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9087. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9088. } else if ( s1 <= extDet ) {
  9089. // region 3
  9090. s0 = 0;
  9091. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9092. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  9093. } else {
  9094. // region 2
  9095. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  9096. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9097. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9098. }
  9099. }
  9100. } else {
  9101. // Ray and segment are parallel.
  9102. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  9103. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9104. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9105. }
  9106. if ( optionalPointOnRay ) {
  9107. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  9108. }
  9109. if ( optionalPointOnSegment ) {
  9110. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  9111. }
  9112. return sqrDist;
  9113. };
  9114. }(),
  9115. intersectSphere: function () {
  9116. var v1 = new Vector3();
  9117. return function intersectSphere( sphere, optionalTarget ) {
  9118. v1.subVectors( sphere.center, this.origin );
  9119. var tca = v1.dot( this.direction );
  9120. var d2 = v1.dot( v1 ) - tca * tca;
  9121. var radius2 = sphere.radius * sphere.radius;
  9122. if ( d2 > radius2 ) return null;
  9123. var thc = Math.sqrt( radius2 - d2 );
  9124. // t0 = first intersect point - entrance on front of sphere
  9125. var t0 = tca - thc;
  9126. // t1 = second intersect point - exit point on back of sphere
  9127. var t1 = tca + thc;
  9128. // test to see if both t0 and t1 are behind the ray - if so, return null
  9129. if ( t0 < 0 && t1 < 0 ) return null;
  9130. // test to see if t0 is behind the ray:
  9131. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  9132. // in order to always return an intersect point that is in front of the ray.
  9133. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  9134. // else t0 is in front of the ray, so return the first collision point scaled by t0
  9135. return this.at( t0, optionalTarget );
  9136. };
  9137. }(),
  9138. intersectsSphere: function ( sphere ) {
  9139. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  9140. },
  9141. distanceToPlane: function ( plane ) {
  9142. var denominator = plane.normal.dot( this.direction );
  9143. if ( denominator === 0 ) {
  9144. // line is coplanar, return origin
  9145. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  9146. return 0;
  9147. }
  9148. // Null is preferable to undefined since undefined means.... it is undefined
  9149. return null;
  9150. }
  9151. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  9152. // Return if the ray never intersects the plane
  9153. return t >= 0 ? t : null;
  9154. },
  9155. intersectPlane: function ( plane, optionalTarget ) {
  9156. var t = this.distanceToPlane( plane );
  9157. if ( t === null ) {
  9158. return null;
  9159. }
  9160. return this.at( t, optionalTarget );
  9161. },
  9162. intersectsPlane: function ( plane ) {
  9163. // check if the ray lies on the plane first
  9164. var distToPoint = plane.distanceToPoint( this.origin );
  9165. if ( distToPoint === 0 ) {
  9166. return true;
  9167. }
  9168. var denominator = plane.normal.dot( this.direction );
  9169. if ( denominator * distToPoint < 0 ) {
  9170. return true;
  9171. }
  9172. // ray origin is behind the plane (and is pointing behind it)
  9173. return false;
  9174. },
  9175. intersectBox: function ( box, optionalTarget ) {
  9176. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  9177. var invdirx = 1 / this.direction.x,
  9178. invdiry = 1 / this.direction.y,
  9179. invdirz = 1 / this.direction.z;
  9180. var origin = this.origin;
  9181. if ( invdirx >= 0 ) {
  9182. tmin = ( box.min.x - origin.x ) * invdirx;
  9183. tmax = ( box.max.x - origin.x ) * invdirx;
  9184. } else {
  9185. tmin = ( box.max.x - origin.x ) * invdirx;
  9186. tmax = ( box.min.x - origin.x ) * invdirx;
  9187. }
  9188. if ( invdiry >= 0 ) {
  9189. tymin = ( box.min.y - origin.y ) * invdiry;
  9190. tymax = ( box.max.y - origin.y ) * invdiry;
  9191. } else {
  9192. tymin = ( box.max.y - origin.y ) * invdiry;
  9193. tymax = ( box.min.y - origin.y ) * invdiry;
  9194. }
  9195. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  9196. // These lines also handle the case where tmin or tmax is NaN
  9197. // (result of 0 * Infinity). x !== x returns true if x is NaN
  9198. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  9199. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  9200. if ( invdirz >= 0 ) {
  9201. tzmin = ( box.min.z - origin.z ) * invdirz;
  9202. tzmax = ( box.max.z - origin.z ) * invdirz;
  9203. } else {
  9204. tzmin = ( box.max.z - origin.z ) * invdirz;
  9205. tzmax = ( box.min.z - origin.z ) * invdirz;
  9206. }
  9207. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  9208. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  9209. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  9210. //return point closest to the ray (positive side)
  9211. if ( tmax < 0 ) return null;
  9212. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  9213. },
  9214. intersectsBox: ( function () {
  9215. var v = new Vector3();
  9216. return function intersectsBox( box ) {
  9217. return this.intersectBox( box, v ) !== null;
  9218. };
  9219. } )(),
  9220. intersectTriangle: function () {
  9221. // Compute the offset origin, edges, and normal.
  9222. var diff = new Vector3();
  9223. var edge1 = new Vector3();
  9224. var edge2 = new Vector3();
  9225. var normal = new Vector3();
  9226. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  9227. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  9228. edge1.subVectors( b, a );
  9229. edge2.subVectors( c, a );
  9230. normal.crossVectors( edge1, edge2 );
  9231. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  9232. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  9233. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  9234. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  9235. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  9236. var DdN = this.direction.dot( normal );
  9237. var sign;
  9238. if ( DdN > 0 ) {
  9239. if ( backfaceCulling ) return null;
  9240. sign = 1;
  9241. } else if ( DdN < 0 ) {
  9242. sign = - 1;
  9243. DdN = - DdN;
  9244. } else {
  9245. return null;
  9246. }
  9247. diff.subVectors( this.origin, a );
  9248. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  9249. // b1 < 0, no intersection
  9250. if ( DdQxE2 < 0 ) {
  9251. return null;
  9252. }
  9253. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  9254. // b2 < 0, no intersection
  9255. if ( DdE1xQ < 0 ) {
  9256. return null;
  9257. }
  9258. // b1+b2 > 1, no intersection
  9259. if ( DdQxE2 + DdE1xQ > DdN ) {
  9260. return null;
  9261. }
  9262. // Line intersects triangle, check if ray does.
  9263. var QdN = - sign * diff.dot( normal );
  9264. // t < 0, no intersection
  9265. if ( QdN < 0 ) {
  9266. return null;
  9267. }
  9268. // Ray intersects triangle.
  9269. return this.at( QdN / DdN, optionalTarget );
  9270. };
  9271. }(),
  9272. applyMatrix4: function ( matrix4 ) {
  9273. this.origin.applyMatrix4( matrix4 );
  9274. this.direction.transformDirection( matrix4 );
  9275. return this;
  9276. },
  9277. equals: function ( ray ) {
  9278. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  9279. }
  9280. } );
  9281. /**
  9282. * @author bhouston / http://clara.io
  9283. */
  9284. function Line3( start, end ) {
  9285. this.start = ( start !== undefined ) ? start : new Vector3();
  9286. this.end = ( end !== undefined ) ? end : new Vector3();
  9287. }
  9288. Object.assign( Line3.prototype, {
  9289. set: function ( start, end ) {
  9290. this.start.copy( start );
  9291. this.end.copy( end );
  9292. return this;
  9293. },
  9294. clone: function () {
  9295. return new this.constructor().copy( this );
  9296. },
  9297. copy: function ( line ) {
  9298. this.start.copy( line.start );
  9299. this.end.copy( line.end );
  9300. return this;
  9301. },
  9302. getCenter: function ( optionalTarget ) {
  9303. var result = optionalTarget || new Vector3();
  9304. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  9305. },
  9306. delta: function ( optionalTarget ) {
  9307. var result = optionalTarget || new Vector3();
  9308. return result.subVectors( this.end, this.start );
  9309. },
  9310. distanceSq: function () {
  9311. return this.start.distanceToSquared( this.end );
  9312. },
  9313. distance: function () {
  9314. return this.start.distanceTo( this.end );
  9315. },
  9316. at: function ( t, optionalTarget ) {
  9317. var result = optionalTarget || new Vector3();
  9318. return this.delta( result ).multiplyScalar( t ).add( this.start );
  9319. },
  9320. closestPointToPointParameter: function () {
  9321. var startP = new Vector3();
  9322. var startEnd = new Vector3();
  9323. return function closestPointToPointParameter( point, clampToLine ) {
  9324. startP.subVectors( point, this.start );
  9325. startEnd.subVectors( this.end, this.start );
  9326. var startEnd2 = startEnd.dot( startEnd );
  9327. var startEnd_startP = startEnd.dot( startP );
  9328. var t = startEnd_startP / startEnd2;
  9329. if ( clampToLine ) {
  9330. t = _Math.clamp( t, 0, 1 );
  9331. }
  9332. return t;
  9333. };
  9334. }(),
  9335. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  9336. var t = this.closestPointToPointParameter( point, clampToLine );
  9337. var result = optionalTarget || new Vector3();
  9338. return this.delta( result ).multiplyScalar( t ).add( this.start );
  9339. },
  9340. applyMatrix4: function ( matrix ) {
  9341. this.start.applyMatrix4( matrix );
  9342. this.end.applyMatrix4( matrix );
  9343. return this;
  9344. },
  9345. equals: function ( line ) {
  9346. return line.start.equals( this.start ) && line.end.equals( this.end );
  9347. }
  9348. } );
  9349. /**
  9350. * @author bhouston / http://clara.io
  9351. * @author mrdoob / http://mrdoob.com/
  9352. */
  9353. function Triangle( a, b, c ) {
  9354. this.a = ( a !== undefined ) ? a : new Vector3();
  9355. this.b = ( b !== undefined ) ? b : new Vector3();
  9356. this.c = ( c !== undefined ) ? c : new Vector3();
  9357. }
  9358. Object.assign( Triangle, {
  9359. normal: function () {
  9360. var v0 = new Vector3();
  9361. return function normal( a, b, c, optionalTarget ) {
  9362. var result = optionalTarget || new Vector3();
  9363. result.subVectors( c, b );
  9364. v0.subVectors( a, b );
  9365. result.cross( v0 );
  9366. var resultLengthSq = result.lengthSq();
  9367. if ( resultLengthSq > 0 ) {
  9368. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  9369. }
  9370. return result.set( 0, 0, 0 );
  9371. };
  9372. }(),
  9373. // static/instance method to calculate barycentric coordinates
  9374. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  9375. barycoordFromPoint: function () {
  9376. var v0 = new Vector3();
  9377. var v1 = new Vector3();
  9378. var v2 = new Vector3();
  9379. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  9380. v0.subVectors( c, a );
  9381. v1.subVectors( b, a );
  9382. v2.subVectors( point, a );
  9383. var dot00 = v0.dot( v0 );
  9384. var dot01 = v0.dot( v1 );
  9385. var dot02 = v0.dot( v2 );
  9386. var dot11 = v1.dot( v1 );
  9387. var dot12 = v1.dot( v2 );
  9388. var denom = ( dot00 * dot11 - dot01 * dot01 );
  9389. var result = optionalTarget || new Vector3();
  9390. // collinear or singular triangle
  9391. if ( denom === 0 ) {
  9392. // arbitrary location outside of triangle?
  9393. // not sure if this is the best idea, maybe should be returning undefined
  9394. return result.set( - 2, - 1, - 1 );
  9395. }
  9396. var invDenom = 1 / denom;
  9397. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  9398. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  9399. // barycentric coordinates must always sum to 1
  9400. return result.set( 1 - u - v, v, u );
  9401. };
  9402. }(),
  9403. containsPoint: function () {
  9404. var v1 = new Vector3();
  9405. return function containsPoint( point, a, b, c ) {
  9406. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  9407. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  9408. };
  9409. }()
  9410. } );
  9411. Object.assign( Triangle.prototype, {
  9412. set: function ( a, b, c ) {
  9413. this.a.copy( a );
  9414. this.b.copy( b );
  9415. this.c.copy( c );
  9416. return this;
  9417. },
  9418. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  9419. this.a.copy( points[ i0 ] );
  9420. this.b.copy( points[ i1 ] );
  9421. this.c.copy( points[ i2 ] );
  9422. return this;
  9423. },
  9424. clone: function () {
  9425. return new this.constructor().copy( this );
  9426. },
  9427. copy: function ( triangle ) {
  9428. this.a.copy( triangle.a );
  9429. this.b.copy( triangle.b );
  9430. this.c.copy( triangle.c );
  9431. return this;
  9432. },
  9433. area: function () {
  9434. var v0 = new Vector3();
  9435. var v1 = new Vector3();
  9436. return function area() {
  9437. v0.subVectors( this.c, this.b );
  9438. v1.subVectors( this.a, this.b );
  9439. return v0.cross( v1 ).length() * 0.5;
  9440. };
  9441. }(),
  9442. midpoint: function ( optionalTarget ) {
  9443. var result = optionalTarget || new Vector3();
  9444. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  9445. },
  9446. normal: function ( optionalTarget ) {
  9447. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  9448. },
  9449. plane: function ( optionalTarget ) {
  9450. var result = optionalTarget || new Plane();
  9451. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  9452. },
  9453. barycoordFromPoint: function ( point, optionalTarget ) {
  9454. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  9455. },
  9456. containsPoint: function ( point ) {
  9457. return Triangle.containsPoint( point, this.a, this.b, this.c );
  9458. },
  9459. closestPointToPoint: function () {
  9460. var plane = new Plane();
  9461. var edgeList = [ new Line3(), new Line3(), new Line3() ];
  9462. var projectedPoint = new Vector3();
  9463. var closestPoint = new Vector3();
  9464. return function closestPointToPoint( point, optionalTarget ) {
  9465. var result = optionalTarget || new Vector3();
  9466. var minDistance = Infinity;
  9467. // project the point onto the plane of the triangle
  9468. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  9469. plane.projectPoint( point, projectedPoint );
  9470. // check if the projection lies within the triangle
  9471. if( this.containsPoint( projectedPoint ) === true ) {
  9472. // if so, this is the closest point
  9473. result.copy( projectedPoint );
  9474. } else {
  9475. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  9476. edgeList[ 0 ].set( this.a, this.b );
  9477. edgeList[ 1 ].set( this.b, this.c );
  9478. edgeList[ 2 ].set( this.c, this.a );
  9479. for( var i = 0; i < edgeList.length; i ++ ) {
  9480. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  9481. var distance = projectedPoint.distanceToSquared( closestPoint );
  9482. if( distance < minDistance ) {
  9483. minDistance = distance;
  9484. result.copy( closestPoint );
  9485. }
  9486. }
  9487. }
  9488. return result;
  9489. };
  9490. }(),
  9491. equals: function ( triangle ) {
  9492. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  9493. }
  9494. } );
  9495. /**
  9496. * @author mrdoob / http://mrdoob.com/
  9497. * @author alteredq / http://alteredqualia.com/
  9498. * @author mikael emtinger / http://gomo.se/
  9499. * @author jonobr1 / http://jonobr1.com/
  9500. */
  9501. function Mesh( geometry, material ) {
  9502. Object3D.call( this );
  9503. this.type = 'Mesh';
  9504. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  9505. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9506. this.drawMode = TrianglesDrawMode;
  9507. this.updateMorphTargets();
  9508. }
  9509. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  9510. constructor: Mesh,
  9511. isMesh: true,
  9512. setDrawMode: function ( value ) {
  9513. this.drawMode = value;
  9514. },
  9515. copy: function ( source ) {
  9516. Object3D.prototype.copy.call( this, source );
  9517. this.drawMode = source.drawMode;
  9518. return this;
  9519. },
  9520. updateMorphTargets: function () {
  9521. var geometry = this.geometry;
  9522. var m, ml, name;
  9523. if ( geometry.isBufferGeometry ) {
  9524. var morphAttributes = geometry.morphAttributes;
  9525. var keys = Object.keys( morphAttributes );
  9526. if ( keys.length > 0 ) {
  9527. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  9528. if ( morphAttribute !== undefined ) {
  9529. this.morphTargetInfluences = [];
  9530. this.morphTargetDictionary = {};
  9531. for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  9532. name = morphAttribute[ m ].name || String( m );
  9533. this.morphTargetInfluences.push( 0 );
  9534. this.morphTargetDictionary[ name ] = m;
  9535. }
  9536. }
  9537. }
  9538. } else {
  9539. var morphTargets = geometry.morphTargets;
  9540. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  9541. this.morphTargetInfluences = [];
  9542. this.morphTargetDictionary = {};
  9543. for ( m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  9544. name = morphTargets[ m ].name || String( m );
  9545. this.morphTargetInfluences.push( 0 );
  9546. this.morphTargetDictionary[ name ] = m;
  9547. }
  9548. }
  9549. }
  9550. },
  9551. raycast: ( function () {
  9552. var inverseMatrix = new Matrix4();
  9553. var ray = new Ray();
  9554. var sphere = new Sphere();
  9555. var vA = new Vector3();
  9556. var vB = new Vector3();
  9557. var vC = new Vector3();
  9558. var tempA = new Vector3();
  9559. var tempB = new Vector3();
  9560. var tempC = new Vector3();
  9561. var uvA = new Vector2();
  9562. var uvB = new Vector2();
  9563. var uvC = new Vector2();
  9564. var barycoord = new Vector3();
  9565. var intersectionPoint = new Vector3();
  9566. var intersectionPointWorld = new Vector3();
  9567. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  9568. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  9569. uv1.multiplyScalar( barycoord.x );
  9570. uv2.multiplyScalar( barycoord.y );
  9571. uv3.multiplyScalar( barycoord.z );
  9572. uv1.add( uv2 ).add( uv3 );
  9573. return uv1.clone();
  9574. }
  9575. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  9576. var intersect;
  9577. if ( material.side === BackSide ) {
  9578. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  9579. } else {
  9580. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  9581. }
  9582. if ( intersect === null ) return null;
  9583. intersectionPointWorld.copy( point );
  9584. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  9585. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  9586. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  9587. return {
  9588. distance: distance,
  9589. point: intersectionPointWorld.clone(),
  9590. object: object
  9591. };
  9592. }
  9593. function checkBufferGeometryIntersection( object, raycaster, ray, position, uv, a, b, c ) {
  9594. vA.fromBufferAttribute( position, a );
  9595. vB.fromBufferAttribute( position, b );
  9596. vC.fromBufferAttribute( position, c );
  9597. var intersection = checkIntersection( object, object.material, raycaster, ray, vA, vB, vC, intersectionPoint );
  9598. if ( intersection ) {
  9599. if ( uv ) {
  9600. uvA.fromBufferAttribute( uv, a );
  9601. uvB.fromBufferAttribute( uv, b );
  9602. uvC.fromBufferAttribute( uv, c );
  9603. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  9604. }
  9605. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  9606. intersection.faceIndex = a;
  9607. }
  9608. return intersection;
  9609. }
  9610. return function raycast( raycaster, intersects ) {
  9611. var geometry = this.geometry;
  9612. var material = this.material;
  9613. var matrixWorld = this.matrixWorld;
  9614. if ( material === undefined ) return;
  9615. // Checking boundingSphere distance to ray
  9616. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9617. sphere.copy( geometry.boundingSphere );
  9618. sphere.applyMatrix4( matrixWorld );
  9619. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  9620. //
  9621. inverseMatrix.getInverse( matrixWorld );
  9622. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9623. // Check boundingBox before continuing
  9624. if ( geometry.boundingBox !== null ) {
  9625. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  9626. }
  9627. var intersection;
  9628. if ( geometry.isBufferGeometry ) {
  9629. var a, b, c;
  9630. var index = geometry.index;
  9631. var position = geometry.attributes.position;
  9632. var uv = geometry.attributes.uv;
  9633. var i, l;
  9634. if ( index !== null ) {
  9635. // indexed buffer geometry
  9636. for ( i = 0, l = index.count; i < l; i += 3 ) {
  9637. a = index.getX( i );
  9638. b = index.getX( i + 1 );
  9639. c = index.getX( i + 2 );
  9640. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  9641. if ( intersection ) {
  9642. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  9643. intersects.push( intersection );
  9644. }
  9645. }
  9646. } else {
  9647. // non-indexed buffer geometry
  9648. for ( i = 0, l = position.count; i < l; i += 3 ) {
  9649. a = i;
  9650. b = i + 1;
  9651. c = i + 2;
  9652. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  9653. if ( intersection ) {
  9654. intersection.index = a; // triangle number in positions buffer semantics
  9655. intersects.push( intersection );
  9656. }
  9657. }
  9658. }
  9659. } else if ( geometry.isGeometry ) {
  9660. var fvA, fvB, fvC;
  9661. var isMultiMaterial = Array.isArray( material );
  9662. var vertices = geometry.vertices;
  9663. var faces = geometry.faces;
  9664. var uvs;
  9665. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  9666. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  9667. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  9668. var face = faces[ f ];
  9669. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  9670. if ( faceMaterial === undefined ) continue;
  9671. fvA = vertices[ face.a ];
  9672. fvB = vertices[ face.b ];
  9673. fvC = vertices[ face.c ];
  9674. if ( faceMaterial.morphTargets === true ) {
  9675. var morphTargets = geometry.morphTargets;
  9676. var morphInfluences = this.morphTargetInfluences;
  9677. vA.set( 0, 0, 0 );
  9678. vB.set( 0, 0, 0 );
  9679. vC.set( 0, 0, 0 );
  9680. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  9681. var influence = morphInfluences[ t ];
  9682. if ( influence === 0 ) continue;
  9683. var targets = morphTargets[ t ].vertices;
  9684. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  9685. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  9686. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  9687. }
  9688. vA.add( fvA );
  9689. vB.add( fvB );
  9690. vC.add( fvC );
  9691. fvA = vA;
  9692. fvB = vB;
  9693. fvC = vC;
  9694. }
  9695. intersection = checkIntersection( this, faceMaterial, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  9696. if ( intersection ) {
  9697. if ( uvs && uvs[ f ] ) {
  9698. var uvs_f = uvs[ f ];
  9699. uvA.copy( uvs_f[ 0 ] );
  9700. uvB.copy( uvs_f[ 1 ] );
  9701. uvC.copy( uvs_f[ 2 ] );
  9702. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  9703. }
  9704. intersection.face = face;
  9705. intersection.faceIndex = f;
  9706. intersects.push( intersection );
  9707. }
  9708. }
  9709. }
  9710. };
  9711. }() ),
  9712. clone: function () {
  9713. return new this.constructor( this.geometry, this.material ).copy( this );
  9714. }
  9715. } );
  9716. /**
  9717. * @author mrdoob / http://mrdoob.com/
  9718. */
  9719. function WebGLBackground( renderer, state, geometries, premultipliedAlpha ) {
  9720. var clearColor = new Color( 0x000000 );
  9721. var clearAlpha = 0;
  9722. var planeCamera, planeMesh;
  9723. var boxMesh;
  9724. function render( renderList, scene, camera, forceClear ) {
  9725. var background = scene.background;
  9726. if ( background === null ) {
  9727. setClear( clearColor, clearAlpha );
  9728. } else if ( background && background.isColor ) {
  9729. setClear( background, 1 );
  9730. forceClear = true;
  9731. }
  9732. if ( renderer.autoClear || forceClear ) {
  9733. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  9734. }
  9735. if ( background && background.isCubeTexture ) {
  9736. if ( boxMesh === undefined ) {
  9737. // TODO Adjust skybox to camera somehow
  9738. boxMesh = new Mesh(
  9739. new BoxBufferGeometry( 5, 5, 5 ),
  9740. new ShaderMaterial( {
  9741. uniforms: ShaderLib.cube.uniforms,
  9742. vertexShader: ShaderLib.cube.vertexShader,
  9743. fragmentShader: ShaderLib.cube.fragmentShader,
  9744. side: BackSide,
  9745. depthTest: false,
  9746. depthWrite: false,
  9747. fog: false
  9748. } )
  9749. );
  9750. geometries.update( boxMesh.geometry );
  9751. }
  9752. boxMesh.material.uniforms.tCube.value = background;
  9753. boxMesh.matrixWorld.copyPosition( camera.matrixWorld );
  9754. renderList.push( boxMesh, boxMesh.geometry, boxMesh.material, 0, null );
  9755. // TOFIX Ideally background should be rendered last
  9756. renderList.opaque.unshift( renderList.opaque.pop() ); // Hack to make sure background gets rendered first
  9757. } else if ( background && background.isTexture ) {
  9758. if ( planeCamera === undefined ) {
  9759. planeCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  9760. planeMesh = new Mesh(
  9761. new PlaneBufferGeometry( 2, 2 ),
  9762. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  9763. );
  9764. geometries.update( planeMesh.geometry );
  9765. }
  9766. planeMesh.material.map = background;
  9767. // TODO Push this to renderList
  9768. renderer.renderBufferDirect( planeCamera, null, planeMesh.geometry, planeMesh.material, planeMesh, null );
  9769. }
  9770. }
  9771. function setClear( color, alpha ) {
  9772. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  9773. }
  9774. return {
  9775. getClearColor: function () {
  9776. return clearColor;
  9777. },
  9778. setClearColor: function ( color, alpha ) {
  9779. clearColor.set( color );
  9780. clearAlpha = alpha !== undefined ? alpha : 1;
  9781. setClear( clearColor, clearAlpha );
  9782. },
  9783. getClearAlpha: function () {
  9784. return clearAlpha;
  9785. },
  9786. setClearAlpha: function ( alpha ) {
  9787. clearAlpha = alpha;
  9788. setClear( clearColor, clearAlpha );
  9789. },
  9790. render: render
  9791. };
  9792. }
  9793. /**
  9794. * @author mrdoob / http://mrdoob.com/
  9795. */
  9796. function painterSortStable( a, b ) {
  9797. if ( a.renderOrder !== b.renderOrder ) {
  9798. return a.renderOrder - b.renderOrder;
  9799. } else if ( a.program && b.program && a.program !== b.program ) {
  9800. return a.program.id - b.program.id;
  9801. } else if ( a.material.id !== b.material.id ) {
  9802. return a.material.id - b.material.id;
  9803. } else if ( a.z !== b.z ) {
  9804. return a.z - b.z;
  9805. } else {
  9806. return a.id - b.id;
  9807. }
  9808. }
  9809. function reversePainterSortStable( a, b ) {
  9810. if ( a.renderOrder !== b.renderOrder ) {
  9811. return a.renderOrder - b.renderOrder;
  9812. } if ( a.z !== b.z ) {
  9813. return b.z - a.z;
  9814. } else {
  9815. return a.id - b.id;
  9816. }
  9817. }
  9818. function WebGLRenderList() {
  9819. var renderItems = [];
  9820. var renderItemsIndex = 0;
  9821. var opaque = [];
  9822. var transparent = [];
  9823. function init() {
  9824. renderItemsIndex = 0;
  9825. opaque.length = 0;
  9826. transparent.length = 0;
  9827. }
  9828. function push( object, geometry, material, z, group ) {
  9829. var renderItem = renderItems[ renderItemsIndex ];
  9830. if ( renderItem === undefined ) {
  9831. renderItem = {
  9832. id: object.id,
  9833. object: object,
  9834. geometry: geometry,
  9835. material: material,
  9836. program: material.program,
  9837. renderOrder: object.renderOrder,
  9838. z: z,
  9839. group: group
  9840. };
  9841. renderItems[ renderItemsIndex ] = renderItem;
  9842. } else {
  9843. renderItem.id = object.id;
  9844. renderItem.object = object;
  9845. renderItem.geometry = geometry;
  9846. renderItem.material = material;
  9847. renderItem.program = material.program;
  9848. renderItem.renderOrder = object.renderOrder;
  9849. renderItem.z = z;
  9850. renderItem.group = group;
  9851. }
  9852. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  9853. renderItemsIndex ++;
  9854. }
  9855. function sort() {
  9856. if ( opaque.length > 1 ) opaque.sort( painterSortStable );
  9857. if ( transparent.length > 1 ) transparent.sort( reversePainterSortStable );
  9858. }
  9859. return {
  9860. opaque: opaque,
  9861. transparent: transparent,
  9862. init: init,
  9863. push: push,
  9864. sort: sort
  9865. };
  9866. }
  9867. function WebGLRenderLists() {
  9868. var lists = {};
  9869. function get( scene, camera ) {
  9870. var hash = scene.id + ',' + camera.id;
  9871. var list = lists[ hash ];
  9872. if ( list === undefined ) {
  9873. // console.log( 'THREE.WebGLRenderLists:', hash );
  9874. list = new WebGLRenderList();
  9875. lists[ hash ] = list;
  9876. }
  9877. return list;
  9878. }
  9879. function dispose() {
  9880. lists = {};
  9881. }
  9882. return {
  9883. get: get,
  9884. dispose: dispose
  9885. };
  9886. }
  9887. /**
  9888. * @author mrdoob / http://mrdoob.com/
  9889. */
  9890. function absNumericalSort( a, b ) {
  9891. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  9892. }
  9893. function WebGLMorphtargets( gl ) {
  9894. var influencesList = {};
  9895. var morphInfluences = new Float32Array( 8 );
  9896. function update( object, geometry, material, program ) {
  9897. var objectInfluences = object.morphTargetInfluences;
  9898. var length = objectInfluences.length;
  9899. var influences = influencesList[ geometry.id ];
  9900. if ( influences === undefined ) {
  9901. // initialise list
  9902. influences = [];
  9903. for ( var i = 0; i < length; i ++ ) {
  9904. influences[ i ] = [ i, 0 ];
  9905. }
  9906. influencesList[ geometry.id ] = influences;
  9907. }
  9908. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  9909. var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  9910. // Remove current morphAttributes
  9911. for ( var i = 0; i < length; i ++ ) {
  9912. var influence = influences[ i ];
  9913. if ( influence[ 1 ] !== 0 ) {
  9914. if ( morphTargets ) geometry.removeAttribute( 'morphTarget' + i );
  9915. if ( morphNormals ) geometry.removeAttribute( 'morphNormal' + i );
  9916. }
  9917. }
  9918. // Collect influences
  9919. for ( var i = 0; i < length; i ++ ) {
  9920. var influence = influences[ i ];
  9921. influence[ 0 ] = i;
  9922. influence[ 1 ] = objectInfluences[ i ];
  9923. }
  9924. influences.sort( absNumericalSort );
  9925. // Add morphAttributes
  9926. for ( var i = 0; i < 8; i ++ ) {
  9927. var influence = influences[ i ];
  9928. if ( influence ) {
  9929. var index = influence[ 0 ];
  9930. var value = influence[ 1 ];
  9931. if ( value ) {
  9932. if ( morphTargets ) geometry.addAttribute( 'morphTarget' + i, morphTargets[ index ] );
  9933. if ( morphNormals ) geometry.addAttribute( 'morphNormal' + i, morphNormals[ index ] );
  9934. morphInfluences[ i ] = value;
  9935. continue;
  9936. }
  9937. }
  9938. morphInfluences[ i ] = 0;
  9939. }
  9940. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  9941. }
  9942. return {
  9943. update: update
  9944. }
  9945. }
  9946. /**
  9947. * @author mrdoob / http://mrdoob.com/
  9948. */
  9949. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  9950. var mode;
  9951. function setMode( value ) {
  9952. mode = value;
  9953. }
  9954. var type, bytesPerElement;
  9955. function setIndex( value ) {
  9956. type = value.type;
  9957. bytesPerElement = value.bytesPerElement;
  9958. }
  9959. function render( start, count ) {
  9960. gl.drawElements( mode, count, type, start * bytesPerElement );
  9961. infoRender.calls ++;
  9962. infoRender.vertices += count;
  9963. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9964. else if ( mode === gl.POINTS ) infoRender.points += count;
  9965. }
  9966. function renderInstances( geometry, start, count ) {
  9967. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9968. if ( extension === null ) {
  9969. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9970. return;
  9971. }
  9972. extension.drawElementsInstancedANGLE( mode, count, type, start * bytesPerElement, geometry.maxInstancedCount );
  9973. infoRender.calls ++;
  9974. infoRender.vertices += count * geometry.maxInstancedCount;
  9975. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9976. else if ( mode === gl.POINTS ) infoRender.points += geometry.maxInstancedCount * count;
  9977. }
  9978. //
  9979. this.setMode = setMode;
  9980. this.setIndex = setIndex;
  9981. this.render = render;
  9982. this.renderInstances = renderInstances;
  9983. }
  9984. /**
  9985. * @author mrdoob / http://mrdoob.com/
  9986. */
  9987. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  9988. var mode;
  9989. function setMode( value ) {
  9990. mode = value;
  9991. }
  9992. function render( start, count ) {
  9993. gl.drawArrays( mode, start, count );
  9994. infoRender.calls ++;
  9995. infoRender.vertices += count;
  9996. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9997. else if ( mode === gl.POINTS ) infoRender.points += count;
  9998. }
  9999. function renderInstances( geometry, start, count ) {
  10000. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  10001. if ( extension === null ) {
  10002. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10003. return;
  10004. }
  10005. var position = geometry.attributes.position;
  10006. if ( position.isInterleavedBufferAttribute ) {
  10007. count = position.data.count;
  10008. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  10009. } else {
  10010. extension.drawArraysInstancedANGLE( mode, start, count, geometry.maxInstancedCount );
  10011. }
  10012. infoRender.calls ++;
  10013. infoRender.vertices += count * geometry.maxInstancedCount;
  10014. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  10015. else if ( mode === gl.POINTS ) infoRender.points += geometry.maxInstancedCount * count;
  10016. }
  10017. //
  10018. this.setMode = setMode;
  10019. this.render = render;
  10020. this.renderInstances = renderInstances;
  10021. }
  10022. /**
  10023. * @author mrdoob / http://mrdoob.com/
  10024. */
  10025. function WebGLGeometries( gl, attributes, infoMemory ) {
  10026. var geometries = {};
  10027. var wireframeAttributes = {};
  10028. function onGeometryDispose( event ) {
  10029. var geometry = event.target;
  10030. var buffergeometry = geometries[ geometry.id ];
  10031. if ( buffergeometry.index !== null ) {
  10032. attributes.remove( buffergeometry.index );
  10033. }
  10034. for ( var name in buffergeometry.attributes ) {
  10035. attributes.remove( buffergeometry.attributes[ name ] );
  10036. }
  10037. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10038. delete geometries[ geometry.id ];
  10039. // TODO Remove duplicate code
  10040. var attribute = wireframeAttributes[ geometry.id ];
  10041. if ( attribute ) {
  10042. attributes.remove( attribute );
  10043. delete wireframeAttributes[ geometry.id ];
  10044. }
  10045. attribute = wireframeAttributes[ buffergeometry.id ];
  10046. if ( attribute ) {
  10047. attributes.remove( attribute );
  10048. delete wireframeAttributes[ buffergeometry.id ];
  10049. }
  10050. //
  10051. infoMemory.geometries --;
  10052. }
  10053. function get( object, geometry ) {
  10054. var buffergeometry = geometries[ geometry.id ];
  10055. if ( buffergeometry ) return buffergeometry;
  10056. geometry.addEventListener( 'dispose', onGeometryDispose );
  10057. if ( geometry.isBufferGeometry ) {
  10058. buffergeometry = geometry;
  10059. } else if ( geometry.isGeometry ) {
  10060. if ( geometry._bufferGeometry === undefined ) {
  10061. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  10062. }
  10063. buffergeometry = geometry._bufferGeometry;
  10064. }
  10065. geometries[ geometry.id ] = buffergeometry;
  10066. infoMemory.geometries ++;
  10067. return buffergeometry;
  10068. }
  10069. function update( geometry ) {
  10070. var index = geometry.index;
  10071. var geometryAttributes = geometry.attributes;
  10072. if ( index !== null ) {
  10073. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  10074. }
  10075. for ( var name in geometryAttributes ) {
  10076. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  10077. }
  10078. // morph targets
  10079. var morphAttributes = geometry.morphAttributes;
  10080. for ( var name in morphAttributes ) {
  10081. var array = morphAttributes[ name ];
  10082. for ( var i = 0, l = array.length; i < l; i ++ ) {
  10083. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  10084. }
  10085. }
  10086. }
  10087. function getWireframeAttribute( geometry ) {
  10088. var attribute = wireframeAttributes[ geometry.id ];
  10089. if ( attribute ) return attribute;
  10090. var indices = [];
  10091. var geometryIndex = geometry.index;
  10092. var geometryAttributes = geometry.attributes;
  10093. // console.time( 'wireframe' );
  10094. if ( geometryIndex !== null ) {
  10095. var array = geometryIndex.array;
  10096. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  10097. var a = array[ i + 0 ];
  10098. var b = array[ i + 1 ];
  10099. var c = array[ i + 2 ];
  10100. indices.push( a, b, b, c, c, a );
  10101. }
  10102. } else {
  10103. var array = geometryAttributes.position.array;
  10104. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10105. var a = i + 0;
  10106. var b = i + 1;
  10107. var c = i + 2;
  10108. indices.push( a, b, b, c, c, a );
  10109. }
  10110. }
  10111. // console.timeEnd( 'wireframe' );
  10112. attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10113. attributes.update( attribute, gl.ELEMENT_ARRAY_BUFFER );
  10114. wireframeAttributes[ geometry.id ] = attribute;
  10115. return attribute;
  10116. }
  10117. return {
  10118. get: get,
  10119. update: update,
  10120. getWireframeAttribute: getWireframeAttribute
  10121. };
  10122. }
  10123. /**
  10124. * @author mrdoob / http://mrdoob.com/
  10125. */
  10126. function UniformsCache() {
  10127. var lights = {};
  10128. return {
  10129. get: function ( light ) {
  10130. if ( lights[ light.id ] !== undefined ) {
  10131. return lights[ light.id ];
  10132. }
  10133. var uniforms;
  10134. switch ( light.type ) {
  10135. case 'DirectionalLight':
  10136. uniforms = {
  10137. direction: new Vector3(),
  10138. color: new Color(),
  10139. shadow: false,
  10140. shadowBias: 0,
  10141. shadowRadius: 1,
  10142. shadowMapSize: new Vector2()
  10143. };
  10144. break;
  10145. case 'SpotLight':
  10146. uniforms = {
  10147. position: new Vector3(),
  10148. direction: new Vector3(),
  10149. color: new Color(),
  10150. distance: 0,
  10151. coneCos: 0,
  10152. penumbraCos: 0,
  10153. decay: 0,
  10154. shadow: false,
  10155. shadowBias: 0,
  10156. shadowRadius: 1,
  10157. shadowMapSize: new Vector2()
  10158. };
  10159. break;
  10160. case 'PointLight':
  10161. uniforms = {
  10162. position: new Vector3(),
  10163. color: new Color(),
  10164. distance: 0,
  10165. decay: 0,
  10166. shadow: false,
  10167. shadowBias: 0,
  10168. shadowRadius: 1,
  10169. shadowMapSize: new Vector2(),
  10170. shadowCameraNear: 1,
  10171. shadowCameraFar: 1000
  10172. };
  10173. break;
  10174. case 'HemisphereLight':
  10175. uniforms = {
  10176. direction: new Vector3(),
  10177. skyColor: new Color(),
  10178. groundColor: new Color()
  10179. };
  10180. break;
  10181. case 'RectAreaLight':
  10182. uniforms = {
  10183. color: new Color(),
  10184. position: new Vector3(),
  10185. halfWidth: new Vector3(),
  10186. halfHeight: new Vector3()
  10187. // TODO (abelnation): set RectAreaLight shadow uniforms
  10188. };
  10189. break;
  10190. }
  10191. lights[ light.id ] = uniforms;
  10192. return uniforms;
  10193. }
  10194. };
  10195. }
  10196. function WebGLLights() {
  10197. var cache = new UniformsCache();
  10198. var state = {
  10199. hash: '',
  10200. ambient: [ 0, 0, 0 ],
  10201. directional: [],
  10202. directionalShadowMap: [],
  10203. directionalShadowMatrix: [],
  10204. spot: [],
  10205. spotShadowMap: [],
  10206. spotShadowMatrix: [],
  10207. rectArea: [],
  10208. point: [],
  10209. pointShadowMap: [],
  10210. pointShadowMatrix: [],
  10211. hemi: []
  10212. };
  10213. var vector3 = new Vector3();
  10214. var matrix4 = new Matrix4();
  10215. var matrix42 = new Matrix4();
  10216. function setup( lights, shadows, camera ) {
  10217. var r = 0, g = 0, b = 0;
  10218. var directionalLength = 0;
  10219. var pointLength = 0;
  10220. var spotLength = 0;
  10221. var rectAreaLength = 0;
  10222. var hemiLength = 0;
  10223. var viewMatrix = camera.matrixWorldInverse;
  10224. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  10225. var light = lights[ i ];
  10226. var color = light.color;
  10227. var intensity = light.intensity;
  10228. var distance = light.distance;
  10229. var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  10230. if ( light.isAmbientLight ) {
  10231. r += color.r * intensity;
  10232. g += color.g * intensity;
  10233. b += color.b * intensity;
  10234. } else if ( light.isDirectionalLight ) {
  10235. var uniforms = cache.get( light );
  10236. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  10237. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  10238. vector3.setFromMatrixPosition( light.target.matrixWorld );
  10239. uniforms.direction.sub( vector3 );
  10240. uniforms.direction.transformDirection( viewMatrix );
  10241. uniforms.shadow = light.castShadow;
  10242. if ( light.castShadow ) {
  10243. var shadow = light.shadow;
  10244. uniforms.shadowBias = shadow.bias;
  10245. uniforms.shadowRadius = shadow.radius;
  10246. uniforms.shadowMapSize = shadow.mapSize;
  10247. }
  10248. state.directionalShadowMap[ directionalLength ] = shadowMap;
  10249. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  10250. state.directional[ directionalLength ] = uniforms;
  10251. directionalLength ++;
  10252. } else if ( light.isSpotLight ) {
  10253. var uniforms = cache.get( light );
  10254. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  10255. uniforms.position.applyMatrix4( viewMatrix );
  10256. uniforms.color.copy( color ).multiplyScalar( intensity );
  10257. uniforms.distance = distance;
  10258. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  10259. vector3.setFromMatrixPosition( light.target.matrixWorld );
  10260. uniforms.direction.sub( vector3 );
  10261. uniforms.direction.transformDirection( viewMatrix );
  10262. uniforms.coneCos = Math.cos( light.angle );
  10263. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  10264. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  10265. uniforms.shadow = light.castShadow;
  10266. if ( light.castShadow ) {
  10267. var shadow = light.shadow;
  10268. uniforms.shadowBias = shadow.bias;
  10269. uniforms.shadowRadius = shadow.radius;
  10270. uniforms.shadowMapSize = shadow.mapSize;
  10271. }
  10272. state.spotShadowMap[ spotLength ] = shadowMap;
  10273. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  10274. state.spot[ spotLength ] = uniforms;
  10275. spotLength ++;
  10276. } else if ( light.isRectAreaLight ) {
  10277. var uniforms = cache.get( light );
  10278. // (a) intensity controls irradiance of entire light
  10279. uniforms.color
  10280. .copy( color )
  10281. .multiplyScalar( intensity / ( light.width * light.height ) );
  10282. // (b) intensity controls the radiance per light area
  10283. // uniforms.color.copy( color ).multiplyScalar( intensity );
  10284. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  10285. uniforms.position.applyMatrix4( viewMatrix );
  10286. // extract local rotation of light to derive width/height half vectors
  10287. matrix42.identity();
  10288. matrix4.copy( light.matrixWorld );
  10289. matrix4.premultiply( viewMatrix );
  10290. matrix42.extractRotation( matrix4 );
  10291. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  10292. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  10293. uniforms.halfWidth.applyMatrix4( matrix42 );
  10294. uniforms.halfHeight.applyMatrix4( matrix42 );
  10295. // TODO (abelnation): RectAreaLight distance?
  10296. // uniforms.distance = distance;
  10297. state.rectArea[ rectAreaLength ] = uniforms;
  10298. rectAreaLength ++;
  10299. } else if ( light.isPointLight ) {
  10300. var uniforms = cache.get( light );
  10301. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  10302. uniforms.position.applyMatrix4( viewMatrix );
  10303. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  10304. uniforms.distance = light.distance;
  10305. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  10306. uniforms.shadow = light.castShadow;
  10307. if ( light.castShadow ) {
  10308. var shadow = light.shadow;
  10309. uniforms.shadowBias = shadow.bias;
  10310. uniforms.shadowRadius = shadow.radius;
  10311. uniforms.shadowMapSize = shadow.mapSize;
  10312. uniforms.shadowCameraNear = shadow.camera.near;
  10313. uniforms.shadowCameraFar = shadow.camera.far;
  10314. }
  10315. state.pointShadowMap[ pointLength ] = shadowMap;
  10316. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  10317. state.point[ pointLength ] = uniforms;
  10318. pointLength ++;
  10319. } else if ( light.isHemisphereLight ) {
  10320. var uniforms = cache.get( light );
  10321. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  10322. uniforms.direction.transformDirection( viewMatrix );
  10323. uniforms.direction.normalize();
  10324. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  10325. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  10326. state.hemi[ hemiLength ] = uniforms;
  10327. hemiLength ++;
  10328. }
  10329. }
  10330. state.ambient[ 0 ] = r;
  10331. state.ambient[ 1 ] = g;
  10332. state.ambient[ 2 ] = b;
  10333. state.directional.length = directionalLength;
  10334. state.spot.length = spotLength;
  10335. state.rectArea.length = rectAreaLength;
  10336. state.point.length = pointLength;
  10337. state.hemi.length = hemiLength;
  10338. // TODO (sam-g-steel) why aren't we using join
  10339. state.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + shadows.length;
  10340. }
  10341. return {
  10342. setup: setup,
  10343. state: state
  10344. }
  10345. }
  10346. /**
  10347. * @author mrdoob / http://mrdoob.com/
  10348. */
  10349. function WebGLObjects( geometries, infoRender ) {
  10350. var updateList = {};
  10351. function update( object ) {
  10352. var frame = infoRender.frame;
  10353. var geometry = object.geometry;
  10354. var buffergeometry = geometries.get( object, geometry );
  10355. // Update once per frame
  10356. if ( updateList[ buffergeometry.id ] !== frame ) {
  10357. if ( geometry.isGeometry ) {
  10358. buffergeometry.updateFromObject( object );
  10359. }
  10360. geometries.update( buffergeometry );
  10361. updateList[ buffergeometry.id ] = frame;
  10362. }
  10363. return buffergeometry;
  10364. }
  10365. function clear() {
  10366. updateList = {};
  10367. }
  10368. return {
  10369. update: update,
  10370. clear: clear
  10371. };
  10372. }
  10373. /**
  10374. * @author mrdoob / http://mrdoob.com/
  10375. */
  10376. function addLineNumbers( string ) {
  10377. var lines = string.split( '\n' );
  10378. for ( var i = 0; i < lines.length; i ++ ) {
  10379. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  10380. }
  10381. return lines.join( '\n' );
  10382. }
  10383. function WebGLShader( gl, type, string ) {
  10384. var shader = gl.createShader( type );
  10385. gl.shaderSource( shader, string );
  10386. gl.compileShader( shader );
  10387. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  10388. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  10389. }
  10390. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  10391. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  10392. }
  10393. // --enable-privileged-webgl-extension
  10394. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10395. return shader;
  10396. }
  10397. /**
  10398. * @author mrdoob / http://mrdoob.com/
  10399. */
  10400. var programIdCount = 0;
  10401. function getEncodingComponents( encoding ) {
  10402. switch ( encoding ) {
  10403. case LinearEncoding:
  10404. return [ 'Linear','( value )' ];
  10405. case sRGBEncoding:
  10406. return [ 'sRGB','( value )' ];
  10407. case RGBEEncoding:
  10408. return [ 'RGBE','( value )' ];
  10409. case RGBM7Encoding:
  10410. return [ 'RGBM','( value, 7.0 )' ];
  10411. case RGBM16Encoding:
  10412. return [ 'RGBM','( value, 16.0 )' ];
  10413. case RGBDEncoding:
  10414. return [ 'RGBD','( value, 256.0 )' ];
  10415. case GammaEncoding:
  10416. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  10417. default:
  10418. throw new Error( 'unsupported encoding: ' + encoding );
  10419. }
  10420. }
  10421. function getTexelDecodingFunction( functionName, encoding ) {
  10422. var components = getEncodingComponents( encoding );
  10423. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  10424. }
  10425. function getTexelEncodingFunction( functionName, encoding ) {
  10426. var components = getEncodingComponents( encoding );
  10427. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  10428. }
  10429. function getToneMappingFunction( functionName, toneMapping ) {
  10430. var toneMappingName;
  10431. switch ( toneMapping ) {
  10432. case LinearToneMapping:
  10433. toneMappingName = "Linear";
  10434. break;
  10435. case ReinhardToneMapping:
  10436. toneMappingName = "Reinhard";
  10437. break;
  10438. case Uncharted2ToneMapping:
  10439. toneMappingName = "Uncharted2";
  10440. break;
  10441. case CineonToneMapping:
  10442. toneMappingName = "OptimizedCineon";
  10443. break;
  10444. default:
  10445. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  10446. }
  10447. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  10448. }
  10449. function generateExtensions( extensions, parameters, rendererExtensions ) {
  10450. extensions = extensions || {};
  10451. var chunks = [
  10452. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10453. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  10454. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10455. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10456. ];
  10457. return chunks.filter( filterEmptyLine ).join( '\n' );
  10458. }
  10459. function generateDefines( defines ) {
  10460. var chunks = [];
  10461. for ( var name in defines ) {
  10462. var value = defines[ name ];
  10463. if ( value === false ) continue;
  10464. chunks.push( '#define ' + name + ' ' + value );
  10465. }
  10466. return chunks.join( '\n' );
  10467. }
  10468. function fetchAttributeLocations( gl, program, identifiers ) {
  10469. var attributes = {};
  10470. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  10471. for ( var i = 0; i < n; i ++ ) {
  10472. var info = gl.getActiveAttrib( program, i );
  10473. var name = info.name;
  10474. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  10475. attributes[ name ] = gl.getAttribLocation( program, name );
  10476. }
  10477. return attributes;
  10478. }
  10479. function filterEmptyLine( string ) {
  10480. return string !== '';
  10481. }
  10482. function replaceLightNums( string, parameters ) {
  10483. return string
  10484. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10485. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10486. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10487. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10488. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  10489. }
  10490. function parseIncludes( string ) {
  10491. var pattern = /^[ \t]*#include +<([\w\d.]+)>/gm;
  10492. function replace( match, include ) {
  10493. var replace = ShaderChunk[ include ];
  10494. if ( replace === undefined ) {
  10495. throw new Error( 'Can not resolve #include <' + include + '>' );
  10496. }
  10497. return parseIncludes( replace );
  10498. }
  10499. return string.replace( pattern, replace );
  10500. }
  10501. function unrollLoops( string ) {
  10502. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10503. function replace( match, start, end, snippet ) {
  10504. var unroll = '';
  10505. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10506. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  10507. }
  10508. return unroll;
  10509. }
  10510. return string.replace( pattern, replace );
  10511. }
  10512. function WebGLProgram( renderer, extensions, code, material, shader, parameters ) {
  10513. var gl = renderer.context;
  10514. var defines = material.defines;
  10515. var vertexShader = shader.vertexShader;
  10516. var fragmentShader = shader.fragmentShader;
  10517. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10518. if ( parameters.shadowMapType === PCFShadowMap ) {
  10519. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10520. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10521. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10522. }
  10523. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10524. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10525. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10526. if ( parameters.envMap ) {
  10527. switch ( material.envMap.mapping ) {
  10528. case CubeReflectionMapping:
  10529. case CubeRefractionMapping:
  10530. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10531. break;
  10532. case CubeUVReflectionMapping:
  10533. case CubeUVRefractionMapping:
  10534. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10535. break;
  10536. case EquirectangularReflectionMapping:
  10537. case EquirectangularRefractionMapping:
  10538. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  10539. break;
  10540. case SphericalReflectionMapping:
  10541. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  10542. break;
  10543. }
  10544. switch ( material.envMap.mapping ) {
  10545. case CubeRefractionMapping:
  10546. case EquirectangularRefractionMapping:
  10547. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10548. break;
  10549. }
  10550. switch ( material.combine ) {
  10551. case MultiplyOperation:
  10552. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10553. break;
  10554. case MixOperation:
  10555. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10556. break;
  10557. case AddOperation:
  10558. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10559. break;
  10560. }
  10561. }
  10562. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  10563. // console.log( 'building new program ' );
  10564. //
  10565. var customExtensions = generateExtensions( material.extensions, parameters, extensions );
  10566. var customDefines = generateDefines( defines );
  10567. //
  10568. var program = gl.createProgram();
  10569. var prefixVertex, prefixFragment;
  10570. if ( material.isRawShaderMaterial ) {
  10571. prefixVertex = [
  10572. customDefines,
  10573. '\n'
  10574. ].filter( filterEmptyLine ).join( '\n' );
  10575. prefixFragment = [
  10576. customExtensions,
  10577. customDefines,
  10578. '\n'
  10579. ].filter( filterEmptyLine ).join( '\n' );
  10580. } else {
  10581. prefixVertex = [
  10582. 'precision ' + parameters.precision + ' float;',
  10583. 'precision ' + parameters.precision + ' int;',
  10584. '#define SHADER_NAME ' + shader.name,
  10585. customDefines,
  10586. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  10587. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10588. '#define MAX_BONES ' + parameters.maxBones,
  10589. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10590. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  10591. parameters.map ? '#define USE_MAP' : '',
  10592. parameters.envMap ? '#define USE_ENVMAP' : '',
  10593. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10594. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10595. parameters.aoMap ? '#define USE_AOMAP' : '',
  10596. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10597. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10598. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10599. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  10600. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10601. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10602. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10603. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10604. parameters.vertexColors ? '#define USE_COLOR' : '',
  10605. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10606. parameters.skinning ? '#define USE_SKINNING' : '',
  10607. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  10608. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  10609. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  10610. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10611. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10612. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  10613. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10614. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10615. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  10616. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10617. parameters.logarithmicDepthBuffer && extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10618. 'uniform mat4 modelMatrix;',
  10619. 'uniform mat4 modelViewMatrix;',
  10620. 'uniform mat4 projectionMatrix;',
  10621. 'uniform mat4 viewMatrix;',
  10622. 'uniform mat3 normalMatrix;',
  10623. 'uniform vec3 cameraPosition;',
  10624. 'attribute vec3 position;',
  10625. 'attribute vec3 normal;',
  10626. 'attribute vec2 uv;',
  10627. '#ifdef USE_COLOR',
  10628. ' attribute vec3 color;',
  10629. '#endif',
  10630. '#ifdef USE_MORPHTARGETS',
  10631. ' attribute vec3 morphTarget0;',
  10632. ' attribute vec3 morphTarget1;',
  10633. ' attribute vec3 morphTarget2;',
  10634. ' attribute vec3 morphTarget3;',
  10635. ' #ifdef USE_MORPHNORMALS',
  10636. ' attribute vec3 morphNormal0;',
  10637. ' attribute vec3 morphNormal1;',
  10638. ' attribute vec3 morphNormal2;',
  10639. ' attribute vec3 morphNormal3;',
  10640. ' #else',
  10641. ' attribute vec3 morphTarget4;',
  10642. ' attribute vec3 morphTarget5;',
  10643. ' attribute vec3 morphTarget6;',
  10644. ' attribute vec3 morphTarget7;',
  10645. ' #endif',
  10646. '#endif',
  10647. '#ifdef USE_SKINNING',
  10648. ' attribute vec4 skinIndex;',
  10649. ' attribute vec4 skinWeight;',
  10650. '#endif',
  10651. '\n'
  10652. ].filter( filterEmptyLine ).join( '\n' );
  10653. prefixFragment = [
  10654. customExtensions,
  10655. 'precision ' + parameters.precision + ' float;',
  10656. 'precision ' + parameters.precision + ' int;',
  10657. '#define SHADER_NAME ' + shader.name,
  10658. customDefines,
  10659. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  10660. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10661. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10662. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  10663. parameters.map ? '#define USE_MAP' : '',
  10664. parameters.envMap ? '#define USE_ENVMAP' : '',
  10665. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  10666. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10667. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  10668. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10669. parameters.aoMap ? '#define USE_AOMAP' : '',
  10670. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10671. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10672. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10673. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10674. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10675. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10676. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10677. parameters.vertexColors ? '#define USE_COLOR' : '',
  10678. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  10679. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10680. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10681. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10682. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  10683. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  10684. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10685. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10686. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  10687. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  10688. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10689. parameters.logarithmicDepthBuffer && extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10690. parameters.envMap && extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  10691. 'uniform mat4 viewMatrix;',
  10692. 'uniform vec3 cameraPosition;',
  10693. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  10694. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  10695. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  10696. parameters.dithering ? '#define DITHERING' : '',
  10697. ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  10698. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  10699. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  10700. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  10701. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  10702. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  10703. '\n'
  10704. ].filter( filterEmptyLine ).join( '\n' );
  10705. }
  10706. vertexShader = parseIncludes( vertexShader );
  10707. vertexShader = replaceLightNums( vertexShader, parameters );
  10708. fragmentShader = parseIncludes( fragmentShader );
  10709. fragmentShader = replaceLightNums( fragmentShader, parameters );
  10710. if ( ! material.isShaderMaterial ) {
  10711. vertexShader = unrollLoops( vertexShader );
  10712. fragmentShader = unrollLoops( fragmentShader );
  10713. }
  10714. var vertexGlsl = prefixVertex + vertexShader;
  10715. var fragmentGlsl = prefixFragment + fragmentShader;
  10716. // console.log( '*VERTEX*', vertexGlsl );
  10717. // console.log( '*FRAGMENT*', fragmentGlsl );
  10718. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  10719. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  10720. gl.attachShader( program, glVertexShader );
  10721. gl.attachShader( program, glFragmentShader );
  10722. // Force a particular attribute to index 0.
  10723. if ( material.index0AttributeName !== undefined ) {
  10724. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  10725. } else if ( parameters.morphTargets === true ) {
  10726. // programs with morphTargets displace position out of attribute 0
  10727. gl.bindAttribLocation( program, 0, 'position' );
  10728. }
  10729. gl.linkProgram( program );
  10730. var programLog = gl.getProgramInfoLog( program );
  10731. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  10732. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  10733. var runnable = true;
  10734. var haveDiagnostics = true;
  10735. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  10736. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  10737. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  10738. runnable = false;
  10739. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  10740. } else if ( programLog !== '' ) {
  10741. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  10742. } else if ( vertexLog === '' || fragmentLog === '' ) {
  10743. haveDiagnostics = false;
  10744. }
  10745. if ( haveDiagnostics ) {
  10746. this.diagnostics = {
  10747. runnable: runnable,
  10748. material: material,
  10749. programLog: programLog,
  10750. vertexShader: {
  10751. log: vertexLog,
  10752. prefix: prefixVertex
  10753. },
  10754. fragmentShader: {
  10755. log: fragmentLog,
  10756. prefix: prefixFragment
  10757. }
  10758. };
  10759. }
  10760. // clean up
  10761. gl.deleteShader( glVertexShader );
  10762. gl.deleteShader( glFragmentShader );
  10763. // set up caching for uniform locations
  10764. var cachedUniforms;
  10765. this.getUniforms = function () {
  10766. if ( cachedUniforms === undefined ) {
  10767. cachedUniforms = new WebGLUniforms( gl, program, renderer );
  10768. }
  10769. return cachedUniforms;
  10770. };
  10771. // set up caching for attribute locations
  10772. var cachedAttributes;
  10773. this.getAttributes = function () {
  10774. if ( cachedAttributes === undefined ) {
  10775. cachedAttributes = fetchAttributeLocations( gl, program );
  10776. }
  10777. return cachedAttributes;
  10778. };
  10779. // free resource
  10780. this.destroy = function() {
  10781. gl.deleteProgram( program );
  10782. this.program = undefined;
  10783. };
  10784. // DEPRECATED
  10785. Object.defineProperties( this, {
  10786. uniforms: {
  10787. get: function() {
  10788. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  10789. return this.getUniforms();
  10790. }
  10791. },
  10792. attributes: {
  10793. get: function() {
  10794. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  10795. return this.getAttributes();
  10796. }
  10797. }
  10798. } );
  10799. //
  10800. this.id = programIdCount ++;
  10801. this.code = code;
  10802. this.usedTimes = 1;
  10803. this.program = program;
  10804. this.vertexShader = glVertexShader;
  10805. this.fragmentShader = glFragmentShader;
  10806. return this;
  10807. }
  10808. /**
  10809. * @author mrdoob / http://mrdoob.com/
  10810. */
  10811. function WebGLPrograms( renderer, extensions, capabilities ) {
  10812. var programs = [];
  10813. var shaderIDs = {
  10814. MeshDepthMaterial: 'depth',
  10815. MeshDistanceMaterial: 'distanceRGBA',
  10816. MeshNormalMaterial: 'normal',
  10817. MeshBasicMaterial: 'basic',
  10818. MeshLambertMaterial: 'lambert',
  10819. MeshPhongMaterial: 'phong',
  10820. MeshToonMaterial: 'phong',
  10821. MeshStandardMaterial: 'physical',
  10822. MeshPhysicalMaterial: 'physical',
  10823. LineBasicMaterial: 'basic',
  10824. LineDashedMaterial: 'dashed',
  10825. PointsMaterial: 'points'
  10826. };
  10827. var parameterNames = [
  10828. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  10829. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  10830. "roughnessMap", "metalnessMap", "gradientMap",
  10831. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  10832. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  10833. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  10834. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  10835. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  10836. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  10837. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering"
  10838. ];
  10839. function allocateBones( object ) {
  10840. var skeleton = object.skeleton;
  10841. var bones = skeleton.bones;
  10842. if ( capabilities.floatVertexTextures ) {
  10843. return 1024;
  10844. } else {
  10845. // default for when object is not specified
  10846. // ( for example when prebuilding shader to be used with multiple objects )
  10847. //
  10848. // - leave some extra space for other uniforms
  10849. // - limit here is ANGLE's 254 max uniform vectors
  10850. // (up to 54 should be safe)
  10851. var nVertexUniforms = capabilities.maxVertexUniforms;
  10852. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  10853. var maxBones = Math.min( nVertexMatrices, bones.length );
  10854. if ( maxBones < bones.length ) {
  10855. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  10856. return 0;
  10857. }
  10858. return maxBones;
  10859. }
  10860. }
  10861. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  10862. var encoding;
  10863. if ( ! map ) {
  10864. encoding = LinearEncoding;
  10865. } else if ( map.isTexture ) {
  10866. encoding = map.encoding;
  10867. } else if ( map.isWebGLRenderTarget ) {
  10868. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  10869. encoding = map.texture.encoding;
  10870. }
  10871. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  10872. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  10873. encoding = GammaEncoding;
  10874. }
  10875. return encoding;
  10876. }
  10877. this.getParameters = function ( material, lights, shadows, fog, nClipPlanes, nClipIntersection, object ) {
  10878. var shaderID = shaderIDs[ material.type ];
  10879. // heuristics to create shader parameters according to lights in the scene
  10880. // (not to blow over maxLights budget)
  10881. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  10882. var precision = capabilities.precision;
  10883. if ( material.precision !== null ) {
  10884. precision = capabilities.getMaxPrecision( material.precision );
  10885. if ( precision !== material.precision ) {
  10886. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  10887. }
  10888. }
  10889. var currentRenderTarget = renderer.getRenderTarget();
  10890. var parameters = {
  10891. shaderID: shaderID,
  10892. precision: precision,
  10893. supportsVertexTextures: capabilities.vertexTextures,
  10894. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  10895. map: !! material.map,
  10896. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  10897. envMap: !! material.envMap,
  10898. envMapMode: material.envMap && material.envMap.mapping,
  10899. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  10900. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  10901. lightMap: !! material.lightMap,
  10902. aoMap: !! material.aoMap,
  10903. emissiveMap: !! material.emissiveMap,
  10904. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  10905. bumpMap: !! material.bumpMap,
  10906. normalMap: !! material.normalMap,
  10907. displacementMap: !! material.displacementMap,
  10908. roughnessMap: !! material.roughnessMap,
  10909. metalnessMap: !! material.metalnessMap,
  10910. specularMap: !! material.specularMap,
  10911. alphaMap: !! material.alphaMap,
  10912. gradientMap: !! material.gradientMap,
  10913. combine: material.combine,
  10914. vertexColors: material.vertexColors,
  10915. fog: !! fog,
  10916. useFog: material.fog,
  10917. fogExp: ( fog && fog.isFogExp2 ),
  10918. flatShading: material.flatShading,
  10919. sizeAttenuation: material.sizeAttenuation,
  10920. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  10921. skinning: material.skinning && maxBones > 0,
  10922. maxBones: maxBones,
  10923. useVertexTexture: capabilities.floatVertexTextures,
  10924. morphTargets: material.morphTargets,
  10925. morphNormals: material.morphNormals,
  10926. maxMorphTargets: renderer.maxMorphTargets,
  10927. maxMorphNormals: renderer.maxMorphNormals,
  10928. numDirLights: lights.directional.length,
  10929. numPointLights: lights.point.length,
  10930. numSpotLights: lights.spot.length,
  10931. numRectAreaLights: lights.rectArea.length,
  10932. numHemiLights: lights.hemi.length,
  10933. numClippingPlanes: nClipPlanes,
  10934. numClipIntersection: nClipIntersection,
  10935. dithering: material.dithering,
  10936. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && shadows.length > 0,
  10937. shadowMapType: renderer.shadowMap.type,
  10938. toneMapping: renderer.toneMapping,
  10939. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10940. premultipliedAlpha: material.premultipliedAlpha,
  10941. alphaTest: material.alphaTest,
  10942. doubleSided: material.side === DoubleSide,
  10943. flipSided: material.side === BackSide,
  10944. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  10945. };
  10946. return parameters;
  10947. };
  10948. this.getProgramCode = function ( material, parameters ) {
  10949. var array = [];
  10950. if ( parameters.shaderID ) {
  10951. array.push( parameters.shaderID );
  10952. } else {
  10953. array.push( material.fragmentShader );
  10954. array.push( material.vertexShader );
  10955. }
  10956. if ( material.defines !== undefined ) {
  10957. for ( var name in material.defines ) {
  10958. array.push( name );
  10959. array.push( material.defines[ name ] );
  10960. }
  10961. }
  10962. for ( var i = 0; i < parameterNames.length; i ++ ) {
  10963. array.push( parameters[ parameterNames[ i ] ] );
  10964. }
  10965. array.push( material.onBeforeCompile.toString() );
  10966. array.push( renderer.gammaOutput );
  10967. return array.join();
  10968. };
  10969. this.acquireProgram = function ( material, shader, parameters, code ) {
  10970. var program;
  10971. // Check if code has been already compiled
  10972. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  10973. var programInfo = programs[ p ];
  10974. if ( programInfo.code === code ) {
  10975. program = programInfo;
  10976. ++ program.usedTimes;
  10977. break;
  10978. }
  10979. }
  10980. if ( program === undefined ) {
  10981. program = new WebGLProgram( renderer, extensions, code, material, shader, parameters );
  10982. programs.push( program );
  10983. }
  10984. return program;
  10985. };
  10986. this.releaseProgram = function ( program ) {
  10987. if ( -- program.usedTimes === 0 ) {
  10988. // Remove from unordered set
  10989. var i = programs.indexOf( program );
  10990. programs[ i ] = programs[ programs.length - 1 ];
  10991. programs.pop();
  10992. // Free WebGL resources
  10993. program.destroy();
  10994. }
  10995. };
  10996. // Exposed for resource monitoring & error feedback via renderer.info:
  10997. this.programs = programs;
  10998. }
  10999. /**
  11000. * @author mrdoob / http://mrdoob.com/
  11001. */
  11002. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, infoMemory ) {
  11003. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  11004. //
  11005. function clampToMaxSize( image, maxSize ) {
  11006. if ( image.width > maxSize || image.height > maxSize ) {
  11007. // Warning: Scaling through the canvas will only work with images that use
  11008. // premultiplied alpha.
  11009. var scale = maxSize / Math.max( image.width, image.height );
  11010. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  11011. canvas.width = Math.floor( image.width * scale );
  11012. canvas.height = Math.floor( image.height * scale );
  11013. var context = canvas.getContext( '2d' );
  11014. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  11015. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  11016. return canvas;
  11017. }
  11018. return image;
  11019. }
  11020. function isPowerOfTwo( image ) {
  11021. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  11022. }
  11023. function makePowerOfTwo( image ) {
  11024. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  11025. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  11026. canvas.width = _Math.nearestPowerOfTwo( image.width );
  11027. canvas.height = _Math.nearestPowerOfTwo( image.height );
  11028. var context = canvas.getContext( '2d' );
  11029. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  11030. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  11031. return canvas;
  11032. }
  11033. return image;
  11034. }
  11035. function textureNeedsPowerOfTwo( texture ) {
  11036. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  11037. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  11038. }
  11039. function textureNeedsGenerateMipmaps( texture, isPowerOfTwo ) {
  11040. return texture.generateMipmaps && isPowerOfTwo &&
  11041. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  11042. }
  11043. // Fallback filters for non-power-of-2 textures
  11044. function filterFallback( f ) {
  11045. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  11046. return _gl.NEAREST;
  11047. }
  11048. return _gl.LINEAR;
  11049. }
  11050. //
  11051. function onTextureDispose( event ) {
  11052. var texture = event.target;
  11053. texture.removeEventListener( 'dispose', onTextureDispose );
  11054. deallocateTexture( texture );
  11055. infoMemory.textures --;
  11056. }
  11057. function onRenderTargetDispose( event ) {
  11058. var renderTarget = event.target;
  11059. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11060. deallocateRenderTarget( renderTarget );
  11061. infoMemory.textures --;
  11062. }
  11063. //
  11064. function deallocateTexture( texture ) {
  11065. var textureProperties = properties.get( texture );
  11066. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  11067. // cube texture
  11068. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  11069. } else {
  11070. // 2D texture
  11071. if ( textureProperties.__webglInit === undefined ) return;
  11072. _gl.deleteTexture( textureProperties.__webglTexture );
  11073. }
  11074. // remove all webgl properties
  11075. properties.remove( texture );
  11076. }
  11077. function deallocateRenderTarget( renderTarget ) {
  11078. var renderTargetProperties = properties.get( renderTarget );
  11079. var textureProperties = properties.get( renderTarget.texture );
  11080. if ( ! renderTarget ) return;
  11081. if ( textureProperties.__webglTexture !== undefined ) {
  11082. _gl.deleteTexture( textureProperties.__webglTexture );
  11083. }
  11084. if ( renderTarget.depthTexture ) {
  11085. renderTarget.depthTexture.dispose();
  11086. }
  11087. if ( renderTarget.isWebGLRenderTargetCube ) {
  11088. for ( var i = 0; i < 6; i ++ ) {
  11089. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  11090. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  11091. }
  11092. } else {
  11093. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  11094. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  11095. }
  11096. properties.remove( renderTarget.texture );
  11097. properties.remove( renderTarget );
  11098. }
  11099. //
  11100. function setTexture2D( texture, slot ) {
  11101. var textureProperties = properties.get( texture );
  11102. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  11103. var image = texture.image;
  11104. if ( image === undefined ) {
  11105. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  11106. } else if ( image.complete === false ) {
  11107. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  11108. } else {
  11109. uploadTexture( textureProperties, texture, slot );
  11110. return;
  11111. }
  11112. }
  11113. state.activeTexture( _gl.TEXTURE0 + slot );
  11114. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  11115. }
  11116. function setTextureCube( texture, slot ) {
  11117. var textureProperties = properties.get( texture );
  11118. if ( texture.image.length === 6 ) {
  11119. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  11120. if ( ! textureProperties.__image__webglTextureCube ) {
  11121. texture.addEventListener( 'dispose', onTextureDispose );
  11122. textureProperties.__image__webglTextureCube = _gl.createTexture();
  11123. infoMemory.textures ++;
  11124. }
  11125. state.activeTexture( _gl.TEXTURE0 + slot );
  11126. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  11127. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  11128. var isCompressed = ( texture && texture.isCompressedTexture );
  11129. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  11130. var cubeImage = [];
  11131. for ( var i = 0; i < 6; i ++ ) {
  11132. if ( ! isCompressed && ! isDataTexture ) {
  11133. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  11134. } else {
  11135. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  11136. }
  11137. }
  11138. var image = cubeImage[ 0 ],
  11139. isPowerOfTwoImage = isPowerOfTwo( image ),
  11140. glFormat = paramThreeToGL( texture.format ),
  11141. glType = paramThreeToGL( texture.type );
  11142. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  11143. for ( var i = 0; i < 6; i ++ ) {
  11144. if ( ! isCompressed ) {
  11145. if ( isDataTexture ) {
  11146. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  11147. } else {
  11148. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  11149. }
  11150. } else {
  11151. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  11152. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  11153. mipmap = mipmaps[ j ];
  11154. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  11155. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  11156. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  11157. } else {
  11158. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  11159. }
  11160. } else {
  11161. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  11162. }
  11163. }
  11164. }
  11165. }
  11166. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) {
  11167. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  11168. }
  11169. textureProperties.__version = texture.version;
  11170. if ( texture.onUpdate ) texture.onUpdate( texture );
  11171. } else {
  11172. state.activeTexture( _gl.TEXTURE0 + slot );
  11173. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  11174. }
  11175. }
  11176. }
  11177. function setTextureCubeDynamic( texture, slot ) {
  11178. state.activeTexture( _gl.TEXTURE0 + slot );
  11179. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  11180. }
  11181. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  11182. var extension;
  11183. if ( isPowerOfTwoImage ) {
  11184. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  11185. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  11186. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  11187. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  11188. } else {
  11189. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  11190. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  11191. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  11192. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  11193. }
  11194. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  11195. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  11196. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  11197. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  11198. }
  11199. }
  11200. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  11201. if ( extension ) {
  11202. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  11203. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  11204. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  11205. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  11206. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  11207. }
  11208. }
  11209. }
  11210. function uploadTexture( textureProperties, texture, slot ) {
  11211. if ( textureProperties.__webglInit === undefined ) {
  11212. textureProperties.__webglInit = true;
  11213. texture.addEventListener( 'dispose', onTextureDispose );
  11214. textureProperties.__webglTexture = _gl.createTexture();
  11215. infoMemory.textures ++;
  11216. }
  11217. state.activeTexture( _gl.TEXTURE0 + slot );
  11218. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  11219. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  11220. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  11221. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  11222. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  11223. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  11224. image = makePowerOfTwo( image );
  11225. }
  11226. var isPowerOfTwoImage = isPowerOfTwo( image ),
  11227. glFormat = paramThreeToGL( texture.format ),
  11228. glType = paramThreeToGL( texture.type );
  11229. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  11230. var mipmap, mipmaps = texture.mipmaps;
  11231. if ( texture.isDepthTexture ) {
  11232. // populate depth texture with dummy data
  11233. var internalFormat = _gl.DEPTH_COMPONENT;
  11234. if ( texture.type === FloatType ) {
  11235. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  11236. internalFormat = _gl.DEPTH_COMPONENT32F;
  11237. } else if ( _isWebGL2 ) {
  11238. // WebGL 2.0 requires signed internalformat for glTexImage2D
  11239. internalFormat = _gl.DEPTH_COMPONENT16;
  11240. }
  11241. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  11242. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  11243. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  11244. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  11245. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  11246. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  11247. texture.type = UnsignedShortType;
  11248. glType = paramThreeToGL( texture.type );
  11249. }
  11250. }
  11251. // Depth stencil textures need the DEPTH_STENCIL internal format
  11252. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  11253. if ( texture.format === DepthStencilFormat ) {
  11254. internalFormat = _gl.DEPTH_STENCIL;
  11255. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  11256. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  11257. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  11258. if ( texture.type !== UnsignedInt248Type ) {
  11259. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  11260. texture.type = UnsignedInt248Type;
  11261. glType = paramThreeToGL( texture.type );
  11262. }
  11263. }
  11264. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  11265. } else if ( texture.isDataTexture ) {
  11266. // use manually created mipmaps if available
  11267. // if there are no manual mipmaps
  11268. // set 0 level mipmap and then use GL to generate other mipmap levels
  11269. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  11270. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  11271. mipmap = mipmaps[ i ];
  11272. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  11273. }
  11274. texture.generateMipmaps = false;
  11275. } else {
  11276. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  11277. }
  11278. } else if ( texture.isCompressedTexture ) {
  11279. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  11280. mipmap = mipmaps[ i ];
  11281. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  11282. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  11283. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  11284. } else {
  11285. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  11286. }
  11287. } else {
  11288. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  11289. }
  11290. }
  11291. } else {
  11292. // regular Texture (image, video, canvas)
  11293. // use manually created mipmaps if available
  11294. // if there are no manual mipmaps
  11295. // set 0 level mipmap and then use GL to generate other mipmap levels
  11296. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  11297. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  11298. mipmap = mipmaps[ i ];
  11299. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  11300. }
  11301. texture.generateMipmaps = false;
  11302. } else {
  11303. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  11304. }
  11305. }
  11306. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) _gl.generateMipmap( _gl.TEXTURE_2D );
  11307. textureProperties.__version = texture.version;
  11308. if ( texture.onUpdate ) texture.onUpdate( texture );
  11309. }
  11310. // Render targets
  11311. // Setup storage for target texture and bind it to correct framebuffer
  11312. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  11313. var glFormat = paramThreeToGL( renderTarget.texture.format );
  11314. var glType = paramThreeToGL( renderTarget.texture.type );
  11315. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  11316. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  11317. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  11318. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  11319. }
  11320. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  11321. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  11322. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  11323. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  11324. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  11325. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  11326. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  11327. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  11328. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  11329. } else {
  11330. // FIXME: We don't support !depth !stencil
  11331. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  11332. }
  11333. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  11334. }
  11335. // Setup resources for a Depth Texture for a FBO (needs an extension)
  11336. function setupDepthTexture( framebuffer, renderTarget ) {
  11337. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  11338. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  11339. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  11340. if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  11341. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  11342. }
  11343. // upload an empty depth texture with framebuffer size
  11344. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  11345. renderTarget.depthTexture.image.width !== renderTarget.width ||
  11346. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  11347. renderTarget.depthTexture.image.width = renderTarget.width;
  11348. renderTarget.depthTexture.image.height = renderTarget.height;
  11349. renderTarget.depthTexture.needsUpdate = true;
  11350. }
  11351. setTexture2D( renderTarget.depthTexture, 0 );
  11352. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  11353. if ( renderTarget.depthTexture.format === DepthFormat ) {
  11354. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  11355. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  11356. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  11357. } else {
  11358. throw new Error( 'Unknown depthTexture format' );
  11359. }
  11360. }
  11361. // Setup GL resources for a non-texture depth buffer
  11362. function setupDepthRenderbuffer( renderTarget ) {
  11363. var renderTargetProperties = properties.get( renderTarget );
  11364. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  11365. if ( renderTarget.depthTexture ) {
  11366. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  11367. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  11368. } else {
  11369. if ( isCube ) {
  11370. renderTargetProperties.__webglDepthbuffer = [];
  11371. for ( var i = 0; i < 6; i ++ ) {
  11372. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  11373. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  11374. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  11375. }
  11376. } else {
  11377. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  11378. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  11379. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  11380. }
  11381. }
  11382. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  11383. }
  11384. // Set up GL resources for the render target
  11385. function setupRenderTarget( renderTarget ) {
  11386. var renderTargetProperties = properties.get( renderTarget );
  11387. var textureProperties = properties.get( renderTarget.texture );
  11388. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  11389. textureProperties.__webglTexture = _gl.createTexture();
  11390. infoMemory.textures ++;
  11391. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  11392. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  11393. // Setup framebuffer
  11394. if ( isCube ) {
  11395. renderTargetProperties.__webglFramebuffer = [];
  11396. for ( var i = 0; i < 6; i ++ ) {
  11397. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  11398. }
  11399. } else {
  11400. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  11401. }
  11402. // Setup color buffer
  11403. if ( isCube ) {
  11404. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  11405. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  11406. for ( var i = 0; i < 6; i ++ ) {
  11407. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  11408. }
  11409. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  11410. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  11411. } else {
  11412. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  11413. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  11414. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  11415. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) _gl.generateMipmap( _gl.TEXTURE_2D );
  11416. state.bindTexture( _gl.TEXTURE_2D, null );
  11417. }
  11418. // Setup depth and stencil buffers
  11419. if ( renderTarget.depthBuffer ) {
  11420. setupDepthRenderbuffer( renderTarget );
  11421. }
  11422. }
  11423. function updateRenderTargetMipmap( renderTarget ) {
  11424. var texture = renderTarget.texture;
  11425. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  11426. if ( textureNeedsGenerateMipmaps( texture, isTargetPowerOfTwo ) ) {
  11427. var target = renderTarget.isWebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  11428. var webglTexture = properties.get( texture ).__webglTexture;
  11429. state.bindTexture( target, webglTexture );
  11430. _gl.generateMipmap( target );
  11431. state.bindTexture( target, null );
  11432. }
  11433. }
  11434. this.setTexture2D = setTexture2D;
  11435. this.setTextureCube = setTextureCube;
  11436. this.setTextureCubeDynamic = setTextureCubeDynamic;
  11437. this.setupRenderTarget = setupRenderTarget;
  11438. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  11439. }
  11440. /**
  11441. * @author fordacious / fordacious.github.io
  11442. */
  11443. function WebGLProperties() {
  11444. var properties = {};
  11445. function get( object ) {
  11446. var uuid = object.uuid;
  11447. var map = properties[ uuid ];
  11448. if ( map === undefined ) {
  11449. map = {};
  11450. properties[ uuid ] = map;
  11451. }
  11452. return map;
  11453. }
  11454. function remove( object ) {
  11455. delete properties[ object.uuid ];
  11456. }
  11457. function clear() {
  11458. properties = {};
  11459. }
  11460. return {
  11461. get: get,
  11462. remove: remove,
  11463. clear: clear
  11464. };
  11465. }
  11466. /**
  11467. * @author mrdoob / http://mrdoob.com/
  11468. */
  11469. function WebGLState( gl, extensions, paramThreeToGL ) {
  11470. function ColorBuffer() {
  11471. var locked = false;
  11472. var color = new Vector4();
  11473. var currentColorMask = null;
  11474. var currentColorClear = new Vector4( 0, 0, 0, 0 );
  11475. return {
  11476. setMask: function ( colorMask ) {
  11477. if ( currentColorMask !== colorMask && ! locked ) {
  11478. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  11479. currentColorMask = colorMask;
  11480. }
  11481. },
  11482. setLocked: function ( lock ) {
  11483. locked = lock;
  11484. },
  11485. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  11486. if ( premultipliedAlpha === true ) {
  11487. r *= a; g *= a; b *= a;
  11488. }
  11489. color.set( r, g, b, a );
  11490. if ( currentColorClear.equals( color ) === false ) {
  11491. gl.clearColor( r, g, b, a );
  11492. currentColorClear.copy( color );
  11493. }
  11494. },
  11495. reset: function () {
  11496. locked = false;
  11497. currentColorMask = null;
  11498. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  11499. }
  11500. };
  11501. }
  11502. function DepthBuffer() {
  11503. var locked = false;
  11504. var currentDepthMask = null;
  11505. var currentDepthFunc = null;
  11506. var currentDepthClear = null;
  11507. return {
  11508. setTest: function ( depthTest ) {
  11509. if ( depthTest ) {
  11510. enable( gl.DEPTH_TEST );
  11511. } else {
  11512. disable( gl.DEPTH_TEST );
  11513. }
  11514. },
  11515. setMask: function ( depthMask ) {
  11516. if ( currentDepthMask !== depthMask && ! locked ) {
  11517. gl.depthMask( depthMask );
  11518. currentDepthMask = depthMask;
  11519. }
  11520. },
  11521. setFunc: function ( depthFunc ) {
  11522. if ( currentDepthFunc !== depthFunc ) {
  11523. if ( depthFunc ) {
  11524. switch ( depthFunc ) {
  11525. case NeverDepth:
  11526. gl.depthFunc( gl.NEVER );
  11527. break;
  11528. case AlwaysDepth:
  11529. gl.depthFunc( gl.ALWAYS );
  11530. break;
  11531. case LessDepth:
  11532. gl.depthFunc( gl.LESS );
  11533. break;
  11534. case LessEqualDepth:
  11535. gl.depthFunc( gl.LEQUAL );
  11536. break;
  11537. case EqualDepth:
  11538. gl.depthFunc( gl.EQUAL );
  11539. break;
  11540. case GreaterEqualDepth:
  11541. gl.depthFunc( gl.GEQUAL );
  11542. break;
  11543. case GreaterDepth:
  11544. gl.depthFunc( gl.GREATER );
  11545. break;
  11546. case NotEqualDepth:
  11547. gl.depthFunc( gl.NOTEQUAL );
  11548. break;
  11549. default:
  11550. gl.depthFunc( gl.LEQUAL );
  11551. }
  11552. } else {
  11553. gl.depthFunc( gl.LEQUAL );
  11554. }
  11555. currentDepthFunc = depthFunc;
  11556. }
  11557. },
  11558. setLocked: function ( lock ) {
  11559. locked = lock;
  11560. },
  11561. setClear: function ( depth ) {
  11562. if ( currentDepthClear !== depth ) {
  11563. gl.clearDepth( depth );
  11564. currentDepthClear = depth;
  11565. }
  11566. },
  11567. reset: function () {
  11568. locked = false;
  11569. currentDepthMask = null;
  11570. currentDepthFunc = null;
  11571. currentDepthClear = null;
  11572. }
  11573. };
  11574. }
  11575. function StencilBuffer() {
  11576. var locked = false;
  11577. var currentStencilMask = null;
  11578. var currentStencilFunc = null;
  11579. var currentStencilRef = null;
  11580. var currentStencilFuncMask = null;
  11581. var currentStencilFail = null;
  11582. var currentStencilZFail = null;
  11583. var currentStencilZPass = null;
  11584. var currentStencilClear = null;
  11585. return {
  11586. setTest: function ( stencilTest ) {
  11587. if ( stencilTest ) {
  11588. enable( gl.STENCIL_TEST );
  11589. } else {
  11590. disable( gl.STENCIL_TEST );
  11591. }
  11592. },
  11593. setMask: function ( stencilMask ) {
  11594. if ( currentStencilMask !== stencilMask && ! locked ) {
  11595. gl.stencilMask( stencilMask );
  11596. currentStencilMask = stencilMask;
  11597. }
  11598. },
  11599. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  11600. if ( currentStencilFunc !== stencilFunc ||
  11601. currentStencilRef !== stencilRef ||
  11602. currentStencilFuncMask !== stencilMask ) {
  11603. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  11604. currentStencilFunc = stencilFunc;
  11605. currentStencilRef = stencilRef;
  11606. currentStencilFuncMask = stencilMask;
  11607. }
  11608. },
  11609. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  11610. if ( currentStencilFail !== stencilFail ||
  11611. currentStencilZFail !== stencilZFail ||
  11612. currentStencilZPass !== stencilZPass ) {
  11613. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  11614. currentStencilFail = stencilFail;
  11615. currentStencilZFail = stencilZFail;
  11616. currentStencilZPass = stencilZPass;
  11617. }
  11618. },
  11619. setLocked: function ( lock ) {
  11620. locked = lock;
  11621. },
  11622. setClear: function ( stencil ) {
  11623. if ( currentStencilClear !== stencil ) {
  11624. gl.clearStencil( stencil );
  11625. currentStencilClear = stencil;
  11626. }
  11627. },
  11628. reset: function () {
  11629. locked = false;
  11630. currentStencilMask = null;
  11631. currentStencilFunc = null;
  11632. currentStencilRef = null;
  11633. currentStencilFuncMask = null;
  11634. currentStencilFail = null;
  11635. currentStencilZFail = null;
  11636. currentStencilZPass = null;
  11637. currentStencilClear = null;
  11638. }
  11639. };
  11640. }
  11641. //
  11642. var colorBuffer = new ColorBuffer();
  11643. var depthBuffer = new DepthBuffer();
  11644. var stencilBuffer = new StencilBuffer();
  11645. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11646. var newAttributes = new Uint8Array( maxVertexAttributes );
  11647. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  11648. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  11649. var capabilities = {};
  11650. var compressedTextureFormats = null;
  11651. var currentProgram = null;
  11652. var currentBlending = null;
  11653. var currentBlendEquation = null;
  11654. var currentBlendSrc = null;
  11655. var currentBlendDst = null;
  11656. var currentBlendEquationAlpha = null;
  11657. var currentBlendSrcAlpha = null;
  11658. var currentBlendDstAlpha = null;
  11659. var currentPremultipledAlpha = false;
  11660. var currentFlipSided = null;
  11661. var currentCullFace = null;
  11662. var currentLineWidth = null;
  11663. var currentPolygonOffsetFactor = null;
  11664. var currentPolygonOffsetUnits = null;
  11665. var currentScissorTest = null;
  11666. var maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  11667. var version = parseFloat( /^WebGL\ ([0-9])/.exec( gl.getParameter( gl.VERSION ) )[ 1 ] );
  11668. var lineWidthAvailable = parseFloat( version ) >= 1.0;
  11669. var currentTextureSlot = null;
  11670. var currentBoundTextures = {};
  11671. var currentScissor = new Vector4();
  11672. var currentViewport = new Vector4();
  11673. function createTexture( type, target, count ) {
  11674. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  11675. var texture = gl.createTexture();
  11676. gl.bindTexture( type, texture );
  11677. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  11678. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  11679. for ( var i = 0; i < count; i ++ ) {
  11680. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  11681. }
  11682. return texture;
  11683. }
  11684. var emptyTextures = {};
  11685. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  11686. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  11687. // init
  11688. colorBuffer.setClear( 0, 0, 0, 1 );
  11689. depthBuffer.setClear( 1 );
  11690. stencilBuffer.setClear( 0 );
  11691. enable( gl.DEPTH_TEST );
  11692. depthBuffer.setFunc( LessEqualDepth );
  11693. setFlipSided( false );
  11694. setCullFace( CullFaceBack );
  11695. enable( gl.CULL_FACE );
  11696. enable( gl.BLEND );
  11697. setBlending( NormalBlending );
  11698. //
  11699. function initAttributes() {
  11700. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  11701. newAttributes[ i ] = 0;
  11702. }
  11703. }
  11704. function enableAttribute( attribute ) {
  11705. newAttributes[ attribute ] = 1;
  11706. if ( enabledAttributes[ attribute ] === 0 ) {
  11707. gl.enableVertexAttribArray( attribute );
  11708. enabledAttributes[ attribute ] = 1;
  11709. }
  11710. if ( attributeDivisors[ attribute ] !== 0 ) {
  11711. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11712. extension.vertexAttribDivisorANGLE( attribute, 0 );
  11713. attributeDivisors[ attribute ] = 0;
  11714. }
  11715. }
  11716. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  11717. newAttributes[ attribute ] = 1;
  11718. if ( enabledAttributes[ attribute ] === 0 ) {
  11719. gl.enableVertexAttribArray( attribute );
  11720. enabledAttributes[ attribute ] = 1;
  11721. }
  11722. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  11723. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11724. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  11725. attributeDivisors[ attribute ] = meshPerAttribute;
  11726. }
  11727. }
  11728. function disableUnusedAttributes() {
  11729. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  11730. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  11731. gl.disableVertexAttribArray( i );
  11732. enabledAttributes[ i ] = 0;
  11733. }
  11734. }
  11735. }
  11736. function enable( id ) {
  11737. if ( capabilities[ id ] !== true ) {
  11738. gl.enable( id );
  11739. capabilities[ id ] = true;
  11740. }
  11741. }
  11742. function disable( id ) {
  11743. if ( capabilities[ id ] !== false ) {
  11744. gl.disable( id );
  11745. capabilities[ id ] = false;
  11746. }
  11747. }
  11748. function getCompressedTextureFormats() {
  11749. if ( compressedTextureFormats === null ) {
  11750. compressedTextureFormats = [];
  11751. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  11752. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  11753. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  11754. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  11755. for ( var i = 0; i < formats.length; i ++ ) {
  11756. compressedTextureFormats.push( formats[ i ] );
  11757. }
  11758. }
  11759. }
  11760. return compressedTextureFormats;
  11761. }
  11762. function useProgram( program ) {
  11763. if ( currentProgram !== program ) {
  11764. gl.useProgram( program );
  11765. currentProgram = program;
  11766. return true;
  11767. }
  11768. return false;
  11769. }
  11770. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11771. if ( blending !== NoBlending ) {
  11772. enable( gl.BLEND );
  11773. } else {
  11774. disable( gl.BLEND );
  11775. }
  11776. if ( blending !== CustomBlending ) {
  11777. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  11778. switch ( blending ) {
  11779. case AdditiveBlending:
  11780. if ( premultipliedAlpha ) {
  11781. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11782. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  11783. } else {
  11784. gl.blendEquation( gl.FUNC_ADD );
  11785. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  11786. }
  11787. break;
  11788. case SubtractiveBlending:
  11789. if ( premultipliedAlpha ) {
  11790. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11791. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  11792. } else {
  11793. gl.blendEquation( gl.FUNC_ADD );
  11794. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  11795. }
  11796. break;
  11797. case MultiplyBlending:
  11798. if ( premultipliedAlpha ) {
  11799. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11800. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  11801. } else {
  11802. gl.blendEquation( gl.FUNC_ADD );
  11803. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  11804. }
  11805. break;
  11806. default:
  11807. if ( premultipliedAlpha ) {
  11808. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11809. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11810. } else {
  11811. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11812. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11813. }
  11814. }
  11815. }
  11816. currentBlendEquation = null;
  11817. currentBlendSrc = null;
  11818. currentBlendDst = null;
  11819. currentBlendEquationAlpha = null;
  11820. currentBlendSrcAlpha = null;
  11821. currentBlendDstAlpha = null;
  11822. } else {
  11823. blendEquationAlpha = blendEquationAlpha || blendEquation;
  11824. blendSrcAlpha = blendSrcAlpha || blendSrc;
  11825. blendDstAlpha = blendDstAlpha || blendDst;
  11826. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  11827. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  11828. currentBlendEquation = blendEquation;
  11829. currentBlendEquationAlpha = blendEquationAlpha;
  11830. }
  11831. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  11832. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  11833. currentBlendSrc = blendSrc;
  11834. currentBlendDst = blendDst;
  11835. currentBlendSrcAlpha = blendSrcAlpha;
  11836. currentBlendDstAlpha = blendDstAlpha;
  11837. }
  11838. }
  11839. currentBlending = blending;
  11840. currentPremultipledAlpha = premultipliedAlpha;
  11841. }
  11842. function setMaterial( material ) {
  11843. material.side === DoubleSide
  11844. ? disable( gl.CULL_FACE )
  11845. : enable( gl.CULL_FACE );
  11846. setFlipSided( material.side === BackSide );
  11847. material.transparent === true
  11848. ? setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  11849. : setBlending( NoBlending );
  11850. depthBuffer.setFunc( material.depthFunc );
  11851. depthBuffer.setTest( material.depthTest );
  11852. depthBuffer.setMask( material.depthWrite );
  11853. colorBuffer.setMask( material.colorWrite );
  11854. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11855. }
  11856. //
  11857. function setFlipSided( flipSided ) {
  11858. if ( currentFlipSided !== flipSided ) {
  11859. if ( flipSided ) {
  11860. gl.frontFace( gl.CW );
  11861. } else {
  11862. gl.frontFace( gl.CCW );
  11863. }
  11864. currentFlipSided = flipSided;
  11865. }
  11866. }
  11867. function setCullFace( cullFace ) {
  11868. if ( cullFace !== CullFaceNone ) {
  11869. enable( gl.CULL_FACE );
  11870. if ( cullFace !== currentCullFace ) {
  11871. if ( cullFace === CullFaceBack ) {
  11872. gl.cullFace( gl.BACK );
  11873. } else if ( cullFace === CullFaceFront ) {
  11874. gl.cullFace( gl.FRONT );
  11875. } else {
  11876. gl.cullFace( gl.FRONT_AND_BACK );
  11877. }
  11878. }
  11879. } else {
  11880. disable( gl.CULL_FACE );
  11881. }
  11882. currentCullFace = cullFace;
  11883. }
  11884. function setLineWidth( width ) {
  11885. if ( width !== currentLineWidth ) {
  11886. if ( lineWidthAvailable ) gl.lineWidth( width );
  11887. currentLineWidth = width;
  11888. }
  11889. }
  11890. function setPolygonOffset( polygonOffset, factor, units ) {
  11891. if ( polygonOffset ) {
  11892. enable( gl.POLYGON_OFFSET_FILL );
  11893. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  11894. gl.polygonOffset( factor, units );
  11895. currentPolygonOffsetFactor = factor;
  11896. currentPolygonOffsetUnits = units;
  11897. }
  11898. } else {
  11899. disable( gl.POLYGON_OFFSET_FILL );
  11900. }
  11901. }
  11902. function getScissorTest() {
  11903. return currentScissorTest;
  11904. }
  11905. function setScissorTest( scissorTest ) {
  11906. currentScissorTest = scissorTest;
  11907. if ( scissorTest ) {
  11908. enable( gl.SCISSOR_TEST );
  11909. } else {
  11910. disable( gl.SCISSOR_TEST );
  11911. }
  11912. }
  11913. // texture
  11914. function activeTexture( webglSlot ) {
  11915. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  11916. if ( currentTextureSlot !== webglSlot ) {
  11917. gl.activeTexture( webglSlot );
  11918. currentTextureSlot = webglSlot;
  11919. }
  11920. }
  11921. function bindTexture( webglType, webglTexture ) {
  11922. if ( currentTextureSlot === null ) {
  11923. activeTexture();
  11924. }
  11925. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  11926. if ( boundTexture === undefined ) {
  11927. boundTexture = { type: undefined, texture: undefined };
  11928. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  11929. }
  11930. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  11931. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  11932. boundTexture.type = webglType;
  11933. boundTexture.texture = webglTexture;
  11934. }
  11935. }
  11936. function compressedTexImage2D() {
  11937. try {
  11938. gl.compressedTexImage2D.apply( gl, arguments );
  11939. } catch ( error ) {
  11940. console.error( 'THREE.WebGLState:', error );
  11941. }
  11942. }
  11943. function texImage2D() {
  11944. try {
  11945. gl.texImage2D.apply( gl, arguments );
  11946. } catch ( error ) {
  11947. console.error( 'THREE.WebGLState:', error );
  11948. }
  11949. }
  11950. //
  11951. function scissor( scissor ) {
  11952. if ( currentScissor.equals( scissor ) === false ) {
  11953. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  11954. currentScissor.copy( scissor );
  11955. }
  11956. }
  11957. function viewport( viewport ) {
  11958. if ( currentViewport.equals( viewport ) === false ) {
  11959. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  11960. currentViewport.copy( viewport );
  11961. }
  11962. }
  11963. //
  11964. function reset() {
  11965. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  11966. if ( enabledAttributes[ i ] === 1 ) {
  11967. gl.disableVertexAttribArray( i );
  11968. enabledAttributes[ i ] = 0;
  11969. }
  11970. }
  11971. capabilities = {};
  11972. compressedTextureFormats = null;
  11973. currentTextureSlot = null;
  11974. currentBoundTextures = {};
  11975. currentProgram = null;
  11976. currentBlending = null;
  11977. currentFlipSided = null;
  11978. currentCullFace = null;
  11979. colorBuffer.reset();
  11980. depthBuffer.reset();
  11981. stencilBuffer.reset();
  11982. }
  11983. return {
  11984. buffers: {
  11985. color: colorBuffer,
  11986. depth: depthBuffer,
  11987. stencil: stencilBuffer
  11988. },
  11989. initAttributes: initAttributes,
  11990. enableAttribute: enableAttribute,
  11991. enableAttributeAndDivisor: enableAttributeAndDivisor,
  11992. disableUnusedAttributes: disableUnusedAttributes,
  11993. enable: enable,
  11994. disable: disable,
  11995. getCompressedTextureFormats: getCompressedTextureFormats,
  11996. useProgram: useProgram,
  11997. setBlending: setBlending,
  11998. setMaterial: setMaterial,
  11999. setFlipSided: setFlipSided,
  12000. setCullFace: setCullFace,
  12001. setLineWidth: setLineWidth,
  12002. setPolygonOffset: setPolygonOffset,
  12003. getScissorTest: getScissorTest,
  12004. setScissorTest: setScissorTest,
  12005. activeTexture: activeTexture,
  12006. bindTexture: bindTexture,
  12007. compressedTexImage2D: compressedTexImage2D,
  12008. texImage2D: texImage2D,
  12009. scissor: scissor,
  12010. viewport: viewport,
  12011. reset: reset
  12012. };
  12013. }
  12014. /**
  12015. * @author mrdoob / http://mrdoob.com/
  12016. */
  12017. function WebGLCapabilities( gl, extensions, parameters ) {
  12018. var maxAnisotropy;
  12019. function getMaxAnisotropy() {
  12020. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  12021. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  12022. if ( extension !== null ) {
  12023. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  12024. } else {
  12025. maxAnisotropy = 0;
  12026. }
  12027. return maxAnisotropy;
  12028. }
  12029. function getMaxPrecision( precision ) {
  12030. if ( precision === 'highp' ) {
  12031. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  12032. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  12033. return 'highp';
  12034. }
  12035. precision = 'mediump';
  12036. }
  12037. if ( precision === 'mediump' ) {
  12038. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  12039. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  12040. return 'mediump';
  12041. }
  12042. }
  12043. return 'lowp';
  12044. }
  12045. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  12046. var maxPrecision = getMaxPrecision( precision );
  12047. if ( maxPrecision !== precision ) {
  12048. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  12049. precision = maxPrecision;
  12050. }
  12051. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  12052. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  12053. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  12054. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  12055. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  12056. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  12057. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  12058. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  12059. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  12060. var vertexTextures = maxVertexTextures > 0;
  12061. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  12062. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  12063. return {
  12064. getMaxAnisotropy: getMaxAnisotropy,
  12065. getMaxPrecision: getMaxPrecision,
  12066. precision: precision,
  12067. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12068. maxTextures: maxTextures,
  12069. maxVertexTextures: maxVertexTextures,
  12070. maxTextureSize: maxTextureSize,
  12071. maxCubemapSize: maxCubemapSize,
  12072. maxAttributes: maxAttributes,
  12073. maxVertexUniforms: maxVertexUniforms,
  12074. maxVaryings: maxVaryings,
  12075. maxFragmentUniforms: maxFragmentUniforms,
  12076. vertexTextures: vertexTextures,
  12077. floatFragmentTextures: floatFragmentTextures,
  12078. floatVertexTextures: floatVertexTextures
  12079. };
  12080. }
  12081. /**
  12082. * @author mrdoob / http://mrdoob.com/
  12083. */
  12084. function ArrayCamera( array ) {
  12085. PerspectiveCamera.call( this );
  12086. this.cameras = array || [];
  12087. }
  12088. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  12089. constructor: ArrayCamera,
  12090. isArrayCamera: true
  12091. } );
  12092. /**
  12093. * @author mrdoob / http://mrdoob.com/
  12094. */
  12095. function WebVRManager( renderer ) {
  12096. var scope = this;
  12097. var device = null;
  12098. var frameData = null;
  12099. if ( 'VRFrameData' in window ) {
  12100. frameData = new window.VRFrameData();
  12101. }
  12102. var matrixWorldInverse = new Matrix4();
  12103. var standingMatrix = new Matrix4();
  12104. var standingMatrixInverse = new Matrix4();
  12105. var cameraL = new PerspectiveCamera();
  12106. cameraL.bounds = new Vector4( 0.0, 0.0, 0.5, 1.0 );
  12107. cameraL.layers.enable( 1 );
  12108. var cameraR = new PerspectiveCamera();
  12109. cameraR.bounds = new Vector4( 0.5, 0.0, 0.5, 1.0 );
  12110. cameraR.layers.enable( 2 );
  12111. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  12112. cameraVR.layers.enable( 1 );
  12113. cameraVR.layers.enable( 2 );
  12114. //
  12115. var currentSize, currentPixelRatio;
  12116. function onVRDisplayPresentChange() {
  12117. if ( device.isPresenting ) {
  12118. var eyeParameters = device.getEyeParameters( 'left' );
  12119. var renderWidth = eyeParameters.renderWidth;
  12120. var renderHeight = eyeParameters.renderHeight;
  12121. currentPixelRatio = renderer.getPixelRatio();
  12122. currentSize = renderer.getSize();
  12123. renderer.setDrawingBufferSize( renderWidth * 2, renderHeight, 1 );
  12124. } else if ( scope.enabled ) {
  12125. renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio );
  12126. }
  12127. }
  12128. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  12129. //
  12130. this.enabled = false;
  12131. this.standing = false;
  12132. this.getDevice = function () {
  12133. return device;
  12134. };
  12135. this.setDevice = function ( value ) {
  12136. if ( value !== undefined ) device = value;
  12137. };
  12138. this.getCamera = function ( camera ) {
  12139. if ( device === null ) return camera;
  12140. device.depthNear = camera.near;
  12141. device.depthFar = camera.far;
  12142. device.getFrameData( frameData );
  12143. //
  12144. var pose = frameData.pose;
  12145. if ( pose.position !== null ) {
  12146. camera.position.fromArray( pose.position );
  12147. } else {
  12148. camera.position.set( 0, 0, 0 );
  12149. }
  12150. if ( pose.orientation !== null ) {
  12151. camera.quaternion.fromArray( pose.orientation );
  12152. }
  12153. camera.updateMatrixWorld();
  12154. var stageParameters = device.stageParameters;
  12155. if ( this.standing && stageParameters ) {
  12156. standingMatrix.fromArray( stageParameters.sittingToStandingTransform );
  12157. standingMatrixInverse.getInverse( standingMatrix );
  12158. camera.matrixWorld.multiply( standingMatrix );
  12159. camera.matrixWorldInverse.multiply( standingMatrixInverse );
  12160. }
  12161. if ( device.isPresenting === false ) return camera;
  12162. //
  12163. cameraVR.matrixWorld.copy( camera.matrixWorld );
  12164. cameraVR.matrixWorldInverse.copy( camera.matrixWorldInverse );
  12165. cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix );
  12166. cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix );
  12167. if ( this.standing && stageParameters ) {
  12168. cameraL.matrixWorldInverse.multiply( standingMatrixInverse );
  12169. cameraR.matrixWorldInverse.multiply( standingMatrixInverse );
  12170. }
  12171. var parent = camera.parent;
  12172. if ( parent !== null ) {
  12173. matrixWorldInverse.getInverse( parent.matrixWorld );
  12174. cameraL.matrixWorldInverse.multiply( matrixWorldInverse );
  12175. cameraR.matrixWorldInverse.multiply( matrixWorldInverse );
  12176. }
  12177. // envMap and Mirror needs camera.matrixWorld
  12178. cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse );
  12179. cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse );
  12180. cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix );
  12181. cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix );
  12182. // HACK @mrdoob
  12183. // https://github.com/w3c/webvr/issues/203
  12184. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  12185. //
  12186. var layers = device.getLayers();
  12187. if ( layers.length ) {
  12188. var layer = layers[ 0 ];
  12189. if ( layer.leftBounds !== null && layer.leftBounds.length === 4 ) {
  12190. cameraL.bounds.fromArray( layer.leftBounds );
  12191. }
  12192. if ( layer.rightBounds !== null && layer.rightBounds.length === 4 ) {
  12193. cameraR.bounds.fromArray( layer.rightBounds );
  12194. }
  12195. }
  12196. return cameraVR;
  12197. };
  12198. this.getStandingMatrix = function () {
  12199. return standingMatrix;
  12200. };
  12201. this.submitFrame = function () {
  12202. if ( device && device.isPresenting ) device.submitFrame();
  12203. };
  12204. this.dispose = function() {
  12205. window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange );
  12206. };
  12207. }
  12208. /**
  12209. * @author mrdoob / http://mrdoob.com/
  12210. */
  12211. function WebGLExtensions( gl ) {
  12212. var extensions = {};
  12213. return {
  12214. get: function ( name ) {
  12215. if ( extensions[ name ] !== undefined ) {
  12216. return extensions[ name ];
  12217. }
  12218. var extension;
  12219. switch ( name ) {
  12220. case 'WEBGL_depth_texture':
  12221. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  12222. break;
  12223. case 'EXT_texture_filter_anisotropic':
  12224. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  12225. break;
  12226. case 'WEBGL_compressed_texture_s3tc':
  12227. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  12228. break;
  12229. case 'WEBGL_compressed_texture_pvrtc':
  12230. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  12231. break;
  12232. case 'WEBGL_compressed_texture_etc1':
  12233. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  12234. break;
  12235. default:
  12236. extension = gl.getExtension( name );
  12237. }
  12238. if ( extension === null ) {
  12239. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  12240. }
  12241. extensions[ name ] = extension;
  12242. return extension;
  12243. }
  12244. };
  12245. }
  12246. /**
  12247. * @author tschw
  12248. */
  12249. function WebGLClipping() {
  12250. var scope = this,
  12251. globalState = null,
  12252. numGlobalPlanes = 0,
  12253. localClippingEnabled = false,
  12254. renderingShadows = false,
  12255. plane = new Plane(),
  12256. viewNormalMatrix = new Matrix3(),
  12257. uniform = { value: null, needsUpdate: false };
  12258. this.uniform = uniform;
  12259. this.numPlanes = 0;
  12260. this.numIntersection = 0;
  12261. this.init = function( planes, enableLocalClipping, camera ) {
  12262. var enabled =
  12263. planes.length !== 0 ||
  12264. enableLocalClipping ||
  12265. // enable state of previous frame - the clipping code has to
  12266. // run another frame in order to reset the state:
  12267. numGlobalPlanes !== 0 ||
  12268. localClippingEnabled;
  12269. localClippingEnabled = enableLocalClipping;
  12270. globalState = projectPlanes( planes, camera, 0 );
  12271. numGlobalPlanes = planes.length;
  12272. return enabled;
  12273. };
  12274. this.beginShadows = function() {
  12275. renderingShadows = true;
  12276. projectPlanes( null );
  12277. };
  12278. this.endShadows = function() {
  12279. renderingShadows = false;
  12280. resetGlobalState();
  12281. };
  12282. this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  12283. if ( ! localClippingEnabled ||
  12284. planes === null || planes.length === 0 ||
  12285. renderingShadows && ! clipShadows ) {
  12286. // there's no local clipping
  12287. if ( renderingShadows ) {
  12288. // there's no global clipping
  12289. projectPlanes( null );
  12290. } else {
  12291. resetGlobalState();
  12292. }
  12293. } else {
  12294. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  12295. lGlobal = nGlobal * 4,
  12296. dstArray = cache.clippingState || null;
  12297. uniform.value = dstArray; // ensure unique state
  12298. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  12299. for ( var i = 0; i !== lGlobal; ++ i ) {
  12300. dstArray[ i ] = globalState[ i ];
  12301. }
  12302. cache.clippingState = dstArray;
  12303. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  12304. this.numPlanes += nGlobal;
  12305. }
  12306. };
  12307. function resetGlobalState() {
  12308. if ( uniform.value !== globalState ) {
  12309. uniform.value = globalState;
  12310. uniform.needsUpdate = numGlobalPlanes > 0;
  12311. }
  12312. scope.numPlanes = numGlobalPlanes;
  12313. scope.numIntersection = 0;
  12314. }
  12315. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  12316. var nPlanes = planes !== null ? planes.length : 0,
  12317. dstArray = null;
  12318. if ( nPlanes !== 0 ) {
  12319. dstArray = uniform.value;
  12320. if ( skipTransform !== true || dstArray === null ) {
  12321. var flatSize = dstOffset + nPlanes * 4,
  12322. viewMatrix = camera.matrixWorldInverse;
  12323. viewNormalMatrix.getNormalMatrix( viewMatrix );
  12324. if ( dstArray === null || dstArray.length < flatSize ) {
  12325. dstArray = new Float32Array( flatSize );
  12326. }
  12327. for ( var i = 0, i4 = dstOffset;
  12328. i !== nPlanes; ++ i, i4 += 4 ) {
  12329. plane.copy( planes[ i ] ).
  12330. applyMatrix4( viewMatrix, viewNormalMatrix );
  12331. plane.normal.toArray( dstArray, i4 );
  12332. dstArray[ i4 + 3 ] = plane.constant;
  12333. }
  12334. }
  12335. uniform.value = dstArray;
  12336. uniform.needsUpdate = true;
  12337. }
  12338. scope.numPlanes = nPlanes;
  12339. return dstArray;
  12340. }
  12341. }
  12342. // import { Sphere } from '../math/Sphere';
  12343. /**
  12344. * @author supereggbert / http://www.paulbrunt.co.uk/
  12345. * @author mrdoob / http://mrdoob.com/
  12346. * @author alteredq / http://alteredqualia.com/
  12347. * @author szimek / https://github.com/szimek/
  12348. * @author tschw
  12349. */
  12350. function WebGLRenderer( parameters ) {
  12351. console.log( 'THREE.WebGLRenderer', REVISION );
  12352. parameters = parameters || {};
  12353. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  12354. _context = parameters.context !== undefined ? parameters.context : null,
  12355. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  12356. _depth = parameters.depth !== undefined ? parameters.depth : true,
  12357. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  12358. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  12359. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  12360. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  12361. var lightsArray = [];
  12362. var shadowsArray = [];
  12363. var currentRenderList = null;
  12364. var spritesArray = [];
  12365. var flaresArray = [];
  12366. // public properties
  12367. this.domElement = _canvas;
  12368. this.context = null;
  12369. // clearing
  12370. this.autoClear = true;
  12371. this.autoClearColor = true;
  12372. this.autoClearDepth = true;
  12373. this.autoClearStencil = true;
  12374. // scene graph
  12375. this.sortObjects = true;
  12376. // user-defined clipping
  12377. this.clippingPlanes = [];
  12378. this.localClippingEnabled = false;
  12379. // physically based shading
  12380. this.gammaFactor = 2.0; // for backwards compatibility
  12381. this.gammaInput = false;
  12382. this.gammaOutput = false;
  12383. // physical lights
  12384. this.physicallyCorrectLights = false;
  12385. // tone mapping
  12386. this.toneMapping = LinearToneMapping;
  12387. this.toneMappingExposure = 1.0;
  12388. this.toneMappingWhitePoint = 1.0;
  12389. // morphs
  12390. this.maxMorphTargets = 8;
  12391. this.maxMorphNormals = 4;
  12392. // internal properties
  12393. var _this = this,
  12394. _isContextLost = false,
  12395. // internal state cache
  12396. _currentRenderTarget = null,
  12397. _currentFramebuffer = null,
  12398. _currentMaterialId = - 1,
  12399. _currentGeometryProgram = '',
  12400. _currentCamera = null,
  12401. _currentArrayCamera = null,
  12402. _currentViewport = new Vector4(),
  12403. _currentScissor = new Vector4(),
  12404. _currentScissorTest = null,
  12405. //
  12406. _usedTextureUnits = 0,
  12407. //
  12408. _width = _canvas.width,
  12409. _height = _canvas.height,
  12410. _pixelRatio = 1,
  12411. _viewport = new Vector4( 0, 0, _width, _height ),
  12412. _scissor = new Vector4( 0, 0, _width, _height ),
  12413. _scissorTest = false,
  12414. // frustum
  12415. _frustum = new Frustum(),
  12416. // clipping
  12417. _clipping = new WebGLClipping(),
  12418. _clippingEnabled = false,
  12419. _localClippingEnabled = false,
  12420. // camera matrices cache
  12421. _projScreenMatrix = new Matrix4(),
  12422. _vector3 = new Vector3(),
  12423. // info
  12424. _infoMemory = {
  12425. geometries: 0,
  12426. textures: 0
  12427. },
  12428. _infoRender = {
  12429. frame: 0,
  12430. calls: 0,
  12431. vertices: 0,
  12432. faces: 0,
  12433. points: 0
  12434. };
  12435. this.info = {
  12436. render: _infoRender,
  12437. memory: _infoMemory,
  12438. programs: null
  12439. };
  12440. function getTargetPixelRatio() {
  12441. return _currentRenderTarget === null ? _pixelRatio : 1;
  12442. }
  12443. // initialize
  12444. var _gl;
  12445. try {
  12446. var contextAttributes = {
  12447. alpha: _alpha,
  12448. depth: _depth,
  12449. stencil: _stencil,
  12450. antialias: _antialias,
  12451. premultipliedAlpha: _premultipliedAlpha,
  12452. preserveDrawingBuffer: _preserveDrawingBuffer
  12453. };
  12454. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  12455. if ( _gl === null ) {
  12456. if ( _canvas.getContext( 'webgl' ) !== null ) {
  12457. throw 'Error creating WebGL context with your selected attributes.';
  12458. } else {
  12459. throw 'Error creating WebGL context.';
  12460. }
  12461. }
  12462. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  12463. if ( _gl.getShaderPrecisionFormat === undefined ) {
  12464. _gl.getShaderPrecisionFormat = function () {
  12465. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  12466. };
  12467. }
  12468. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  12469. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  12470. } catch ( error ) {
  12471. console.error( 'THREE.WebGLRenderer: ' + error );
  12472. }
  12473. var extensions, capabilities, state;
  12474. var properties, textures, attributes, geometries, objects, lights;
  12475. var programCache, renderLists;
  12476. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  12477. var flareRenderer, spriteRenderer;
  12478. function initGLContext() {
  12479. extensions = new WebGLExtensions( _gl );
  12480. extensions.get( 'WEBGL_depth_texture' );
  12481. extensions.get( 'OES_texture_float' );
  12482. extensions.get( 'OES_texture_float_linear' );
  12483. extensions.get( 'OES_texture_half_float' );
  12484. extensions.get( 'OES_texture_half_float_linear' );
  12485. extensions.get( 'OES_standard_derivatives' );
  12486. extensions.get( 'ANGLE_instanced_arrays' );
  12487. if ( extensions.get( 'OES_element_index_uint' ) ) {
  12488. BufferGeometry.MaxIndex = 4294967296;
  12489. }
  12490. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  12491. state = new WebGLState( _gl, extensions, paramThreeToGL );
  12492. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  12493. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  12494. properties = new WebGLProperties();
  12495. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, _infoMemory );
  12496. attributes = new WebGLAttributes( _gl );
  12497. geometries = new WebGLGeometries( _gl, attributes, _infoMemory );
  12498. objects = new WebGLObjects( geometries, _infoRender );
  12499. morphtargets = new WebGLMorphtargets( _gl );
  12500. programCache = new WebGLPrograms( _this, extensions, capabilities );
  12501. lights = new WebGLLights();
  12502. renderLists = new WebGLRenderLists();
  12503. background = new WebGLBackground( _this, state, geometries, _premultipliedAlpha );
  12504. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  12505. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  12506. flareRenderer = new WebGLFlareRenderer( _this, _gl, state, textures, capabilities );
  12507. spriteRenderer = new WebGLSpriteRenderer( _this, _gl, state, textures, capabilities );
  12508. _this.info.programs = programCache.programs;
  12509. _this.context = _gl;
  12510. _this.capabilities = capabilities;
  12511. _this.extensions = extensions;
  12512. _this.properties = properties;
  12513. _this.renderLists = renderLists;
  12514. _this.state = state;
  12515. }
  12516. initGLContext();
  12517. // vr
  12518. var vr = new WebVRManager( _this );
  12519. this.vr = vr;
  12520. // shadow map
  12521. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  12522. this.shadowMap = shadowMap;
  12523. // API
  12524. this.getContext = function () {
  12525. return _gl;
  12526. };
  12527. this.getContextAttributes = function () {
  12528. return _gl.getContextAttributes();
  12529. };
  12530. this.forceContextLoss = function () {
  12531. var extension = extensions.get( 'WEBGL_lose_context' );
  12532. if ( extension ) extension.loseContext();
  12533. };
  12534. this.forceContextRestore = function () {
  12535. var extension = extensions.get( 'WEBGL_lose_context' );
  12536. if ( extension ) extension.restoreContext();
  12537. };
  12538. this.getPixelRatio = function () {
  12539. return _pixelRatio;
  12540. };
  12541. this.setPixelRatio = function ( value ) {
  12542. if ( value === undefined ) return;
  12543. _pixelRatio = value;
  12544. this.setSize( _width, _height, false );
  12545. };
  12546. this.getSize = function () {
  12547. return {
  12548. width: _width,
  12549. height: _height
  12550. };
  12551. };
  12552. this.setSize = function ( width, height, updateStyle ) {
  12553. var device = vr.getDevice();
  12554. if ( device && device.isPresenting ) {
  12555. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  12556. return;
  12557. }
  12558. _width = width;
  12559. _height = height;
  12560. _canvas.width = width * _pixelRatio;
  12561. _canvas.height = height * _pixelRatio;
  12562. if ( updateStyle !== false ) {
  12563. _canvas.style.width = width + 'px';
  12564. _canvas.style.height = height + 'px';
  12565. }
  12566. this.setViewport( 0, 0, width, height );
  12567. };
  12568. this.getDrawingBufferSize = function () {
  12569. return {
  12570. width: _width * _pixelRatio,
  12571. height: _height * _pixelRatio
  12572. };
  12573. };
  12574. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  12575. _width = width;
  12576. _height = height;
  12577. _pixelRatio = pixelRatio;
  12578. _canvas.width = width * pixelRatio;
  12579. _canvas.height = height * pixelRatio;
  12580. this.setViewport( 0, 0, width, height );
  12581. };
  12582. this.setViewport = function ( x, y, width, height ) {
  12583. _viewport.set( x, _height - y - height, width, height );
  12584. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  12585. };
  12586. this.setScissor = function ( x, y, width, height ) {
  12587. _scissor.set( x, _height - y - height, width, height );
  12588. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  12589. };
  12590. this.setScissorTest = function ( boolean ) {
  12591. state.setScissorTest( _scissorTest = boolean );
  12592. };
  12593. // Clearing
  12594. this.getClearColor = background.getClearColor;
  12595. this.setClearColor = background.setClearColor;
  12596. this.getClearAlpha = background.getClearAlpha;
  12597. this.setClearAlpha = background.setClearAlpha;
  12598. this.clear = function ( color, depth, stencil ) {
  12599. var bits = 0;
  12600. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12601. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12602. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12603. _gl.clear( bits );
  12604. };
  12605. this.clearColor = function () {
  12606. this.clear( true, false, false );
  12607. };
  12608. this.clearDepth = function () {
  12609. this.clear( false, true, false );
  12610. };
  12611. this.clearStencil = function () {
  12612. this.clear( false, false, true );
  12613. };
  12614. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12615. this.setRenderTarget( renderTarget );
  12616. this.clear( color, depth, stencil );
  12617. };
  12618. //
  12619. this.dispose = function () {
  12620. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  12621. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  12622. renderLists.dispose();
  12623. vr.dispose();
  12624. };
  12625. // Events
  12626. function onContextLost( event ) {
  12627. event.preventDefault();
  12628. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  12629. _isContextLost = true;
  12630. }
  12631. function onContextRestore( event ) {
  12632. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  12633. _isContextLost = false;
  12634. initGLContext();
  12635. }
  12636. function onMaterialDispose( event ) {
  12637. var material = event.target;
  12638. material.removeEventListener( 'dispose', onMaterialDispose );
  12639. deallocateMaterial( material );
  12640. }
  12641. // Buffer deallocation
  12642. function deallocateMaterial( material ) {
  12643. releaseMaterialProgramReference( material );
  12644. properties.remove( material );
  12645. }
  12646. function releaseMaterialProgramReference( material ) {
  12647. var programInfo = properties.get( material ).program;
  12648. material.program = undefined;
  12649. if ( programInfo !== undefined ) {
  12650. programCache.releaseProgram( programInfo );
  12651. }
  12652. }
  12653. // Buffer rendering
  12654. function renderObjectImmediate( object, program, material ) {
  12655. object.render( function ( object ) {
  12656. _this.renderBufferImmediate( object, program, material );
  12657. } );
  12658. }
  12659. this.renderBufferImmediate = function ( object, program, material ) {
  12660. state.initAttributes();
  12661. var buffers = properties.get( object );
  12662. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  12663. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  12664. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  12665. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  12666. var programAttributes = program.getAttributes();
  12667. if ( object.hasPositions ) {
  12668. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  12669. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12670. state.enableAttribute( programAttributes.position );
  12671. _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12672. }
  12673. if ( object.hasNormals ) {
  12674. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  12675. if ( ! material.isMeshPhongMaterial &&
  12676. ! material.isMeshStandardMaterial &&
  12677. ! material.isMeshNormalMaterial &&
  12678. material.flatShading === true ) {
  12679. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  12680. var array = object.normalArray;
  12681. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  12682. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  12683. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  12684. array[ i + 0 ] = nx;
  12685. array[ i + 1 ] = ny;
  12686. array[ i + 2 ] = nz;
  12687. array[ i + 3 ] = nx;
  12688. array[ i + 4 ] = ny;
  12689. array[ i + 5 ] = nz;
  12690. array[ i + 6 ] = nx;
  12691. array[ i + 7 ] = ny;
  12692. array[ i + 8 ] = nz;
  12693. }
  12694. }
  12695. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12696. state.enableAttribute( programAttributes.normal );
  12697. _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12698. }
  12699. if ( object.hasUvs && material.map ) {
  12700. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  12701. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12702. state.enableAttribute( programAttributes.uv );
  12703. _gl.vertexAttribPointer( programAttributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12704. }
  12705. if ( object.hasColors && material.vertexColors !== NoColors ) {
  12706. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  12707. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12708. state.enableAttribute( programAttributes.color );
  12709. _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12710. }
  12711. state.disableUnusedAttributes();
  12712. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12713. object.count = 0;
  12714. };
  12715. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  12716. state.setMaterial( material );
  12717. var program = setProgram( camera, fog, material, object );
  12718. var geometryProgram = geometry.id + '_' + program.id + '_' + ( material.wireframe === true );
  12719. var updateBuffers = false;
  12720. if ( geometryProgram !== _currentGeometryProgram ) {
  12721. _currentGeometryProgram = geometryProgram;
  12722. updateBuffers = true;
  12723. }
  12724. if ( object.morphTargetInfluences ) {
  12725. morphtargets.update( object, geometry, material, program );
  12726. updateBuffers = true;
  12727. }
  12728. //
  12729. var index = geometry.index;
  12730. var position = geometry.attributes.position;
  12731. var rangeFactor = 1;
  12732. if ( material.wireframe === true ) {
  12733. index = geometries.getWireframeAttribute( geometry );
  12734. rangeFactor = 2;
  12735. }
  12736. var attribute;
  12737. var renderer = bufferRenderer;
  12738. if ( index !== null ) {
  12739. attribute = attributes.get( index );
  12740. renderer = indexedBufferRenderer;
  12741. renderer.setIndex( attribute );
  12742. }
  12743. if ( updateBuffers ) {
  12744. setupVertexAttributes( material, program, geometry );
  12745. if ( index !== null ) {
  12746. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attribute.buffer );
  12747. }
  12748. }
  12749. //
  12750. var dataCount = 0;
  12751. if ( index !== null ) {
  12752. dataCount = index.count;
  12753. } else if ( position !== undefined ) {
  12754. dataCount = position.count;
  12755. }
  12756. var rangeStart = geometry.drawRange.start * rangeFactor;
  12757. var rangeCount = geometry.drawRange.count * rangeFactor;
  12758. var groupStart = group !== null ? group.start * rangeFactor : 0;
  12759. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  12760. var drawStart = Math.max( rangeStart, groupStart );
  12761. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  12762. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  12763. if ( drawCount === 0 ) return;
  12764. //
  12765. if ( object.isMesh ) {
  12766. if ( material.wireframe === true ) {
  12767. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  12768. renderer.setMode( _gl.LINES );
  12769. } else {
  12770. switch ( object.drawMode ) {
  12771. case TrianglesDrawMode:
  12772. renderer.setMode( _gl.TRIANGLES );
  12773. break;
  12774. case TriangleStripDrawMode:
  12775. renderer.setMode( _gl.TRIANGLE_STRIP );
  12776. break;
  12777. case TriangleFanDrawMode:
  12778. renderer.setMode( _gl.TRIANGLE_FAN );
  12779. break;
  12780. }
  12781. }
  12782. } else if ( object.isLine ) {
  12783. var lineWidth = material.linewidth;
  12784. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  12785. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  12786. if ( object.isLineSegments ) {
  12787. renderer.setMode( _gl.LINES );
  12788. } else if ( object.isLineLoop ) {
  12789. renderer.setMode( _gl.LINE_LOOP );
  12790. } else {
  12791. renderer.setMode( _gl.LINE_STRIP );
  12792. }
  12793. } else if ( object.isPoints ) {
  12794. renderer.setMode( _gl.POINTS );
  12795. }
  12796. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12797. if ( geometry.maxInstancedCount > 0 ) {
  12798. renderer.renderInstances( geometry, drawStart, drawCount );
  12799. }
  12800. } else {
  12801. renderer.render( drawStart, drawCount );
  12802. }
  12803. };
  12804. function setupVertexAttributes( material, program, geometry, startIndex ) {
  12805. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12806. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  12807. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12808. return;
  12809. }
  12810. }
  12811. if ( startIndex === undefined ) startIndex = 0;
  12812. state.initAttributes();
  12813. var geometryAttributes = geometry.attributes;
  12814. var programAttributes = program.getAttributes();
  12815. var materialDefaultAttributeValues = material.defaultAttributeValues;
  12816. for ( var name in programAttributes ) {
  12817. var programAttribute = programAttributes[ name ];
  12818. if ( programAttribute >= 0 ) {
  12819. var geometryAttribute = geometryAttributes[ name ];
  12820. if ( geometryAttribute !== undefined ) {
  12821. var normalized = geometryAttribute.normalized;
  12822. var size = geometryAttribute.itemSize;
  12823. var attribute = attributes.get( geometryAttribute );
  12824. // TODO Attribute may not be available on context restore
  12825. if ( attribute === undefined ) continue;
  12826. var buffer = attribute.buffer;
  12827. var type = attribute.type;
  12828. var bytesPerElement = attribute.bytesPerElement;
  12829. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  12830. var data = geometryAttribute.data;
  12831. var stride = data.stride;
  12832. var offset = geometryAttribute.offset;
  12833. if ( data && data.isInstancedInterleavedBuffer ) {
  12834. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  12835. if ( geometry.maxInstancedCount === undefined ) {
  12836. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  12837. }
  12838. } else {
  12839. state.enableAttribute( programAttribute );
  12840. }
  12841. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12842. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  12843. } else {
  12844. if ( geometryAttribute.isInstancedBufferAttribute ) {
  12845. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  12846. if ( geometry.maxInstancedCount === undefined ) {
  12847. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  12848. }
  12849. } else {
  12850. state.enableAttribute( programAttribute );
  12851. }
  12852. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12853. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  12854. }
  12855. } else if ( materialDefaultAttributeValues !== undefined ) {
  12856. var value = materialDefaultAttributeValues[ name ];
  12857. if ( value !== undefined ) {
  12858. switch ( value.length ) {
  12859. case 2:
  12860. _gl.vertexAttrib2fv( programAttribute, value );
  12861. break;
  12862. case 3:
  12863. _gl.vertexAttrib3fv( programAttribute, value );
  12864. break;
  12865. case 4:
  12866. _gl.vertexAttrib4fv( programAttribute, value );
  12867. break;
  12868. default:
  12869. _gl.vertexAttrib1fv( programAttribute, value );
  12870. }
  12871. }
  12872. }
  12873. }
  12874. }
  12875. state.disableUnusedAttributes();
  12876. }
  12877. // Compile
  12878. this.compile = function ( scene, camera ) {
  12879. lightsArray.length = 0;
  12880. shadowsArray.length = 0;
  12881. scene.traverse( function ( object ) {
  12882. if ( object.isLight ) {
  12883. lightsArray.push( object );
  12884. if ( object.castShadow ) {
  12885. shadowsArray.push( object );
  12886. }
  12887. }
  12888. } );
  12889. lights.setup( lightsArray, shadowsArray, camera );
  12890. scene.traverse( function ( object ) {
  12891. if ( object.material ) {
  12892. if ( Array.isArray( object.material ) ) {
  12893. for ( var i = 0; i < object.material.length; i ++ ) {
  12894. initMaterial( object.material[ i ], scene.fog, object );
  12895. }
  12896. } else {
  12897. initMaterial( object.material, scene.fog, object );
  12898. }
  12899. }
  12900. } );
  12901. };
  12902. // Rendering
  12903. this.animate = function ( callback ) {
  12904. function onFrame() {
  12905. callback();
  12906. ( vr.getDevice() || window ).requestAnimationFrame( onFrame );
  12907. }
  12908. ( vr.getDevice() || window ).requestAnimationFrame( onFrame );
  12909. };
  12910. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12911. if ( ! ( camera && camera.isCamera ) ) {
  12912. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12913. return;
  12914. }
  12915. if ( _isContextLost ) return;
  12916. // reset caching for this frame
  12917. _currentGeometryProgram = '';
  12918. _currentMaterialId = - 1;
  12919. _currentCamera = null;
  12920. // update scene graph
  12921. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12922. // update camera matrices and frustum
  12923. if ( camera.parent === null ) camera.updateMatrixWorld();
  12924. if ( vr.enabled ) {
  12925. camera = vr.getCamera( camera );
  12926. }
  12927. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12928. _frustum.setFromMatrix( _projScreenMatrix );
  12929. lightsArray.length = 0;
  12930. shadowsArray.length = 0;
  12931. spritesArray.length = 0;
  12932. flaresArray.length = 0;
  12933. _localClippingEnabled = this.localClippingEnabled;
  12934. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  12935. currentRenderList = renderLists.get( scene, camera );
  12936. currentRenderList.init();
  12937. projectObject( scene, camera, _this.sortObjects );
  12938. if ( _this.sortObjects === true ) {
  12939. currentRenderList.sort();
  12940. }
  12941. //
  12942. if ( _clippingEnabled ) _clipping.beginShadows();
  12943. shadowMap.render( shadowsArray, scene, camera );
  12944. lights.setup( lightsArray, shadowsArray, camera );
  12945. if ( _clippingEnabled ) _clipping.endShadows();
  12946. //
  12947. _infoRender.frame ++;
  12948. _infoRender.calls = 0;
  12949. _infoRender.vertices = 0;
  12950. _infoRender.faces = 0;
  12951. _infoRender.points = 0;
  12952. if ( renderTarget === undefined ) {
  12953. renderTarget = null;
  12954. }
  12955. this.setRenderTarget( renderTarget );
  12956. //
  12957. background.render( currentRenderList, scene, camera, forceClear );
  12958. // render scene
  12959. var opaqueObjects = currentRenderList.opaque;
  12960. var transparentObjects = currentRenderList.transparent;
  12961. if ( scene.overrideMaterial ) {
  12962. var overrideMaterial = scene.overrideMaterial;
  12963. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  12964. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  12965. } else {
  12966. // opaque pass (front-to-back order)
  12967. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  12968. // transparent pass (back-to-front order)
  12969. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  12970. }
  12971. // custom renderers
  12972. spriteRenderer.render( spritesArray, scene, camera );
  12973. flareRenderer.render( flaresArray, scene, camera, _currentViewport );
  12974. // Generate mipmap if we're using any kind of mipmap filtering
  12975. if ( renderTarget ) {
  12976. textures.updateRenderTargetMipmap( renderTarget );
  12977. }
  12978. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12979. state.buffers.depth.setTest( true );
  12980. state.buffers.depth.setMask( true );
  12981. state.buffers.color.setMask( true );
  12982. if ( vr.enabled ) {
  12983. vr.submitFrame();
  12984. }
  12985. // _gl.finish();
  12986. };
  12987. /*
  12988. // TODO Duplicated code (Frustum)
  12989. var _sphere = new Sphere();
  12990. function isObjectViewable( object ) {
  12991. var geometry = object.geometry;
  12992. if ( geometry.boundingSphere === null )
  12993. geometry.computeBoundingSphere();
  12994. _sphere.copy( geometry.boundingSphere ).
  12995. applyMatrix4( object.matrixWorld );
  12996. return isSphereViewable( _sphere );
  12997. }
  12998. function isSpriteViewable( sprite ) {
  12999. _sphere.center.set( 0, 0, 0 );
  13000. _sphere.radius = 0.7071067811865476;
  13001. _sphere.applyMatrix4( sprite.matrixWorld );
  13002. return isSphereViewable( _sphere );
  13003. }
  13004. function isSphereViewable( sphere ) {
  13005. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  13006. var numPlanes = _clipping.numPlanes;
  13007. if ( numPlanes === 0 ) return true;
  13008. var planes = _this.clippingPlanes,
  13009. center = sphere.center,
  13010. negRad = - sphere.radius,
  13011. i = 0;
  13012. do {
  13013. // out when deeper than radius in the negative halfspace
  13014. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  13015. } while ( ++ i !== numPlanes );
  13016. return true;
  13017. }
  13018. */
  13019. function projectObject( object, camera, sortObjects ) {
  13020. if ( ! object.visible ) return;
  13021. var visible = object.layers.test( camera.layers );
  13022. if ( visible ) {
  13023. if ( object.isLight ) {
  13024. lightsArray.push( object );
  13025. if ( object.castShadow ) {
  13026. shadowsArray.push( object );
  13027. }
  13028. } else if ( object.isSprite ) {
  13029. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  13030. spritesArray.push( object );
  13031. }
  13032. } else if ( object.isLensFlare ) {
  13033. flaresArray.push( object );
  13034. } else if ( object.isImmediateRenderObject ) {
  13035. if ( sortObjects ) {
  13036. _vector3.setFromMatrixPosition( object.matrixWorld )
  13037. .applyMatrix4( _projScreenMatrix );
  13038. }
  13039. currentRenderList.push( object, null, object.material, _vector3.z, null );
  13040. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  13041. if ( object.isSkinnedMesh ) {
  13042. object.skeleton.update();
  13043. }
  13044. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  13045. if ( sortObjects ) {
  13046. _vector3.setFromMatrixPosition( object.matrixWorld )
  13047. .applyMatrix4( _projScreenMatrix );
  13048. }
  13049. var geometry = objects.update( object );
  13050. var material = object.material;
  13051. if ( Array.isArray( material ) ) {
  13052. var groups = geometry.groups;
  13053. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  13054. var group = groups[ i ];
  13055. var groupMaterial = material[ group.materialIndex ];
  13056. if ( groupMaterial && groupMaterial.visible ) {
  13057. currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group );
  13058. }
  13059. }
  13060. } else if ( material.visible ) {
  13061. currentRenderList.push( object, geometry, material, _vector3.z, null );
  13062. }
  13063. }
  13064. }
  13065. }
  13066. var children = object.children;
  13067. for ( var i = 0, l = children.length; i < l; i ++ ) {
  13068. projectObject( children[ i ], camera, sortObjects );
  13069. }
  13070. }
  13071. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  13072. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  13073. var renderItem = renderList[ i ];
  13074. var object = renderItem.object;
  13075. var geometry = renderItem.geometry;
  13076. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  13077. var group = renderItem.group;
  13078. if ( camera.isArrayCamera ) {
  13079. _currentArrayCamera = camera;
  13080. var cameras = camera.cameras;
  13081. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  13082. var camera2 = cameras[ j ];
  13083. if ( object.layers.test( camera2.layers ) ) {
  13084. var bounds = camera2.bounds;
  13085. var x = bounds.x * _width;
  13086. var y = bounds.y * _height;
  13087. var width = bounds.z * _width;
  13088. var height = bounds.w * _height;
  13089. state.viewport( _currentViewport.set( x, y, width, height ).multiplyScalar( _pixelRatio ) );
  13090. state.scissor( _currentScissor.set( x, y, width, height ).multiplyScalar( _pixelRatio ) );
  13091. state.setScissorTest( true );
  13092. renderObject( object, scene, camera2, geometry, material, group );
  13093. }
  13094. }
  13095. } else {
  13096. _currentArrayCamera = null;
  13097. renderObject( object, scene, camera, geometry, material, group );
  13098. }
  13099. }
  13100. }
  13101. function renderObject( object, scene, camera, geometry, material, group ) {
  13102. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  13103. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  13104. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  13105. if ( object.isImmediateRenderObject ) {
  13106. state.setMaterial( material );
  13107. var program = setProgram( camera, scene.fog, material, object );
  13108. _currentGeometryProgram = '';
  13109. renderObjectImmediate( object, program, material );
  13110. } else {
  13111. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  13112. }
  13113. object.onAfterRender( _this, scene, camera, geometry, material, group );
  13114. }
  13115. function initMaterial( material, fog, object ) {
  13116. var materialProperties = properties.get( material );
  13117. var parameters = programCache.getParameters(
  13118. material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  13119. var code = programCache.getProgramCode( material, parameters );
  13120. var program = materialProperties.program;
  13121. var programChange = true;
  13122. if ( program === undefined ) {
  13123. // new material
  13124. material.addEventListener( 'dispose', onMaterialDispose );
  13125. } else if ( program.code !== code ) {
  13126. // changed glsl or parameters
  13127. releaseMaterialProgramReference( material );
  13128. } else if ( parameters.shaderID !== undefined ) {
  13129. // same glsl and uniform list
  13130. return;
  13131. } else {
  13132. // only rebuild uniform list
  13133. programChange = false;
  13134. }
  13135. if ( programChange ) {
  13136. if ( parameters.shaderID ) {
  13137. var shader = ShaderLib[ parameters.shaderID ];
  13138. materialProperties.shader = {
  13139. name: material.type,
  13140. uniforms: UniformsUtils.clone( shader.uniforms ),
  13141. vertexShader: shader.vertexShader,
  13142. fragmentShader: shader.fragmentShader
  13143. };
  13144. } else {
  13145. materialProperties.shader = {
  13146. name: material.type,
  13147. uniforms: material.uniforms,
  13148. vertexShader: material.vertexShader,
  13149. fragmentShader: material.fragmentShader
  13150. };
  13151. }
  13152. material.onBeforeCompile( materialProperties.shader );
  13153. program = programCache.acquireProgram( material, materialProperties.shader, parameters, code );
  13154. materialProperties.program = program;
  13155. material.program = program;
  13156. }
  13157. var programAttributes = program.getAttributes();
  13158. if ( material.morphTargets ) {
  13159. material.numSupportedMorphTargets = 0;
  13160. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  13161. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  13162. material.numSupportedMorphTargets ++;
  13163. }
  13164. }
  13165. }
  13166. if ( material.morphNormals ) {
  13167. material.numSupportedMorphNormals = 0;
  13168. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  13169. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  13170. material.numSupportedMorphNormals ++;
  13171. }
  13172. }
  13173. }
  13174. var uniforms = materialProperties.shader.uniforms;
  13175. if ( ! material.isShaderMaterial &&
  13176. ! material.isRawShaderMaterial ||
  13177. material.clipping === true ) {
  13178. materialProperties.numClippingPlanes = _clipping.numPlanes;
  13179. materialProperties.numIntersection = _clipping.numIntersection;
  13180. uniforms.clippingPlanes = _clipping.uniform;
  13181. }
  13182. materialProperties.fog = fog;
  13183. // store the light setup it was created for
  13184. materialProperties.lightsHash = lights.state.hash;
  13185. if ( material.lights ) {
  13186. // wire up the material to this renderer's lighting state
  13187. uniforms.ambientLightColor.value = lights.state.ambient;
  13188. uniforms.directionalLights.value = lights.state.directional;
  13189. uniforms.spotLights.value = lights.state.spot;
  13190. uniforms.rectAreaLights.value = lights.state.rectArea;
  13191. uniforms.pointLights.value = lights.state.point;
  13192. uniforms.hemisphereLights.value = lights.state.hemi;
  13193. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  13194. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  13195. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  13196. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  13197. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  13198. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  13199. // TODO (abelnation): add area lights shadow info to uniforms
  13200. }
  13201. var progUniforms = materialProperties.program.getUniforms(),
  13202. uniformsList =
  13203. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  13204. materialProperties.uniformsList = uniformsList;
  13205. }
  13206. function setProgram( camera, fog, material, object ) {
  13207. _usedTextureUnits = 0;
  13208. var materialProperties = properties.get( material );
  13209. if ( _clippingEnabled ) {
  13210. if ( _localClippingEnabled || camera !== _currentCamera ) {
  13211. var useCache =
  13212. camera === _currentCamera &&
  13213. material.id === _currentMaterialId;
  13214. // we might want to call this function with some ClippingGroup
  13215. // object instead of the material, once it becomes feasible
  13216. // (#8465, #8379)
  13217. _clipping.setState(
  13218. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  13219. camera, materialProperties, useCache );
  13220. }
  13221. }
  13222. if ( material.needsUpdate === false ) {
  13223. if ( materialProperties.program === undefined ) {
  13224. material.needsUpdate = true;
  13225. } else if ( material.fog && materialProperties.fog !== fog ) {
  13226. material.needsUpdate = true;
  13227. } else if ( material.lights && materialProperties.lightsHash !== lights.state.hash ) {
  13228. material.needsUpdate = true;
  13229. } else if ( materialProperties.numClippingPlanes !== undefined &&
  13230. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  13231. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  13232. material.needsUpdate = true;
  13233. }
  13234. }
  13235. if ( material.needsUpdate ) {
  13236. initMaterial( material, fog, object );
  13237. material.needsUpdate = false;
  13238. }
  13239. var refreshProgram = false;
  13240. var refreshMaterial = false;
  13241. var refreshLights = false;
  13242. var program = materialProperties.program,
  13243. p_uniforms = program.getUniforms(),
  13244. m_uniforms = materialProperties.shader.uniforms;
  13245. if ( state.useProgram( program.program ) ) {
  13246. refreshProgram = true;
  13247. refreshMaterial = true;
  13248. refreshLights = true;
  13249. }
  13250. if ( material.id !== _currentMaterialId ) {
  13251. _currentMaterialId = material.id;
  13252. refreshMaterial = true;
  13253. }
  13254. if ( refreshProgram || camera !== _currentCamera ) {
  13255. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  13256. if ( capabilities.logarithmicDepthBuffer ) {
  13257. p_uniforms.setValue( _gl, 'logDepthBufFC',
  13258. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  13259. }
  13260. // Avoid unneeded uniform updates per ArrayCamera's sub-camera
  13261. if ( _currentCamera !== ( _currentArrayCamera || camera ) ) {
  13262. _currentCamera = ( _currentArrayCamera || camera );
  13263. // lighting uniforms depend on the camera so enforce an update
  13264. // now, in case this material supports lights - or later, when
  13265. // the next material that does gets activated:
  13266. refreshMaterial = true; // set to true on material change
  13267. refreshLights = true; // remains set until update done
  13268. }
  13269. // load material specific uniforms
  13270. // (shader material also gets them for the sake of genericity)
  13271. if ( material.isShaderMaterial ||
  13272. material.isMeshPhongMaterial ||
  13273. material.isMeshStandardMaterial ||
  13274. material.envMap ) {
  13275. var uCamPos = p_uniforms.map.cameraPosition;
  13276. if ( uCamPos !== undefined ) {
  13277. uCamPos.setValue( _gl,
  13278. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  13279. }
  13280. }
  13281. if ( material.isMeshPhongMaterial ||
  13282. material.isMeshLambertMaterial ||
  13283. material.isMeshBasicMaterial ||
  13284. material.isMeshStandardMaterial ||
  13285. material.isShaderMaterial ||
  13286. material.skinning ) {
  13287. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  13288. }
  13289. }
  13290. // skinning uniforms must be set even if material didn't change
  13291. // auto-setting of texture unit for bone texture must go before other textures
  13292. // not sure why, but otherwise weird things happen
  13293. if ( material.skinning ) {
  13294. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  13295. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  13296. var skeleton = object.skeleton;
  13297. if ( skeleton ) {
  13298. var bones = skeleton.bones;
  13299. if ( capabilities.floatVertexTextures ) {
  13300. if ( skeleton.boneTexture === undefined ) {
  13301. // layout (1 matrix = 4 pixels)
  13302. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13303. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13304. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13305. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13306. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13307. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  13308. size = _Math.nextPowerOfTwo( Math.ceil( size ) );
  13309. size = Math.max( size, 4 );
  13310. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  13311. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  13312. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  13313. skeleton.boneMatrices = boneMatrices;
  13314. skeleton.boneTexture = boneTexture;
  13315. skeleton.boneTextureSize = size;
  13316. }
  13317. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture );
  13318. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  13319. } else {
  13320. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  13321. }
  13322. }
  13323. }
  13324. if ( refreshMaterial ) {
  13325. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  13326. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  13327. if ( material.lights ) {
  13328. // the current material requires lighting info
  13329. // note: all lighting uniforms are always set correctly
  13330. // they simply reference the renderer's state for their
  13331. // values
  13332. //
  13333. // use the current material's .needsUpdate flags to set
  13334. // the GL state when required
  13335. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  13336. }
  13337. // refresh uniforms common to several materials
  13338. if ( fog && material.fog ) {
  13339. refreshUniformsFog( m_uniforms, fog );
  13340. }
  13341. if ( material.isMeshBasicMaterial ||
  13342. material.isMeshLambertMaterial ||
  13343. material.isMeshPhongMaterial ||
  13344. material.isMeshStandardMaterial ||
  13345. material.isMeshNormalMaterial ||
  13346. material.isMeshDepthMaterial ||
  13347. material.isMeshDistanceMaterial ) {
  13348. refreshUniformsCommon( m_uniforms, material );
  13349. }
  13350. // refresh single material specific uniforms
  13351. if ( material.isLineBasicMaterial ) {
  13352. refreshUniformsLine( m_uniforms, material );
  13353. } else if ( material.isLineDashedMaterial ) {
  13354. refreshUniformsLine( m_uniforms, material );
  13355. refreshUniformsDash( m_uniforms, material );
  13356. } else if ( material.isPointsMaterial ) {
  13357. refreshUniformsPoints( m_uniforms, material );
  13358. } else if ( material.isMeshLambertMaterial ) {
  13359. refreshUniformsLambert( m_uniforms, material );
  13360. } else if ( material.isMeshToonMaterial ) {
  13361. refreshUniformsToon( m_uniforms, material );
  13362. } else if ( material.isMeshPhongMaterial ) {
  13363. refreshUniformsPhong( m_uniforms, material );
  13364. } else if ( material.isMeshPhysicalMaterial ) {
  13365. refreshUniformsPhysical( m_uniforms, material );
  13366. } else if ( material.isMeshStandardMaterial ) {
  13367. refreshUniformsStandard( m_uniforms, material );
  13368. } else if ( material.isMeshDepthMaterial ) {
  13369. refreshUniformsDepth( m_uniforms, material );
  13370. } else if ( material.isMeshDistanceMaterial ) {
  13371. refreshUniformsDistance( m_uniforms, material );
  13372. } else if ( material.isMeshNormalMaterial ) {
  13373. refreshUniformsNormal( m_uniforms, material );
  13374. }
  13375. // RectAreaLight Texture
  13376. // TODO (mrdoob): Find a nicer implementation
  13377. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = UniformsLib.LTC_MAT_TEXTURE;
  13378. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = UniformsLib.LTC_MAG_TEXTURE;
  13379. WebGLUniforms.upload(
  13380. _gl, materialProperties.uniformsList, m_uniforms, _this );
  13381. }
  13382. // common matrices
  13383. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  13384. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  13385. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  13386. return program;
  13387. }
  13388. // Uniforms (refresh uniforms objects)
  13389. function refreshUniformsCommon( uniforms, material ) {
  13390. uniforms.opacity.value = material.opacity;
  13391. if ( material.color ) {
  13392. uniforms.diffuse.value = material.color;
  13393. }
  13394. if ( material.emissive ) {
  13395. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  13396. }
  13397. if ( material.map ) {
  13398. uniforms.map.value = material.map;
  13399. }
  13400. if ( material.alphaMap ) {
  13401. uniforms.alphaMap.value = material.alphaMap;
  13402. }
  13403. if ( material.specularMap ) {
  13404. uniforms.specularMap.value = material.specularMap;
  13405. }
  13406. if ( material.envMap ) {
  13407. uniforms.envMap.value = material.envMap;
  13408. // don't flip CubeTexture envMaps, flip everything else:
  13409. // WebGLRenderTargetCube will be flipped for backwards compatibility
  13410. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  13411. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  13412. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  13413. uniforms.reflectivity.value = material.reflectivity;
  13414. uniforms.refractionRatio.value = material.refractionRatio;
  13415. }
  13416. if ( material.lightMap ) {
  13417. uniforms.lightMap.value = material.lightMap;
  13418. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13419. }
  13420. if ( material.aoMap ) {
  13421. uniforms.aoMap.value = material.aoMap;
  13422. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13423. }
  13424. // uv repeat and offset setting priorities
  13425. // 1. color map
  13426. // 2. specular map
  13427. // 3. normal map
  13428. // 4. bump map
  13429. // 5. alpha map
  13430. // 6. emissive map
  13431. var uvScaleMap;
  13432. if ( material.map ) {
  13433. uvScaleMap = material.map;
  13434. } else if ( material.specularMap ) {
  13435. uvScaleMap = material.specularMap;
  13436. } else if ( material.displacementMap ) {
  13437. uvScaleMap = material.displacementMap;
  13438. } else if ( material.normalMap ) {
  13439. uvScaleMap = material.normalMap;
  13440. } else if ( material.bumpMap ) {
  13441. uvScaleMap = material.bumpMap;
  13442. } else if ( material.roughnessMap ) {
  13443. uvScaleMap = material.roughnessMap;
  13444. } else if ( material.metalnessMap ) {
  13445. uvScaleMap = material.metalnessMap;
  13446. } else if ( material.alphaMap ) {
  13447. uvScaleMap = material.alphaMap;
  13448. } else if ( material.emissiveMap ) {
  13449. uvScaleMap = material.emissiveMap;
  13450. }
  13451. if ( uvScaleMap !== undefined ) {
  13452. // backwards compatibility
  13453. if ( uvScaleMap.isWebGLRenderTarget ) {
  13454. uvScaleMap = uvScaleMap.texture;
  13455. }
  13456. var offset = uvScaleMap.offset;
  13457. var repeat = uvScaleMap.repeat;
  13458. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13459. }
  13460. }
  13461. function refreshUniformsLine( uniforms, material ) {
  13462. uniforms.diffuse.value = material.color;
  13463. uniforms.opacity.value = material.opacity;
  13464. }
  13465. function refreshUniformsDash( uniforms, material ) {
  13466. uniforms.dashSize.value = material.dashSize;
  13467. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13468. uniforms.scale.value = material.scale;
  13469. }
  13470. function refreshUniformsPoints( uniforms, material ) {
  13471. uniforms.diffuse.value = material.color;
  13472. uniforms.opacity.value = material.opacity;
  13473. uniforms.size.value = material.size * _pixelRatio;
  13474. uniforms.scale.value = _height * 0.5;
  13475. uniforms.map.value = material.map;
  13476. if ( material.map !== null ) {
  13477. var offset = material.map.offset;
  13478. var repeat = material.map.repeat;
  13479. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13480. }
  13481. }
  13482. function refreshUniformsFog( uniforms, fog ) {
  13483. uniforms.fogColor.value = fog.color;
  13484. if ( fog.isFog ) {
  13485. uniforms.fogNear.value = fog.near;
  13486. uniforms.fogFar.value = fog.far;
  13487. } else if ( fog.isFogExp2 ) {
  13488. uniforms.fogDensity.value = fog.density;
  13489. }
  13490. }
  13491. function refreshUniformsLambert( uniforms, material ) {
  13492. if ( material.emissiveMap ) {
  13493. uniforms.emissiveMap.value = material.emissiveMap;
  13494. }
  13495. }
  13496. function refreshUniformsPhong( uniforms, material ) {
  13497. uniforms.specular.value = material.specular;
  13498. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13499. if ( material.emissiveMap ) {
  13500. uniforms.emissiveMap.value = material.emissiveMap;
  13501. }
  13502. if ( material.bumpMap ) {
  13503. uniforms.bumpMap.value = material.bumpMap;
  13504. uniforms.bumpScale.value = material.bumpScale;
  13505. }
  13506. if ( material.normalMap ) {
  13507. uniforms.normalMap.value = material.normalMap;
  13508. uniforms.normalScale.value.copy( material.normalScale );
  13509. }
  13510. if ( material.displacementMap ) {
  13511. uniforms.displacementMap.value = material.displacementMap;
  13512. uniforms.displacementScale.value = material.displacementScale;
  13513. uniforms.displacementBias.value = material.displacementBias;
  13514. }
  13515. }
  13516. function refreshUniformsToon( uniforms, material ) {
  13517. refreshUniformsPhong( uniforms, material );
  13518. if ( material.gradientMap ) {
  13519. uniforms.gradientMap.value = material.gradientMap;
  13520. }
  13521. }
  13522. function refreshUniformsStandard( uniforms, material ) {
  13523. uniforms.roughness.value = material.roughness;
  13524. uniforms.metalness.value = material.metalness;
  13525. if ( material.roughnessMap ) {
  13526. uniforms.roughnessMap.value = material.roughnessMap;
  13527. }
  13528. if ( material.metalnessMap ) {
  13529. uniforms.metalnessMap.value = material.metalnessMap;
  13530. }
  13531. if ( material.emissiveMap ) {
  13532. uniforms.emissiveMap.value = material.emissiveMap;
  13533. }
  13534. if ( material.bumpMap ) {
  13535. uniforms.bumpMap.value = material.bumpMap;
  13536. uniforms.bumpScale.value = material.bumpScale;
  13537. }
  13538. if ( material.normalMap ) {
  13539. uniforms.normalMap.value = material.normalMap;
  13540. uniforms.normalScale.value.copy( material.normalScale );
  13541. }
  13542. if ( material.displacementMap ) {
  13543. uniforms.displacementMap.value = material.displacementMap;
  13544. uniforms.displacementScale.value = material.displacementScale;
  13545. uniforms.displacementBias.value = material.displacementBias;
  13546. }
  13547. if ( material.envMap ) {
  13548. //uniforms.envMap.value = material.envMap; // part of uniforms common
  13549. uniforms.envMapIntensity.value = material.envMapIntensity;
  13550. }
  13551. }
  13552. function refreshUniformsPhysical( uniforms, material ) {
  13553. uniforms.clearCoat.value = material.clearCoat;
  13554. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  13555. refreshUniformsStandard( uniforms, material );
  13556. }
  13557. function refreshUniformsDepth( uniforms, material ) {
  13558. if ( material.displacementMap ) {
  13559. uniforms.displacementMap.value = material.displacementMap;
  13560. uniforms.displacementScale.value = material.displacementScale;
  13561. uniforms.displacementBias.value = material.displacementBias;
  13562. }
  13563. }
  13564. function refreshUniformsDistance( uniforms, material ) {
  13565. if ( material.displacementMap ) {
  13566. uniforms.displacementMap.value = material.displacementMap;
  13567. uniforms.displacementScale.value = material.displacementScale;
  13568. uniforms.displacementBias.value = material.displacementBias;
  13569. }
  13570. uniforms.referencePosition.value.copy( material.referencePosition );
  13571. uniforms.nearDistance.value = material.nearDistance;
  13572. uniforms.farDistance.value = material.farDistance;
  13573. }
  13574. function refreshUniformsNormal( uniforms, material ) {
  13575. if ( material.bumpMap ) {
  13576. uniforms.bumpMap.value = material.bumpMap;
  13577. uniforms.bumpScale.value = material.bumpScale;
  13578. }
  13579. if ( material.normalMap ) {
  13580. uniforms.normalMap.value = material.normalMap;
  13581. uniforms.normalScale.value.copy( material.normalScale );
  13582. }
  13583. if ( material.displacementMap ) {
  13584. uniforms.displacementMap.value = material.displacementMap;
  13585. uniforms.displacementScale.value = material.displacementScale;
  13586. uniforms.displacementBias.value = material.displacementBias;
  13587. }
  13588. }
  13589. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  13590. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  13591. uniforms.ambientLightColor.needsUpdate = value;
  13592. uniforms.directionalLights.needsUpdate = value;
  13593. uniforms.pointLights.needsUpdate = value;
  13594. uniforms.spotLights.needsUpdate = value;
  13595. uniforms.rectAreaLights.needsUpdate = value;
  13596. uniforms.hemisphereLights.needsUpdate = value;
  13597. }
  13598. // GL state setting
  13599. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13600. state.setCullFace( cullFace );
  13601. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  13602. };
  13603. // Textures
  13604. function allocTextureUnit() {
  13605. var textureUnit = _usedTextureUnits;
  13606. if ( textureUnit >= capabilities.maxTextures ) {
  13607. console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  13608. }
  13609. _usedTextureUnits += 1;
  13610. return textureUnit;
  13611. }
  13612. this.allocTextureUnit = allocTextureUnit;
  13613. // this.setTexture2D = setTexture2D;
  13614. this.setTexture2D = ( function () {
  13615. var warned = false;
  13616. // backwards compatibility: peel texture.texture
  13617. return function setTexture2D( texture, slot ) {
  13618. if ( texture && texture.isWebGLRenderTarget ) {
  13619. if ( ! warned ) {
  13620. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  13621. warned = true;
  13622. }
  13623. texture = texture.texture;
  13624. }
  13625. textures.setTexture2D( texture, slot );
  13626. };
  13627. }() );
  13628. this.setTexture = ( function () {
  13629. var warned = false;
  13630. return function setTexture( texture, slot ) {
  13631. if ( ! warned ) {
  13632. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  13633. warned = true;
  13634. }
  13635. textures.setTexture2D( texture, slot );
  13636. };
  13637. }() );
  13638. this.setTextureCube = ( function () {
  13639. var warned = false;
  13640. return function setTextureCube( texture, slot ) {
  13641. // backwards compatibility: peel texture.texture
  13642. if ( texture && texture.isWebGLRenderTargetCube ) {
  13643. if ( ! warned ) {
  13644. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  13645. warned = true;
  13646. }
  13647. texture = texture.texture;
  13648. }
  13649. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  13650. // TODO: unify these code paths
  13651. if ( ( texture && texture.isCubeTexture ) ||
  13652. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  13653. // CompressedTexture can have Array in image :/
  13654. // this function alone should take care of cube textures
  13655. textures.setTextureCube( texture, slot );
  13656. } else {
  13657. // assumed: texture property of THREE.WebGLRenderTargetCube
  13658. textures.setTextureCubeDynamic( texture, slot );
  13659. }
  13660. };
  13661. }() );
  13662. this.getRenderTarget = function () {
  13663. return _currentRenderTarget;
  13664. };
  13665. this.setRenderTarget = function ( renderTarget ) {
  13666. _currentRenderTarget = renderTarget;
  13667. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  13668. textures.setupRenderTarget( renderTarget );
  13669. }
  13670. var framebuffer = null;
  13671. var isCube = false;
  13672. if ( renderTarget ) {
  13673. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  13674. if ( renderTarget.isWebGLRenderTargetCube ) {
  13675. framebuffer = __webglFramebuffer[ renderTarget.activeCubeFace ];
  13676. isCube = true;
  13677. } else {
  13678. framebuffer = __webglFramebuffer;
  13679. }
  13680. _currentViewport.copy( renderTarget.viewport );
  13681. _currentScissor.copy( renderTarget.scissor );
  13682. _currentScissorTest = renderTarget.scissorTest;
  13683. } else {
  13684. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  13685. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  13686. _currentScissorTest = _scissorTest;
  13687. }
  13688. if ( _currentFramebuffer !== framebuffer ) {
  13689. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13690. _currentFramebuffer = framebuffer;
  13691. }
  13692. state.viewport( _currentViewport );
  13693. state.scissor( _currentScissor );
  13694. state.setScissorTest( _currentScissorTest );
  13695. if ( isCube ) {
  13696. var textureProperties = properties.get( renderTarget.texture );
  13697. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  13698. }
  13699. };
  13700. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  13701. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  13702. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  13703. return;
  13704. }
  13705. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  13706. if ( framebuffer ) {
  13707. var restore = false;
  13708. if ( framebuffer !== _currentFramebuffer ) {
  13709. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13710. restore = true;
  13711. }
  13712. try {
  13713. var texture = renderTarget.texture;
  13714. var textureFormat = texture.format;
  13715. var textureType = texture.type;
  13716. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  13717. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  13718. return;
  13719. }
  13720. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  13721. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  13722. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  13723. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  13724. return;
  13725. }
  13726. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13727. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  13728. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  13729. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  13730. }
  13731. } else {
  13732. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13733. }
  13734. } finally {
  13735. if ( restore ) {
  13736. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13737. }
  13738. }
  13739. }
  13740. };
  13741. // Map three.js constants to WebGL constants
  13742. function paramThreeToGL( p ) {
  13743. var extension;
  13744. if ( p === RepeatWrapping ) return _gl.REPEAT;
  13745. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13746. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13747. if ( p === NearestFilter ) return _gl.NEAREST;
  13748. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13749. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13750. if ( p === LinearFilter ) return _gl.LINEAR;
  13751. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13752. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13753. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13754. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13755. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13756. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13757. if ( p === ByteType ) return _gl.BYTE;
  13758. if ( p === ShortType ) return _gl.SHORT;
  13759. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13760. if ( p === IntType ) return _gl.INT;
  13761. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  13762. if ( p === FloatType ) return _gl.FLOAT;
  13763. if ( p === HalfFloatType ) {
  13764. extension = extensions.get( 'OES_texture_half_float' );
  13765. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  13766. }
  13767. if ( p === AlphaFormat ) return _gl.ALPHA;
  13768. if ( p === RGBFormat ) return _gl.RGB;
  13769. if ( p === RGBAFormat ) return _gl.RGBA;
  13770. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  13771. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13772. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  13773. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  13774. if ( p === AddEquation ) return _gl.FUNC_ADD;
  13775. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13776. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13777. if ( p === ZeroFactor ) return _gl.ZERO;
  13778. if ( p === OneFactor ) return _gl.ONE;
  13779. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  13780. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13781. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13782. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13783. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  13784. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13785. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  13786. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13787. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13788. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  13789. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  13790. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13791. if ( extension !== null ) {
  13792. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13793. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13794. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13795. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13796. }
  13797. }
  13798. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  13799. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  13800. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13801. if ( extension !== null ) {
  13802. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13803. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13804. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13805. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13806. }
  13807. }
  13808. if ( p === RGB_ETC1_Format ) {
  13809. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13810. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13811. }
  13812. if ( p === MinEquation || p === MaxEquation ) {
  13813. extension = extensions.get( 'EXT_blend_minmax' );
  13814. if ( extension !== null ) {
  13815. if ( p === MinEquation ) return extension.MIN_EXT;
  13816. if ( p === MaxEquation ) return extension.MAX_EXT;
  13817. }
  13818. }
  13819. if ( p === UnsignedInt248Type ) {
  13820. extension = extensions.get( 'WEBGL_depth_texture' );
  13821. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  13822. }
  13823. return 0;
  13824. }
  13825. }
  13826. /**
  13827. * @author mrdoob / http://mrdoob.com/
  13828. * @author alteredq / http://alteredqualia.com/
  13829. */
  13830. function FogExp2 ( color, density ) {
  13831. this.name = '';
  13832. this.color = new Color( color );
  13833. this.density = ( density !== undefined ) ? density : 0.00025;
  13834. }
  13835. FogExp2.prototype.isFogExp2 = true;
  13836. FogExp2.prototype.clone = function () {
  13837. return new FogExp2( this.color.getHex(), this.density );
  13838. };
  13839. FogExp2.prototype.toJSON = function ( meta ) {
  13840. return {
  13841. type: 'FogExp2',
  13842. color: this.color.getHex(),
  13843. density: this.density
  13844. };
  13845. };
  13846. /**
  13847. * @author mrdoob / http://mrdoob.com/
  13848. * @author alteredq / http://alteredqualia.com/
  13849. */
  13850. function Fog ( color, near, far ) {
  13851. this.name = '';
  13852. this.color = new Color( color );
  13853. this.near = ( near !== undefined ) ? near : 1;
  13854. this.far = ( far !== undefined ) ? far : 1000;
  13855. }
  13856. Fog.prototype.isFog = true;
  13857. Fog.prototype.clone = function () {
  13858. return new Fog( this.color.getHex(), this.near, this.far );
  13859. };
  13860. Fog.prototype.toJSON = function ( meta ) {
  13861. return {
  13862. type: 'Fog',
  13863. color: this.color.getHex(),
  13864. near: this.near,
  13865. far: this.far
  13866. };
  13867. };
  13868. /**
  13869. * @author mrdoob / http://mrdoob.com/
  13870. */
  13871. function Scene () {
  13872. Object3D.call( this );
  13873. this.type = 'Scene';
  13874. this.background = null;
  13875. this.fog = null;
  13876. this.overrideMaterial = null;
  13877. this.autoUpdate = true; // checked by the renderer
  13878. }
  13879. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13880. constructor: Scene,
  13881. copy: function ( source, recursive ) {
  13882. Object3D.prototype.copy.call( this, source, recursive );
  13883. if ( source.background !== null ) this.background = source.background.clone();
  13884. if ( source.fog !== null ) this.fog = source.fog.clone();
  13885. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13886. this.autoUpdate = source.autoUpdate;
  13887. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13888. return this;
  13889. },
  13890. toJSON: function ( meta ) {
  13891. var data = Object3D.prototype.toJSON.call( this, meta );
  13892. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  13893. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13894. return data;
  13895. }
  13896. } );
  13897. /**
  13898. * @author mikael emtinger / http://gomo.se/
  13899. * @author alteredq / http://alteredqualia.com/
  13900. */
  13901. function LensFlare( texture, size, distance, blending, color ) {
  13902. Object3D.call( this );
  13903. this.lensFlares = [];
  13904. this.positionScreen = new Vector3();
  13905. this.customUpdateCallback = undefined;
  13906. if ( texture !== undefined ) {
  13907. this.add( texture, size, distance, blending, color );
  13908. }
  13909. }
  13910. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13911. constructor: LensFlare,
  13912. isLensFlare: true,
  13913. copy: function ( source ) {
  13914. Object3D.prototype.copy.call( this, source );
  13915. this.positionScreen.copy( source.positionScreen );
  13916. this.customUpdateCallback = source.customUpdateCallback;
  13917. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13918. this.lensFlares.push( source.lensFlares[ i ] );
  13919. }
  13920. return this;
  13921. },
  13922. add: function ( texture, size, distance, blending, color, opacity ) {
  13923. if ( size === undefined ) size = - 1;
  13924. if ( distance === undefined ) distance = 0;
  13925. if ( opacity === undefined ) opacity = 1;
  13926. if ( color === undefined ) color = new Color( 0xffffff );
  13927. if ( blending === undefined ) blending = NormalBlending;
  13928. distance = Math.min( distance, Math.max( 0, distance ) );
  13929. this.lensFlares.push( {
  13930. texture: texture, // THREE.Texture
  13931. size: size, // size in pixels (-1 = use texture.width)
  13932. distance: distance, // distance (0-1) from light source (0=at light source)
  13933. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13934. scale: 1, // scale
  13935. rotation: 0, // rotation
  13936. opacity: opacity, // opacity
  13937. color: color, // color
  13938. blending: blending // blending
  13939. } );
  13940. },
  13941. /*
  13942. * Update lens flares update positions on all flares based on the screen position
  13943. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13944. */
  13945. updateLensFlares: function () {
  13946. var f, fl = this.lensFlares.length;
  13947. var flare;
  13948. var vecX = - this.positionScreen.x * 2;
  13949. var vecY = - this.positionScreen.y * 2;
  13950. for ( f = 0; f < fl; f ++ ) {
  13951. flare = this.lensFlares[ f ];
  13952. flare.x = this.positionScreen.x + vecX * flare.distance;
  13953. flare.y = this.positionScreen.y + vecY * flare.distance;
  13954. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13955. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13956. }
  13957. }
  13958. } );
  13959. /**
  13960. * @author alteredq / http://alteredqualia.com/
  13961. *
  13962. * parameters = {
  13963. * color: <hex>,
  13964. * opacity: <float>,
  13965. * map: new THREE.Texture( <Image> ),
  13966. *
  13967. * uvOffset: new THREE.Vector2(),
  13968. * uvScale: new THREE.Vector2()
  13969. * }
  13970. */
  13971. function SpriteMaterial( parameters ) {
  13972. Material.call( this );
  13973. this.type = 'SpriteMaterial';
  13974. this.color = new Color( 0xffffff );
  13975. this.map = null;
  13976. this.rotation = 0;
  13977. this.fog = false;
  13978. this.lights = false;
  13979. this.setValues( parameters );
  13980. }
  13981. SpriteMaterial.prototype = Object.create( Material.prototype );
  13982. SpriteMaterial.prototype.constructor = SpriteMaterial;
  13983. SpriteMaterial.prototype.isSpriteMaterial = true;
  13984. SpriteMaterial.prototype.copy = function ( source ) {
  13985. Material.prototype.copy.call( this, source );
  13986. this.color.copy( source.color );
  13987. this.map = source.map;
  13988. this.rotation = source.rotation;
  13989. return this;
  13990. };
  13991. /**
  13992. * @author mikael emtinger / http://gomo.se/
  13993. * @author alteredq / http://alteredqualia.com/
  13994. */
  13995. function Sprite( material ) {
  13996. Object3D.call( this );
  13997. this.type = 'Sprite';
  13998. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  13999. }
  14000. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14001. constructor: Sprite,
  14002. isSprite: true,
  14003. raycast: ( function () {
  14004. var intersectPoint = new Vector3();
  14005. var worldPosition = new Vector3();
  14006. var worldScale = new Vector3();
  14007. return function raycast( raycaster, intersects ) {
  14008. worldPosition.setFromMatrixPosition( this.matrixWorld );
  14009. raycaster.ray.closestPointToPoint( worldPosition, intersectPoint );
  14010. worldScale.setFromMatrixScale( this.matrixWorld );
  14011. var guessSizeSq = worldScale.x * worldScale.y / 4;
  14012. if ( worldPosition.distanceToSquared( intersectPoint ) > guessSizeSq ) return;
  14013. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  14014. if ( distance < raycaster.near || distance > raycaster.far ) return;
  14015. intersects.push( {
  14016. distance: distance,
  14017. point: intersectPoint.clone(),
  14018. face: null,
  14019. object: this
  14020. } );
  14021. };
  14022. }() ),
  14023. clone: function () {
  14024. return new this.constructor( this.material ).copy( this );
  14025. }
  14026. } );
  14027. /**
  14028. * @author mikael emtinger / http://gomo.se/
  14029. * @author alteredq / http://alteredqualia.com/
  14030. * @author mrdoob / http://mrdoob.com/
  14031. */
  14032. function LOD() {
  14033. Object3D.call( this );
  14034. this.type = 'LOD';
  14035. Object.defineProperties( this, {
  14036. levels: {
  14037. enumerable: true,
  14038. value: []
  14039. }
  14040. } );
  14041. }
  14042. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14043. constructor: LOD,
  14044. copy: function ( source ) {
  14045. Object3D.prototype.copy.call( this, source, false );
  14046. var levels = source.levels;
  14047. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  14048. var level = levels[ i ];
  14049. this.addLevel( level.object.clone(), level.distance );
  14050. }
  14051. return this;
  14052. },
  14053. addLevel: function ( object, distance ) {
  14054. if ( distance === undefined ) distance = 0;
  14055. distance = Math.abs( distance );
  14056. var levels = this.levels;
  14057. for ( var l = 0; l < levels.length; l ++ ) {
  14058. if ( distance < levels[ l ].distance ) {
  14059. break;
  14060. }
  14061. }
  14062. levels.splice( l, 0, { distance: distance, object: object } );
  14063. this.add( object );
  14064. },
  14065. getObjectForDistance: function ( distance ) {
  14066. var levels = this.levels;
  14067. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  14068. if ( distance < levels[ i ].distance ) {
  14069. break;
  14070. }
  14071. }
  14072. return levels[ i - 1 ].object;
  14073. },
  14074. raycast: ( function () {
  14075. var matrixPosition = new Vector3();
  14076. return function raycast( raycaster, intersects ) {
  14077. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  14078. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  14079. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  14080. };
  14081. }() ),
  14082. update: function () {
  14083. var v1 = new Vector3();
  14084. var v2 = new Vector3();
  14085. return function update( camera ) {
  14086. var levels = this.levels;
  14087. if ( levels.length > 1 ) {
  14088. v1.setFromMatrixPosition( camera.matrixWorld );
  14089. v2.setFromMatrixPosition( this.matrixWorld );
  14090. var distance = v1.distanceTo( v2 );
  14091. levels[ 0 ].object.visible = true;
  14092. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  14093. if ( distance >= levels[ i ].distance ) {
  14094. levels[ i - 1 ].object.visible = false;
  14095. levels[ i ].object.visible = true;
  14096. } else {
  14097. break;
  14098. }
  14099. }
  14100. for ( ; i < l; i ++ ) {
  14101. levels[ i ].object.visible = false;
  14102. }
  14103. }
  14104. };
  14105. }(),
  14106. toJSON: function ( meta ) {
  14107. var data = Object3D.prototype.toJSON.call( this, meta );
  14108. data.object.levels = [];
  14109. var levels = this.levels;
  14110. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  14111. var level = levels[ i ];
  14112. data.object.levels.push( {
  14113. object: level.object.uuid,
  14114. distance: level.distance
  14115. } );
  14116. }
  14117. return data;
  14118. }
  14119. } );
  14120. /**
  14121. * @author mikael emtinger / http://gomo.se/
  14122. * @author alteredq / http://alteredqualia.com/
  14123. * @author michael guerrero / http://realitymeltdown.com
  14124. * @author ikerr / http://verold.com
  14125. */
  14126. function Skeleton( bones, boneInverses ) {
  14127. // copy the bone array
  14128. bones = bones || [];
  14129. this.bones = bones.slice( 0 );
  14130. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  14131. // use the supplied bone inverses or calculate the inverses
  14132. if ( boneInverses === undefined ) {
  14133. this.calculateInverses();
  14134. } else {
  14135. if ( this.bones.length === boneInverses.length ) {
  14136. this.boneInverses = boneInverses.slice( 0 );
  14137. } else {
  14138. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  14139. this.boneInverses = [];
  14140. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  14141. this.boneInverses.push( new Matrix4() );
  14142. }
  14143. }
  14144. }
  14145. }
  14146. Object.assign( Skeleton.prototype, {
  14147. calculateInverses: function () {
  14148. this.boneInverses = [];
  14149. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  14150. var inverse = new Matrix4();
  14151. if ( this.bones[ i ] ) {
  14152. inverse.getInverse( this.bones[ i ].matrixWorld );
  14153. }
  14154. this.boneInverses.push( inverse );
  14155. }
  14156. },
  14157. pose: function () {
  14158. var bone, i, il;
  14159. // recover the bind-time world matrices
  14160. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  14161. bone = this.bones[ i ];
  14162. if ( bone ) {
  14163. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  14164. }
  14165. }
  14166. // compute the local matrices, positions, rotations and scales
  14167. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  14168. bone = this.bones[ i ];
  14169. if ( bone ) {
  14170. if ( bone.parent && bone.parent.isBone ) {
  14171. bone.matrix.getInverse( bone.parent.matrixWorld );
  14172. bone.matrix.multiply( bone.matrixWorld );
  14173. } else {
  14174. bone.matrix.copy( bone.matrixWorld );
  14175. }
  14176. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  14177. }
  14178. }
  14179. },
  14180. update: ( function () {
  14181. var offsetMatrix = new Matrix4();
  14182. var identityMatrix = new Matrix4();
  14183. return function update() {
  14184. var bones = this.bones;
  14185. var boneInverses = this.boneInverses;
  14186. var boneMatrices = this.boneMatrices;
  14187. var boneTexture = this.boneTexture;
  14188. // flatten bone matrices to array
  14189. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  14190. // compute the offset between the current and the original transform
  14191. var matrix = bones[ i ] ? bones[ i ].matrixWorld : identityMatrix;
  14192. offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  14193. offsetMatrix.toArray( boneMatrices, i * 16 );
  14194. }
  14195. if ( boneTexture !== undefined ) {
  14196. boneTexture.needsUpdate = true;
  14197. }
  14198. };
  14199. } )(),
  14200. clone: function () {
  14201. return new Skeleton( this.bones, this.boneInverses );
  14202. }
  14203. } );
  14204. /**
  14205. * @author mikael emtinger / http://gomo.se/
  14206. * @author alteredq / http://alteredqualia.com/
  14207. * @author ikerr / http://verold.com
  14208. */
  14209. function Bone() {
  14210. Object3D.call( this );
  14211. this.type = 'Bone';
  14212. }
  14213. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14214. constructor: Bone,
  14215. isBone: true
  14216. } );
  14217. /**
  14218. * @author mikael emtinger / http://gomo.se/
  14219. * @author alteredq / http://alteredqualia.com/
  14220. * @author ikerr / http://verold.com
  14221. */
  14222. function SkinnedMesh( geometry, material ) {
  14223. Mesh.call( this, geometry, material );
  14224. this.type = 'SkinnedMesh';
  14225. this.bindMode = 'attached';
  14226. this.bindMatrix = new Matrix4();
  14227. this.bindMatrixInverse = new Matrix4();
  14228. var bones = this.initBones();
  14229. var skeleton = new Skeleton( bones );
  14230. this.bind( skeleton, this.matrixWorld );
  14231. this.normalizeSkinWeights();
  14232. }
  14233. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  14234. constructor: SkinnedMesh,
  14235. isSkinnedMesh: true,
  14236. initBones: function () {
  14237. var bones = [], bone, gbone;
  14238. var i, il;
  14239. if ( this.geometry && this.geometry.bones !== undefined ) {
  14240. // first, create array of 'Bone' objects from geometry data
  14241. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  14242. gbone = this.geometry.bones[ i ];
  14243. // create new 'Bone' object
  14244. bone = new Bone();
  14245. bones.push( bone );
  14246. // apply values
  14247. bone.name = gbone.name;
  14248. bone.position.fromArray( gbone.pos );
  14249. bone.quaternion.fromArray( gbone.rotq );
  14250. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  14251. }
  14252. // second, create bone hierarchy
  14253. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  14254. gbone = this.geometry.bones[ i ];
  14255. if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) {
  14256. // subsequent bones in the hierarchy
  14257. bones[ gbone.parent ].add( bones[ i ] );
  14258. } else {
  14259. // topmost bone, immediate child of the skinned mesh
  14260. this.add( bones[ i ] );
  14261. }
  14262. }
  14263. }
  14264. // now the bones are part of the scene graph and children of the skinned mesh.
  14265. // let's update the corresponding matrices
  14266. this.updateMatrixWorld( true );
  14267. return bones;
  14268. },
  14269. bind: function ( skeleton, bindMatrix ) {
  14270. this.skeleton = skeleton;
  14271. if ( bindMatrix === undefined ) {
  14272. this.updateMatrixWorld( true );
  14273. this.skeleton.calculateInverses();
  14274. bindMatrix = this.matrixWorld;
  14275. }
  14276. this.bindMatrix.copy( bindMatrix );
  14277. this.bindMatrixInverse.getInverse( bindMatrix );
  14278. },
  14279. pose: function () {
  14280. this.skeleton.pose();
  14281. },
  14282. normalizeSkinWeights: function () {
  14283. var scale, i;
  14284. if ( this.geometry && this.geometry.isGeometry ) {
  14285. for ( i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  14286. var sw = this.geometry.skinWeights[ i ];
  14287. scale = 1.0 / sw.lengthManhattan();
  14288. if ( scale !== Infinity ) {
  14289. sw.multiplyScalar( scale );
  14290. } else {
  14291. sw.set( 1, 0, 0, 0 ); // do something reasonable
  14292. }
  14293. }
  14294. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  14295. var vec = new Vector4();
  14296. var skinWeight = this.geometry.attributes.skinWeight;
  14297. for ( i = 0; i < skinWeight.count; i ++ ) {
  14298. vec.x = skinWeight.getX( i );
  14299. vec.y = skinWeight.getY( i );
  14300. vec.z = skinWeight.getZ( i );
  14301. vec.w = skinWeight.getW( i );
  14302. scale = 1.0 / vec.lengthManhattan();
  14303. if ( scale !== Infinity ) {
  14304. vec.multiplyScalar( scale );
  14305. } else {
  14306. vec.set( 1, 0, 0, 0 ); // do something reasonable
  14307. }
  14308. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  14309. }
  14310. }
  14311. },
  14312. updateMatrixWorld: function ( force ) {
  14313. Mesh.prototype.updateMatrixWorld.call( this, force );
  14314. if ( this.bindMode === 'attached' ) {
  14315. this.bindMatrixInverse.getInverse( this.matrixWorld );
  14316. } else if ( this.bindMode === 'detached' ) {
  14317. this.bindMatrixInverse.getInverse( this.bindMatrix );
  14318. } else {
  14319. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  14320. }
  14321. },
  14322. clone: function () {
  14323. return new this.constructor( this.geometry, this.material ).copy( this );
  14324. }
  14325. } );
  14326. /**
  14327. * @author mrdoob / http://mrdoob.com/
  14328. * @author alteredq / http://alteredqualia.com/
  14329. *
  14330. * parameters = {
  14331. * color: <hex>,
  14332. * opacity: <float>,
  14333. *
  14334. * linewidth: <float>,
  14335. * linecap: "round",
  14336. * linejoin: "round"
  14337. * }
  14338. */
  14339. function LineBasicMaterial( parameters ) {
  14340. Material.call( this );
  14341. this.type = 'LineBasicMaterial';
  14342. this.color = new Color( 0xffffff );
  14343. this.linewidth = 1;
  14344. this.linecap = 'round';
  14345. this.linejoin = 'round';
  14346. this.lights = false;
  14347. this.setValues( parameters );
  14348. }
  14349. LineBasicMaterial.prototype = Object.create( Material.prototype );
  14350. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  14351. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  14352. LineBasicMaterial.prototype.copy = function ( source ) {
  14353. Material.prototype.copy.call( this, source );
  14354. this.color.copy( source.color );
  14355. this.linewidth = source.linewidth;
  14356. this.linecap = source.linecap;
  14357. this.linejoin = source.linejoin;
  14358. return this;
  14359. };
  14360. /**
  14361. * @author mrdoob / http://mrdoob.com/
  14362. */
  14363. function Line( geometry, material, mode ) {
  14364. if ( mode === 1 ) {
  14365. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  14366. return new LineSegments( geometry, material );
  14367. }
  14368. Object3D.call( this );
  14369. this.type = 'Line';
  14370. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14371. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  14372. }
  14373. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14374. constructor: Line,
  14375. isLine: true,
  14376. raycast: ( function () {
  14377. var inverseMatrix = new Matrix4();
  14378. var ray = new Ray();
  14379. var sphere = new Sphere();
  14380. return function raycast( raycaster, intersects ) {
  14381. var precision = raycaster.linePrecision;
  14382. var precisionSq = precision * precision;
  14383. var geometry = this.geometry;
  14384. var matrixWorld = this.matrixWorld;
  14385. // Checking boundingSphere distance to ray
  14386. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14387. sphere.copy( geometry.boundingSphere );
  14388. sphere.applyMatrix4( matrixWorld );
  14389. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14390. //
  14391. inverseMatrix.getInverse( matrixWorld );
  14392. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14393. var vStart = new Vector3();
  14394. var vEnd = new Vector3();
  14395. var interSegment = new Vector3();
  14396. var interRay = new Vector3();
  14397. var step = (this && this.isLineSegments) ? 2 : 1;
  14398. if ( geometry.isBufferGeometry ) {
  14399. var index = geometry.index;
  14400. var attributes = geometry.attributes;
  14401. var positions = attributes.position.array;
  14402. if ( index !== null ) {
  14403. var indices = index.array;
  14404. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  14405. var a = indices[ i ];
  14406. var b = indices[ i + 1 ];
  14407. vStart.fromArray( positions, a * 3 );
  14408. vEnd.fromArray( positions, b * 3 );
  14409. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  14410. if ( distSq > precisionSq ) continue;
  14411. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14412. var distance = raycaster.ray.origin.distanceTo( interRay );
  14413. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14414. intersects.push( {
  14415. distance: distance,
  14416. // What do we want? intersection point on the ray or on the segment??
  14417. // point: raycaster.ray.at( distance ),
  14418. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14419. index: i,
  14420. face: null,
  14421. faceIndex: null,
  14422. object: this
  14423. } );
  14424. }
  14425. } else {
  14426. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  14427. vStart.fromArray( positions, 3 * i );
  14428. vEnd.fromArray( positions, 3 * i + 3 );
  14429. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  14430. if ( distSq > precisionSq ) continue;
  14431. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14432. var distance = raycaster.ray.origin.distanceTo( interRay );
  14433. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14434. intersects.push( {
  14435. distance: distance,
  14436. // What do we want? intersection point on the ray or on the segment??
  14437. // point: raycaster.ray.at( distance ),
  14438. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14439. index: i,
  14440. face: null,
  14441. faceIndex: null,
  14442. object: this
  14443. } );
  14444. }
  14445. }
  14446. } else if ( geometry.isGeometry ) {
  14447. var vertices = geometry.vertices;
  14448. var nbVertices = vertices.length;
  14449. for ( var i = 0; i < nbVertices - 1; i += step ) {
  14450. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  14451. if ( distSq > precisionSq ) continue;
  14452. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14453. var distance = raycaster.ray.origin.distanceTo( interRay );
  14454. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14455. intersects.push( {
  14456. distance: distance,
  14457. // What do we want? intersection point on the ray or on the segment??
  14458. // point: raycaster.ray.at( distance ),
  14459. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14460. index: i,
  14461. face: null,
  14462. faceIndex: null,
  14463. object: this
  14464. } );
  14465. }
  14466. }
  14467. };
  14468. }() ),
  14469. clone: function () {
  14470. return new this.constructor( this.geometry, this.material ).copy( this );
  14471. }
  14472. } );
  14473. /**
  14474. * @author mrdoob / http://mrdoob.com/
  14475. */
  14476. function LineSegments( geometry, material ) {
  14477. Line.call( this, geometry, material );
  14478. this.type = 'LineSegments';
  14479. }
  14480. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  14481. constructor: LineSegments,
  14482. isLineSegments: true
  14483. } );
  14484. /**
  14485. * @author mgreter / http://github.com/mgreter
  14486. */
  14487. function LineLoop( geometry, material ) {
  14488. Line.call( this, geometry, material );
  14489. this.type = 'LineLoop';
  14490. }
  14491. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  14492. constructor: LineLoop,
  14493. isLineLoop: true,
  14494. } );
  14495. /**
  14496. * @author mrdoob / http://mrdoob.com/
  14497. * @author alteredq / http://alteredqualia.com/
  14498. *
  14499. * parameters = {
  14500. * color: <hex>,
  14501. * opacity: <float>,
  14502. * map: new THREE.Texture( <Image> ),
  14503. *
  14504. * size: <float>,
  14505. * sizeAttenuation: <bool>
  14506. * }
  14507. */
  14508. function PointsMaterial( parameters ) {
  14509. Material.call( this );
  14510. this.type = 'PointsMaterial';
  14511. this.color = new Color( 0xffffff );
  14512. this.map = null;
  14513. this.size = 1;
  14514. this.sizeAttenuation = true;
  14515. this.lights = false;
  14516. this.setValues( parameters );
  14517. }
  14518. PointsMaterial.prototype = Object.create( Material.prototype );
  14519. PointsMaterial.prototype.constructor = PointsMaterial;
  14520. PointsMaterial.prototype.isPointsMaterial = true;
  14521. PointsMaterial.prototype.copy = function ( source ) {
  14522. Material.prototype.copy.call( this, source );
  14523. this.color.copy( source.color );
  14524. this.map = source.map;
  14525. this.size = source.size;
  14526. this.sizeAttenuation = source.sizeAttenuation;
  14527. return this;
  14528. };
  14529. /**
  14530. * @author alteredq / http://alteredqualia.com/
  14531. */
  14532. function Points( geometry, material ) {
  14533. Object3D.call( this );
  14534. this.type = 'Points';
  14535. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14536. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  14537. }
  14538. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14539. constructor: Points,
  14540. isPoints: true,
  14541. raycast: ( function () {
  14542. var inverseMatrix = new Matrix4();
  14543. var ray = new Ray();
  14544. var sphere = new Sphere();
  14545. return function raycast( raycaster, intersects ) {
  14546. var object = this;
  14547. var geometry = this.geometry;
  14548. var matrixWorld = this.matrixWorld;
  14549. var threshold = raycaster.params.Points.threshold;
  14550. // Checking boundingSphere distance to ray
  14551. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14552. sphere.copy( geometry.boundingSphere );
  14553. sphere.applyMatrix4( matrixWorld );
  14554. sphere.radius += threshold;
  14555. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14556. //
  14557. inverseMatrix.getInverse( matrixWorld );
  14558. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14559. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  14560. var localThresholdSq = localThreshold * localThreshold;
  14561. var position = new Vector3();
  14562. function testPoint( point, index ) {
  14563. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  14564. if ( rayPointDistanceSq < localThresholdSq ) {
  14565. var intersectPoint = ray.closestPointToPoint( point );
  14566. intersectPoint.applyMatrix4( matrixWorld );
  14567. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  14568. if ( distance < raycaster.near || distance > raycaster.far ) return;
  14569. intersects.push( {
  14570. distance: distance,
  14571. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  14572. point: intersectPoint.clone(),
  14573. index: index,
  14574. face: null,
  14575. object: object
  14576. } );
  14577. }
  14578. }
  14579. if ( geometry.isBufferGeometry ) {
  14580. var index = geometry.index;
  14581. var attributes = geometry.attributes;
  14582. var positions = attributes.position.array;
  14583. if ( index !== null ) {
  14584. var indices = index.array;
  14585. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  14586. var a = indices[ i ];
  14587. position.fromArray( positions, a * 3 );
  14588. testPoint( position, a );
  14589. }
  14590. } else {
  14591. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  14592. position.fromArray( positions, i * 3 );
  14593. testPoint( position, i );
  14594. }
  14595. }
  14596. } else {
  14597. var vertices = geometry.vertices;
  14598. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  14599. testPoint( vertices[ i ], i );
  14600. }
  14601. }
  14602. };
  14603. }() ),
  14604. clone: function () {
  14605. return new this.constructor( this.geometry, this.material ).copy( this );
  14606. }
  14607. } );
  14608. /**
  14609. * @author mrdoob / http://mrdoob.com/
  14610. */
  14611. function Group() {
  14612. Object3D.call( this );
  14613. this.type = 'Group';
  14614. }
  14615. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14616. constructor: Group
  14617. } );
  14618. /**
  14619. * @author mrdoob / http://mrdoob.com/
  14620. */
  14621. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14622. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14623. this.generateMipmaps = false;
  14624. var scope = this;
  14625. function update() {
  14626. requestAnimationFrame( update );
  14627. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  14628. scope.needsUpdate = true;
  14629. }
  14630. }
  14631. update();
  14632. }
  14633. VideoTexture.prototype = Object.create( Texture.prototype );
  14634. VideoTexture.prototype.constructor = VideoTexture;
  14635. /**
  14636. * @author alteredq / http://alteredqualia.com/
  14637. */
  14638. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  14639. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  14640. this.image = { width: width, height: height };
  14641. this.mipmaps = mipmaps;
  14642. // no flipping for cube textures
  14643. // (also flipping doesn't work for compressed textures )
  14644. this.flipY = false;
  14645. // can't generate mipmaps for compressed textures
  14646. // mips must be embedded in DDS files
  14647. this.generateMipmaps = false;
  14648. }
  14649. CompressedTexture.prototype = Object.create( Texture.prototype );
  14650. CompressedTexture.prototype.constructor = CompressedTexture;
  14651. CompressedTexture.prototype.isCompressedTexture = true;
  14652. /**
  14653. * @author Matt DesLauriers / @mattdesl
  14654. * @author atix / arthursilber.de
  14655. */
  14656. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  14657. format = format !== undefined ? format : DepthFormat;
  14658. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  14659. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  14660. }
  14661. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  14662. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  14663. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14664. this.image = { width: width, height: height };
  14665. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14666. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14667. this.flipY = false;
  14668. this.generateMipmaps = false;
  14669. }
  14670. DepthTexture.prototype = Object.create( Texture.prototype );
  14671. DepthTexture.prototype.constructor = DepthTexture;
  14672. DepthTexture.prototype.isDepthTexture = true;
  14673. /**
  14674. * @author mrdoob / http://mrdoob.com/
  14675. * @author Mugen87 / https://github.com/Mugen87
  14676. */
  14677. function WireframeGeometry( geometry ) {
  14678. BufferGeometry.call( this );
  14679. this.type = 'WireframeGeometry';
  14680. // buffer
  14681. var vertices = [];
  14682. // helper variables
  14683. var i, j, l, o, ol;
  14684. var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
  14685. var key, keys = [ 'a', 'b', 'c' ];
  14686. var vertex;
  14687. // different logic for Geometry and BufferGeometry
  14688. if ( geometry && geometry.isGeometry ) {
  14689. // create a data structure that contains all edges without duplicates
  14690. var faces = geometry.faces;
  14691. for ( i = 0, l = faces.length; i < l; i ++ ) {
  14692. var face = faces[ i ];
  14693. for ( j = 0; j < 3; j ++ ) {
  14694. edge1 = face[ keys[ j ] ];
  14695. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  14696. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  14697. edge[ 1 ] = Math.max( edge1, edge2 );
  14698. key = edge[ 0 ] + ',' + edge[ 1 ];
  14699. if ( edges[ key ] === undefined ) {
  14700. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  14701. }
  14702. }
  14703. }
  14704. // generate vertices
  14705. for ( key in edges ) {
  14706. e = edges[ key ];
  14707. vertex = geometry.vertices[ e.index1 ];
  14708. vertices.push( vertex.x, vertex.y, vertex.z );
  14709. vertex = geometry.vertices[ e.index2 ];
  14710. vertices.push( vertex.x, vertex.y, vertex.z );
  14711. }
  14712. } else if ( geometry && geometry.isBufferGeometry ) {
  14713. var position, indices, groups;
  14714. var group, start, count;
  14715. var index1, index2;
  14716. vertex = new Vector3();
  14717. if ( geometry.index !== null ) {
  14718. // indexed BufferGeometry
  14719. position = geometry.attributes.position;
  14720. indices = geometry.index;
  14721. groups = geometry.groups;
  14722. if ( groups.length === 0 ) {
  14723. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  14724. }
  14725. // create a data structure that contains all eges without duplicates
  14726. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  14727. group = groups[ o ];
  14728. start = group.start;
  14729. count = group.count;
  14730. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  14731. for ( j = 0; j < 3; j ++ ) {
  14732. edge1 = indices.getX( i + j );
  14733. edge2 = indices.getX( i + ( j + 1 ) % 3 );
  14734. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  14735. edge[ 1 ] = Math.max( edge1, edge2 );
  14736. key = edge[ 0 ] + ',' + edge[ 1 ];
  14737. if ( edges[ key ] === undefined ) {
  14738. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  14739. }
  14740. }
  14741. }
  14742. }
  14743. // generate vertices
  14744. for ( key in edges ) {
  14745. e = edges[ key ];
  14746. vertex.fromBufferAttribute( position, e.index1 );
  14747. vertices.push( vertex.x, vertex.y, vertex.z );
  14748. vertex.fromBufferAttribute( position, e.index2 );
  14749. vertices.push( vertex.x, vertex.y, vertex.z );
  14750. }
  14751. } else {
  14752. // non-indexed BufferGeometry
  14753. position = geometry.attributes.position;
  14754. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  14755. for ( j = 0; j < 3; j ++ ) {
  14756. // three edges per triangle, an edge is represented as (index1, index2)
  14757. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  14758. index1 = 3 * i + j;
  14759. vertex.fromBufferAttribute( position, index1 );
  14760. vertices.push( vertex.x, vertex.y, vertex.z );
  14761. index2 = 3 * i + ( ( j + 1 ) % 3 );
  14762. vertex.fromBufferAttribute( position, index2 );
  14763. vertices.push( vertex.x, vertex.y, vertex.z );
  14764. }
  14765. }
  14766. }
  14767. }
  14768. // build geometry
  14769. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14770. }
  14771. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  14772. WireframeGeometry.prototype.constructor = WireframeGeometry;
  14773. /**
  14774. * @author zz85 / https://github.com/zz85
  14775. * @author Mugen87 / https://github.com/Mugen87
  14776. *
  14777. * Parametric Surfaces Geometry
  14778. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  14779. */
  14780. // ParametricGeometry
  14781. function ParametricGeometry( func, slices, stacks ) {
  14782. Geometry.call( this );
  14783. this.type = 'ParametricGeometry';
  14784. this.parameters = {
  14785. func: func,
  14786. slices: slices,
  14787. stacks: stacks
  14788. };
  14789. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  14790. this.mergeVertices();
  14791. }
  14792. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  14793. ParametricGeometry.prototype.constructor = ParametricGeometry;
  14794. // ParametricBufferGeometry
  14795. function ParametricBufferGeometry( func, slices, stacks ) {
  14796. BufferGeometry.call( this );
  14797. this.type = 'ParametricBufferGeometry';
  14798. this.parameters = {
  14799. func: func,
  14800. slices: slices,
  14801. stacks: stacks
  14802. };
  14803. // buffers
  14804. var indices = [];
  14805. var vertices = [];
  14806. var normals = [];
  14807. var uvs = [];
  14808. var EPS = 0.00001;
  14809. var normal = new Vector3();
  14810. var p0 = new Vector3(), p1 = new Vector3();
  14811. var pu = new Vector3(), pv = new Vector3();
  14812. var i, j;
  14813. // generate vertices, normals and uvs
  14814. var sliceCount = slices + 1;
  14815. for ( i = 0; i <= stacks; i ++ ) {
  14816. var v = i / stacks;
  14817. for ( j = 0; j <= slices; j ++ ) {
  14818. var u = j / slices;
  14819. // vertex
  14820. p0 = func( u, v, p0 );
  14821. vertices.push( p0.x, p0.y, p0.z );
  14822. // normal
  14823. // approximate tangent vectors via finite differences
  14824. if ( u - EPS >= 0 ) {
  14825. p1 = func( u - EPS, v, p1 );
  14826. pu.subVectors( p0, p1 );
  14827. } else {
  14828. p1 = func( u + EPS, v, p1 );
  14829. pu.subVectors( p1, p0 );
  14830. }
  14831. if ( v - EPS >= 0 ) {
  14832. p1 = func( u, v - EPS, p1 );
  14833. pv.subVectors( p0, p1 );
  14834. } else {
  14835. p1 = func( u, v + EPS, p1 );
  14836. pv.subVectors( p1, p0 );
  14837. }
  14838. // cross product of tangent vectors returns surface normal
  14839. normal.crossVectors( pu, pv ).normalize();
  14840. normals.push( normal.x, normal.y, normal.z );
  14841. // uv
  14842. uvs.push( u, v );
  14843. }
  14844. }
  14845. // generate indices
  14846. for ( i = 0; i < stacks; i ++ ) {
  14847. for ( j = 0; j < slices; j ++ ) {
  14848. var a = i * sliceCount + j;
  14849. var b = i * sliceCount + j + 1;
  14850. var c = ( i + 1 ) * sliceCount + j + 1;
  14851. var d = ( i + 1 ) * sliceCount + j;
  14852. // faces one and two
  14853. indices.push( a, b, d );
  14854. indices.push( b, c, d );
  14855. }
  14856. }
  14857. // build geometry
  14858. this.setIndex( indices );
  14859. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14860. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  14861. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14862. }
  14863. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14864. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  14865. /**
  14866. * @author clockworkgeek / https://github.com/clockworkgeek
  14867. * @author timothypratley / https://github.com/timothypratley
  14868. * @author WestLangley / http://github.com/WestLangley
  14869. * @author Mugen87 / https://github.com/Mugen87
  14870. */
  14871. // PolyhedronGeometry
  14872. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  14873. Geometry.call( this );
  14874. this.type = 'PolyhedronGeometry';
  14875. this.parameters = {
  14876. vertices: vertices,
  14877. indices: indices,
  14878. radius: radius,
  14879. detail: detail
  14880. };
  14881. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  14882. this.mergeVertices();
  14883. }
  14884. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  14885. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  14886. // PolyhedronBufferGeometry
  14887. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  14888. BufferGeometry.call( this );
  14889. this.type = 'PolyhedronBufferGeometry';
  14890. this.parameters = {
  14891. vertices: vertices,
  14892. indices: indices,
  14893. radius: radius,
  14894. detail: detail
  14895. };
  14896. radius = radius || 1;
  14897. detail = detail || 0;
  14898. // default buffer data
  14899. var vertexBuffer = [];
  14900. var uvBuffer = [];
  14901. // the subdivision creates the vertex buffer data
  14902. subdivide( detail );
  14903. // all vertices should lie on a conceptual sphere with a given radius
  14904. appplyRadius( radius );
  14905. // finally, create the uv data
  14906. generateUVs();
  14907. // build non-indexed geometry
  14908. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  14909. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  14910. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  14911. if ( detail === 0 ) {
  14912. this.computeVertexNormals(); // flat normals
  14913. } else {
  14914. this.normalizeNormals(); // smooth normals
  14915. }
  14916. // helper functions
  14917. function subdivide( detail ) {
  14918. var a = new Vector3();
  14919. var b = new Vector3();
  14920. var c = new Vector3();
  14921. // iterate over all faces and apply a subdivison with the given detail value
  14922. for ( var i = 0; i < indices.length; i += 3 ) {
  14923. // get the vertices of the face
  14924. getVertexByIndex( indices[ i + 0 ], a );
  14925. getVertexByIndex( indices[ i + 1 ], b );
  14926. getVertexByIndex( indices[ i + 2 ], c );
  14927. // perform subdivision
  14928. subdivideFace( a, b, c, detail );
  14929. }
  14930. }
  14931. function subdivideFace( a, b, c, detail ) {
  14932. var cols = Math.pow( 2, detail );
  14933. // we use this multidimensional array as a data structure for creating the subdivision
  14934. var v = [];
  14935. var i, j;
  14936. // construct all of the vertices for this subdivision
  14937. for ( i = 0; i <= cols; i ++ ) {
  14938. v[ i ] = [];
  14939. var aj = a.clone().lerp( c, i / cols );
  14940. var bj = b.clone().lerp( c, i / cols );
  14941. var rows = cols - i;
  14942. for ( j = 0; j <= rows; j ++ ) {
  14943. if ( j === 0 && i === cols ) {
  14944. v[ i ][ j ] = aj;
  14945. } else {
  14946. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  14947. }
  14948. }
  14949. }
  14950. // construct all of the faces
  14951. for ( i = 0; i < cols; i ++ ) {
  14952. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  14953. var k = Math.floor( j / 2 );
  14954. if ( j % 2 === 0 ) {
  14955. pushVertex( v[ i ][ k + 1 ] );
  14956. pushVertex( v[ i + 1 ][ k ] );
  14957. pushVertex( v[ i ][ k ] );
  14958. } else {
  14959. pushVertex( v[ i ][ k + 1 ] );
  14960. pushVertex( v[ i + 1 ][ k + 1 ] );
  14961. pushVertex( v[ i + 1 ][ k ] );
  14962. }
  14963. }
  14964. }
  14965. }
  14966. function appplyRadius( radius ) {
  14967. var vertex = new Vector3();
  14968. // iterate over the entire buffer and apply the radius to each vertex
  14969. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14970. vertex.x = vertexBuffer[ i + 0 ];
  14971. vertex.y = vertexBuffer[ i + 1 ];
  14972. vertex.z = vertexBuffer[ i + 2 ];
  14973. vertex.normalize().multiplyScalar( radius );
  14974. vertexBuffer[ i + 0 ] = vertex.x;
  14975. vertexBuffer[ i + 1 ] = vertex.y;
  14976. vertexBuffer[ i + 2 ] = vertex.z;
  14977. }
  14978. }
  14979. function generateUVs() {
  14980. var vertex = new Vector3();
  14981. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14982. vertex.x = vertexBuffer[ i + 0 ];
  14983. vertex.y = vertexBuffer[ i + 1 ];
  14984. vertex.z = vertexBuffer[ i + 2 ];
  14985. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  14986. var v = inclination( vertex ) / Math.PI + 0.5;
  14987. uvBuffer.push( u, 1 - v );
  14988. }
  14989. correctUVs();
  14990. correctSeam();
  14991. }
  14992. function correctSeam() {
  14993. // handle case when face straddles the seam, see #3269
  14994. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  14995. // uv data of a single face
  14996. var x0 = uvBuffer[ i + 0 ];
  14997. var x1 = uvBuffer[ i + 2 ];
  14998. var x2 = uvBuffer[ i + 4 ];
  14999. var max = Math.max( x0, x1, x2 );
  15000. var min = Math.min( x0, x1, x2 );
  15001. // 0.9 is somewhat arbitrary
  15002. if ( max > 0.9 && min < 0.1 ) {
  15003. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  15004. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  15005. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  15006. }
  15007. }
  15008. }
  15009. function pushVertex( vertex ) {
  15010. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  15011. }
  15012. function getVertexByIndex( index, vertex ) {
  15013. var stride = index * 3;
  15014. vertex.x = vertices[ stride + 0 ];
  15015. vertex.y = vertices[ stride + 1 ];
  15016. vertex.z = vertices[ stride + 2 ];
  15017. }
  15018. function correctUVs() {
  15019. var a = new Vector3();
  15020. var b = new Vector3();
  15021. var c = new Vector3();
  15022. var centroid = new Vector3();
  15023. var uvA = new Vector2();
  15024. var uvB = new Vector2();
  15025. var uvC = new Vector2();
  15026. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  15027. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  15028. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  15029. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  15030. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  15031. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  15032. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  15033. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  15034. var azi = azimuth( centroid );
  15035. correctUV( uvA, j + 0, a, azi );
  15036. correctUV( uvB, j + 2, b, azi );
  15037. correctUV( uvC, j + 4, c, azi );
  15038. }
  15039. }
  15040. function correctUV( uv, stride, vector, azimuth ) {
  15041. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  15042. uvBuffer[ stride ] = uv.x - 1;
  15043. }
  15044. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  15045. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  15046. }
  15047. }
  15048. // Angle around the Y axis, counter-clockwise when looking from above.
  15049. function azimuth( vector ) {
  15050. return Math.atan2( vector.z, - vector.x );
  15051. }
  15052. // Angle above the XZ plane.
  15053. function inclination( vector ) {
  15054. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  15055. }
  15056. }
  15057. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15058. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  15059. /**
  15060. * @author timothypratley / https://github.com/timothypratley
  15061. * @author Mugen87 / https://github.com/Mugen87
  15062. */
  15063. // TetrahedronGeometry
  15064. function TetrahedronGeometry( radius, detail ) {
  15065. Geometry.call( this );
  15066. this.type = 'TetrahedronGeometry';
  15067. this.parameters = {
  15068. radius: radius,
  15069. detail: detail
  15070. };
  15071. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  15072. this.mergeVertices();
  15073. }
  15074. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  15075. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  15076. // TetrahedronBufferGeometry
  15077. function TetrahedronBufferGeometry( radius, detail ) {
  15078. var vertices = [
  15079. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  15080. ];
  15081. var indices = [
  15082. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  15083. ];
  15084. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15085. this.type = 'TetrahedronBufferGeometry';
  15086. this.parameters = {
  15087. radius: radius,
  15088. detail: detail
  15089. };
  15090. }
  15091. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15092. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  15093. /**
  15094. * @author timothypratley / https://github.com/timothypratley
  15095. * @author Mugen87 / https://github.com/Mugen87
  15096. */
  15097. // OctahedronGeometry
  15098. function OctahedronGeometry( radius, detail ) {
  15099. Geometry.call( this );
  15100. this.type = 'OctahedronGeometry';
  15101. this.parameters = {
  15102. radius: radius,
  15103. detail: detail
  15104. };
  15105. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  15106. this.mergeVertices();
  15107. }
  15108. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  15109. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  15110. // OctahedronBufferGeometry
  15111. function OctahedronBufferGeometry( radius, detail ) {
  15112. var vertices = [
  15113. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  15114. ];
  15115. var indices = [
  15116. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  15117. ];
  15118. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15119. this.type = 'OctahedronBufferGeometry';
  15120. this.parameters = {
  15121. radius: radius,
  15122. detail: detail
  15123. };
  15124. }
  15125. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15126. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  15127. /**
  15128. * @author timothypratley / https://github.com/timothypratley
  15129. * @author Mugen87 / https://github.com/Mugen87
  15130. */
  15131. // IcosahedronGeometry
  15132. function IcosahedronGeometry( radius, detail ) {
  15133. Geometry.call( this );
  15134. this.type = 'IcosahedronGeometry';
  15135. this.parameters = {
  15136. radius: radius,
  15137. detail: detail
  15138. };
  15139. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  15140. this.mergeVertices();
  15141. }
  15142. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  15143. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  15144. // IcosahedronBufferGeometry
  15145. function IcosahedronBufferGeometry( radius, detail ) {
  15146. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  15147. var vertices = [
  15148. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  15149. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  15150. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  15151. ];
  15152. var indices = [
  15153. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  15154. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  15155. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  15156. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  15157. ];
  15158. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15159. this.type = 'IcosahedronBufferGeometry';
  15160. this.parameters = {
  15161. radius: radius,
  15162. detail: detail
  15163. };
  15164. }
  15165. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15166. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  15167. /**
  15168. * @author Abe Pazos / https://hamoid.com
  15169. * @author Mugen87 / https://github.com/Mugen87
  15170. */
  15171. // DodecahedronGeometry
  15172. function DodecahedronGeometry( radius, detail ) {
  15173. Geometry.call( this );
  15174. this.type = 'DodecahedronGeometry';
  15175. this.parameters = {
  15176. radius: radius,
  15177. detail: detail
  15178. };
  15179. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  15180. this.mergeVertices();
  15181. }
  15182. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  15183. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  15184. // DodecahedronBufferGeometry
  15185. function DodecahedronBufferGeometry( radius, detail ) {
  15186. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  15187. var r = 1 / t;
  15188. var vertices = [
  15189. // (±1, ±1, ±1)
  15190. - 1, - 1, - 1, - 1, - 1, 1,
  15191. - 1, 1, - 1, - 1, 1, 1,
  15192. 1, - 1, - 1, 1, - 1, 1,
  15193. 1, 1, - 1, 1, 1, 1,
  15194. // (0, ±1/φ, ±φ)
  15195. 0, - r, - t, 0, - r, t,
  15196. 0, r, - t, 0, r, t,
  15197. // (±1/φ, ±φ, 0)
  15198. - r, - t, 0, - r, t, 0,
  15199. r, - t, 0, r, t, 0,
  15200. // (±φ, 0, ±1/φ)
  15201. - t, 0, - r, t, 0, - r,
  15202. - t, 0, r, t, 0, r
  15203. ];
  15204. var indices = [
  15205. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  15206. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  15207. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  15208. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  15209. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  15210. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  15211. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  15212. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  15213. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  15214. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  15215. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  15216. 1, 12, 14, 1, 14, 5, 1, 5, 9
  15217. ];
  15218. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15219. this.type = 'DodecahedronBufferGeometry';
  15220. this.parameters = {
  15221. radius: radius,
  15222. detail: detail
  15223. };
  15224. }
  15225. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15226. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  15227. /**
  15228. * @author oosmoxiecode / https://github.com/oosmoxiecode
  15229. * @author WestLangley / https://github.com/WestLangley
  15230. * @author zz85 / https://github.com/zz85
  15231. * @author miningold / https://github.com/miningold
  15232. * @author jonobr1 / https://github.com/jonobr1
  15233. * @author Mugen87 / https://github.com/Mugen87
  15234. *
  15235. */
  15236. // TubeGeometry
  15237. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  15238. Geometry.call( this );
  15239. this.type = 'TubeGeometry';
  15240. this.parameters = {
  15241. path: path,
  15242. tubularSegments: tubularSegments,
  15243. radius: radius,
  15244. radialSegments: radialSegments,
  15245. closed: closed
  15246. };
  15247. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  15248. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  15249. // expose internals
  15250. this.tangents = bufferGeometry.tangents;
  15251. this.normals = bufferGeometry.normals;
  15252. this.binormals = bufferGeometry.binormals;
  15253. // create geometry
  15254. this.fromBufferGeometry( bufferGeometry );
  15255. this.mergeVertices();
  15256. }
  15257. TubeGeometry.prototype = Object.create( Geometry.prototype );
  15258. TubeGeometry.prototype.constructor = TubeGeometry;
  15259. // TubeBufferGeometry
  15260. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  15261. BufferGeometry.call( this );
  15262. this.type = 'TubeBufferGeometry';
  15263. this.parameters = {
  15264. path: path,
  15265. tubularSegments: tubularSegments,
  15266. radius: radius,
  15267. radialSegments: radialSegments,
  15268. closed: closed
  15269. };
  15270. tubularSegments = tubularSegments || 64;
  15271. radius = radius || 1;
  15272. radialSegments = radialSegments || 8;
  15273. closed = closed || false;
  15274. var frames = path.computeFrenetFrames( tubularSegments, closed );
  15275. // expose internals
  15276. this.tangents = frames.tangents;
  15277. this.normals = frames.normals;
  15278. this.binormals = frames.binormals;
  15279. // helper variables
  15280. var vertex = new Vector3();
  15281. var normal = new Vector3();
  15282. var uv = new Vector2();
  15283. var i, j;
  15284. // buffer
  15285. var vertices = [];
  15286. var normals = [];
  15287. var uvs = [];
  15288. var indices = [];
  15289. // create buffer data
  15290. generateBufferData();
  15291. // build geometry
  15292. this.setIndex( indices );
  15293. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15294. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15295. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15296. // functions
  15297. function generateBufferData() {
  15298. for ( i = 0; i < tubularSegments; i ++ ) {
  15299. generateSegment( i );
  15300. }
  15301. // if the geometry is not closed, generate the last row of vertices and normals
  15302. // at the regular position on the given path
  15303. //
  15304. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  15305. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  15306. // uvs are generated in a separate function.
  15307. // this makes it easy compute correct values for closed geometries
  15308. generateUVs();
  15309. // finally create faces
  15310. generateIndices();
  15311. }
  15312. function generateSegment( i ) {
  15313. // we use getPointAt to sample evenly distributed points from the given path
  15314. var P = path.getPointAt( i / tubularSegments );
  15315. // retrieve corresponding normal and binormal
  15316. var N = frames.normals[ i ];
  15317. var B = frames.binormals[ i ];
  15318. // generate normals and vertices for the current segment
  15319. for ( j = 0; j <= radialSegments; j ++ ) {
  15320. var v = j / radialSegments * Math.PI * 2;
  15321. var sin = Math.sin( v );
  15322. var cos = - Math.cos( v );
  15323. // normal
  15324. normal.x = ( cos * N.x + sin * B.x );
  15325. normal.y = ( cos * N.y + sin * B.y );
  15326. normal.z = ( cos * N.z + sin * B.z );
  15327. normal.normalize();
  15328. normals.push( normal.x, normal.y, normal.z );
  15329. // vertex
  15330. vertex.x = P.x + radius * normal.x;
  15331. vertex.y = P.y + radius * normal.y;
  15332. vertex.z = P.z + radius * normal.z;
  15333. vertices.push( vertex.x, vertex.y, vertex.z );
  15334. }
  15335. }
  15336. function generateIndices() {
  15337. for ( j = 1; j <= tubularSegments; j ++ ) {
  15338. for ( i = 1; i <= radialSegments; i ++ ) {
  15339. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15340. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  15341. var c = ( radialSegments + 1 ) * j + i;
  15342. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15343. // faces
  15344. indices.push( a, b, d );
  15345. indices.push( b, c, d );
  15346. }
  15347. }
  15348. }
  15349. function generateUVs() {
  15350. for ( i = 0; i <= tubularSegments; i ++ ) {
  15351. for ( j = 0; j <= radialSegments; j ++ ) {
  15352. uv.x = i / tubularSegments;
  15353. uv.y = j / radialSegments;
  15354. uvs.push( uv.x, uv.y );
  15355. }
  15356. }
  15357. }
  15358. }
  15359. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15360. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  15361. /**
  15362. * @author oosmoxiecode
  15363. * @author Mugen87 / https://github.com/Mugen87
  15364. *
  15365. * based on http://www.blackpawn.com/texts/pqtorus/
  15366. */
  15367. // TorusKnotGeometry
  15368. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  15369. Geometry.call( this );
  15370. this.type = 'TorusKnotGeometry';
  15371. this.parameters = {
  15372. radius: radius,
  15373. tube: tube,
  15374. tubularSegments: tubularSegments,
  15375. radialSegments: radialSegments,
  15376. p: p,
  15377. q: q
  15378. };
  15379. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  15380. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  15381. this.mergeVertices();
  15382. }
  15383. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  15384. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  15385. // TorusKnotBufferGeometry
  15386. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  15387. BufferGeometry.call( this );
  15388. this.type = 'TorusKnotBufferGeometry';
  15389. this.parameters = {
  15390. radius: radius,
  15391. tube: tube,
  15392. tubularSegments: tubularSegments,
  15393. radialSegments: radialSegments,
  15394. p: p,
  15395. q: q
  15396. };
  15397. radius = radius || 100;
  15398. tube = tube || 40;
  15399. tubularSegments = Math.floor( tubularSegments ) || 64;
  15400. radialSegments = Math.floor( radialSegments ) || 8;
  15401. p = p || 2;
  15402. q = q || 3;
  15403. // buffers
  15404. var indices = [];
  15405. var vertices = [];
  15406. var normals = [];
  15407. var uvs = [];
  15408. // helper variables
  15409. var i, j;
  15410. var vertex = new Vector3();
  15411. var normal = new Vector3();
  15412. var P1 = new Vector3();
  15413. var P2 = new Vector3();
  15414. var B = new Vector3();
  15415. var T = new Vector3();
  15416. var N = new Vector3();
  15417. // generate vertices, normals and uvs
  15418. for ( i = 0; i <= tubularSegments; ++ i ) {
  15419. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  15420. var u = i / tubularSegments * p * Math.PI * 2;
  15421. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  15422. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  15423. calculatePositionOnCurve( u, p, q, radius, P1 );
  15424. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  15425. // calculate orthonormal basis
  15426. T.subVectors( P2, P1 );
  15427. N.addVectors( P2, P1 );
  15428. B.crossVectors( T, N );
  15429. N.crossVectors( B, T );
  15430. // normalize B, N. T can be ignored, we don't use it
  15431. B.normalize();
  15432. N.normalize();
  15433. for ( j = 0; j <= radialSegments; ++ j ) {
  15434. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  15435. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  15436. var v = j / radialSegments * Math.PI * 2;
  15437. var cx = - tube * Math.cos( v );
  15438. var cy = tube * Math.sin( v );
  15439. // now calculate the final vertex position.
  15440. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  15441. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  15442. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  15443. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  15444. vertices.push( vertex.x, vertex.y, vertex.z );
  15445. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  15446. normal.subVectors( vertex, P1 ).normalize();
  15447. normals.push( normal.x, normal.y, normal.z );
  15448. // uv
  15449. uvs.push( i / tubularSegments );
  15450. uvs.push( j / radialSegments );
  15451. }
  15452. }
  15453. // generate indices
  15454. for ( j = 1; j <= tubularSegments; j ++ ) {
  15455. for ( i = 1; i <= radialSegments; i ++ ) {
  15456. // indices
  15457. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15458. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  15459. var c = ( radialSegments + 1 ) * j + i;
  15460. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15461. // faces
  15462. indices.push( a, b, d );
  15463. indices.push( b, c, d );
  15464. }
  15465. }
  15466. // build geometry
  15467. this.setIndex( indices );
  15468. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15469. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15470. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15471. // this function calculates the current position on the torus curve
  15472. function calculatePositionOnCurve( u, p, q, radius, position ) {
  15473. var cu = Math.cos( u );
  15474. var su = Math.sin( u );
  15475. var quOverP = q / p * u;
  15476. var cs = Math.cos( quOverP );
  15477. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  15478. position.y = radius * ( 2 + cs ) * su * 0.5;
  15479. position.z = radius * Math.sin( quOverP ) * 0.5;
  15480. }
  15481. }
  15482. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15483. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  15484. /**
  15485. * @author oosmoxiecode
  15486. * @author mrdoob / http://mrdoob.com/
  15487. * @author Mugen87 / https://github.com/Mugen87
  15488. */
  15489. // TorusGeometry
  15490. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15491. Geometry.call( this );
  15492. this.type = 'TorusGeometry';
  15493. this.parameters = {
  15494. radius: radius,
  15495. tube: tube,
  15496. radialSegments: radialSegments,
  15497. tubularSegments: tubularSegments,
  15498. arc: arc
  15499. };
  15500. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  15501. this.mergeVertices();
  15502. }
  15503. TorusGeometry.prototype = Object.create( Geometry.prototype );
  15504. TorusGeometry.prototype.constructor = TorusGeometry;
  15505. // TorusBufferGeometry
  15506. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15507. BufferGeometry.call( this );
  15508. this.type = 'TorusBufferGeometry';
  15509. this.parameters = {
  15510. radius: radius,
  15511. tube: tube,
  15512. radialSegments: radialSegments,
  15513. tubularSegments: tubularSegments,
  15514. arc: arc
  15515. };
  15516. radius = radius || 100;
  15517. tube = tube || 40;
  15518. radialSegments = Math.floor( radialSegments ) || 8;
  15519. tubularSegments = Math.floor( tubularSegments ) || 6;
  15520. arc = arc || Math.PI * 2;
  15521. // buffers
  15522. var indices = [];
  15523. var vertices = [];
  15524. var normals = [];
  15525. var uvs = [];
  15526. // helper variables
  15527. var center = new Vector3();
  15528. var vertex = new Vector3();
  15529. var normal = new Vector3();
  15530. var j, i;
  15531. // generate vertices, normals and uvs
  15532. for ( j = 0; j <= radialSegments; j ++ ) {
  15533. for ( i = 0; i <= tubularSegments; i ++ ) {
  15534. var u = i / tubularSegments * arc;
  15535. var v = j / radialSegments * Math.PI * 2;
  15536. // vertex
  15537. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  15538. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  15539. vertex.z = tube * Math.sin( v );
  15540. vertices.push( vertex.x, vertex.y, vertex.z );
  15541. // normal
  15542. center.x = radius * Math.cos( u );
  15543. center.y = radius * Math.sin( u );
  15544. normal.subVectors( vertex, center ).normalize();
  15545. normals.push( normal.x, normal.y, normal.z );
  15546. // uv
  15547. uvs.push( i / tubularSegments );
  15548. uvs.push( j / radialSegments );
  15549. }
  15550. }
  15551. // generate indices
  15552. for ( j = 1; j <= radialSegments; j ++ ) {
  15553. for ( i = 1; i <= tubularSegments; i ++ ) {
  15554. // indices
  15555. var a = ( tubularSegments + 1 ) * j + i - 1;
  15556. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  15557. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  15558. var d = ( tubularSegments + 1 ) * j + i;
  15559. // faces
  15560. indices.push( a, b, d );
  15561. indices.push( b, c, d );
  15562. }
  15563. }
  15564. // build geometry
  15565. this.setIndex( indices );
  15566. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15567. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15568. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15569. }
  15570. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15571. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  15572. /**
  15573. * @author zz85 / http://www.lab4games.net/zz85/blog
  15574. */
  15575. var ShapeUtils = {
  15576. // calculate area of the contour polygon
  15577. area: function ( contour ) {
  15578. var n = contour.length;
  15579. var a = 0.0;
  15580. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  15581. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15582. }
  15583. return a * 0.5;
  15584. },
  15585. triangulate: ( function () {
  15586. /**
  15587. * This code is a quick port of code written in C++ which was submitted to
  15588. * flipcode.com by John W. Ratcliff // July 22, 2000
  15589. * See original code and more information here:
  15590. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15591. *
  15592. * ported to actionscript by Zevan Rosser
  15593. * www.actionsnippet.com
  15594. *
  15595. * ported to javascript by Joshua Koo
  15596. * http://www.lab4games.net/zz85/blog
  15597. *
  15598. */
  15599. function snip( contour, u, v, w, n, verts ) {
  15600. var p;
  15601. var ax, ay, bx, by;
  15602. var cx, cy, px, py;
  15603. ax = contour[ verts[ u ] ].x;
  15604. ay = contour[ verts[ u ] ].y;
  15605. bx = contour[ verts[ v ] ].x;
  15606. by = contour[ verts[ v ] ].y;
  15607. cx = contour[ verts[ w ] ].x;
  15608. cy = contour[ verts[ w ] ].y;
  15609. if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false;
  15610. var aX, aY, bX, bY, cX, cY;
  15611. var apx, apy, bpx, bpy, cpx, cpy;
  15612. var cCROSSap, bCROSScp, aCROSSbp;
  15613. aX = cx - bx; aY = cy - by;
  15614. bX = ax - cx; bY = ay - cy;
  15615. cX = bx - ax; cY = by - ay;
  15616. for ( p = 0; p < n; p ++ ) {
  15617. px = contour[ verts[ p ] ].x;
  15618. py = contour[ verts[ p ] ].y;
  15619. if ( ( ( px === ax ) && ( py === ay ) ) ||
  15620. ( ( px === bx ) && ( py === by ) ) ||
  15621. ( ( px === cx ) && ( py === cy ) ) ) continue;
  15622. apx = px - ax; apy = py - ay;
  15623. bpx = px - bx; bpy = py - by;
  15624. cpx = px - cx; cpy = py - cy;
  15625. // see if p is inside triangle abc
  15626. aCROSSbp = aX * bpy - aY * bpx;
  15627. cCROSSap = cX * apy - cY * apx;
  15628. bCROSScp = bX * cpy - bY * cpx;
  15629. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  15630. }
  15631. return true;
  15632. }
  15633. // takes in an contour array and returns
  15634. return function triangulate( contour, indices ) {
  15635. var n = contour.length;
  15636. if ( n < 3 ) return null;
  15637. var result = [],
  15638. verts = [],
  15639. vertIndices = [];
  15640. /* we want a counter-clockwise polygon in verts */
  15641. var u, v, w;
  15642. if ( ShapeUtils.area( contour ) > 0.0 ) {
  15643. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  15644. } else {
  15645. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  15646. }
  15647. var nv = n;
  15648. /* remove nv - 2 vertices, creating 1 triangle every time */
  15649. var count = 2 * nv; /* error detection */
  15650. for ( v = nv - 1; nv > 2; ) {
  15651. /* if we loop, it is probably a non-simple polygon */
  15652. if ( ( count -- ) <= 0 ) {
  15653. //** Triangulate: ERROR - probable bad polygon!
  15654. //throw ( "Warning, unable to triangulate polygon!" );
  15655. //return null;
  15656. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15657. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  15658. if ( indices ) return vertIndices;
  15659. return result;
  15660. }
  15661. /* three consecutive vertices in current polygon, <u,v,w> */
  15662. u = v; if ( nv <= u ) u = 0; /* previous */
  15663. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15664. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15665. if ( snip( contour, u, v, w, nv, verts ) ) {
  15666. var a, b, c, s, t;
  15667. /* true names of the vertices */
  15668. a = verts[ u ];
  15669. b = verts[ v ];
  15670. c = verts[ w ];
  15671. /* output Triangle */
  15672. result.push( [ contour[ a ],
  15673. contour[ b ],
  15674. contour[ c ] ] );
  15675. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15676. /* remove v from the remaining polygon */
  15677. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  15678. verts[ s ] = verts[ t ];
  15679. }
  15680. nv --;
  15681. /* reset error detection counter */
  15682. count = 2 * nv;
  15683. }
  15684. }
  15685. if ( indices ) return vertIndices;
  15686. return result;
  15687. };
  15688. } )(),
  15689. triangulateShape: function ( contour, holes ) {
  15690. function removeDupEndPts(points) {
  15691. var l = points.length;
  15692. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  15693. points.pop();
  15694. }
  15695. }
  15696. removeDupEndPts( contour );
  15697. holes.forEach( removeDupEndPts );
  15698. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  15699. // inOtherPt needs to be collinear to the inSegment
  15700. if ( inSegPt1.x !== inSegPt2.x ) {
  15701. if ( inSegPt1.x < inSegPt2.x ) {
  15702. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  15703. } else {
  15704. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  15705. }
  15706. } else {
  15707. if ( inSegPt1.y < inSegPt2.y ) {
  15708. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  15709. } else {
  15710. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  15711. }
  15712. }
  15713. }
  15714. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  15715. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  15716. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  15717. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  15718. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  15719. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  15720. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  15721. if ( Math.abs( limit ) > Number.EPSILON ) {
  15722. // not parallel
  15723. var perpSeg2;
  15724. if ( limit > 0 ) {
  15725. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  15726. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15727. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  15728. } else {
  15729. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  15730. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15731. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  15732. }
  15733. // i.e. to reduce rounding errors
  15734. // intersection at endpoint of segment#1?
  15735. if ( perpSeg2 === 0 ) {
  15736. if ( ( inExcludeAdjacentSegs ) &&
  15737. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15738. return [ inSeg1Pt1 ];
  15739. }
  15740. if ( perpSeg2 === limit ) {
  15741. if ( ( inExcludeAdjacentSegs ) &&
  15742. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15743. return [ inSeg1Pt2 ];
  15744. }
  15745. // intersection at endpoint of segment#2?
  15746. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  15747. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  15748. // return real intersection point
  15749. var factorSeg1 = perpSeg2 / limit;
  15750. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  15751. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  15752. } else {
  15753. // parallel or collinear
  15754. if ( ( perpSeg1 !== 0 ) ||
  15755. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  15756. // they are collinear or degenerate
  15757. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  15758. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  15759. // both segments are points
  15760. if ( seg1Pt && seg2Pt ) {
  15761. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  15762. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  15763. return [ inSeg1Pt1 ]; // they are the same point
  15764. }
  15765. // segment#1 is a single point
  15766. if ( seg1Pt ) {
  15767. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  15768. return [ inSeg1Pt1 ];
  15769. }
  15770. // segment#2 is a single point
  15771. if ( seg2Pt ) {
  15772. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  15773. return [ inSeg2Pt1 ];
  15774. }
  15775. // they are collinear segments, which might overlap
  15776. var seg1min, seg1max, seg1minVal, seg1maxVal;
  15777. var seg2min, seg2max, seg2minVal, seg2maxVal;
  15778. if ( seg1dx !== 0 ) {
  15779. // the segments are NOT on a vertical line
  15780. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  15781. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  15782. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  15783. } else {
  15784. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  15785. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  15786. }
  15787. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  15788. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  15789. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  15790. } else {
  15791. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  15792. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  15793. }
  15794. } else {
  15795. // the segments are on a vertical line
  15796. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  15797. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  15798. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  15799. } else {
  15800. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  15801. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  15802. }
  15803. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  15804. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  15805. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  15806. } else {
  15807. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  15808. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  15809. }
  15810. }
  15811. if ( seg1minVal <= seg2minVal ) {
  15812. if ( seg1maxVal < seg2minVal ) return [];
  15813. if ( seg1maxVal === seg2minVal ) {
  15814. if ( inExcludeAdjacentSegs ) return [];
  15815. return [ seg2min ];
  15816. }
  15817. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  15818. return [ seg2min, seg2max ];
  15819. } else {
  15820. if ( seg1minVal > seg2maxVal ) return [];
  15821. if ( seg1minVal === seg2maxVal ) {
  15822. if ( inExcludeAdjacentSegs ) return [];
  15823. return [ seg1min ];
  15824. }
  15825. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  15826. return [ seg1min, seg2max ];
  15827. }
  15828. }
  15829. }
  15830. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  15831. // The order of legs is important
  15832. // translation of all points, so that Vertex is at (0,0)
  15833. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  15834. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  15835. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  15836. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  15837. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  15838. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  15839. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  15840. // angle != 180 deg.
  15841. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  15842. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  15843. if ( from2toAngle > 0 ) {
  15844. // main angle < 180 deg.
  15845. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  15846. } else {
  15847. // main angle > 180 deg.
  15848. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  15849. }
  15850. } else {
  15851. // angle == 180 deg.
  15852. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  15853. return ( from2otherAngle > 0 );
  15854. }
  15855. }
  15856. function removeHoles( contour, holes ) {
  15857. var shape = contour.concat(); // work on this shape
  15858. var hole;
  15859. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  15860. // Check if hole point lies within angle around shape point
  15861. var lastShapeIdx = shape.length - 1;
  15862. var prevShapeIdx = inShapeIdx - 1;
  15863. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  15864. var nextShapeIdx = inShapeIdx + 1;
  15865. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  15866. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  15867. if ( ! insideAngle ) {
  15868. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  15869. return false;
  15870. }
  15871. // Check if shape point lies within angle around hole point
  15872. var lastHoleIdx = hole.length - 1;
  15873. var prevHoleIdx = inHoleIdx - 1;
  15874. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  15875. var nextHoleIdx = inHoleIdx + 1;
  15876. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  15877. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  15878. if ( ! insideAngle ) {
  15879. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  15880. return false;
  15881. }
  15882. return true;
  15883. }
  15884. function intersectsShapeEdge( inShapePt, inHolePt ) {
  15885. // checks for intersections with shape edges
  15886. var sIdx, nextIdx, intersection;
  15887. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  15888. nextIdx = sIdx + 1; nextIdx %= shape.length;
  15889. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  15890. if ( intersection.length > 0 ) return true;
  15891. }
  15892. return false;
  15893. }
  15894. var indepHoles = [];
  15895. function intersectsHoleEdge( inShapePt, inHolePt ) {
  15896. // checks for intersections with hole edges
  15897. var ihIdx, chkHole,
  15898. hIdx, nextIdx, intersection;
  15899. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  15900. chkHole = holes[ indepHoles[ ihIdx ] ];
  15901. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  15902. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  15903. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  15904. if ( intersection.length > 0 ) return true;
  15905. }
  15906. }
  15907. return false;
  15908. }
  15909. var holeIndex, shapeIndex,
  15910. shapePt, holePt,
  15911. holeIdx, cutKey, failedCuts = [],
  15912. tmpShape1, tmpShape2,
  15913. tmpHole1, tmpHole2;
  15914. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15915. indepHoles.push( h );
  15916. }
  15917. var minShapeIndex = 0;
  15918. var counter = indepHoles.length * 2;
  15919. while ( indepHoles.length > 0 ) {
  15920. counter --;
  15921. if ( counter < 0 ) {
  15922. console.log( 'THREE.ShapeUtils: Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!' );
  15923. break;
  15924. }
  15925. // search for shape-vertex and hole-vertex,
  15926. // which can be connected without intersections
  15927. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  15928. shapePt = shape[ shapeIndex ];
  15929. holeIndex = - 1;
  15930. // search for hole which can be reached without intersections
  15931. for ( var h = 0; h < indepHoles.length; h ++ ) {
  15932. holeIdx = indepHoles[ h ];
  15933. // prevent multiple checks
  15934. cutKey = shapePt.x + ':' + shapePt.y + ':' + holeIdx;
  15935. if ( failedCuts[ cutKey ] !== undefined ) continue;
  15936. hole = holes[ holeIdx ];
  15937. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  15938. holePt = hole[ h2 ];
  15939. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  15940. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  15941. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  15942. holeIndex = h2;
  15943. indepHoles.splice( h, 1 );
  15944. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  15945. tmpShape2 = shape.slice( shapeIndex );
  15946. tmpHole1 = hole.slice( holeIndex );
  15947. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  15948. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  15949. minShapeIndex = shapeIndex;
  15950. // Debug only, to show the selected cuts
  15951. // glob_CutLines.push( [ shapePt, holePt ] );
  15952. break;
  15953. }
  15954. if ( holeIndex >= 0 ) break; // hole-vertex found
  15955. failedCuts[ cutKey ] = true; // remember failure
  15956. }
  15957. if ( holeIndex >= 0 ) break; // hole-vertex found
  15958. }
  15959. }
  15960. return shape; /* shape with no holes */
  15961. }
  15962. var i, il, f, face,
  15963. key, index,
  15964. allPointsMap = {};
  15965. // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first.
  15966. var allpoints = contour.concat();
  15967. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15968. Array.prototype.push.apply( allpoints, holes[ h ] );
  15969. }
  15970. //console.log( "allpoints",allpoints, allpoints.length );
  15971. // prepare all points map
  15972. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  15973. key = allpoints[ i ].x + ':' + allpoints[ i ].y;
  15974. if ( allPointsMap[ key ] !== undefined ) {
  15975. console.warn( 'THREE.ShapeUtils: Duplicate point', key, i );
  15976. }
  15977. allPointsMap[ key ] = i;
  15978. }
  15979. // remove holes by cutting paths to holes and adding them to the shape
  15980. var shapeWithoutHoles = removeHoles( contour, holes );
  15981. var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  15982. //console.log( "triangles",triangles, triangles.length );
  15983. // check all face vertices against all points map
  15984. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  15985. face = triangles[ i ];
  15986. for ( f = 0; f < 3; f ++ ) {
  15987. key = face[ f ].x + ':' + face[ f ].y;
  15988. index = allPointsMap[ key ];
  15989. if ( index !== undefined ) {
  15990. face[ f ] = index;
  15991. }
  15992. }
  15993. }
  15994. return triangles.concat();
  15995. },
  15996. isClockWise: function ( pts ) {
  15997. return ShapeUtils.area( pts ) < 0;
  15998. }
  15999. };
  16000. /**
  16001. * @author zz85 / http://www.lab4games.net/zz85/blog
  16002. *
  16003. * Creates extruded geometry from a path shape.
  16004. *
  16005. * parameters = {
  16006. *
  16007. * curveSegments: <int>, // number of points on the curves
  16008. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  16009. * amount: <int>, // Depth to extrude the shape
  16010. *
  16011. * bevelEnabled: <bool>, // turn on bevel
  16012. * bevelThickness: <float>, // how deep into the original shape bevel goes
  16013. * bevelSize: <float>, // how far from shape outline is bevel
  16014. * bevelSegments: <int>, // number of bevel layers
  16015. *
  16016. * extrudePath: <THREE.Curve> // curve to extrude shape along
  16017. * frames: <Object> // containing arrays of tangents, normals, binormals
  16018. *
  16019. * UVGenerator: <Object> // object that provides UV generator functions
  16020. *
  16021. * }
  16022. */
  16023. // ExtrudeGeometry
  16024. function ExtrudeGeometry( shapes, options ) {
  16025. Geometry.call( this );
  16026. this.type = 'ExtrudeGeometry';
  16027. this.parameters = {
  16028. shapes: shapes,
  16029. options: options
  16030. };
  16031. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  16032. this.mergeVertices();
  16033. }
  16034. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  16035. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  16036. // ExtrudeBufferGeometry
  16037. function ExtrudeBufferGeometry( shapes, options ) {
  16038. if ( typeof ( shapes ) === "undefined" ) {
  16039. return;
  16040. }
  16041. BufferGeometry.call( this );
  16042. this.type = 'ExtrudeBufferGeometry';
  16043. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  16044. this.addShapeList( shapes, options );
  16045. this.computeVertexNormals();
  16046. // can't really use automatic vertex normals
  16047. // as then front and back sides get smoothed too
  16048. // should do separate smoothing just for sides
  16049. //this.computeVertexNormals();
  16050. //console.log( "took", ( Date.now() - startTime ) );
  16051. }
  16052. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16053. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  16054. ExtrudeBufferGeometry.prototype.getArrays = function () {
  16055. var positionAttribute = this.getAttribute( "position" );
  16056. var verticesArray = positionAttribute ? Array.prototype.slice.call( positionAttribute.array ) : [];
  16057. var uvAttribute = this.getAttribute( "uv" );
  16058. var uvArray = uvAttribute ? Array.prototype.slice.call( uvAttribute.array ) : [];
  16059. var IndexAttribute = this.index;
  16060. var indicesArray = IndexAttribute ? Array.prototype.slice.call( IndexAttribute.array ) : [];
  16061. return {
  16062. position: verticesArray,
  16063. uv: uvArray,
  16064. index: indicesArray
  16065. };
  16066. };
  16067. ExtrudeBufferGeometry.prototype.addShapeList = function ( shapes, options ) {
  16068. var sl = shapes.length;
  16069. options.arrays = this.getArrays();
  16070. for ( var s = 0; s < sl; s ++ ) {
  16071. var shape = shapes[ s ];
  16072. this.addShape( shape, options );
  16073. }
  16074. this.setIndex( options.arrays.index );
  16075. this.addAttribute( 'position', new Float32BufferAttribute( options.arrays.position, 3 ) );
  16076. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  16077. };
  16078. ExtrudeBufferGeometry.prototype.addShape = function ( shape, options ) {
  16079. var arrays = options.arrays ? options.arrays : this.getArrays();
  16080. var verticesArray = arrays.position;
  16081. var indicesArray = arrays.index;
  16082. var uvArray = arrays.uv;
  16083. var placeholder = [];
  16084. var amount = options.amount !== undefined ? options.amount : 100;
  16085. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  16086. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  16087. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  16088. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  16089. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  16090. var steps = options.steps !== undefined ? options.steps : 1;
  16091. var extrudePath = options.extrudePath;
  16092. var extrudePts, extrudeByPath = false;
  16093. // Use default WorldUVGenerator if no UV generators are specified.
  16094. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  16095. var splineTube, binormal, normal, position2;
  16096. if ( extrudePath ) {
  16097. extrudePts = extrudePath.getSpacedPoints( steps );
  16098. extrudeByPath = true;
  16099. bevelEnabled = false; // bevels not supported for path extrusion
  16100. // SETUP TNB variables
  16101. // TODO1 - have a .isClosed in spline?
  16102. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  16103. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  16104. binormal = new Vector3();
  16105. normal = new Vector3();
  16106. position2 = new Vector3();
  16107. }
  16108. // Safeguards if bevels are not enabled
  16109. if ( ! bevelEnabled ) {
  16110. bevelSegments = 0;
  16111. bevelThickness = 0;
  16112. bevelSize = 0;
  16113. }
  16114. // Variables initialization
  16115. var ahole, h, hl; // looping of holes
  16116. var scope = this;
  16117. var shapePoints = shape.extractPoints( curveSegments );
  16118. var vertices = shapePoints.shape;
  16119. var holes = shapePoints.holes;
  16120. var reverse = ! ShapeUtils.isClockWise( vertices );
  16121. if ( reverse ) {
  16122. vertices = vertices.reverse();
  16123. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  16124. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16125. ahole = holes[ h ];
  16126. if ( ShapeUtils.isClockWise( ahole ) ) {
  16127. holes[ h ] = ahole.reverse();
  16128. }
  16129. }
  16130. }
  16131. var faces = ShapeUtils.triangulateShape( vertices, holes );
  16132. /* Vertices */
  16133. var contour = vertices; // vertices has all points but contour has only points of circumference
  16134. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16135. ahole = holes[ h ];
  16136. vertices = vertices.concat( ahole );
  16137. }
  16138. function scalePt2( pt, vec, size ) {
  16139. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  16140. return vec.clone().multiplyScalar( size ).add( pt );
  16141. }
  16142. var b, bs, t, z,
  16143. vert, vlen = vertices.length,
  16144. face, flen = faces.length;
  16145. // Find directions for point movement
  16146. function getBevelVec( inPt, inPrev, inNext ) {
  16147. // computes for inPt the corresponding point inPt' on a new contour
  16148. // shifted by 1 unit (length of normalized vector) to the left
  16149. // if we walk along contour clockwise, this new contour is outside the old one
  16150. //
  16151. // inPt' is the intersection of the two lines parallel to the two
  16152. // adjacent edges of inPt at a distance of 1 unit on the left side.
  16153. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  16154. // good reading for geometry algorithms (here: line-line intersection)
  16155. // http://geomalgorithms.com/a05-_intersect-1.html
  16156. var v_prev_x = inPt.x - inPrev.x,
  16157. v_prev_y = inPt.y - inPrev.y;
  16158. var v_next_x = inNext.x - inPt.x,
  16159. v_next_y = inNext.y - inPt.y;
  16160. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  16161. // check for collinear edges
  16162. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  16163. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  16164. // not collinear
  16165. // length of vectors for normalizing
  16166. var v_prev_len = Math.sqrt( v_prev_lensq );
  16167. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  16168. // shift adjacent points by unit vectors to the left
  16169. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  16170. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  16171. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  16172. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  16173. // scaling factor for v_prev to intersection point
  16174. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  16175. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  16176. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  16177. // vector from inPt to intersection point
  16178. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  16179. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  16180. // Don't normalize!, otherwise sharp corners become ugly
  16181. // but prevent crazy spikes
  16182. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  16183. if ( v_trans_lensq <= 2 ) {
  16184. return new Vector2( v_trans_x, v_trans_y );
  16185. } else {
  16186. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  16187. }
  16188. } else {
  16189. // handle special case of collinear edges
  16190. var direction_eq = false; // assumes: opposite
  16191. if ( v_prev_x > Number.EPSILON ) {
  16192. if ( v_next_x > Number.EPSILON ) {
  16193. direction_eq = true;
  16194. }
  16195. } else {
  16196. if ( v_prev_x < - Number.EPSILON ) {
  16197. if ( v_next_x < - Number.EPSILON ) {
  16198. direction_eq = true;
  16199. }
  16200. } else {
  16201. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  16202. direction_eq = true;
  16203. }
  16204. }
  16205. }
  16206. if ( direction_eq ) {
  16207. // console.log("Warning: lines are a straight sequence");
  16208. v_trans_x = - v_prev_y;
  16209. v_trans_y = v_prev_x;
  16210. shrink_by = Math.sqrt( v_prev_lensq );
  16211. } else {
  16212. // console.log("Warning: lines are a straight spike");
  16213. v_trans_x = v_prev_x;
  16214. v_trans_y = v_prev_y;
  16215. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  16216. }
  16217. }
  16218. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  16219. }
  16220. var contourMovements = [];
  16221. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  16222. if ( j === il ) j = 0;
  16223. if ( k === il ) k = 0;
  16224. // (j)---(i)---(k)
  16225. // console.log('i,j,k', i, j , k)
  16226. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  16227. }
  16228. var holesMovements = [],
  16229. oneHoleMovements, verticesMovements = contourMovements.concat();
  16230. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16231. ahole = holes[ h ];
  16232. oneHoleMovements = [];
  16233. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  16234. if ( j === il ) j = 0;
  16235. if ( k === il ) k = 0;
  16236. // (j)---(i)---(k)
  16237. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  16238. }
  16239. holesMovements.push( oneHoleMovements );
  16240. verticesMovements = verticesMovements.concat( oneHoleMovements );
  16241. }
  16242. // Loop bevelSegments, 1 for the front, 1 for the back
  16243. for ( b = 0; b < bevelSegments; b ++ ) {
  16244. //for ( b = bevelSegments; b > 0; b -- ) {
  16245. t = b / bevelSegments;
  16246. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  16247. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  16248. // contract shape
  16249. for ( i = 0, il = contour.length; i < il; i ++ ) {
  16250. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  16251. v( vert.x, vert.y, - z );
  16252. }
  16253. // expand holes
  16254. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16255. ahole = holes[ h ];
  16256. oneHoleMovements = holesMovements[ h ];
  16257. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  16258. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  16259. v( vert.x, vert.y, - z );
  16260. }
  16261. }
  16262. }
  16263. bs = bevelSize;
  16264. // Back facing vertices
  16265. for ( i = 0; i < vlen; i ++ ) {
  16266. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  16267. if ( ! extrudeByPath ) {
  16268. v( vert.x, vert.y, 0 );
  16269. } else {
  16270. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  16271. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  16272. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  16273. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  16274. v( position2.x, position2.y, position2.z );
  16275. }
  16276. }
  16277. // Add stepped vertices...
  16278. // Including front facing vertices
  16279. var s;
  16280. for ( s = 1; s <= steps; s ++ ) {
  16281. for ( i = 0; i < vlen; i ++ ) {
  16282. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  16283. if ( ! extrudeByPath ) {
  16284. v( vert.x, vert.y, amount / steps * s );
  16285. } else {
  16286. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  16287. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  16288. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  16289. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  16290. v( position2.x, position2.y, position2.z );
  16291. }
  16292. }
  16293. }
  16294. // Add bevel segments planes
  16295. //for ( b = 1; b <= bevelSegments; b ++ ) {
  16296. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  16297. t = b / bevelSegments;
  16298. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  16299. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  16300. // contract shape
  16301. for ( i = 0, il = contour.length; i < il; i ++ ) {
  16302. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  16303. v( vert.x, vert.y, amount + z );
  16304. }
  16305. // expand holes
  16306. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16307. ahole = holes[ h ];
  16308. oneHoleMovements = holesMovements[ h ];
  16309. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  16310. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  16311. if ( ! extrudeByPath ) {
  16312. v( vert.x, vert.y, amount + z );
  16313. } else {
  16314. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  16315. }
  16316. }
  16317. }
  16318. }
  16319. /* Faces */
  16320. // Top and bottom faces
  16321. buildLidFaces();
  16322. // Sides faces
  16323. buildSideFaces();
  16324. ///// Internal functions
  16325. function buildLidFaces() {
  16326. var start = verticesArray.length/3;
  16327. if ( bevelEnabled ) {
  16328. var layer = 0; // steps + 1
  16329. var offset = vlen * layer;
  16330. // Bottom faces
  16331. for ( i = 0; i < flen; i ++ ) {
  16332. face = faces[ i ];
  16333. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  16334. }
  16335. layer = steps + bevelSegments * 2;
  16336. offset = vlen * layer;
  16337. // Top faces
  16338. for ( i = 0; i < flen; i ++ ) {
  16339. face = faces[ i ];
  16340. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  16341. }
  16342. } else {
  16343. // Bottom faces
  16344. for ( i = 0; i < flen; i ++ ) {
  16345. face = faces[ i ];
  16346. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  16347. }
  16348. // Top faces
  16349. for ( i = 0; i < flen; i ++ ) {
  16350. face = faces[ i ];
  16351. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  16352. }
  16353. }
  16354. scope.addGroup( start, verticesArray.length/3 -start, options.material !== undefined ? options.material : 0);
  16355. }
  16356. // Create faces for the z-sides of the shape
  16357. function buildSideFaces() {
  16358. var start = verticesArray.length/3;
  16359. var layeroffset = 0;
  16360. sidewalls( contour, layeroffset );
  16361. layeroffset += contour.length;
  16362. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16363. ahole = holes[ h ];
  16364. sidewalls( ahole, layeroffset );
  16365. //, true
  16366. layeroffset += ahole.length;
  16367. }
  16368. scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);
  16369. }
  16370. function sidewalls( contour, layeroffset ) {
  16371. var j, k;
  16372. i = contour.length;
  16373. while ( -- i >= 0 ) {
  16374. j = i;
  16375. k = i - 1;
  16376. if ( k < 0 ) k = contour.length - 1;
  16377. //console.log('b', i,j, i-1, k,vertices.length);
  16378. var s = 0,
  16379. sl = steps + bevelSegments * 2;
  16380. for ( s = 0; s < sl; s ++ ) {
  16381. var slen1 = vlen * s;
  16382. var slen2 = vlen * ( s + 1 );
  16383. var a = layeroffset + j + slen1,
  16384. b = layeroffset + k + slen1,
  16385. c = layeroffset + k + slen2,
  16386. d = layeroffset + j + slen2;
  16387. f4( a, b, c, d, contour, s, sl, j, k );
  16388. }
  16389. }
  16390. }
  16391. function v( x, y, z ) {
  16392. placeholder.push( x );
  16393. placeholder.push( y );
  16394. placeholder.push( z );
  16395. }
  16396. function f3( a, b, c ) {
  16397. addVertex( a );
  16398. addVertex( b );
  16399. addVertex( c );
  16400. var nextIndex = verticesArray.length / 3;
  16401. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  16402. addUV( uvs[ 0 ] );
  16403. addUV( uvs[ 1 ] );
  16404. addUV( uvs[ 2 ] );
  16405. }
  16406. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  16407. addVertex( a );
  16408. addVertex( b );
  16409. addVertex( d );
  16410. addVertex( b );
  16411. addVertex( c );
  16412. addVertex( d );
  16413. var nextIndex = verticesArray.length / 3;
  16414. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  16415. addUV( uvs[ 0 ] );
  16416. addUV( uvs[ 1 ] );
  16417. addUV( uvs[ 3 ] );
  16418. addUV( uvs[ 1 ] );
  16419. addUV( uvs[ 2 ] );
  16420. addUV( uvs[ 3 ] );
  16421. }
  16422. function addVertex( index ) {
  16423. indicesArray.push( verticesArray.length / 3 );
  16424. verticesArray.push( placeholder[ index * 3 + 0 ] );
  16425. verticesArray.push( placeholder[ index * 3 + 1 ] );
  16426. verticesArray.push( placeholder[ index * 3 + 2 ] );
  16427. }
  16428. function addUV( vector2 ) {
  16429. uvArray.push( vector2.x );
  16430. uvArray.push( vector2.y );
  16431. }
  16432. if ( ! options.arrays ) {
  16433. this.setIndex( indicesArray );
  16434. this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  16435. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  16436. }
  16437. };
  16438. ExtrudeGeometry.WorldUVGenerator = {
  16439. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  16440. var a_x = vertices[ indexA * 3 ];
  16441. var a_y = vertices[ indexA * 3 + 1 ];
  16442. var b_x = vertices[ indexB * 3 ];
  16443. var b_y = vertices[ indexB * 3 + 1 ];
  16444. var c_x = vertices[ indexC * 3 ];
  16445. var c_y = vertices[ indexC * 3 + 1 ];
  16446. return [
  16447. new Vector2( a_x, a_y ),
  16448. new Vector2( b_x, b_y ),
  16449. new Vector2( c_x, c_y )
  16450. ];
  16451. },
  16452. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  16453. var a_x = vertices[ indexA * 3 ];
  16454. var a_y = vertices[ indexA * 3 + 1 ];
  16455. var a_z = vertices[ indexA * 3 + 2 ];
  16456. var b_x = vertices[ indexB * 3 ];
  16457. var b_y = vertices[ indexB * 3 + 1 ];
  16458. var b_z = vertices[ indexB * 3 + 2 ];
  16459. var c_x = vertices[ indexC * 3 ];
  16460. var c_y = vertices[ indexC * 3 + 1 ];
  16461. var c_z = vertices[ indexC * 3 + 2 ];
  16462. var d_x = vertices[ indexD * 3 ];
  16463. var d_y = vertices[ indexD * 3 + 1 ];
  16464. var d_z = vertices[ indexD * 3 + 2 ];
  16465. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  16466. return [
  16467. new Vector2( a_x, 1 - a_z ),
  16468. new Vector2( b_x, 1 - b_z ),
  16469. new Vector2( c_x, 1 - c_z ),
  16470. new Vector2( d_x, 1 - d_z )
  16471. ];
  16472. } else {
  16473. return [
  16474. new Vector2( a_y, 1 - a_z ),
  16475. new Vector2( b_y, 1 - b_z ),
  16476. new Vector2( c_y, 1 - c_z ),
  16477. new Vector2( d_y, 1 - d_z )
  16478. ];
  16479. }
  16480. }
  16481. };
  16482. /**
  16483. * @author zz85 / http://www.lab4games.net/zz85/blog
  16484. * @author alteredq / http://alteredqualia.com/
  16485. *
  16486. * Text = 3D Text
  16487. *
  16488. * parameters = {
  16489. * font: <THREE.Font>, // font
  16490. *
  16491. * size: <float>, // size of the text
  16492. * height: <float>, // thickness to extrude text
  16493. * curveSegments: <int>, // number of points on the curves
  16494. *
  16495. * bevelEnabled: <bool>, // turn on bevel
  16496. * bevelThickness: <float>, // how deep into text bevel goes
  16497. * bevelSize: <float> // how far from text outline is bevel
  16498. * }
  16499. */
  16500. // TextGeometry
  16501. function TextGeometry( text, parameters ) {
  16502. Geometry.call( this );
  16503. this.type = 'TextGeometry';
  16504. this.parameters = {
  16505. text: text,
  16506. parameters: parameters
  16507. };
  16508. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  16509. this.mergeVertices();
  16510. }
  16511. TextGeometry.prototype = Object.create( Geometry.prototype );
  16512. TextGeometry.prototype.constructor = TextGeometry;
  16513. // TextBufferGeometry
  16514. function TextBufferGeometry( text, parameters ) {
  16515. parameters = parameters || {};
  16516. var font = parameters.font;
  16517. if ( ! ( font && font.isFont ) ) {
  16518. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  16519. return new Geometry();
  16520. }
  16521. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  16522. // translate parameters to ExtrudeGeometry API
  16523. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  16524. // defaults
  16525. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  16526. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  16527. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  16528. ExtrudeBufferGeometry.call( this, shapes, parameters );
  16529. this.type = 'TextBufferGeometry';
  16530. }
  16531. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  16532. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  16533. /**
  16534. * @author mrdoob / http://mrdoob.com/
  16535. * @author benaadams / https://twitter.com/ben_a_adams
  16536. * @author Mugen87 / https://github.com/Mugen87
  16537. */
  16538. // SphereGeometry
  16539. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16540. Geometry.call( this );
  16541. this.type = 'SphereGeometry';
  16542. this.parameters = {
  16543. radius: radius,
  16544. widthSegments: widthSegments,
  16545. heightSegments: heightSegments,
  16546. phiStart: phiStart,
  16547. phiLength: phiLength,
  16548. thetaStart: thetaStart,
  16549. thetaLength: thetaLength
  16550. };
  16551. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  16552. this.mergeVertices();
  16553. }
  16554. SphereGeometry.prototype = Object.create( Geometry.prototype );
  16555. SphereGeometry.prototype.constructor = SphereGeometry;
  16556. // SphereBufferGeometry
  16557. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16558. BufferGeometry.call( this );
  16559. this.type = 'SphereBufferGeometry';
  16560. this.parameters = {
  16561. radius: radius,
  16562. widthSegments: widthSegments,
  16563. heightSegments: heightSegments,
  16564. phiStart: phiStart,
  16565. phiLength: phiLength,
  16566. thetaStart: thetaStart,
  16567. thetaLength: thetaLength
  16568. };
  16569. radius = radius || 50;
  16570. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  16571. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  16572. phiStart = phiStart !== undefined ? phiStart : 0;
  16573. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  16574. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16575. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  16576. var thetaEnd = thetaStart + thetaLength;
  16577. var ix, iy;
  16578. var index = 0;
  16579. var grid = [];
  16580. var vertex = new Vector3();
  16581. var normal = new Vector3();
  16582. // buffers
  16583. var indices = [];
  16584. var vertices = [];
  16585. var normals = [];
  16586. var uvs = [];
  16587. // generate vertices, normals and uvs
  16588. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  16589. var verticesRow = [];
  16590. var v = iy / heightSegments;
  16591. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  16592. var u = ix / widthSegments;
  16593. // vertex
  16594. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16595. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  16596. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16597. vertices.push( vertex.x, vertex.y, vertex.z );
  16598. // normal
  16599. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  16600. normals.push( normal.x, normal.y, normal.z );
  16601. // uv
  16602. uvs.push( u, 1 - v );
  16603. verticesRow.push( index ++ );
  16604. }
  16605. grid.push( verticesRow );
  16606. }
  16607. // indices
  16608. for ( iy = 0; iy < heightSegments; iy ++ ) {
  16609. for ( ix = 0; ix < widthSegments; ix ++ ) {
  16610. var a = grid[ iy ][ ix + 1 ];
  16611. var b = grid[ iy ][ ix ];
  16612. var c = grid[ iy + 1 ][ ix ];
  16613. var d = grid[ iy + 1 ][ ix + 1 ];
  16614. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  16615. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  16616. }
  16617. }
  16618. // build geometry
  16619. this.setIndex( indices );
  16620. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16621. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16622. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16623. }
  16624. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16625. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  16626. /**
  16627. * @author Kaleb Murphy
  16628. * @author Mugen87 / https://github.com/Mugen87
  16629. */
  16630. // RingGeometry
  16631. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16632. Geometry.call( this );
  16633. this.type = 'RingGeometry';
  16634. this.parameters = {
  16635. innerRadius: innerRadius,
  16636. outerRadius: outerRadius,
  16637. thetaSegments: thetaSegments,
  16638. phiSegments: phiSegments,
  16639. thetaStart: thetaStart,
  16640. thetaLength: thetaLength
  16641. };
  16642. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  16643. this.mergeVertices();
  16644. }
  16645. RingGeometry.prototype = Object.create( Geometry.prototype );
  16646. RingGeometry.prototype.constructor = RingGeometry;
  16647. // RingBufferGeometry
  16648. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16649. BufferGeometry.call( this );
  16650. this.type = 'RingBufferGeometry';
  16651. this.parameters = {
  16652. innerRadius: innerRadius,
  16653. outerRadius: outerRadius,
  16654. thetaSegments: thetaSegments,
  16655. phiSegments: phiSegments,
  16656. thetaStart: thetaStart,
  16657. thetaLength: thetaLength
  16658. };
  16659. innerRadius = innerRadius || 20;
  16660. outerRadius = outerRadius || 50;
  16661. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16662. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16663. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  16664. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  16665. // buffers
  16666. var indices = [];
  16667. var vertices = [];
  16668. var normals = [];
  16669. var uvs = [];
  16670. // some helper variables
  16671. var segment;
  16672. var radius = innerRadius;
  16673. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  16674. var vertex = new Vector3();
  16675. var uv = new Vector2();
  16676. var j, i;
  16677. // generate vertices, normals and uvs
  16678. for ( j = 0; j <= phiSegments; j ++ ) {
  16679. for ( i = 0; i <= thetaSegments; i ++ ) {
  16680. // values are generate from the inside of the ring to the outside
  16681. segment = thetaStart + i / thetaSegments * thetaLength;
  16682. // vertex
  16683. vertex.x = radius * Math.cos( segment );
  16684. vertex.y = radius * Math.sin( segment );
  16685. vertices.push( vertex.x, vertex.y, vertex.z );
  16686. // normal
  16687. normals.push( 0, 0, 1 );
  16688. // uv
  16689. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  16690. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  16691. uvs.push( uv.x, uv.y );
  16692. }
  16693. // increase the radius for next row of vertices
  16694. radius += radiusStep;
  16695. }
  16696. // indices
  16697. for ( j = 0; j < phiSegments; j ++ ) {
  16698. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  16699. for ( i = 0; i < thetaSegments; i ++ ) {
  16700. segment = i + thetaSegmentLevel;
  16701. var a = segment;
  16702. var b = segment + thetaSegments + 1;
  16703. var c = segment + thetaSegments + 2;
  16704. var d = segment + 1;
  16705. // faces
  16706. indices.push( a, b, d );
  16707. indices.push( b, c, d );
  16708. }
  16709. }
  16710. // build geometry
  16711. this.setIndex( indices );
  16712. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16713. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16714. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16715. }
  16716. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16717. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  16718. /**
  16719. * @author astrodud / http://astrodud.isgreat.org/
  16720. * @author zz85 / https://github.com/zz85
  16721. * @author bhouston / http://clara.io
  16722. * @author Mugen87 / https://github.com/Mugen87
  16723. */
  16724. // LatheGeometry
  16725. function LatheGeometry( points, segments, phiStart, phiLength ) {
  16726. Geometry.call( this );
  16727. this.type = 'LatheGeometry';
  16728. this.parameters = {
  16729. points: points,
  16730. segments: segments,
  16731. phiStart: phiStart,
  16732. phiLength: phiLength
  16733. };
  16734. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  16735. this.mergeVertices();
  16736. }
  16737. LatheGeometry.prototype = Object.create( Geometry.prototype );
  16738. LatheGeometry.prototype.constructor = LatheGeometry;
  16739. // LatheBufferGeometry
  16740. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  16741. BufferGeometry.call( this );
  16742. this.type = 'LatheBufferGeometry';
  16743. this.parameters = {
  16744. points: points,
  16745. segments: segments,
  16746. phiStart: phiStart,
  16747. phiLength: phiLength
  16748. };
  16749. segments = Math.floor( segments ) || 12;
  16750. phiStart = phiStart || 0;
  16751. phiLength = phiLength || Math.PI * 2;
  16752. // clamp phiLength so it's in range of [ 0, 2PI ]
  16753. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  16754. // buffers
  16755. var indices = [];
  16756. var vertices = [];
  16757. var uvs = [];
  16758. // helper variables
  16759. var base;
  16760. var inverseSegments = 1.0 / segments;
  16761. var vertex = new Vector3();
  16762. var uv = new Vector2();
  16763. var i, j;
  16764. // generate vertices and uvs
  16765. for ( i = 0; i <= segments; i ++ ) {
  16766. var phi = phiStart + i * inverseSegments * phiLength;
  16767. var sin = Math.sin( phi );
  16768. var cos = Math.cos( phi );
  16769. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  16770. // vertex
  16771. vertex.x = points[ j ].x * sin;
  16772. vertex.y = points[ j ].y;
  16773. vertex.z = points[ j ].x * cos;
  16774. vertices.push( vertex.x, vertex.y, vertex.z );
  16775. // uv
  16776. uv.x = i / segments;
  16777. uv.y = j / ( points.length - 1 );
  16778. uvs.push( uv.x, uv.y );
  16779. }
  16780. }
  16781. // indices
  16782. for ( i = 0; i < segments; i ++ ) {
  16783. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  16784. base = j + i * points.length;
  16785. var a = base;
  16786. var b = base + points.length;
  16787. var c = base + points.length + 1;
  16788. var d = base + 1;
  16789. // faces
  16790. indices.push( a, b, d );
  16791. indices.push( b, c, d );
  16792. }
  16793. }
  16794. // build geometry
  16795. this.setIndex( indices );
  16796. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16797. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16798. // generate normals
  16799. this.computeVertexNormals();
  16800. // if the geometry is closed, we need to average the normals along the seam.
  16801. // because the corresponding vertices are identical (but still have different UVs).
  16802. if ( phiLength === Math.PI * 2 ) {
  16803. var normals = this.attributes.normal.array;
  16804. var n1 = new Vector3();
  16805. var n2 = new Vector3();
  16806. var n = new Vector3();
  16807. // this is the buffer offset for the last line of vertices
  16808. base = segments * points.length * 3;
  16809. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  16810. // select the normal of the vertex in the first line
  16811. n1.x = normals[ j + 0 ];
  16812. n1.y = normals[ j + 1 ];
  16813. n1.z = normals[ j + 2 ];
  16814. // select the normal of the vertex in the last line
  16815. n2.x = normals[ base + j + 0 ];
  16816. n2.y = normals[ base + j + 1 ];
  16817. n2.z = normals[ base + j + 2 ];
  16818. // average normals
  16819. n.addVectors( n1, n2 ).normalize();
  16820. // assign the new values to both normals
  16821. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  16822. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  16823. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  16824. }
  16825. }
  16826. }
  16827. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16828. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  16829. /**
  16830. * @author jonobr1 / http://jonobr1.com
  16831. * @author Mugen87 / https://github.com/Mugen87
  16832. */
  16833. // ShapeGeometry
  16834. function ShapeGeometry( shapes, curveSegments ) {
  16835. Geometry.call( this );
  16836. this.type = 'ShapeGeometry';
  16837. if ( typeof curveSegments === 'object' ) {
  16838. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  16839. curveSegments = curveSegments.curveSegments;
  16840. }
  16841. this.parameters = {
  16842. shapes: shapes,
  16843. curveSegments: curveSegments
  16844. };
  16845. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  16846. this.mergeVertices();
  16847. }
  16848. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  16849. ShapeGeometry.prototype.constructor = ShapeGeometry;
  16850. // ShapeBufferGeometry
  16851. function ShapeBufferGeometry( shapes, curveSegments ) {
  16852. BufferGeometry.call( this );
  16853. this.type = 'ShapeBufferGeometry';
  16854. this.parameters = {
  16855. shapes: shapes,
  16856. curveSegments: curveSegments
  16857. };
  16858. curveSegments = curveSegments || 12;
  16859. // buffers
  16860. var indices = [];
  16861. var vertices = [];
  16862. var normals = [];
  16863. var uvs = [];
  16864. // helper variables
  16865. var groupStart = 0;
  16866. var groupCount = 0;
  16867. // allow single and array values for "shapes" parameter
  16868. if ( Array.isArray( shapes ) === false ) {
  16869. addShape( shapes );
  16870. } else {
  16871. for ( var i = 0; i < shapes.length; i ++ ) {
  16872. addShape( shapes[ i ] );
  16873. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  16874. groupStart += groupCount;
  16875. groupCount = 0;
  16876. }
  16877. }
  16878. // build geometry
  16879. this.setIndex( indices );
  16880. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16881. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16882. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16883. // helper functions
  16884. function addShape( shape ) {
  16885. var i, l, shapeHole;
  16886. var indexOffset = vertices.length / 3;
  16887. var points = shape.extractPoints( curveSegments );
  16888. var shapeVertices = points.shape;
  16889. var shapeHoles = points.holes;
  16890. // check direction of vertices
  16891. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  16892. shapeVertices = shapeVertices.reverse();
  16893. // also check if holes are in the opposite direction
  16894. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16895. shapeHole = shapeHoles[ i ];
  16896. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  16897. shapeHoles[ i ] = shapeHole.reverse();
  16898. }
  16899. }
  16900. }
  16901. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  16902. // join vertices of inner and outer paths to a single array
  16903. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16904. shapeHole = shapeHoles[ i ];
  16905. shapeVertices = shapeVertices.concat( shapeHole );
  16906. }
  16907. // vertices, normals, uvs
  16908. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  16909. var vertex = shapeVertices[ i ];
  16910. vertices.push( vertex.x, vertex.y, 0 );
  16911. normals.push( 0, 0, 1 );
  16912. uvs.push( vertex.x, vertex.y ); // world uvs
  16913. }
  16914. // incides
  16915. for ( i = 0, l = faces.length; i < l; i ++ ) {
  16916. var face = faces[ i ];
  16917. var a = face[ 0 ] + indexOffset;
  16918. var b = face[ 1 ] + indexOffset;
  16919. var c = face[ 2 ] + indexOffset;
  16920. indices.push( a, b, c );
  16921. groupCount += 3;
  16922. }
  16923. }
  16924. }
  16925. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16926. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  16927. /**
  16928. * @author WestLangley / http://github.com/WestLangley
  16929. * @author Mugen87 / https://github.com/Mugen87
  16930. */
  16931. function EdgesGeometry( geometry, thresholdAngle ) {
  16932. BufferGeometry.call( this );
  16933. this.type = 'EdgesGeometry';
  16934. this.parameters = {
  16935. thresholdAngle: thresholdAngle
  16936. };
  16937. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  16938. // buffer
  16939. var vertices = [];
  16940. // helper variables
  16941. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  16942. var edge = [ 0, 0 ], edges = {}, edge1, edge2;
  16943. var key, keys = [ 'a', 'b', 'c' ];
  16944. // prepare source geometry
  16945. var geometry2;
  16946. if ( geometry.isBufferGeometry ) {
  16947. geometry2 = new Geometry();
  16948. geometry2.fromBufferGeometry( geometry );
  16949. } else {
  16950. geometry2 = geometry.clone();
  16951. }
  16952. geometry2.mergeVertices();
  16953. geometry2.computeFaceNormals();
  16954. var sourceVertices = geometry2.vertices;
  16955. var faces = geometry2.faces;
  16956. // now create a data structure where each entry represents an edge with its adjoining faces
  16957. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  16958. var face = faces[ i ];
  16959. for ( var j = 0; j < 3; j ++ ) {
  16960. edge1 = face[ keys[ j ] ];
  16961. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  16962. edge[ 0 ] = Math.min( edge1, edge2 );
  16963. edge[ 1 ] = Math.max( edge1, edge2 );
  16964. key = edge[ 0 ] + ',' + edge[ 1 ];
  16965. if ( edges[ key ] === undefined ) {
  16966. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  16967. } else {
  16968. edges[ key ].face2 = i;
  16969. }
  16970. }
  16971. }
  16972. // generate vertices
  16973. for ( key in edges ) {
  16974. var e = edges[ key ];
  16975. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  16976. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  16977. var vertex = sourceVertices[ e.index1 ];
  16978. vertices.push( vertex.x, vertex.y, vertex.z );
  16979. vertex = sourceVertices[ e.index2 ];
  16980. vertices.push( vertex.x, vertex.y, vertex.z );
  16981. }
  16982. }
  16983. // build geometry
  16984. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16985. }
  16986. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  16987. EdgesGeometry.prototype.constructor = EdgesGeometry;
  16988. /**
  16989. * @author mrdoob / http://mrdoob.com/
  16990. * @author Mugen87 / https://github.com/Mugen87
  16991. */
  16992. // CylinderGeometry
  16993. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16994. Geometry.call( this );
  16995. this.type = 'CylinderGeometry';
  16996. this.parameters = {
  16997. radiusTop: radiusTop,
  16998. radiusBottom: radiusBottom,
  16999. height: height,
  17000. radialSegments: radialSegments,
  17001. heightSegments: heightSegments,
  17002. openEnded: openEnded,
  17003. thetaStart: thetaStart,
  17004. thetaLength: thetaLength
  17005. };
  17006. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  17007. this.mergeVertices();
  17008. }
  17009. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  17010. CylinderGeometry.prototype.constructor = CylinderGeometry;
  17011. // CylinderBufferGeometry
  17012. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  17013. BufferGeometry.call( this );
  17014. this.type = 'CylinderBufferGeometry';
  17015. this.parameters = {
  17016. radiusTop: radiusTop,
  17017. radiusBottom: radiusBottom,
  17018. height: height,
  17019. radialSegments: radialSegments,
  17020. heightSegments: heightSegments,
  17021. openEnded: openEnded,
  17022. thetaStart: thetaStart,
  17023. thetaLength: thetaLength
  17024. };
  17025. var scope = this;
  17026. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  17027. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  17028. height = height !== undefined ? height : 100;
  17029. radialSegments = Math.floor( radialSegments ) || 8;
  17030. heightSegments = Math.floor( heightSegments ) || 1;
  17031. openEnded = openEnded !== undefined ? openEnded : false;
  17032. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  17033. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  17034. // buffers
  17035. var indices = [];
  17036. var vertices = [];
  17037. var normals = [];
  17038. var uvs = [];
  17039. // helper variables
  17040. var index = 0;
  17041. var indexArray = [];
  17042. var halfHeight = height / 2;
  17043. var groupStart = 0;
  17044. // generate geometry
  17045. generateTorso();
  17046. if ( openEnded === false ) {
  17047. if ( radiusTop > 0 ) generateCap( true );
  17048. if ( radiusBottom > 0 ) generateCap( false );
  17049. }
  17050. // build geometry
  17051. this.setIndex( indices );
  17052. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17053. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17054. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17055. function generateTorso() {
  17056. var x, y;
  17057. var normal = new Vector3();
  17058. var vertex = new Vector3();
  17059. var groupCount = 0;
  17060. // this will be used to calculate the normal
  17061. var slope = ( radiusBottom - radiusTop ) / height;
  17062. // generate vertices, normals and uvs
  17063. for ( y = 0; y <= heightSegments; y ++ ) {
  17064. var indexRow = [];
  17065. var v = y / heightSegments;
  17066. // calculate the radius of the current row
  17067. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17068. for ( x = 0; x <= radialSegments; x ++ ) {
  17069. var u = x / radialSegments;
  17070. var theta = u * thetaLength + thetaStart;
  17071. var sinTheta = Math.sin( theta );
  17072. var cosTheta = Math.cos( theta );
  17073. // vertex
  17074. vertex.x = radius * sinTheta;
  17075. vertex.y = - v * height + halfHeight;
  17076. vertex.z = radius * cosTheta;
  17077. vertices.push( vertex.x, vertex.y, vertex.z );
  17078. // normal
  17079. normal.set( sinTheta, slope, cosTheta ).normalize();
  17080. normals.push( normal.x, normal.y, normal.z );
  17081. // uv
  17082. uvs.push( u, 1 - v );
  17083. // save index of vertex in respective row
  17084. indexRow.push( index ++ );
  17085. }
  17086. // now save vertices of the row in our index array
  17087. indexArray.push( indexRow );
  17088. }
  17089. // generate indices
  17090. for ( x = 0; x < radialSegments; x ++ ) {
  17091. for ( y = 0; y < heightSegments; y ++ ) {
  17092. // we use the index array to access the correct indices
  17093. var a = indexArray[ y ][ x ];
  17094. var b = indexArray[ y + 1 ][ x ];
  17095. var c = indexArray[ y + 1 ][ x + 1 ];
  17096. var d = indexArray[ y ][ x + 1 ];
  17097. // faces
  17098. indices.push( a, b, d );
  17099. indices.push( b, c, d );
  17100. // update group counter
  17101. groupCount += 6;
  17102. }
  17103. }
  17104. // add a group to the geometry. this will ensure multi material support
  17105. scope.addGroup( groupStart, groupCount, 0 );
  17106. // calculate new start value for groups
  17107. groupStart += groupCount;
  17108. }
  17109. function generateCap( top ) {
  17110. var x, centerIndexStart, centerIndexEnd;
  17111. var uv = new Vector2();
  17112. var vertex = new Vector3();
  17113. var groupCount = 0;
  17114. var radius = ( top === true ) ? radiusTop : radiusBottom;
  17115. var sign = ( top === true ) ? 1 : - 1;
  17116. // save the index of the first center vertex
  17117. centerIndexStart = index;
  17118. // first we generate the center vertex data of the cap.
  17119. // because the geometry needs one set of uvs per face,
  17120. // we must generate a center vertex per face/segment
  17121. for ( x = 1; x <= radialSegments; x ++ ) {
  17122. // vertex
  17123. vertices.push( 0, halfHeight * sign, 0 );
  17124. // normal
  17125. normals.push( 0, sign, 0 );
  17126. // uv
  17127. uvs.push( 0.5, 0.5 );
  17128. // increase index
  17129. index ++;
  17130. }
  17131. // save the index of the last center vertex
  17132. centerIndexEnd = index;
  17133. // now we generate the surrounding vertices, normals and uvs
  17134. for ( x = 0; x <= radialSegments; x ++ ) {
  17135. var u = x / radialSegments;
  17136. var theta = u * thetaLength + thetaStart;
  17137. var cosTheta = Math.cos( theta );
  17138. var sinTheta = Math.sin( theta );
  17139. // vertex
  17140. vertex.x = radius * sinTheta;
  17141. vertex.y = halfHeight * sign;
  17142. vertex.z = radius * cosTheta;
  17143. vertices.push( vertex.x, vertex.y, vertex.z );
  17144. // normal
  17145. normals.push( 0, sign, 0 );
  17146. // uv
  17147. uv.x = ( cosTheta * 0.5 ) + 0.5;
  17148. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  17149. uvs.push( uv.x, uv.y );
  17150. // increase index
  17151. index ++;
  17152. }
  17153. // generate indices
  17154. for ( x = 0; x < radialSegments; x ++ ) {
  17155. var c = centerIndexStart + x;
  17156. var i = centerIndexEnd + x;
  17157. if ( top === true ) {
  17158. // face top
  17159. indices.push( i, i + 1, c );
  17160. } else {
  17161. // face bottom
  17162. indices.push( i + 1, i, c );
  17163. }
  17164. groupCount += 3;
  17165. }
  17166. // add a group to the geometry. this will ensure multi material support
  17167. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  17168. // calculate new start value for groups
  17169. groupStart += groupCount;
  17170. }
  17171. }
  17172. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  17173. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  17174. /**
  17175. * @author abelnation / http://github.com/abelnation
  17176. */
  17177. // ConeGeometry
  17178. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  17179. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  17180. this.type = 'ConeGeometry';
  17181. this.parameters = {
  17182. radius: radius,
  17183. height: height,
  17184. radialSegments: radialSegments,
  17185. heightSegments: heightSegments,
  17186. openEnded: openEnded,
  17187. thetaStart: thetaStart,
  17188. thetaLength: thetaLength
  17189. };
  17190. }
  17191. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  17192. ConeGeometry.prototype.constructor = ConeGeometry;
  17193. // ConeBufferGeometry
  17194. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  17195. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  17196. this.type = 'ConeBufferGeometry';
  17197. this.parameters = {
  17198. radius: radius,
  17199. height: height,
  17200. radialSegments: radialSegments,
  17201. heightSegments: heightSegments,
  17202. openEnded: openEnded,
  17203. thetaStart: thetaStart,
  17204. thetaLength: thetaLength
  17205. };
  17206. }
  17207. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  17208. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  17209. /**
  17210. * @author benaadams / https://twitter.com/ben_a_adams
  17211. * @author Mugen87 / https://github.com/Mugen87
  17212. * @author hughes
  17213. */
  17214. // CircleGeometry
  17215. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  17216. Geometry.call( this );
  17217. this.type = 'CircleGeometry';
  17218. this.parameters = {
  17219. radius: radius,
  17220. segments: segments,
  17221. thetaStart: thetaStart,
  17222. thetaLength: thetaLength
  17223. };
  17224. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  17225. this.mergeVertices();
  17226. }
  17227. CircleGeometry.prototype = Object.create( Geometry.prototype );
  17228. CircleGeometry.prototype.constructor = CircleGeometry;
  17229. // CircleBufferGeometry
  17230. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  17231. BufferGeometry.call( this );
  17232. this.type = 'CircleBufferGeometry';
  17233. this.parameters = {
  17234. radius: radius,
  17235. segments: segments,
  17236. thetaStart: thetaStart,
  17237. thetaLength: thetaLength
  17238. };
  17239. radius = radius || 50;
  17240. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  17241. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  17242. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  17243. // buffers
  17244. var indices = [];
  17245. var vertices = [];
  17246. var normals = [];
  17247. var uvs = [];
  17248. // helper variables
  17249. var i, s;
  17250. var vertex = new Vector3();
  17251. var uv = new Vector2();
  17252. // center point
  17253. vertices.push( 0, 0, 0 );
  17254. normals.push( 0, 0, 1 );
  17255. uvs.push( 0.5, 0.5 );
  17256. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  17257. var segment = thetaStart + s / segments * thetaLength;
  17258. // vertex
  17259. vertex.x = radius * Math.cos( segment );
  17260. vertex.y = radius * Math.sin( segment );
  17261. vertices.push( vertex.x, vertex.y, vertex.z );
  17262. // normal
  17263. normals.push( 0, 0, 1 );
  17264. // uvs
  17265. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  17266. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  17267. uvs.push( uv.x, uv.y );
  17268. }
  17269. // indices
  17270. for ( i = 1; i <= segments; i ++ ) {
  17271. indices.push( i, i + 1, 0 );
  17272. }
  17273. // build geometry
  17274. this.setIndex( indices );
  17275. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17276. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17277. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17278. }
  17279. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  17280. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  17281. var Geometries = Object.freeze({
  17282. WireframeGeometry: WireframeGeometry,
  17283. ParametricGeometry: ParametricGeometry,
  17284. ParametricBufferGeometry: ParametricBufferGeometry,
  17285. TetrahedronGeometry: TetrahedronGeometry,
  17286. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  17287. OctahedronGeometry: OctahedronGeometry,
  17288. OctahedronBufferGeometry: OctahedronBufferGeometry,
  17289. IcosahedronGeometry: IcosahedronGeometry,
  17290. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  17291. DodecahedronGeometry: DodecahedronGeometry,
  17292. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  17293. PolyhedronGeometry: PolyhedronGeometry,
  17294. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  17295. TubeGeometry: TubeGeometry,
  17296. TubeBufferGeometry: TubeBufferGeometry,
  17297. TorusKnotGeometry: TorusKnotGeometry,
  17298. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  17299. TorusGeometry: TorusGeometry,
  17300. TorusBufferGeometry: TorusBufferGeometry,
  17301. TextGeometry: TextGeometry,
  17302. TextBufferGeometry: TextBufferGeometry,
  17303. SphereGeometry: SphereGeometry,
  17304. SphereBufferGeometry: SphereBufferGeometry,
  17305. RingGeometry: RingGeometry,
  17306. RingBufferGeometry: RingBufferGeometry,
  17307. PlaneGeometry: PlaneGeometry,
  17308. PlaneBufferGeometry: PlaneBufferGeometry,
  17309. LatheGeometry: LatheGeometry,
  17310. LatheBufferGeometry: LatheBufferGeometry,
  17311. ShapeGeometry: ShapeGeometry,
  17312. ShapeBufferGeometry: ShapeBufferGeometry,
  17313. ExtrudeGeometry: ExtrudeGeometry,
  17314. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  17315. EdgesGeometry: EdgesGeometry,
  17316. ConeGeometry: ConeGeometry,
  17317. ConeBufferGeometry: ConeBufferGeometry,
  17318. CylinderGeometry: CylinderGeometry,
  17319. CylinderBufferGeometry: CylinderBufferGeometry,
  17320. CircleGeometry: CircleGeometry,
  17321. CircleBufferGeometry: CircleBufferGeometry,
  17322. BoxGeometry: BoxGeometry,
  17323. BoxBufferGeometry: BoxBufferGeometry
  17324. });
  17325. /**
  17326. * @author mrdoob / http://mrdoob.com/
  17327. *
  17328. * parameters = {
  17329. * opacity: <float>
  17330. * }
  17331. */
  17332. function ShadowMaterial( parameters ) {
  17333. ShaderMaterial.call( this, {
  17334. uniforms: UniformsUtils.merge( [
  17335. UniformsLib.lights,
  17336. {
  17337. opacity: { value: 1.0 }
  17338. }
  17339. ] ),
  17340. vertexShader: ShaderChunk[ 'shadow_vert' ],
  17341. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  17342. } );
  17343. this.lights = true;
  17344. this.transparent = true;
  17345. Object.defineProperties( this, {
  17346. opacity: {
  17347. enumerable: true,
  17348. get: function () {
  17349. return this.uniforms.opacity.value;
  17350. },
  17351. set: function ( value ) {
  17352. this.uniforms.opacity.value = value;
  17353. }
  17354. }
  17355. } );
  17356. this.setValues( parameters );
  17357. }
  17358. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  17359. ShadowMaterial.prototype.constructor = ShadowMaterial;
  17360. ShadowMaterial.prototype.isShadowMaterial = true;
  17361. /**
  17362. * @author mrdoob / http://mrdoob.com/
  17363. */
  17364. function RawShaderMaterial( parameters ) {
  17365. ShaderMaterial.call( this, parameters );
  17366. this.type = 'RawShaderMaterial';
  17367. }
  17368. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  17369. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  17370. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  17371. /**
  17372. * @author WestLangley / http://github.com/WestLangley
  17373. *
  17374. * parameters = {
  17375. * color: <hex>,
  17376. * roughness: <float>,
  17377. * metalness: <float>,
  17378. * opacity: <float>,
  17379. *
  17380. * map: new THREE.Texture( <Image> ),
  17381. *
  17382. * lightMap: new THREE.Texture( <Image> ),
  17383. * lightMapIntensity: <float>
  17384. *
  17385. * aoMap: new THREE.Texture( <Image> ),
  17386. * aoMapIntensity: <float>
  17387. *
  17388. * emissive: <hex>,
  17389. * emissiveIntensity: <float>
  17390. * emissiveMap: new THREE.Texture( <Image> ),
  17391. *
  17392. * bumpMap: new THREE.Texture( <Image> ),
  17393. * bumpScale: <float>,
  17394. *
  17395. * normalMap: new THREE.Texture( <Image> ),
  17396. * normalScale: <Vector2>,
  17397. *
  17398. * displacementMap: new THREE.Texture( <Image> ),
  17399. * displacementScale: <float>,
  17400. * displacementBias: <float>,
  17401. *
  17402. * roughnessMap: new THREE.Texture( <Image> ),
  17403. *
  17404. * metalnessMap: new THREE.Texture( <Image> ),
  17405. *
  17406. * alphaMap: new THREE.Texture( <Image> ),
  17407. *
  17408. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  17409. * envMapIntensity: <float>
  17410. *
  17411. * refractionRatio: <float>,
  17412. *
  17413. * wireframe: <boolean>,
  17414. * wireframeLinewidth: <float>,
  17415. *
  17416. * skinning: <bool>,
  17417. * morphTargets: <bool>,
  17418. * morphNormals: <bool>
  17419. * }
  17420. */
  17421. function MeshStandardMaterial( parameters ) {
  17422. Material.call( this );
  17423. this.defines = { 'STANDARD': '' };
  17424. this.type = 'MeshStandardMaterial';
  17425. this.color = new Color( 0xffffff ); // diffuse
  17426. this.roughness = 0.5;
  17427. this.metalness = 0.5;
  17428. this.map = null;
  17429. this.lightMap = null;
  17430. this.lightMapIntensity = 1.0;
  17431. this.aoMap = null;
  17432. this.aoMapIntensity = 1.0;
  17433. this.emissive = new Color( 0x000000 );
  17434. this.emissiveIntensity = 1.0;
  17435. this.emissiveMap = null;
  17436. this.bumpMap = null;
  17437. this.bumpScale = 1;
  17438. this.normalMap = null;
  17439. this.normalScale = new Vector2( 1, 1 );
  17440. this.displacementMap = null;
  17441. this.displacementScale = 1;
  17442. this.displacementBias = 0;
  17443. this.roughnessMap = null;
  17444. this.metalnessMap = null;
  17445. this.alphaMap = null;
  17446. this.envMap = null;
  17447. this.envMapIntensity = 1.0;
  17448. this.refractionRatio = 0.98;
  17449. this.wireframe = false;
  17450. this.wireframeLinewidth = 1;
  17451. this.wireframeLinecap = 'round';
  17452. this.wireframeLinejoin = 'round';
  17453. this.skinning = false;
  17454. this.morphTargets = false;
  17455. this.morphNormals = false;
  17456. this.setValues( parameters );
  17457. }
  17458. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  17459. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  17460. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  17461. MeshStandardMaterial.prototype.copy = function ( source ) {
  17462. Material.prototype.copy.call( this, source );
  17463. this.defines = { 'STANDARD': '' };
  17464. this.color.copy( source.color );
  17465. this.roughness = source.roughness;
  17466. this.metalness = source.metalness;
  17467. this.map = source.map;
  17468. this.lightMap = source.lightMap;
  17469. this.lightMapIntensity = source.lightMapIntensity;
  17470. this.aoMap = source.aoMap;
  17471. this.aoMapIntensity = source.aoMapIntensity;
  17472. this.emissive.copy( source.emissive );
  17473. this.emissiveMap = source.emissiveMap;
  17474. this.emissiveIntensity = source.emissiveIntensity;
  17475. this.bumpMap = source.bumpMap;
  17476. this.bumpScale = source.bumpScale;
  17477. this.normalMap = source.normalMap;
  17478. this.normalScale.copy( source.normalScale );
  17479. this.displacementMap = source.displacementMap;
  17480. this.displacementScale = source.displacementScale;
  17481. this.displacementBias = source.displacementBias;
  17482. this.roughnessMap = source.roughnessMap;
  17483. this.metalnessMap = source.metalnessMap;
  17484. this.alphaMap = source.alphaMap;
  17485. this.envMap = source.envMap;
  17486. this.envMapIntensity = source.envMapIntensity;
  17487. this.refractionRatio = source.refractionRatio;
  17488. this.wireframe = source.wireframe;
  17489. this.wireframeLinewidth = source.wireframeLinewidth;
  17490. this.wireframeLinecap = source.wireframeLinecap;
  17491. this.wireframeLinejoin = source.wireframeLinejoin;
  17492. this.skinning = source.skinning;
  17493. this.morphTargets = source.morphTargets;
  17494. this.morphNormals = source.morphNormals;
  17495. return this;
  17496. };
  17497. /**
  17498. * @author WestLangley / http://github.com/WestLangley
  17499. *
  17500. * parameters = {
  17501. * reflectivity: <float>
  17502. * }
  17503. */
  17504. function MeshPhysicalMaterial( parameters ) {
  17505. MeshStandardMaterial.call( this );
  17506. this.defines = { 'PHYSICAL': '' };
  17507. this.type = 'MeshPhysicalMaterial';
  17508. this.reflectivity = 0.5; // maps to F0 = 0.04
  17509. this.clearCoat = 0.0;
  17510. this.clearCoatRoughness = 0.0;
  17511. this.setValues( parameters );
  17512. }
  17513. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  17514. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  17515. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  17516. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  17517. MeshStandardMaterial.prototype.copy.call( this, source );
  17518. this.defines = { 'PHYSICAL': '' };
  17519. this.reflectivity = source.reflectivity;
  17520. this.clearCoat = source.clearCoat;
  17521. this.clearCoatRoughness = source.clearCoatRoughness;
  17522. return this;
  17523. };
  17524. /**
  17525. * @author mrdoob / http://mrdoob.com/
  17526. * @author alteredq / http://alteredqualia.com/
  17527. *
  17528. * parameters = {
  17529. * color: <hex>,
  17530. * specular: <hex>,
  17531. * shininess: <float>,
  17532. * opacity: <float>,
  17533. *
  17534. * map: new THREE.Texture( <Image> ),
  17535. *
  17536. * lightMap: new THREE.Texture( <Image> ),
  17537. * lightMapIntensity: <float>
  17538. *
  17539. * aoMap: new THREE.Texture( <Image> ),
  17540. * aoMapIntensity: <float>
  17541. *
  17542. * emissive: <hex>,
  17543. * emissiveIntensity: <float>
  17544. * emissiveMap: new THREE.Texture( <Image> ),
  17545. *
  17546. * bumpMap: new THREE.Texture( <Image> ),
  17547. * bumpScale: <float>,
  17548. *
  17549. * normalMap: new THREE.Texture( <Image> ),
  17550. * normalScale: <Vector2>,
  17551. *
  17552. * displacementMap: new THREE.Texture( <Image> ),
  17553. * displacementScale: <float>,
  17554. * displacementBias: <float>,
  17555. *
  17556. * specularMap: new THREE.Texture( <Image> ),
  17557. *
  17558. * alphaMap: new THREE.Texture( <Image> ),
  17559. *
  17560. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17561. * combine: THREE.Multiply,
  17562. * reflectivity: <float>,
  17563. * refractionRatio: <float>,
  17564. *
  17565. * wireframe: <boolean>,
  17566. * wireframeLinewidth: <float>,
  17567. *
  17568. * skinning: <bool>,
  17569. * morphTargets: <bool>,
  17570. * morphNormals: <bool>
  17571. * }
  17572. */
  17573. function MeshPhongMaterial( parameters ) {
  17574. Material.call( this );
  17575. this.type = 'MeshPhongMaterial';
  17576. this.color = new Color( 0xffffff ); // diffuse
  17577. this.specular = new Color( 0x111111 );
  17578. this.shininess = 30;
  17579. this.map = null;
  17580. this.lightMap = null;
  17581. this.lightMapIntensity = 1.0;
  17582. this.aoMap = null;
  17583. this.aoMapIntensity = 1.0;
  17584. this.emissive = new Color( 0x000000 );
  17585. this.emissiveIntensity = 1.0;
  17586. this.emissiveMap = null;
  17587. this.bumpMap = null;
  17588. this.bumpScale = 1;
  17589. this.normalMap = null;
  17590. this.normalScale = new Vector2( 1, 1 );
  17591. this.displacementMap = null;
  17592. this.displacementScale = 1;
  17593. this.displacementBias = 0;
  17594. this.specularMap = null;
  17595. this.alphaMap = null;
  17596. this.envMap = null;
  17597. this.combine = MultiplyOperation;
  17598. this.reflectivity = 1;
  17599. this.refractionRatio = 0.98;
  17600. this.wireframe = false;
  17601. this.wireframeLinewidth = 1;
  17602. this.wireframeLinecap = 'round';
  17603. this.wireframeLinejoin = 'round';
  17604. this.skinning = false;
  17605. this.morphTargets = false;
  17606. this.morphNormals = false;
  17607. this.setValues( parameters );
  17608. }
  17609. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  17610. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  17611. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  17612. MeshPhongMaterial.prototype.copy = function ( source ) {
  17613. Material.prototype.copy.call( this, source );
  17614. this.color.copy( source.color );
  17615. this.specular.copy( source.specular );
  17616. this.shininess = source.shininess;
  17617. this.map = source.map;
  17618. this.lightMap = source.lightMap;
  17619. this.lightMapIntensity = source.lightMapIntensity;
  17620. this.aoMap = source.aoMap;
  17621. this.aoMapIntensity = source.aoMapIntensity;
  17622. this.emissive.copy( source.emissive );
  17623. this.emissiveMap = source.emissiveMap;
  17624. this.emissiveIntensity = source.emissiveIntensity;
  17625. this.bumpMap = source.bumpMap;
  17626. this.bumpScale = source.bumpScale;
  17627. this.normalMap = source.normalMap;
  17628. this.normalScale.copy( source.normalScale );
  17629. this.displacementMap = source.displacementMap;
  17630. this.displacementScale = source.displacementScale;
  17631. this.displacementBias = source.displacementBias;
  17632. this.specularMap = source.specularMap;
  17633. this.alphaMap = source.alphaMap;
  17634. this.envMap = source.envMap;
  17635. this.combine = source.combine;
  17636. this.reflectivity = source.reflectivity;
  17637. this.refractionRatio = source.refractionRatio;
  17638. this.wireframe = source.wireframe;
  17639. this.wireframeLinewidth = source.wireframeLinewidth;
  17640. this.wireframeLinecap = source.wireframeLinecap;
  17641. this.wireframeLinejoin = source.wireframeLinejoin;
  17642. this.skinning = source.skinning;
  17643. this.morphTargets = source.morphTargets;
  17644. this.morphNormals = source.morphNormals;
  17645. return this;
  17646. };
  17647. /**
  17648. * @author takahirox / http://github.com/takahirox
  17649. *
  17650. * parameters = {
  17651. * gradientMap: new THREE.Texture( <Image> )
  17652. * }
  17653. */
  17654. function MeshToonMaterial( parameters ) {
  17655. MeshPhongMaterial.call( this );
  17656. this.defines = { 'TOON': '' };
  17657. this.type = 'MeshToonMaterial';
  17658. this.gradientMap = null;
  17659. this.setValues( parameters );
  17660. }
  17661. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  17662. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  17663. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  17664. MeshToonMaterial.prototype.copy = function ( source ) {
  17665. MeshPhongMaterial.prototype.copy.call( this, source );
  17666. this.gradientMap = source.gradientMap;
  17667. return this;
  17668. };
  17669. /**
  17670. * @author mrdoob / http://mrdoob.com/
  17671. * @author WestLangley / http://github.com/WestLangley
  17672. *
  17673. * parameters = {
  17674. * opacity: <float>,
  17675. *
  17676. * bumpMap: new THREE.Texture( <Image> ),
  17677. * bumpScale: <float>,
  17678. *
  17679. * normalMap: new THREE.Texture( <Image> ),
  17680. * normalScale: <Vector2>,
  17681. *
  17682. * displacementMap: new THREE.Texture( <Image> ),
  17683. * displacementScale: <float>,
  17684. * displacementBias: <float>,
  17685. *
  17686. * wireframe: <boolean>,
  17687. * wireframeLinewidth: <float>
  17688. *
  17689. * skinning: <bool>,
  17690. * morphTargets: <bool>,
  17691. * morphNormals: <bool>
  17692. * }
  17693. */
  17694. function MeshNormalMaterial( parameters ) {
  17695. Material.call( this );
  17696. this.type = 'MeshNormalMaterial';
  17697. this.bumpMap = null;
  17698. this.bumpScale = 1;
  17699. this.normalMap = null;
  17700. this.normalScale = new Vector2( 1, 1 );
  17701. this.displacementMap = null;
  17702. this.displacementScale = 1;
  17703. this.displacementBias = 0;
  17704. this.wireframe = false;
  17705. this.wireframeLinewidth = 1;
  17706. this.fog = false;
  17707. this.lights = false;
  17708. this.skinning = false;
  17709. this.morphTargets = false;
  17710. this.morphNormals = false;
  17711. this.setValues( parameters );
  17712. }
  17713. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  17714. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  17715. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  17716. MeshNormalMaterial.prototype.copy = function ( source ) {
  17717. Material.prototype.copy.call( this, source );
  17718. this.bumpMap = source.bumpMap;
  17719. this.bumpScale = source.bumpScale;
  17720. this.normalMap = source.normalMap;
  17721. this.normalScale.copy( source.normalScale );
  17722. this.displacementMap = source.displacementMap;
  17723. this.displacementScale = source.displacementScale;
  17724. this.displacementBias = source.displacementBias;
  17725. this.wireframe = source.wireframe;
  17726. this.wireframeLinewidth = source.wireframeLinewidth;
  17727. this.skinning = source.skinning;
  17728. this.morphTargets = source.morphTargets;
  17729. this.morphNormals = source.morphNormals;
  17730. return this;
  17731. };
  17732. /**
  17733. * @author mrdoob / http://mrdoob.com/
  17734. * @author alteredq / http://alteredqualia.com/
  17735. *
  17736. * parameters = {
  17737. * color: <hex>,
  17738. * opacity: <float>,
  17739. *
  17740. * map: new THREE.Texture( <Image> ),
  17741. *
  17742. * lightMap: new THREE.Texture( <Image> ),
  17743. * lightMapIntensity: <float>
  17744. *
  17745. * aoMap: new THREE.Texture( <Image> ),
  17746. * aoMapIntensity: <float>
  17747. *
  17748. * emissive: <hex>,
  17749. * emissiveIntensity: <float>
  17750. * emissiveMap: new THREE.Texture( <Image> ),
  17751. *
  17752. * specularMap: new THREE.Texture( <Image> ),
  17753. *
  17754. * alphaMap: new THREE.Texture( <Image> ),
  17755. *
  17756. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17757. * combine: THREE.Multiply,
  17758. * reflectivity: <float>,
  17759. * refractionRatio: <float>,
  17760. *
  17761. * wireframe: <boolean>,
  17762. * wireframeLinewidth: <float>,
  17763. *
  17764. * skinning: <bool>,
  17765. * morphTargets: <bool>,
  17766. * morphNormals: <bool>
  17767. * }
  17768. */
  17769. function MeshLambertMaterial( parameters ) {
  17770. Material.call( this );
  17771. this.type = 'MeshLambertMaterial';
  17772. this.color = new Color( 0xffffff ); // diffuse
  17773. this.map = null;
  17774. this.lightMap = null;
  17775. this.lightMapIntensity = 1.0;
  17776. this.aoMap = null;
  17777. this.aoMapIntensity = 1.0;
  17778. this.emissive = new Color( 0x000000 );
  17779. this.emissiveIntensity = 1.0;
  17780. this.emissiveMap = null;
  17781. this.specularMap = null;
  17782. this.alphaMap = null;
  17783. this.envMap = null;
  17784. this.combine = MultiplyOperation;
  17785. this.reflectivity = 1;
  17786. this.refractionRatio = 0.98;
  17787. this.wireframe = false;
  17788. this.wireframeLinewidth = 1;
  17789. this.wireframeLinecap = 'round';
  17790. this.wireframeLinejoin = 'round';
  17791. this.skinning = false;
  17792. this.morphTargets = false;
  17793. this.morphNormals = false;
  17794. this.setValues( parameters );
  17795. }
  17796. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  17797. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  17798. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  17799. MeshLambertMaterial.prototype.copy = function ( source ) {
  17800. Material.prototype.copy.call( this, source );
  17801. this.color.copy( source.color );
  17802. this.map = source.map;
  17803. this.lightMap = source.lightMap;
  17804. this.lightMapIntensity = source.lightMapIntensity;
  17805. this.aoMap = source.aoMap;
  17806. this.aoMapIntensity = source.aoMapIntensity;
  17807. this.emissive.copy( source.emissive );
  17808. this.emissiveMap = source.emissiveMap;
  17809. this.emissiveIntensity = source.emissiveIntensity;
  17810. this.specularMap = source.specularMap;
  17811. this.alphaMap = source.alphaMap;
  17812. this.envMap = source.envMap;
  17813. this.combine = source.combine;
  17814. this.reflectivity = source.reflectivity;
  17815. this.refractionRatio = source.refractionRatio;
  17816. this.wireframe = source.wireframe;
  17817. this.wireframeLinewidth = source.wireframeLinewidth;
  17818. this.wireframeLinecap = source.wireframeLinecap;
  17819. this.wireframeLinejoin = source.wireframeLinejoin;
  17820. this.skinning = source.skinning;
  17821. this.morphTargets = source.morphTargets;
  17822. this.morphNormals = source.morphNormals;
  17823. return this;
  17824. };
  17825. /**
  17826. * @author alteredq / http://alteredqualia.com/
  17827. *
  17828. * parameters = {
  17829. * color: <hex>,
  17830. * opacity: <float>,
  17831. *
  17832. * linewidth: <float>,
  17833. *
  17834. * scale: <float>,
  17835. * dashSize: <float>,
  17836. * gapSize: <float>
  17837. * }
  17838. */
  17839. function LineDashedMaterial( parameters ) {
  17840. Material.call( this );
  17841. this.type = 'LineDashedMaterial';
  17842. this.color = new Color( 0xffffff );
  17843. this.linewidth = 1;
  17844. this.scale = 1;
  17845. this.dashSize = 3;
  17846. this.gapSize = 1;
  17847. this.lights = false;
  17848. this.setValues( parameters );
  17849. }
  17850. LineDashedMaterial.prototype = Object.create( Material.prototype );
  17851. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  17852. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  17853. LineDashedMaterial.prototype.copy = function ( source ) {
  17854. Material.prototype.copy.call( this, source );
  17855. this.color.copy( source.color );
  17856. this.linewidth = source.linewidth;
  17857. this.scale = source.scale;
  17858. this.dashSize = source.dashSize;
  17859. this.gapSize = source.gapSize;
  17860. return this;
  17861. };
  17862. var Materials = Object.freeze({
  17863. ShadowMaterial: ShadowMaterial,
  17864. SpriteMaterial: SpriteMaterial,
  17865. RawShaderMaterial: RawShaderMaterial,
  17866. ShaderMaterial: ShaderMaterial,
  17867. PointsMaterial: PointsMaterial,
  17868. MeshPhysicalMaterial: MeshPhysicalMaterial,
  17869. MeshStandardMaterial: MeshStandardMaterial,
  17870. MeshPhongMaterial: MeshPhongMaterial,
  17871. MeshToonMaterial: MeshToonMaterial,
  17872. MeshNormalMaterial: MeshNormalMaterial,
  17873. MeshLambertMaterial: MeshLambertMaterial,
  17874. MeshDepthMaterial: MeshDepthMaterial,
  17875. MeshDistanceMaterial: MeshDistanceMaterial,
  17876. MeshBasicMaterial: MeshBasicMaterial,
  17877. LineDashedMaterial: LineDashedMaterial,
  17878. LineBasicMaterial: LineBasicMaterial,
  17879. Material: Material
  17880. });
  17881. /**
  17882. * @author mrdoob / http://mrdoob.com/
  17883. */
  17884. var Cache = {
  17885. enabled: false,
  17886. files: {},
  17887. add: function ( key, file ) {
  17888. if ( this.enabled === false ) return;
  17889. // console.log( 'THREE.Cache', 'Adding key:', key );
  17890. this.files[ key ] = file;
  17891. },
  17892. get: function ( key ) {
  17893. if ( this.enabled === false ) return;
  17894. // console.log( 'THREE.Cache', 'Checking key:', key );
  17895. return this.files[ key ];
  17896. },
  17897. remove: function ( key ) {
  17898. delete this.files[ key ];
  17899. },
  17900. clear: function () {
  17901. this.files = {};
  17902. }
  17903. };
  17904. /**
  17905. * @author mrdoob / http://mrdoob.com/
  17906. */
  17907. function LoadingManager( onLoad, onProgress, onError ) {
  17908. var scope = this;
  17909. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  17910. this.onStart = undefined;
  17911. this.onLoad = onLoad;
  17912. this.onProgress = onProgress;
  17913. this.onError = onError;
  17914. this.itemStart = function ( url ) {
  17915. itemsTotal ++;
  17916. if ( isLoading === false ) {
  17917. if ( scope.onStart !== undefined ) {
  17918. scope.onStart( url, itemsLoaded, itemsTotal );
  17919. }
  17920. }
  17921. isLoading = true;
  17922. };
  17923. this.itemEnd = function ( url ) {
  17924. itemsLoaded ++;
  17925. if ( scope.onProgress !== undefined ) {
  17926. scope.onProgress( url, itemsLoaded, itemsTotal );
  17927. }
  17928. if ( itemsLoaded === itemsTotal ) {
  17929. isLoading = false;
  17930. if ( scope.onLoad !== undefined ) {
  17931. scope.onLoad();
  17932. }
  17933. }
  17934. };
  17935. this.itemError = function ( url ) {
  17936. if ( scope.onError !== undefined ) {
  17937. scope.onError( url );
  17938. }
  17939. };
  17940. }
  17941. var DefaultLoadingManager = new LoadingManager();
  17942. /**
  17943. * @author mrdoob / http://mrdoob.com/
  17944. */
  17945. function FileLoader( manager ) {
  17946. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17947. }
  17948. Object.assign( FileLoader.prototype, {
  17949. load: function ( url, onLoad, onProgress, onError ) {
  17950. if ( url === undefined ) url = '';
  17951. if ( this.path !== undefined ) url = this.path + url;
  17952. var scope = this;
  17953. var cached = Cache.get( url );
  17954. if ( cached !== undefined ) {
  17955. scope.manager.itemStart( url );
  17956. setTimeout( function () {
  17957. if ( onLoad ) onLoad( cached );
  17958. scope.manager.itemEnd( url );
  17959. }, 0 );
  17960. return cached;
  17961. }
  17962. // Check for data: URI
  17963. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  17964. var dataUriRegexResult = url.match( dataUriRegex );
  17965. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  17966. if ( dataUriRegexResult ) {
  17967. var mimeType = dataUriRegexResult[ 1 ];
  17968. var isBase64 = !! dataUriRegexResult[ 2 ];
  17969. var data = dataUriRegexResult[ 3 ];
  17970. data = window.decodeURIComponent( data );
  17971. if ( isBase64 ) data = window.atob( data );
  17972. try {
  17973. var response;
  17974. var responseType = ( this.responseType || '' ).toLowerCase();
  17975. switch ( responseType ) {
  17976. case 'arraybuffer':
  17977. case 'blob':
  17978. response = new ArrayBuffer( data.length );
  17979. var view = new Uint8Array( response );
  17980. for ( var i = 0; i < data.length; i ++ ) {
  17981. view[ i ] = data.charCodeAt( i );
  17982. }
  17983. if ( responseType === 'blob' ) {
  17984. response = new Blob( [ response ], { type: mimeType } );
  17985. }
  17986. break;
  17987. case 'document':
  17988. var parser = new DOMParser();
  17989. response = parser.parseFromString( data, mimeType );
  17990. break;
  17991. case 'json':
  17992. response = JSON.parse( data );
  17993. break;
  17994. default: // 'text' or other
  17995. response = data;
  17996. break;
  17997. }
  17998. // Wait for next browser tick
  17999. window.setTimeout( function () {
  18000. if ( onLoad ) onLoad( response );
  18001. scope.manager.itemEnd( url );
  18002. }, 0 );
  18003. } catch ( error ) {
  18004. // Wait for next browser tick
  18005. window.setTimeout( function () {
  18006. if ( onError ) onError( error );
  18007. scope.manager.itemEnd( url );
  18008. scope.manager.itemError( url );
  18009. }, 0 );
  18010. }
  18011. } else {
  18012. var request = new XMLHttpRequest();
  18013. request.open( 'GET', url, true );
  18014. request.addEventListener( 'load', function ( event ) {
  18015. var response = event.target.response;
  18016. Cache.add( url, response );
  18017. if ( this.status === 200 ) {
  18018. if ( onLoad ) onLoad( response );
  18019. scope.manager.itemEnd( url );
  18020. } else if ( this.status === 0 ) {
  18021. // Some browsers return HTTP Status 0 when using non-http protocol
  18022. // e.g. 'file://' or 'data://'. Handle as success.
  18023. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  18024. if ( onLoad ) onLoad( response );
  18025. scope.manager.itemEnd( url );
  18026. } else {
  18027. if ( onError ) onError( event );
  18028. scope.manager.itemEnd( url );
  18029. scope.manager.itemError( url );
  18030. }
  18031. }, false );
  18032. if ( onProgress !== undefined ) {
  18033. request.addEventListener( 'progress', function ( event ) {
  18034. onProgress( event );
  18035. }, false );
  18036. }
  18037. request.addEventListener( 'error', function ( event ) {
  18038. if ( onError ) onError( event );
  18039. scope.manager.itemEnd( url );
  18040. scope.manager.itemError( url );
  18041. }, false );
  18042. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  18043. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  18044. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  18045. for ( var header in this.requestHeader ) {
  18046. request.setRequestHeader( header, this.requestHeader[ header ] );
  18047. }
  18048. request.send( null );
  18049. }
  18050. scope.manager.itemStart( url );
  18051. return request;
  18052. },
  18053. setPath: function ( value ) {
  18054. this.path = value;
  18055. return this;
  18056. },
  18057. setResponseType: function ( value ) {
  18058. this.responseType = value;
  18059. return this;
  18060. },
  18061. setWithCredentials: function ( value ) {
  18062. this.withCredentials = value;
  18063. return this;
  18064. },
  18065. setMimeType: function ( value ) {
  18066. this.mimeType = value;
  18067. return this;
  18068. },
  18069. setRequestHeader: function ( value ) {
  18070. this.requestHeader = value;
  18071. return this;
  18072. }
  18073. } );
  18074. /**
  18075. * @author mrdoob / http://mrdoob.com/
  18076. *
  18077. * Abstract Base class to block based textures loader (dds, pvr, ...)
  18078. */
  18079. function CompressedTextureLoader( manager ) {
  18080. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18081. // override in sub classes
  18082. this._parser = null;
  18083. }
  18084. Object.assign( CompressedTextureLoader.prototype, {
  18085. load: function ( url, onLoad, onProgress, onError ) {
  18086. var scope = this;
  18087. var images = [];
  18088. var texture = new CompressedTexture();
  18089. texture.image = images;
  18090. var loader = new FileLoader( this.manager );
  18091. loader.setPath( this.path );
  18092. loader.setResponseType( 'arraybuffer' );
  18093. function loadTexture( i ) {
  18094. loader.load( url[ i ], function ( buffer ) {
  18095. var texDatas = scope._parser( buffer, true );
  18096. images[ i ] = {
  18097. width: texDatas.width,
  18098. height: texDatas.height,
  18099. format: texDatas.format,
  18100. mipmaps: texDatas.mipmaps
  18101. };
  18102. loaded += 1;
  18103. if ( loaded === 6 ) {
  18104. if ( texDatas.mipmapCount === 1 )
  18105. texture.minFilter = LinearFilter;
  18106. texture.format = texDatas.format;
  18107. texture.needsUpdate = true;
  18108. if ( onLoad ) onLoad( texture );
  18109. }
  18110. }, onProgress, onError );
  18111. }
  18112. if ( Array.isArray( url ) ) {
  18113. var loaded = 0;
  18114. for ( var i = 0, il = url.length; i < il; ++ i ) {
  18115. loadTexture( i );
  18116. }
  18117. } else {
  18118. // compressed cubemap texture stored in a single DDS file
  18119. loader.load( url, function ( buffer ) {
  18120. var texDatas = scope._parser( buffer, true );
  18121. if ( texDatas.isCubemap ) {
  18122. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  18123. for ( var f = 0; f < faces; f ++ ) {
  18124. images[ f ] = { mipmaps : [] };
  18125. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  18126. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  18127. images[ f ].format = texDatas.format;
  18128. images[ f ].width = texDatas.width;
  18129. images[ f ].height = texDatas.height;
  18130. }
  18131. }
  18132. } else {
  18133. texture.image.width = texDatas.width;
  18134. texture.image.height = texDatas.height;
  18135. texture.mipmaps = texDatas.mipmaps;
  18136. }
  18137. if ( texDatas.mipmapCount === 1 ) {
  18138. texture.minFilter = LinearFilter;
  18139. }
  18140. texture.format = texDatas.format;
  18141. texture.needsUpdate = true;
  18142. if ( onLoad ) onLoad( texture );
  18143. }, onProgress, onError );
  18144. }
  18145. return texture;
  18146. },
  18147. setPath: function ( value ) {
  18148. this.path = value;
  18149. return this;
  18150. }
  18151. } );
  18152. /**
  18153. * @author Nikos M. / https://github.com/foo123/
  18154. *
  18155. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  18156. */
  18157. function DataTextureLoader( manager ) {
  18158. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18159. // override in sub classes
  18160. this._parser = null;
  18161. }
  18162. Object.assign( DataTextureLoader.prototype, {
  18163. load: function ( url, onLoad, onProgress, onError ) {
  18164. var scope = this;
  18165. var texture = new DataTexture();
  18166. var loader = new FileLoader( this.manager );
  18167. loader.setResponseType( 'arraybuffer' );
  18168. loader.load( url, function ( buffer ) {
  18169. var texData = scope._parser( buffer );
  18170. if ( ! texData ) return;
  18171. if ( undefined !== texData.image ) {
  18172. texture.image = texData.image;
  18173. } else if ( undefined !== texData.data ) {
  18174. texture.image.width = texData.width;
  18175. texture.image.height = texData.height;
  18176. texture.image.data = texData.data;
  18177. }
  18178. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  18179. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  18180. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  18181. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  18182. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  18183. if ( undefined !== texData.format ) {
  18184. texture.format = texData.format;
  18185. }
  18186. if ( undefined !== texData.type ) {
  18187. texture.type = texData.type;
  18188. }
  18189. if ( undefined !== texData.mipmaps ) {
  18190. texture.mipmaps = texData.mipmaps;
  18191. }
  18192. if ( 1 === texData.mipmapCount ) {
  18193. texture.minFilter = LinearFilter;
  18194. }
  18195. texture.needsUpdate = true;
  18196. if ( onLoad ) onLoad( texture, texData );
  18197. }, onProgress, onError );
  18198. return texture;
  18199. }
  18200. } );
  18201. /**
  18202. * @author mrdoob / http://mrdoob.com/
  18203. */
  18204. function ImageLoader( manager ) {
  18205. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18206. }
  18207. Object.assign( ImageLoader.prototype, {
  18208. crossOrigin: 'Anonymous',
  18209. load: function ( url, onLoad, onProgress, onError ) {
  18210. if ( url === undefined ) url = '';
  18211. if ( this.path !== undefined ) url = this.path + url;
  18212. var scope = this;
  18213. var cached = Cache.get( url );
  18214. if ( cached !== undefined ) {
  18215. scope.manager.itemStart( url );
  18216. setTimeout( function () {
  18217. if ( onLoad ) onLoad( cached );
  18218. scope.manager.itemEnd( url );
  18219. }, 0 );
  18220. return cached;
  18221. }
  18222. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  18223. image.addEventListener( 'load', function () {
  18224. Cache.add( url, this );
  18225. if ( onLoad ) onLoad( this );
  18226. scope.manager.itemEnd( url );
  18227. }, false );
  18228. /*
  18229. image.addEventListener( 'progress', function ( event ) {
  18230. if ( onProgress ) onProgress( event );
  18231. }, false );
  18232. */
  18233. image.addEventListener( 'error', function ( event ) {
  18234. if ( onError ) onError( event );
  18235. scope.manager.itemEnd( url );
  18236. scope.manager.itemError( url );
  18237. }, false );
  18238. if ( url.substr( 0, 5 ) !== 'data:' ) {
  18239. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  18240. }
  18241. scope.manager.itemStart( url );
  18242. image.src = url;
  18243. return image;
  18244. },
  18245. setCrossOrigin: function ( value ) {
  18246. this.crossOrigin = value;
  18247. return this;
  18248. },
  18249. setPath: function ( value ) {
  18250. this.path = value;
  18251. return this;
  18252. }
  18253. } );
  18254. /**
  18255. * @author mrdoob / http://mrdoob.com/
  18256. */
  18257. function CubeTextureLoader( manager ) {
  18258. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18259. }
  18260. Object.assign( CubeTextureLoader.prototype, {
  18261. crossOrigin: 'Anonymous',
  18262. load: function ( urls, onLoad, onProgress, onError ) {
  18263. var texture = new CubeTexture();
  18264. var loader = new ImageLoader( this.manager );
  18265. loader.setCrossOrigin( this.crossOrigin );
  18266. loader.setPath( this.path );
  18267. var loaded = 0;
  18268. function loadTexture( i ) {
  18269. loader.load( urls[ i ], function ( image ) {
  18270. texture.images[ i ] = image;
  18271. loaded ++;
  18272. if ( loaded === 6 ) {
  18273. texture.needsUpdate = true;
  18274. if ( onLoad ) onLoad( texture );
  18275. }
  18276. }, undefined, onError );
  18277. }
  18278. for ( var i = 0; i < urls.length; ++ i ) {
  18279. loadTexture( i );
  18280. }
  18281. return texture;
  18282. },
  18283. setCrossOrigin: function ( value ) {
  18284. this.crossOrigin = value;
  18285. return this;
  18286. },
  18287. setPath: function ( value ) {
  18288. this.path = value;
  18289. return this;
  18290. }
  18291. } );
  18292. /**
  18293. * @author mrdoob / http://mrdoob.com/
  18294. */
  18295. function TextureLoader( manager ) {
  18296. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18297. }
  18298. Object.assign( TextureLoader.prototype, {
  18299. crossOrigin: 'Anonymous',
  18300. load: function ( url, onLoad, onProgress, onError ) {
  18301. var loader = new ImageLoader( this.manager );
  18302. loader.setCrossOrigin( this.crossOrigin );
  18303. loader.setPath( this.path );
  18304. var texture = new Texture();
  18305. texture.image = loader.load( url, function () {
  18306. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  18307. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  18308. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  18309. texture.needsUpdate = true;
  18310. if ( onLoad !== undefined ) {
  18311. onLoad( texture );
  18312. }
  18313. }, onProgress, onError );
  18314. return texture;
  18315. },
  18316. setCrossOrigin: function ( value ) {
  18317. this.crossOrigin = value;
  18318. return this;
  18319. },
  18320. setPath: function ( value ) {
  18321. this.path = value;
  18322. return this;
  18323. }
  18324. } );
  18325. /**
  18326. * @author mrdoob / http://mrdoob.com/
  18327. * @author alteredq / http://alteredqualia.com/
  18328. */
  18329. function Light( color, intensity ) {
  18330. Object3D.call( this );
  18331. this.type = 'Light';
  18332. this.color = new Color( color );
  18333. this.intensity = intensity !== undefined ? intensity : 1;
  18334. this.receiveShadow = undefined;
  18335. }
  18336. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18337. constructor: Light,
  18338. isLight: true,
  18339. copy: function ( source ) {
  18340. Object3D.prototype.copy.call( this, source );
  18341. this.color.copy( source.color );
  18342. this.intensity = source.intensity;
  18343. return this;
  18344. },
  18345. toJSON: function ( meta ) {
  18346. var data = Object3D.prototype.toJSON.call( this, meta );
  18347. data.object.color = this.color.getHex();
  18348. data.object.intensity = this.intensity;
  18349. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  18350. if ( this.distance !== undefined ) data.object.distance = this.distance;
  18351. if ( this.angle !== undefined ) data.object.angle = this.angle;
  18352. if ( this.decay !== undefined ) data.object.decay = this.decay;
  18353. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  18354. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  18355. return data;
  18356. }
  18357. } );
  18358. /**
  18359. * @author alteredq / http://alteredqualia.com/
  18360. */
  18361. function HemisphereLight( skyColor, groundColor, intensity ) {
  18362. Light.call( this, skyColor, intensity );
  18363. this.type = 'HemisphereLight';
  18364. this.castShadow = undefined;
  18365. this.position.copy( Object3D.DefaultUp );
  18366. this.updateMatrix();
  18367. this.groundColor = new Color( groundColor );
  18368. }
  18369. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18370. constructor: HemisphereLight,
  18371. isHemisphereLight: true,
  18372. copy: function ( source ) {
  18373. Light.prototype.copy.call( this, source );
  18374. this.groundColor.copy( source.groundColor );
  18375. return this;
  18376. }
  18377. } );
  18378. /**
  18379. * @author mrdoob / http://mrdoob.com/
  18380. */
  18381. function LightShadow( camera ) {
  18382. this.camera = camera;
  18383. this.bias = 0;
  18384. this.radius = 1;
  18385. this.mapSize = new Vector2( 512, 512 );
  18386. this.map = null;
  18387. this.matrix = new Matrix4();
  18388. }
  18389. Object.assign( LightShadow.prototype, {
  18390. copy: function ( source ) {
  18391. this.camera = source.camera.clone();
  18392. this.bias = source.bias;
  18393. this.radius = source.radius;
  18394. this.mapSize.copy( source.mapSize );
  18395. return this;
  18396. },
  18397. clone: function () {
  18398. return new this.constructor().copy( this );
  18399. },
  18400. toJSON: function () {
  18401. var object = {};
  18402. if ( this.bias !== 0 ) object.bias = this.bias;
  18403. if ( this.radius !== 1 ) object.radius = this.radius;
  18404. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  18405. object.camera = this.camera.toJSON( false ).object;
  18406. delete object.camera.matrix;
  18407. return object;
  18408. }
  18409. } );
  18410. /**
  18411. * @author mrdoob / http://mrdoob.com/
  18412. */
  18413. function SpotLightShadow() {
  18414. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  18415. }
  18416. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18417. constructor: SpotLightShadow,
  18418. isSpotLightShadow: true,
  18419. update: function ( light ) {
  18420. var camera = this.camera;
  18421. var fov = _Math.RAD2DEG * 2 * light.angle;
  18422. var aspect = this.mapSize.width / this.mapSize.height;
  18423. var far = light.distance || camera.far;
  18424. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  18425. camera.fov = fov;
  18426. camera.aspect = aspect;
  18427. camera.far = far;
  18428. camera.updateProjectionMatrix();
  18429. }
  18430. }
  18431. } );
  18432. /**
  18433. * @author alteredq / http://alteredqualia.com/
  18434. */
  18435. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  18436. Light.call( this, color, intensity );
  18437. this.type = 'SpotLight';
  18438. this.position.copy( Object3D.DefaultUp );
  18439. this.updateMatrix();
  18440. this.target = new Object3D();
  18441. Object.defineProperty( this, 'power', {
  18442. get: function () {
  18443. // intensity = power per solid angle.
  18444. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18445. return this.intensity * Math.PI;
  18446. },
  18447. set: function ( power ) {
  18448. // intensity = power per solid angle.
  18449. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18450. this.intensity = power / Math.PI;
  18451. }
  18452. } );
  18453. this.distance = ( distance !== undefined ) ? distance : 0;
  18454. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  18455. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  18456. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18457. this.shadow = new SpotLightShadow();
  18458. }
  18459. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18460. constructor: SpotLight,
  18461. isSpotLight: true,
  18462. copy: function ( source ) {
  18463. Light.prototype.copy.call( this, source );
  18464. this.distance = source.distance;
  18465. this.angle = source.angle;
  18466. this.penumbra = source.penumbra;
  18467. this.decay = source.decay;
  18468. this.target = source.target.clone();
  18469. this.shadow = source.shadow.clone();
  18470. return this;
  18471. }
  18472. } );
  18473. /**
  18474. * @author mrdoob / http://mrdoob.com/
  18475. */
  18476. function PointLight( color, intensity, distance, decay ) {
  18477. Light.call( this, color, intensity );
  18478. this.type = 'PointLight';
  18479. Object.defineProperty( this, 'power', {
  18480. get: function () {
  18481. // intensity = power per solid angle.
  18482. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18483. return this.intensity * 4 * Math.PI;
  18484. },
  18485. set: function ( power ) {
  18486. // intensity = power per solid angle.
  18487. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18488. this.intensity = power / ( 4 * Math.PI );
  18489. }
  18490. } );
  18491. this.distance = ( distance !== undefined ) ? distance : 0;
  18492. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18493. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  18494. }
  18495. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18496. constructor: PointLight,
  18497. isPointLight: true,
  18498. copy: function ( source ) {
  18499. Light.prototype.copy.call( this, source );
  18500. this.distance = source.distance;
  18501. this.decay = source.decay;
  18502. this.shadow = source.shadow.clone();
  18503. return this;
  18504. }
  18505. } );
  18506. /**
  18507. * @author mrdoob / http://mrdoob.com/
  18508. */
  18509. function DirectionalLightShadow( ) {
  18510. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  18511. }
  18512. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18513. constructor: DirectionalLightShadow
  18514. } );
  18515. /**
  18516. * @author mrdoob / http://mrdoob.com/
  18517. * @author alteredq / http://alteredqualia.com/
  18518. */
  18519. function DirectionalLight( color, intensity ) {
  18520. Light.call( this, color, intensity );
  18521. this.type = 'DirectionalLight';
  18522. this.position.copy( Object3D.DefaultUp );
  18523. this.updateMatrix();
  18524. this.target = new Object3D();
  18525. this.shadow = new DirectionalLightShadow();
  18526. }
  18527. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18528. constructor: DirectionalLight,
  18529. isDirectionalLight: true,
  18530. copy: function ( source ) {
  18531. Light.prototype.copy.call( this, source );
  18532. this.target = source.target.clone();
  18533. this.shadow = source.shadow.clone();
  18534. return this;
  18535. }
  18536. } );
  18537. /**
  18538. * @author mrdoob / http://mrdoob.com/
  18539. */
  18540. function AmbientLight( color, intensity ) {
  18541. Light.call( this, color, intensity );
  18542. this.type = 'AmbientLight';
  18543. this.castShadow = undefined;
  18544. }
  18545. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18546. constructor: AmbientLight,
  18547. isAmbientLight: true
  18548. } );
  18549. /**
  18550. * @author abelnation / http://github.com/abelnation
  18551. */
  18552. function RectAreaLight( color, intensity, width, height ) {
  18553. Light.call( this, color, intensity );
  18554. this.type = 'RectAreaLight';
  18555. this.position.set( 0, 1, 0 );
  18556. this.updateMatrix();
  18557. this.width = ( width !== undefined ) ? width : 10;
  18558. this.height = ( height !== undefined ) ? height : 10;
  18559. // TODO (abelnation): distance/decay
  18560. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  18561. // TODO (abelnation): shadows
  18562. }
  18563. // TODO (abelnation): RectAreaLight update when light shape is changed
  18564. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18565. constructor: RectAreaLight,
  18566. isRectAreaLight: true,
  18567. copy: function ( source ) {
  18568. Light.prototype.copy.call( this, source );
  18569. this.width = source.width;
  18570. this.height = source.height;
  18571. return this;
  18572. },
  18573. toJSON: function ( meta ) {
  18574. var data = Light.prototype.toJSON.call( this, meta );
  18575. data.object.width = this.width;
  18576. data.object.height = this.height;
  18577. return data;
  18578. }
  18579. } );
  18580. /**
  18581. * @author tschw
  18582. * @author Ben Houston / http://clara.io/
  18583. * @author David Sarno / http://lighthaus.us/
  18584. */
  18585. var AnimationUtils = {
  18586. // same as Array.prototype.slice, but also works on typed arrays
  18587. arraySlice: function ( array, from, to ) {
  18588. if ( AnimationUtils.isTypedArray( array ) ) {
  18589. // in ios9 array.subarray(from, undefined) will return empty array
  18590. // but array.subarray(from) or array.subarray(from, len) is correct
  18591. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  18592. }
  18593. return array.slice( from, to );
  18594. },
  18595. // converts an array to a specific type
  18596. convertArray: function ( array, type, forceClone ) {
  18597. if ( ! array || // let 'undefined' and 'null' pass
  18598. ! forceClone && array.constructor === type ) return array;
  18599. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  18600. return new type( array ); // create typed array
  18601. }
  18602. return Array.prototype.slice.call( array ); // create Array
  18603. },
  18604. isTypedArray: function ( object ) {
  18605. return ArrayBuffer.isView( object ) &&
  18606. ! ( object instanceof DataView );
  18607. },
  18608. // returns an array by which times and values can be sorted
  18609. getKeyframeOrder: function ( times ) {
  18610. function compareTime( i, j ) {
  18611. return times[ i ] - times[ j ];
  18612. }
  18613. var n = times.length;
  18614. var result = new Array( n );
  18615. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  18616. result.sort( compareTime );
  18617. return result;
  18618. },
  18619. // uses the array previously returned by 'getKeyframeOrder' to sort data
  18620. sortedArray: function ( values, stride, order ) {
  18621. var nValues = values.length;
  18622. var result = new values.constructor( nValues );
  18623. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  18624. var srcOffset = order[ i ] * stride;
  18625. for ( var j = 0; j !== stride; ++ j ) {
  18626. result[ dstOffset ++ ] = values[ srcOffset + j ];
  18627. }
  18628. }
  18629. return result;
  18630. },
  18631. // function for parsing AOS keyframe formats
  18632. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  18633. var i = 1, key = jsonKeys[ 0 ];
  18634. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  18635. key = jsonKeys[ i ++ ];
  18636. }
  18637. if ( key === undefined ) return; // no data
  18638. var value = key[ valuePropertyName ];
  18639. if ( value === undefined ) return; // no data
  18640. if ( Array.isArray( value ) ) {
  18641. do {
  18642. value = key[ valuePropertyName ];
  18643. if ( value !== undefined ) {
  18644. times.push( key.time );
  18645. values.push.apply( values, value ); // push all elements
  18646. }
  18647. key = jsonKeys[ i ++ ];
  18648. } while ( key !== undefined );
  18649. } else if ( value.toArray !== undefined ) {
  18650. // ...assume THREE.Math-ish
  18651. do {
  18652. value = key[ valuePropertyName ];
  18653. if ( value !== undefined ) {
  18654. times.push( key.time );
  18655. value.toArray( values, values.length );
  18656. }
  18657. key = jsonKeys[ i ++ ];
  18658. } while ( key !== undefined );
  18659. } else {
  18660. // otherwise push as-is
  18661. do {
  18662. value = key[ valuePropertyName ];
  18663. if ( value !== undefined ) {
  18664. times.push( key.time );
  18665. values.push( value );
  18666. }
  18667. key = jsonKeys[ i ++ ];
  18668. } while ( key !== undefined );
  18669. }
  18670. }
  18671. };
  18672. /**
  18673. * Abstract base class of interpolants over parametric samples.
  18674. *
  18675. * The parameter domain is one dimensional, typically the time or a path
  18676. * along a curve defined by the data.
  18677. *
  18678. * The sample values can have any dimensionality and derived classes may
  18679. * apply special interpretations to the data.
  18680. *
  18681. * This class provides the interval seek in a Template Method, deferring
  18682. * the actual interpolation to derived classes.
  18683. *
  18684. * Time complexity is O(1) for linear access crossing at most two points
  18685. * and O(log N) for random access, where N is the number of positions.
  18686. *
  18687. * References:
  18688. *
  18689. * http://www.oodesign.com/template-method-pattern.html
  18690. *
  18691. * @author tschw
  18692. */
  18693. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18694. this.parameterPositions = parameterPositions;
  18695. this._cachedIndex = 0;
  18696. this.resultBuffer = resultBuffer !== undefined ?
  18697. resultBuffer : new sampleValues.constructor( sampleSize );
  18698. this.sampleValues = sampleValues;
  18699. this.valueSize = sampleSize;
  18700. }
  18701. Object.assign( Interpolant.prototype, {
  18702. evaluate: function( t ) {
  18703. var pp = this.parameterPositions,
  18704. i1 = this._cachedIndex,
  18705. t1 = pp[ i1 ],
  18706. t0 = pp[ i1 - 1 ];
  18707. validate_interval: {
  18708. seek: {
  18709. var right;
  18710. linear_scan: {
  18711. //- See http://jsperf.com/comparison-to-undefined/3
  18712. //- slower code:
  18713. //-
  18714. //- if ( t >= t1 || t1 === undefined ) {
  18715. forward_scan: if ( ! ( t < t1 ) ) {
  18716. for ( var giveUpAt = i1 + 2; ;) {
  18717. if ( t1 === undefined ) {
  18718. if ( t < t0 ) break forward_scan;
  18719. // after end
  18720. i1 = pp.length;
  18721. this._cachedIndex = i1;
  18722. return this.afterEnd_( i1 - 1, t, t0 );
  18723. }
  18724. if ( i1 === giveUpAt ) break; // this loop
  18725. t0 = t1;
  18726. t1 = pp[ ++ i1 ];
  18727. if ( t < t1 ) {
  18728. // we have arrived at the sought interval
  18729. break seek;
  18730. }
  18731. }
  18732. // prepare binary search on the right side of the index
  18733. right = pp.length;
  18734. break linear_scan;
  18735. }
  18736. //- slower code:
  18737. //- if ( t < t0 || t0 === undefined ) {
  18738. if ( ! ( t >= t0 ) ) {
  18739. // looping?
  18740. var t1global = pp[ 1 ];
  18741. if ( t < t1global ) {
  18742. i1 = 2; // + 1, using the scan for the details
  18743. t0 = t1global;
  18744. }
  18745. // linear reverse scan
  18746. for ( var giveUpAt = i1 - 2; ;) {
  18747. if ( t0 === undefined ) {
  18748. // before start
  18749. this._cachedIndex = 0;
  18750. return this.beforeStart_( 0, t, t1 );
  18751. }
  18752. if ( i1 === giveUpAt ) break; // this loop
  18753. t1 = t0;
  18754. t0 = pp[ -- i1 - 1 ];
  18755. if ( t >= t0 ) {
  18756. // we have arrived at the sought interval
  18757. break seek;
  18758. }
  18759. }
  18760. // prepare binary search on the left side of the index
  18761. right = i1;
  18762. i1 = 0;
  18763. break linear_scan;
  18764. }
  18765. // the interval is valid
  18766. break validate_interval;
  18767. } // linear scan
  18768. // binary search
  18769. while ( i1 < right ) {
  18770. var mid = ( i1 + right ) >>> 1;
  18771. if ( t < pp[ mid ] ) {
  18772. right = mid;
  18773. } else {
  18774. i1 = mid + 1;
  18775. }
  18776. }
  18777. t1 = pp[ i1 ];
  18778. t0 = pp[ i1 - 1 ];
  18779. // check boundary cases, again
  18780. if ( t0 === undefined ) {
  18781. this._cachedIndex = 0;
  18782. return this.beforeStart_( 0, t, t1 );
  18783. }
  18784. if ( t1 === undefined ) {
  18785. i1 = pp.length;
  18786. this._cachedIndex = i1;
  18787. return this.afterEnd_( i1 - 1, t0, t );
  18788. }
  18789. } // seek
  18790. this._cachedIndex = i1;
  18791. this.intervalChanged_( i1, t0, t1 );
  18792. } // validate_interval
  18793. return this.interpolate_( i1, t0, t, t1 );
  18794. },
  18795. settings: null, // optional, subclass-specific settings structure
  18796. // Note: The indirection allows central control of many interpolants.
  18797. // --- Protected interface
  18798. DefaultSettings_: {},
  18799. getSettings_: function() {
  18800. return this.settings || this.DefaultSettings_;
  18801. },
  18802. copySampleValue_: function( index ) {
  18803. // copies a sample value to the result buffer
  18804. var result = this.resultBuffer,
  18805. values = this.sampleValues,
  18806. stride = this.valueSize,
  18807. offset = index * stride;
  18808. for ( var i = 0; i !== stride; ++ i ) {
  18809. result[ i ] = values[ offset + i ];
  18810. }
  18811. return result;
  18812. },
  18813. // Template methods for derived classes:
  18814. interpolate_: function( i1, t0, t, t1 ) {
  18815. throw new Error( "call to abstract method" );
  18816. // implementations shall return this.resultBuffer
  18817. },
  18818. intervalChanged_: function( i1, t0, t1 ) {
  18819. // empty
  18820. }
  18821. } );
  18822. //!\ DECLARE ALIAS AFTER assign prototype !
  18823. Object.assign( Interpolant.prototype, {
  18824. //( 0, t, t0 ), returns this.resultBuffer
  18825. beforeStart_: Interpolant.prototype.copySampleValue_,
  18826. //( N-1, tN-1, t ), returns this.resultBuffer
  18827. afterEnd_: Interpolant.prototype.copySampleValue_,
  18828. } );
  18829. /**
  18830. * Fast and simple cubic spline interpolant.
  18831. *
  18832. * It was derived from a Hermitian construction setting the first derivative
  18833. * at each sample position to the linear slope between neighboring positions
  18834. * over their parameter interval.
  18835. *
  18836. * @author tschw
  18837. */
  18838. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18839. Interpolant.call(
  18840. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18841. this._weightPrev = -0;
  18842. this._offsetPrev = -0;
  18843. this._weightNext = -0;
  18844. this._offsetNext = -0;
  18845. }
  18846. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18847. constructor: CubicInterpolant,
  18848. DefaultSettings_: {
  18849. endingStart: ZeroCurvatureEnding,
  18850. endingEnd: ZeroCurvatureEnding
  18851. },
  18852. intervalChanged_: function( i1, t0, t1 ) {
  18853. var pp = this.parameterPositions,
  18854. iPrev = i1 - 2,
  18855. iNext = i1 + 1,
  18856. tPrev = pp[ iPrev ],
  18857. tNext = pp[ iNext ];
  18858. if ( tPrev === undefined ) {
  18859. switch ( this.getSettings_().endingStart ) {
  18860. case ZeroSlopeEnding:
  18861. // f'(t0) = 0
  18862. iPrev = i1;
  18863. tPrev = 2 * t0 - t1;
  18864. break;
  18865. case WrapAroundEnding:
  18866. // use the other end of the curve
  18867. iPrev = pp.length - 2;
  18868. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  18869. break;
  18870. default: // ZeroCurvatureEnding
  18871. // f''(t0) = 0 a.k.a. Natural Spline
  18872. iPrev = i1;
  18873. tPrev = t1;
  18874. }
  18875. }
  18876. if ( tNext === undefined ) {
  18877. switch ( this.getSettings_().endingEnd ) {
  18878. case ZeroSlopeEnding:
  18879. // f'(tN) = 0
  18880. iNext = i1;
  18881. tNext = 2 * t1 - t0;
  18882. break;
  18883. case WrapAroundEnding:
  18884. // use the other end of the curve
  18885. iNext = 1;
  18886. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  18887. break;
  18888. default: // ZeroCurvatureEnding
  18889. // f''(tN) = 0, a.k.a. Natural Spline
  18890. iNext = i1 - 1;
  18891. tNext = t0;
  18892. }
  18893. }
  18894. var halfDt = ( t1 - t0 ) * 0.5,
  18895. stride = this.valueSize;
  18896. this._weightPrev = halfDt / ( t0 - tPrev );
  18897. this._weightNext = halfDt / ( tNext - t1 );
  18898. this._offsetPrev = iPrev * stride;
  18899. this._offsetNext = iNext * stride;
  18900. },
  18901. interpolate_: function( i1, t0, t, t1 ) {
  18902. var result = this.resultBuffer,
  18903. values = this.sampleValues,
  18904. stride = this.valueSize,
  18905. o1 = i1 * stride, o0 = o1 - stride,
  18906. oP = this._offsetPrev, oN = this._offsetNext,
  18907. wP = this._weightPrev, wN = this._weightNext,
  18908. p = ( t - t0 ) / ( t1 - t0 ),
  18909. pp = p * p,
  18910. ppp = pp * p;
  18911. // evaluate polynomials
  18912. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  18913. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  18914. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  18915. var sN = wN * ppp - wN * pp;
  18916. // combine data linearly
  18917. for ( var i = 0; i !== stride; ++ i ) {
  18918. result[ i ] =
  18919. sP * values[ oP + i ] +
  18920. s0 * values[ o0 + i ] +
  18921. s1 * values[ o1 + i ] +
  18922. sN * values[ oN + i ];
  18923. }
  18924. return result;
  18925. }
  18926. } );
  18927. /**
  18928. * @author tschw
  18929. */
  18930. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18931. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18932. }
  18933. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18934. constructor: LinearInterpolant,
  18935. interpolate_: function( i1, t0, t, t1 ) {
  18936. var result = this.resultBuffer,
  18937. values = this.sampleValues,
  18938. stride = this.valueSize,
  18939. offset1 = i1 * stride,
  18940. offset0 = offset1 - stride,
  18941. weight1 = ( t - t0 ) / ( t1 - t0 ),
  18942. weight0 = 1 - weight1;
  18943. for ( var i = 0; i !== stride; ++ i ) {
  18944. result[ i ] =
  18945. values[ offset0 + i ] * weight0 +
  18946. values[ offset1 + i ] * weight1;
  18947. }
  18948. return result;
  18949. }
  18950. } );
  18951. /**
  18952. *
  18953. * Interpolant that evaluates to the sample value at the position preceeding
  18954. * the parameter.
  18955. *
  18956. * @author tschw
  18957. */
  18958. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18959. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18960. }
  18961. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18962. constructor: DiscreteInterpolant,
  18963. interpolate_: function( i1, t0, t, t1 ) {
  18964. return this.copySampleValue_( i1 - 1 );
  18965. }
  18966. } );
  18967. var KeyframeTrackPrototype;
  18968. KeyframeTrackPrototype = {
  18969. TimeBufferType: Float32Array,
  18970. ValueBufferType: Float32Array,
  18971. DefaultInterpolation: InterpolateLinear,
  18972. InterpolantFactoryMethodDiscrete: function ( result ) {
  18973. return new DiscreteInterpolant(
  18974. this.times, this.values, this.getValueSize(), result );
  18975. },
  18976. InterpolantFactoryMethodLinear: function ( result ) {
  18977. return new LinearInterpolant(
  18978. this.times, this.values, this.getValueSize(), result );
  18979. },
  18980. InterpolantFactoryMethodSmooth: function ( result ) {
  18981. return new CubicInterpolant(
  18982. this.times, this.values, this.getValueSize(), result );
  18983. },
  18984. setInterpolation: function ( interpolation ) {
  18985. var factoryMethod;
  18986. switch ( interpolation ) {
  18987. case InterpolateDiscrete:
  18988. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  18989. break;
  18990. case InterpolateLinear:
  18991. factoryMethod = this.InterpolantFactoryMethodLinear;
  18992. break;
  18993. case InterpolateSmooth:
  18994. factoryMethod = this.InterpolantFactoryMethodSmooth;
  18995. break;
  18996. }
  18997. if ( factoryMethod === undefined ) {
  18998. var message = "unsupported interpolation for " +
  18999. this.ValueTypeName + " keyframe track named " + this.name;
  19000. if ( this.createInterpolant === undefined ) {
  19001. // fall back to default, unless the default itself is messed up
  19002. if ( interpolation !== this.DefaultInterpolation ) {
  19003. this.setInterpolation( this.DefaultInterpolation );
  19004. } else {
  19005. throw new Error( message ); // fatal, in this case
  19006. }
  19007. }
  19008. console.warn( 'THREE.KeyframeTrackPrototype:', message );
  19009. return;
  19010. }
  19011. this.createInterpolant = factoryMethod;
  19012. },
  19013. getInterpolation: function () {
  19014. switch ( this.createInterpolant ) {
  19015. case this.InterpolantFactoryMethodDiscrete:
  19016. return InterpolateDiscrete;
  19017. case this.InterpolantFactoryMethodLinear:
  19018. return InterpolateLinear;
  19019. case this.InterpolantFactoryMethodSmooth:
  19020. return InterpolateSmooth;
  19021. }
  19022. },
  19023. getValueSize: function () {
  19024. return this.values.length / this.times.length;
  19025. },
  19026. // move all keyframes either forwards or backwards in time
  19027. shift: function ( timeOffset ) {
  19028. if ( timeOffset !== 0.0 ) {
  19029. var times = this.times;
  19030. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  19031. times[ i ] += timeOffset;
  19032. }
  19033. }
  19034. return this;
  19035. },
  19036. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  19037. scale: function ( timeScale ) {
  19038. if ( timeScale !== 1.0 ) {
  19039. var times = this.times;
  19040. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  19041. times[ i ] *= timeScale;
  19042. }
  19043. }
  19044. return this;
  19045. },
  19046. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  19047. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  19048. trim: function ( startTime, endTime ) {
  19049. var times = this.times,
  19050. nKeys = times.length,
  19051. from = 0,
  19052. to = nKeys - 1;
  19053. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  19054. while ( to !== - 1 && times[ to ] > endTime ) -- to;
  19055. ++ to; // inclusive -> exclusive bound
  19056. if ( from !== 0 || to !== nKeys ) {
  19057. // empty tracks are forbidden, so keep at least one keyframe
  19058. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  19059. var stride = this.getValueSize();
  19060. this.times = AnimationUtils.arraySlice( times, from, to );
  19061. this.values = AnimationUtils.
  19062. arraySlice( this.values, from * stride, to * stride );
  19063. }
  19064. return this;
  19065. },
  19066. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  19067. validate: function () {
  19068. var valid = true;
  19069. var valueSize = this.getValueSize();
  19070. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  19071. console.error( 'THREE.KeyframeTrackPrototype: Invalid value size in track.', this );
  19072. valid = false;
  19073. }
  19074. var times = this.times,
  19075. values = this.values,
  19076. nKeys = times.length;
  19077. if ( nKeys === 0 ) {
  19078. console.error( 'THREE.KeyframeTrackPrototype: Track is empty.', this );
  19079. valid = false;
  19080. }
  19081. var prevTime = null;
  19082. for ( var i = 0; i !== nKeys; i ++ ) {
  19083. var currTime = times[ i ];
  19084. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  19085. console.error( 'THREE.KeyframeTrackPrototype: Time is not a valid number.', this, i, currTime );
  19086. valid = false;
  19087. break;
  19088. }
  19089. if ( prevTime !== null && prevTime > currTime ) {
  19090. console.error( 'THREE.KeyframeTrackPrototype: Out of order keys.', this, i, currTime, prevTime );
  19091. valid = false;
  19092. break;
  19093. }
  19094. prevTime = currTime;
  19095. }
  19096. if ( values !== undefined ) {
  19097. if ( AnimationUtils.isTypedArray( values ) ) {
  19098. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  19099. var value = values[ i ];
  19100. if ( isNaN( value ) ) {
  19101. console.error( 'THREE.KeyframeTrackPrototype: Value is not a valid number.', this, i, value );
  19102. valid = false;
  19103. break;
  19104. }
  19105. }
  19106. }
  19107. }
  19108. return valid;
  19109. },
  19110. // removes equivalent sequential keys as common in morph target sequences
  19111. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  19112. optimize: function () {
  19113. var times = this.times,
  19114. values = this.values,
  19115. stride = this.getValueSize(),
  19116. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  19117. writeIndex = 1,
  19118. lastIndex = times.length - 1;
  19119. for ( var i = 1; i < lastIndex; ++ i ) {
  19120. var keep = false;
  19121. var time = times[ i ];
  19122. var timeNext = times[ i + 1 ];
  19123. // remove adjacent keyframes scheduled at the same time
  19124. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  19125. if ( ! smoothInterpolation ) {
  19126. // remove unnecessary keyframes same as their neighbors
  19127. var offset = i * stride,
  19128. offsetP = offset - stride,
  19129. offsetN = offset + stride;
  19130. for ( var j = 0; j !== stride; ++ j ) {
  19131. var value = values[ offset + j ];
  19132. if ( value !== values[ offsetP + j ] ||
  19133. value !== values[ offsetN + j ] ) {
  19134. keep = true;
  19135. break;
  19136. }
  19137. }
  19138. } else keep = true;
  19139. }
  19140. // in-place compaction
  19141. if ( keep ) {
  19142. if ( i !== writeIndex ) {
  19143. times[ writeIndex ] = times[ i ];
  19144. var readOffset = i * stride,
  19145. writeOffset = writeIndex * stride;
  19146. for ( var j = 0; j !== stride; ++ j )
  19147. values[ writeOffset + j ] = values[ readOffset + j ];
  19148. }
  19149. ++ writeIndex;
  19150. }
  19151. }
  19152. // flush last keyframe (compaction looks ahead)
  19153. if ( lastIndex > 0 ) {
  19154. times[ writeIndex ] = times[ lastIndex ];
  19155. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j )
  19156. values[ writeOffset + j ] = values[ readOffset + j ];
  19157. ++ writeIndex;
  19158. }
  19159. if ( writeIndex !== times.length ) {
  19160. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  19161. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  19162. }
  19163. return this;
  19164. }
  19165. };
  19166. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  19167. if ( name === undefined ) throw new Error( "track name is undefined" );
  19168. if ( times === undefined || times.length === 0 ) {
  19169. throw new Error( "no keyframes in track named " + name );
  19170. }
  19171. this.name = name;
  19172. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  19173. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  19174. this.setInterpolation( interpolation || this.DefaultInterpolation );
  19175. this.validate();
  19176. this.optimize();
  19177. }
  19178. /**
  19179. *
  19180. * A Track of vectored keyframe values.
  19181. *
  19182. *
  19183. * @author Ben Houston / http://clara.io/
  19184. * @author David Sarno / http://lighthaus.us/
  19185. * @author tschw
  19186. */
  19187. function VectorKeyframeTrack( name, times, values, interpolation ) {
  19188. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19189. }
  19190. VectorKeyframeTrack.prototype =
  19191. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19192. constructor: VectorKeyframeTrack,
  19193. ValueTypeName: 'vector'
  19194. // ValueBufferType is inherited
  19195. // DefaultInterpolation is inherited
  19196. } );
  19197. /**
  19198. * Spherical linear unit quaternion interpolant.
  19199. *
  19200. * @author tschw
  19201. */
  19202. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19203. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  19204. }
  19205. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  19206. constructor: QuaternionLinearInterpolant,
  19207. interpolate_: function( i1, t0, t, t1 ) {
  19208. var result = this.resultBuffer,
  19209. values = this.sampleValues,
  19210. stride = this.valueSize,
  19211. offset = i1 * stride,
  19212. alpha = ( t - t0 ) / ( t1 - t0 );
  19213. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  19214. Quaternion.slerpFlat( result, 0,
  19215. values, offset - stride, values, offset, alpha );
  19216. }
  19217. return result;
  19218. }
  19219. } );
  19220. /**
  19221. *
  19222. * A Track of quaternion keyframe values.
  19223. *
  19224. * @author Ben Houston / http://clara.io/
  19225. * @author David Sarno / http://lighthaus.us/
  19226. * @author tschw
  19227. */
  19228. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  19229. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19230. }
  19231. QuaternionKeyframeTrack.prototype =
  19232. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19233. constructor: QuaternionKeyframeTrack,
  19234. ValueTypeName: 'quaternion',
  19235. // ValueBufferType is inherited
  19236. DefaultInterpolation: InterpolateLinear,
  19237. InterpolantFactoryMethodLinear: function( result ) {
  19238. return new QuaternionLinearInterpolant(
  19239. this.times, this.values, this.getValueSize(), result );
  19240. },
  19241. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  19242. } );
  19243. /**
  19244. *
  19245. * A Track of numeric keyframe values.
  19246. *
  19247. * @author Ben Houston / http://clara.io/
  19248. * @author David Sarno / http://lighthaus.us/
  19249. * @author tschw
  19250. */
  19251. function NumberKeyframeTrack( name, times, values, interpolation ) {
  19252. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19253. }
  19254. NumberKeyframeTrack.prototype =
  19255. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19256. constructor: NumberKeyframeTrack,
  19257. ValueTypeName: 'number'
  19258. // ValueBufferType is inherited
  19259. // DefaultInterpolation is inherited
  19260. } );
  19261. /**
  19262. *
  19263. * A Track that interpolates Strings
  19264. *
  19265. *
  19266. * @author Ben Houston / http://clara.io/
  19267. * @author David Sarno / http://lighthaus.us/
  19268. * @author tschw
  19269. */
  19270. function StringKeyframeTrack( name, times, values, interpolation ) {
  19271. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19272. }
  19273. StringKeyframeTrack.prototype =
  19274. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19275. constructor: StringKeyframeTrack,
  19276. ValueTypeName: 'string',
  19277. ValueBufferType: Array,
  19278. DefaultInterpolation: InterpolateDiscrete,
  19279. InterpolantFactoryMethodLinear: undefined,
  19280. InterpolantFactoryMethodSmooth: undefined
  19281. } );
  19282. /**
  19283. *
  19284. * A Track of Boolean keyframe values.
  19285. *
  19286. *
  19287. * @author Ben Houston / http://clara.io/
  19288. * @author David Sarno / http://lighthaus.us/
  19289. * @author tschw
  19290. */
  19291. function BooleanKeyframeTrack( name, times, values ) {
  19292. KeyframeTrackConstructor.call( this, name, times, values );
  19293. }
  19294. BooleanKeyframeTrack.prototype =
  19295. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19296. constructor: BooleanKeyframeTrack,
  19297. ValueTypeName: 'bool',
  19298. ValueBufferType: Array,
  19299. DefaultInterpolation: InterpolateDiscrete,
  19300. InterpolantFactoryMethodLinear: undefined,
  19301. InterpolantFactoryMethodSmooth: undefined
  19302. // Note: Actually this track could have a optimized / compressed
  19303. // representation of a single value and a custom interpolant that
  19304. // computes "firstValue ^ isOdd( index )".
  19305. } );
  19306. /**
  19307. *
  19308. * A Track of keyframe values that represent color.
  19309. *
  19310. *
  19311. * @author Ben Houston / http://clara.io/
  19312. * @author David Sarno / http://lighthaus.us/
  19313. * @author tschw
  19314. */
  19315. function ColorKeyframeTrack( name, times, values, interpolation ) {
  19316. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19317. }
  19318. ColorKeyframeTrack.prototype =
  19319. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19320. constructor: ColorKeyframeTrack,
  19321. ValueTypeName: 'color'
  19322. // ValueBufferType is inherited
  19323. // DefaultInterpolation is inherited
  19324. // Note: Very basic implementation and nothing special yet.
  19325. // However, this is the place for color space parameterization.
  19326. } );
  19327. /**
  19328. *
  19329. * A timed sequence of keyframes for a specific property.
  19330. *
  19331. *
  19332. * @author Ben Houston / http://clara.io/
  19333. * @author David Sarno / http://lighthaus.us/
  19334. * @author tschw
  19335. */
  19336. function KeyframeTrack( name, times, values, interpolation ) {
  19337. KeyframeTrackConstructor.apply( this, arguments );
  19338. }
  19339. KeyframeTrack.prototype = KeyframeTrackPrototype;
  19340. KeyframeTrackPrototype.constructor = KeyframeTrack;
  19341. // Static methods:
  19342. Object.assign( KeyframeTrack, {
  19343. // Serialization (in static context, because of constructor invocation
  19344. // and automatic invocation of .toJSON):
  19345. parse: function( json ) {
  19346. if( json.type === undefined ) {
  19347. throw new Error( "track type undefined, can not parse" );
  19348. }
  19349. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  19350. if ( json.times === undefined ) {
  19351. var times = [], values = [];
  19352. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  19353. json.times = times;
  19354. json.values = values;
  19355. }
  19356. // derived classes can define a static parse method
  19357. if ( trackType.parse !== undefined ) {
  19358. return trackType.parse( json );
  19359. } else {
  19360. // by default, we assume a constructor compatible with the base
  19361. return new trackType(
  19362. json.name, json.times, json.values, json.interpolation );
  19363. }
  19364. },
  19365. toJSON: function( track ) {
  19366. var trackType = track.constructor;
  19367. var json;
  19368. // derived classes can define a static toJSON method
  19369. if ( trackType.toJSON !== undefined ) {
  19370. json = trackType.toJSON( track );
  19371. } else {
  19372. // by default, we assume the data can be serialized as-is
  19373. json = {
  19374. 'name': track.name,
  19375. 'times': AnimationUtils.convertArray( track.times, Array ),
  19376. 'values': AnimationUtils.convertArray( track.values, Array )
  19377. };
  19378. var interpolation = track.getInterpolation();
  19379. if ( interpolation !== track.DefaultInterpolation ) {
  19380. json.interpolation = interpolation;
  19381. }
  19382. }
  19383. json.type = track.ValueTypeName; // mandatory
  19384. return json;
  19385. },
  19386. _getTrackTypeForValueTypeName: function( typeName ) {
  19387. switch( typeName.toLowerCase() ) {
  19388. case "scalar":
  19389. case "double":
  19390. case "float":
  19391. case "number":
  19392. case "integer":
  19393. return NumberKeyframeTrack;
  19394. case "vector":
  19395. case "vector2":
  19396. case "vector3":
  19397. case "vector4":
  19398. return VectorKeyframeTrack;
  19399. case "color":
  19400. return ColorKeyframeTrack;
  19401. case "quaternion":
  19402. return QuaternionKeyframeTrack;
  19403. case "bool":
  19404. case "boolean":
  19405. return BooleanKeyframeTrack;
  19406. case "string":
  19407. return StringKeyframeTrack;
  19408. }
  19409. throw new Error( "Unsupported typeName: " + typeName );
  19410. }
  19411. } );
  19412. /**
  19413. *
  19414. * Reusable set of Tracks that represent an animation.
  19415. *
  19416. * @author Ben Houston / http://clara.io/
  19417. * @author David Sarno / http://lighthaus.us/
  19418. */
  19419. function AnimationClip( name, duration, tracks ) {
  19420. this.name = name;
  19421. this.tracks = tracks;
  19422. this.duration = ( duration !== undefined ) ? duration : - 1;
  19423. this.uuid = _Math.generateUUID();
  19424. // this means it should figure out its duration by scanning the tracks
  19425. if ( this.duration < 0 ) {
  19426. this.resetDuration();
  19427. }
  19428. this.optimize();
  19429. }
  19430. Object.assign( AnimationClip, {
  19431. parse: function ( json ) {
  19432. var tracks = [],
  19433. jsonTracks = json.tracks,
  19434. frameTime = 1.0 / ( json.fps || 1.0 );
  19435. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  19436. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  19437. }
  19438. return new AnimationClip( json.name, json.duration, tracks );
  19439. },
  19440. toJSON: function ( clip ) {
  19441. var tracks = [],
  19442. clipTracks = clip.tracks;
  19443. var json = {
  19444. 'name': clip.name,
  19445. 'duration': clip.duration,
  19446. 'tracks': tracks
  19447. };
  19448. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  19449. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  19450. }
  19451. return json;
  19452. },
  19453. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  19454. var numMorphTargets = morphTargetSequence.length;
  19455. var tracks = [];
  19456. for ( var i = 0; i < numMorphTargets; i ++ ) {
  19457. var times = [];
  19458. var values = [];
  19459. times.push(
  19460. ( i + numMorphTargets - 1 ) % numMorphTargets,
  19461. i,
  19462. ( i + 1 ) % numMorphTargets );
  19463. values.push( 0, 1, 0 );
  19464. var order = AnimationUtils.getKeyframeOrder( times );
  19465. times = AnimationUtils.sortedArray( times, 1, order );
  19466. values = AnimationUtils.sortedArray( values, 1, order );
  19467. // if there is a key at the first frame, duplicate it as the
  19468. // last frame as well for perfect loop.
  19469. if ( ! noLoop && times[ 0 ] === 0 ) {
  19470. times.push( numMorphTargets );
  19471. values.push( values[ 0 ] );
  19472. }
  19473. tracks.push(
  19474. new NumberKeyframeTrack(
  19475. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  19476. times, values
  19477. ).scale( 1.0 / fps ) );
  19478. }
  19479. return new AnimationClip( name, - 1, tracks );
  19480. },
  19481. findByName: function ( objectOrClipArray, name ) {
  19482. var clipArray = objectOrClipArray;
  19483. if ( ! Array.isArray( objectOrClipArray ) ) {
  19484. var o = objectOrClipArray;
  19485. clipArray = o.geometry && o.geometry.animations || o.animations;
  19486. }
  19487. for ( var i = 0; i < clipArray.length; i ++ ) {
  19488. if ( clipArray[ i ].name === name ) {
  19489. return clipArray[ i ];
  19490. }
  19491. }
  19492. return null;
  19493. },
  19494. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  19495. var animationToMorphTargets = {};
  19496. // tested with https://regex101.com/ on trick sequences
  19497. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  19498. var pattern = /^([\w-]*?)([\d]+)$/;
  19499. // sort morph target names into animation groups based
  19500. // patterns like Walk_001, Walk_002, Run_001, Run_002
  19501. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  19502. var morphTarget = morphTargets[ i ];
  19503. var parts = morphTarget.name.match( pattern );
  19504. if ( parts && parts.length > 1 ) {
  19505. var name = parts[ 1 ];
  19506. var animationMorphTargets = animationToMorphTargets[ name ];
  19507. if ( ! animationMorphTargets ) {
  19508. animationToMorphTargets[ name ] = animationMorphTargets = [];
  19509. }
  19510. animationMorphTargets.push( morphTarget );
  19511. }
  19512. }
  19513. var clips = [];
  19514. for ( var name in animationToMorphTargets ) {
  19515. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  19516. }
  19517. return clips;
  19518. },
  19519. // parse the animation.hierarchy format
  19520. parseAnimation: function ( animation, bones ) {
  19521. if ( ! animation ) {
  19522. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  19523. return null;
  19524. }
  19525. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  19526. // only return track if there are actually keys.
  19527. if ( animationKeys.length !== 0 ) {
  19528. var times = [];
  19529. var values = [];
  19530. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  19531. // empty keys are filtered out, so check again
  19532. if ( times.length !== 0 ) {
  19533. destTracks.push( new trackType( trackName, times, values ) );
  19534. }
  19535. }
  19536. };
  19537. var tracks = [];
  19538. var clipName = animation.name || 'default';
  19539. // automatic length determination in AnimationClip.
  19540. var duration = animation.length || - 1;
  19541. var fps = animation.fps || 30;
  19542. var hierarchyTracks = animation.hierarchy || [];
  19543. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  19544. var animationKeys = hierarchyTracks[ h ].keys;
  19545. // skip empty tracks
  19546. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  19547. // process morph targets
  19548. if ( animationKeys[ 0 ].morphTargets ) {
  19549. // figure out all morph targets used in this track
  19550. var morphTargetNames = {};
  19551. for ( var k = 0; k < animationKeys.length; k ++ ) {
  19552. if ( animationKeys[ k ].morphTargets ) {
  19553. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  19554. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  19555. }
  19556. }
  19557. }
  19558. // create a track for each morph target with all zero
  19559. // morphTargetInfluences except for the keys in which
  19560. // the morphTarget is named.
  19561. for ( var morphTargetName in morphTargetNames ) {
  19562. var times = [];
  19563. var values = [];
  19564. for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  19565. var animationKey = animationKeys[ k ];
  19566. times.push( animationKey.time );
  19567. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  19568. }
  19569. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  19570. }
  19571. duration = morphTargetNames.length * ( fps || 1.0 );
  19572. } else {
  19573. // ...assume skeletal animation
  19574. var boneName = '.bones[' + bones[ h ].name + ']';
  19575. addNonemptyTrack(
  19576. VectorKeyframeTrack, boneName + '.position',
  19577. animationKeys, 'pos', tracks );
  19578. addNonemptyTrack(
  19579. QuaternionKeyframeTrack, boneName + '.quaternion',
  19580. animationKeys, 'rot', tracks );
  19581. addNonemptyTrack(
  19582. VectorKeyframeTrack, boneName + '.scale',
  19583. animationKeys, 'scl', tracks );
  19584. }
  19585. }
  19586. if ( tracks.length === 0 ) {
  19587. return null;
  19588. }
  19589. var clip = new AnimationClip( clipName, duration, tracks );
  19590. return clip;
  19591. }
  19592. } );
  19593. Object.assign( AnimationClip.prototype, {
  19594. resetDuration: function () {
  19595. var tracks = this.tracks, duration = 0;
  19596. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  19597. var track = this.tracks[ i ];
  19598. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  19599. }
  19600. this.duration = duration;
  19601. },
  19602. trim: function () {
  19603. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19604. this.tracks[ i ].trim( 0, this.duration );
  19605. }
  19606. return this;
  19607. },
  19608. optimize: function () {
  19609. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19610. this.tracks[ i ].optimize();
  19611. }
  19612. return this;
  19613. }
  19614. } );
  19615. /**
  19616. * @author mrdoob / http://mrdoob.com/
  19617. */
  19618. function MaterialLoader( manager ) {
  19619. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19620. this.textures = {};
  19621. }
  19622. Object.assign( MaterialLoader.prototype, {
  19623. load: function ( url, onLoad, onProgress, onError ) {
  19624. var scope = this;
  19625. var loader = new FileLoader( scope.manager );
  19626. loader.load( url, function ( text ) {
  19627. onLoad( scope.parse( JSON.parse( text ) ) );
  19628. }, onProgress, onError );
  19629. },
  19630. setTextures: function ( value ) {
  19631. this.textures = value;
  19632. },
  19633. parse: function ( json ) {
  19634. var textures = this.textures;
  19635. function getTexture( name ) {
  19636. if ( textures[ name ] === undefined ) {
  19637. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  19638. }
  19639. return textures[ name ];
  19640. }
  19641. var material = new Materials[ json.type ]();
  19642. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  19643. if ( json.name !== undefined ) material.name = json.name;
  19644. if ( json.color !== undefined ) material.color.setHex( json.color );
  19645. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  19646. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  19647. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  19648. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  19649. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  19650. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  19651. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  19652. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  19653. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  19654. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  19655. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  19656. if ( json.fog !== undefined ) material.fog = json.fog;
  19657. if ( json.shading !== undefined ) material.shading = json.shading;
  19658. if ( json.blending !== undefined ) material.blending = json.blending;
  19659. if ( json.side !== undefined ) material.side = json.side;
  19660. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  19661. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  19662. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  19663. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  19664. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  19665. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  19666. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  19667. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  19668. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  19669. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  19670. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  19671. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  19672. // for PointsMaterial
  19673. if ( json.size !== undefined ) material.size = json.size;
  19674. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  19675. // maps
  19676. if ( json.map !== undefined ) material.map = getTexture( json.map );
  19677. if ( json.alphaMap !== undefined ) {
  19678. material.alphaMap = getTexture( json.alphaMap );
  19679. material.transparent = true;
  19680. }
  19681. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  19682. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  19683. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  19684. if ( json.normalScale !== undefined ) {
  19685. var normalScale = json.normalScale;
  19686. if ( Array.isArray( normalScale ) === false ) {
  19687. // Blender exporter used to export a scalar. See #7459
  19688. normalScale = [ normalScale, normalScale ];
  19689. }
  19690. material.normalScale = new Vector2().fromArray( normalScale );
  19691. }
  19692. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  19693. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  19694. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  19695. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  19696. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  19697. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  19698. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  19699. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  19700. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  19701. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  19702. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  19703. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  19704. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  19705. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  19706. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  19707. return material;
  19708. }
  19709. } );
  19710. /**
  19711. * @author mrdoob / http://mrdoob.com/
  19712. */
  19713. function BufferGeometryLoader( manager ) {
  19714. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19715. }
  19716. Object.assign( BufferGeometryLoader.prototype, {
  19717. load: function ( url, onLoad, onProgress, onError ) {
  19718. var scope = this;
  19719. var loader = new FileLoader( scope.manager );
  19720. loader.load( url, function ( text ) {
  19721. onLoad( scope.parse( JSON.parse( text ) ) );
  19722. }, onProgress, onError );
  19723. },
  19724. parse: function ( json ) {
  19725. var geometry = new BufferGeometry();
  19726. var index = json.data.index;
  19727. if ( index !== undefined ) {
  19728. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  19729. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  19730. }
  19731. var attributes = json.data.attributes;
  19732. for ( var key in attributes ) {
  19733. var attribute = attributes[ key ];
  19734. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  19735. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  19736. }
  19737. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  19738. if ( groups !== undefined ) {
  19739. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  19740. var group = groups[ i ];
  19741. geometry.addGroup( group.start, group.count, group.materialIndex );
  19742. }
  19743. }
  19744. var boundingSphere = json.data.boundingSphere;
  19745. if ( boundingSphere !== undefined ) {
  19746. var center = new Vector3();
  19747. if ( boundingSphere.center !== undefined ) {
  19748. center.fromArray( boundingSphere.center );
  19749. }
  19750. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  19751. }
  19752. return geometry;
  19753. }
  19754. } );
  19755. var TYPED_ARRAYS = {
  19756. Int8Array: Int8Array,
  19757. Uint8Array: Uint8Array,
  19758. // Workaround for IE11 pre KB2929437. See #11440
  19759. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  19760. Int16Array: Int16Array,
  19761. Uint16Array: Uint16Array,
  19762. Int32Array: Int32Array,
  19763. Uint32Array: Uint32Array,
  19764. Float32Array: Float32Array,
  19765. Float64Array: Float64Array
  19766. };
  19767. /**
  19768. * @author alteredq / http://alteredqualia.com/
  19769. */
  19770. function Loader() {
  19771. this.onLoadStart = function () {};
  19772. this.onLoadProgress = function () {};
  19773. this.onLoadComplete = function () {};
  19774. }
  19775. Loader.Handlers = {
  19776. handlers: [],
  19777. add: function ( regex, loader ) {
  19778. this.handlers.push( regex, loader );
  19779. },
  19780. get: function ( file ) {
  19781. var handlers = this.handlers;
  19782. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  19783. var regex = handlers[ i ];
  19784. var loader = handlers[ i + 1 ];
  19785. if ( regex.test( file ) ) {
  19786. return loader;
  19787. }
  19788. }
  19789. return null;
  19790. }
  19791. };
  19792. Object.assign( Loader.prototype, {
  19793. crossOrigin: undefined,
  19794. extractUrlBase: function ( url ) {
  19795. var parts = url.split( '/' );
  19796. if ( parts.length === 1 ) return './';
  19797. parts.pop();
  19798. return parts.join( '/' ) + '/';
  19799. },
  19800. initMaterials: function ( materials, texturePath, crossOrigin ) {
  19801. var array = [];
  19802. for ( var i = 0; i < materials.length; ++ i ) {
  19803. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  19804. }
  19805. return array;
  19806. },
  19807. createMaterial: ( function () {
  19808. var BlendingMode = {
  19809. NoBlending: NoBlending,
  19810. NormalBlending: NormalBlending,
  19811. AdditiveBlending: AdditiveBlending,
  19812. SubtractiveBlending: SubtractiveBlending,
  19813. MultiplyBlending: MultiplyBlending,
  19814. CustomBlending: CustomBlending
  19815. };
  19816. var color = new Color();
  19817. var textureLoader = new TextureLoader();
  19818. var materialLoader = new MaterialLoader();
  19819. return function createMaterial( m, texturePath, crossOrigin ) {
  19820. // convert from old material format
  19821. var textures = {};
  19822. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  19823. var fullPath = texturePath + path;
  19824. var loader = Loader.Handlers.get( fullPath );
  19825. var texture;
  19826. if ( loader !== null ) {
  19827. texture = loader.load( fullPath );
  19828. } else {
  19829. textureLoader.setCrossOrigin( crossOrigin );
  19830. texture = textureLoader.load( fullPath );
  19831. }
  19832. if ( repeat !== undefined ) {
  19833. texture.repeat.fromArray( repeat );
  19834. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  19835. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  19836. }
  19837. if ( offset !== undefined ) {
  19838. texture.offset.fromArray( offset );
  19839. }
  19840. if ( wrap !== undefined ) {
  19841. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  19842. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  19843. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  19844. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  19845. }
  19846. if ( anisotropy !== undefined ) {
  19847. texture.anisotropy = anisotropy;
  19848. }
  19849. var uuid = _Math.generateUUID();
  19850. textures[ uuid ] = texture;
  19851. return uuid;
  19852. }
  19853. //
  19854. var json = {
  19855. uuid: _Math.generateUUID(),
  19856. type: 'MeshLambertMaterial'
  19857. };
  19858. for ( var name in m ) {
  19859. var value = m[ name ];
  19860. switch ( name ) {
  19861. case 'DbgColor':
  19862. case 'DbgIndex':
  19863. case 'opticalDensity':
  19864. case 'illumination':
  19865. break;
  19866. case 'DbgName':
  19867. json.name = value;
  19868. break;
  19869. case 'blending':
  19870. json.blending = BlendingMode[ value ];
  19871. break;
  19872. case 'colorAmbient':
  19873. case 'mapAmbient':
  19874. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  19875. break;
  19876. case 'colorDiffuse':
  19877. json.color = color.fromArray( value ).getHex();
  19878. break;
  19879. case 'colorSpecular':
  19880. json.specular = color.fromArray( value ).getHex();
  19881. break;
  19882. case 'colorEmissive':
  19883. json.emissive = color.fromArray( value ).getHex();
  19884. break;
  19885. case 'specularCoef':
  19886. json.shininess = value;
  19887. break;
  19888. case 'shading':
  19889. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  19890. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  19891. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  19892. break;
  19893. case 'mapDiffuse':
  19894. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  19895. break;
  19896. case 'mapDiffuseRepeat':
  19897. case 'mapDiffuseOffset':
  19898. case 'mapDiffuseWrap':
  19899. case 'mapDiffuseAnisotropy':
  19900. break;
  19901. case 'mapEmissive':
  19902. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  19903. break;
  19904. case 'mapEmissiveRepeat':
  19905. case 'mapEmissiveOffset':
  19906. case 'mapEmissiveWrap':
  19907. case 'mapEmissiveAnisotropy':
  19908. break;
  19909. case 'mapLight':
  19910. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  19911. break;
  19912. case 'mapLightRepeat':
  19913. case 'mapLightOffset':
  19914. case 'mapLightWrap':
  19915. case 'mapLightAnisotropy':
  19916. break;
  19917. case 'mapAO':
  19918. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  19919. break;
  19920. case 'mapAORepeat':
  19921. case 'mapAOOffset':
  19922. case 'mapAOWrap':
  19923. case 'mapAOAnisotropy':
  19924. break;
  19925. case 'mapBump':
  19926. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  19927. break;
  19928. case 'mapBumpScale':
  19929. json.bumpScale = value;
  19930. break;
  19931. case 'mapBumpRepeat':
  19932. case 'mapBumpOffset':
  19933. case 'mapBumpWrap':
  19934. case 'mapBumpAnisotropy':
  19935. break;
  19936. case 'mapNormal':
  19937. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  19938. break;
  19939. case 'mapNormalFactor':
  19940. json.normalScale = [ value, value ];
  19941. break;
  19942. case 'mapNormalRepeat':
  19943. case 'mapNormalOffset':
  19944. case 'mapNormalWrap':
  19945. case 'mapNormalAnisotropy':
  19946. break;
  19947. case 'mapSpecular':
  19948. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  19949. break;
  19950. case 'mapSpecularRepeat':
  19951. case 'mapSpecularOffset':
  19952. case 'mapSpecularWrap':
  19953. case 'mapSpecularAnisotropy':
  19954. break;
  19955. case 'mapMetalness':
  19956. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  19957. break;
  19958. case 'mapMetalnessRepeat':
  19959. case 'mapMetalnessOffset':
  19960. case 'mapMetalnessWrap':
  19961. case 'mapMetalnessAnisotropy':
  19962. break;
  19963. case 'mapRoughness':
  19964. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  19965. break;
  19966. case 'mapRoughnessRepeat':
  19967. case 'mapRoughnessOffset':
  19968. case 'mapRoughnessWrap':
  19969. case 'mapRoughnessAnisotropy':
  19970. break;
  19971. case 'mapAlpha':
  19972. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  19973. break;
  19974. case 'mapAlphaRepeat':
  19975. case 'mapAlphaOffset':
  19976. case 'mapAlphaWrap':
  19977. case 'mapAlphaAnisotropy':
  19978. break;
  19979. case 'flipSided':
  19980. json.side = BackSide;
  19981. break;
  19982. case 'doubleSided':
  19983. json.side = DoubleSide;
  19984. break;
  19985. case 'transparency':
  19986. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  19987. json.opacity = value;
  19988. break;
  19989. case 'depthTest':
  19990. case 'depthWrite':
  19991. case 'colorWrite':
  19992. case 'opacity':
  19993. case 'reflectivity':
  19994. case 'transparent':
  19995. case 'visible':
  19996. case 'wireframe':
  19997. json[ name ] = value;
  19998. break;
  19999. case 'vertexColors':
  20000. if ( value === true ) json.vertexColors = VertexColors;
  20001. if ( value === 'face' ) json.vertexColors = FaceColors;
  20002. break;
  20003. default:
  20004. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  20005. break;
  20006. }
  20007. }
  20008. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  20009. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  20010. if ( json.opacity < 1 ) json.transparent = true;
  20011. materialLoader.setTextures( textures );
  20012. return materialLoader.parse( json );
  20013. };
  20014. } )()
  20015. } );
  20016. /**
  20017. * @author mrdoob / http://mrdoob.com/
  20018. * @author alteredq / http://alteredqualia.com/
  20019. */
  20020. function JSONLoader( manager ) {
  20021. if ( typeof manager === 'boolean' ) {
  20022. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  20023. manager = undefined;
  20024. }
  20025. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  20026. this.withCredentials = false;
  20027. }
  20028. Object.assign( JSONLoader.prototype, {
  20029. load: function ( url, onLoad, onProgress, onError ) {
  20030. var scope = this;
  20031. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  20032. var loader = new FileLoader( this.manager );
  20033. loader.setWithCredentials( this.withCredentials );
  20034. loader.load( url, function ( text ) {
  20035. var json = JSON.parse( text );
  20036. var metadata = json.metadata;
  20037. if ( metadata !== undefined ) {
  20038. var type = metadata.type;
  20039. if ( type !== undefined ) {
  20040. if ( type.toLowerCase() === 'object' ) {
  20041. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  20042. return;
  20043. }
  20044. if ( type.toLowerCase() === 'scene' ) {
  20045. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  20046. return;
  20047. }
  20048. }
  20049. }
  20050. var object = scope.parse( json, texturePath );
  20051. onLoad( object.geometry, object.materials );
  20052. }, onProgress, onError );
  20053. },
  20054. setTexturePath: function ( value ) {
  20055. this.texturePath = value;
  20056. },
  20057. parse: ( function () {
  20058. function parseModel( json, geometry ) {
  20059. function isBitSet( value, position ) {
  20060. return value & ( 1 << position );
  20061. }
  20062. var i, j, fi,
  20063. offset, zLength,
  20064. colorIndex, normalIndex, uvIndex, materialIndex,
  20065. type,
  20066. isQuad,
  20067. hasMaterial,
  20068. hasFaceVertexUv,
  20069. hasFaceNormal, hasFaceVertexNormal,
  20070. hasFaceColor, hasFaceVertexColor,
  20071. vertex, face, faceA, faceB, hex, normal,
  20072. uvLayer, uv, u, v,
  20073. faces = json.faces,
  20074. vertices = json.vertices,
  20075. normals = json.normals,
  20076. colors = json.colors,
  20077. scale = json.scale,
  20078. nUvLayers = 0;
  20079. if ( json.uvs !== undefined ) {
  20080. // disregard empty arrays
  20081. for ( i = 0; i < json.uvs.length; i ++ ) {
  20082. if ( json.uvs[ i ].length ) nUvLayers ++;
  20083. }
  20084. for ( i = 0; i < nUvLayers; i ++ ) {
  20085. geometry.faceVertexUvs[ i ] = [];
  20086. }
  20087. }
  20088. offset = 0;
  20089. zLength = vertices.length;
  20090. while ( offset < zLength ) {
  20091. vertex = new Vector3();
  20092. vertex.x = vertices[ offset ++ ] * scale;
  20093. vertex.y = vertices[ offset ++ ] * scale;
  20094. vertex.z = vertices[ offset ++ ] * scale;
  20095. geometry.vertices.push( vertex );
  20096. }
  20097. offset = 0;
  20098. zLength = faces.length;
  20099. while ( offset < zLength ) {
  20100. type = faces[ offset ++ ];
  20101. isQuad = isBitSet( type, 0 );
  20102. hasMaterial = isBitSet( type, 1 );
  20103. hasFaceVertexUv = isBitSet( type, 3 );
  20104. hasFaceNormal = isBitSet( type, 4 );
  20105. hasFaceVertexNormal = isBitSet( type, 5 );
  20106. hasFaceColor = isBitSet( type, 6 );
  20107. hasFaceVertexColor = isBitSet( type, 7 );
  20108. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  20109. if ( isQuad ) {
  20110. faceA = new Face3();
  20111. faceA.a = faces[ offset ];
  20112. faceA.b = faces[ offset + 1 ];
  20113. faceA.c = faces[ offset + 3 ];
  20114. faceB = new Face3();
  20115. faceB.a = faces[ offset + 1 ];
  20116. faceB.b = faces[ offset + 2 ];
  20117. faceB.c = faces[ offset + 3 ];
  20118. offset += 4;
  20119. if ( hasMaterial ) {
  20120. materialIndex = faces[ offset ++ ];
  20121. faceA.materialIndex = materialIndex;
  20122. faceB.materialIndex = materialIndex;
  20123. }
  20124. // to get face <=> uv index correspondence
  20125. fi = geometry.faces.length;
  20126. if ( hasFaceVertexUv ) {
  20127. for ( i = 0; i < nUvLayers; i ++ ) {
  20128. uvLayer = json.uvs[ i ];
  20129. geometry.faceVertexUvs[ i ][ fi ] = [];
  20130. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  20131. for ( j = 0; j < 4; j ++ ) {
  20132. uvIndex = faces[ offset ++ ];
  20133. u = uvLayer[ uvIndex * 2 ];
  20134. v = uvLayer[ uvIndex * 2 + 1 ];
  20135. uv = new Vector2( u, v );
  20136. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  20137. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  20138. }
  20139. }
  20140. }
  20141. if ( hasFaceNormal ) {
  20142. normalIndex = faces[ offset ++ ] * 3;
  20143. faceA.normal.set(
  20144. normals[ normalIndex ++ ],
  20145. normals[ normalIndex ++ ],
  20146. normals[ normalIndex ]
  20147. );
  20148. faceB.normal.copy( faceA.normal );
  20149. }
  20150. if ( hasFaceVertexNormal ) {
  20151. for ( i = 0; i < 4; i ++ ) {
  20152. normalIndex = faces[ offset ++ ] * 3;
  20153. normal = new Vector3(
  20154. normals[ normalIndex ++ ],
  20155. normals[ normalIndex ++ ],
  20156. normals[ normalIndex ]
  20157. );
  20158. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  20159. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  20160. }
  20161. }
  20162. if ( hasFaceColor ) {
  20163. colorIndex = faces[ offset ++ ];
  20164. hex = colors[ colorIndex ];
  20165. faceA.color.setHex( hex );
  20166. faceB.color.setHex( hex );
  20167. }
  20168. if ( hasFaceVertexColor ) {
  20169. for ( i = 0; i < 4; i ++ ) {
  20170. colorIndex = faces[ offset ++ ];
  20171. hex = colors[ colorIndex ];
  20172. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  20173. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  20174. }
  20175. }
  20176. geometry.faces.push( faceA );
  20177. geometry.faces.push( faceB );
  20178. } else {
  20179. face = new Face3();
  20180. face.a = faces[ offset ++ ];
  20181. face.b = faces[ offset ++ ];
  20182. face.c = faces[ offset ++ ];
  20183. if ( hasMaterial ) {
  20184. materialIndex = faces[ offset ++ ];
  20185. face.materialIndex = materialIndex;
  20186. }
  20187. // to get face <=> uv index correspondence
  20188. fi = geometry.faces.length;
  20189. if ( hasFaceVertexUv ) {
  20190. for ( i = 0; i < nUvLayers; i ++ ) {
  20191. uvLayer = json.uvs[ i ];
  20192. geometry.faceVertexUvs[ i ][ fi ] = [];
  20193. for ( j = 0; j < 3; j ++ ) {
  20194. uvIndex = faces[ offset ++ ];
  20195. u = uvLayer[ uvIndex * 2 ];
  20196. v = uvLayer[ uvIndex * 2 + 1 ];
  20197. uv = new Vector2( u, v );
  20198. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  20199. }
  20200. }
  20201. }
  20202. if ( hasFaceNormal ) {
  20203. normalIndex = faces[ offset ++ ] * 3;
  20204. face.normal.set(
  20205. normals[ normalIndex ++ ],
  20206. normals[ normalIndex ++ ],
  20207. normals[ normalIndex ]
  20208. );
  20209. }
  20210. if ( hasFaceVertexNormal ) {
  20211. for ( i = 0; i < 3; i ++ ) {
  20212. normalIndex = faces[ offset ++ ] * 3;
  20213. normal = new Vector3(
  20214. normals[ normalIndex ++ ],
  20215. normals[ normalIndex ++ ],
  20216. normals[ normalIndex ]
  20217. );
  20218. face.vertexNormals.push( normal );
  20219. }
  20220. }
  20221. if ( hasFaceColor ) {
  20222. colorIndex = faces[ offset ++ ];
  20223. face.color.setHex( colors[ colorIndex ] );
  20224. }
  20225. if ( hasFaceVertexColor ) {
  20226. for ( i = 0; i < 3; i ++ ) {
  20227. colorIndex = faces[ offset ++ ];
  20228. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  20229. }
  20230. }
  20231. geometry.faces.push( face );
  20232. }
  20233. }
  20234. }
  20235. function parseSkin( json, geometry ) {
  20236. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  20237. if ( json.skinWeights ) {
  20238. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  20239. var x = json.skinWeights[ i ];
  20240. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  20241. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  20242. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  20243. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  20244. }
  20245. }
  20246. if ( json.skinIndices ) {
  20247. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  20248. var a = json.skinIndices[ i ];
  20249. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  20250. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  20251. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  20252. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  20253. }
  20254. }
  20255. geometry.bones = json.bones;
  20256. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  20257. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  20258. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  20259. }
  20260. }
  20261. function parseMorphing( json, geometry ) {
  20262. var scale = json.scale;
  20263. if ( json.morphTargets !== undefined ) {
  20264. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  20265. geometry.morphTargets[ i ] = {};
  20266. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  20267. geometry.morphTargets[ i ].vertices = [];
  20268. var dstVertices = geometry.morphTargets[ i ].vertices;
  20269. var srcVertices = json.morphTargets[ i ].vertices;
  20270. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  20271. var vertex = new Vector3();
  20272. vertex.x = srcVertices[ v ] * scale;
  20273. vertex.y = srcVertices[ v + 1 ] * scale;
  20274. vertex.z = srcVertices[ v + 2 ] * scale;
  20275. dstVertices.push( vertex );
  20276. }
  20277. }
  20278. }
  20279. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  20280. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  20281. var faces = geometry.faces;
  20282. var morphColors = json.morphColors[ 0 ].colors;
  20283. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20284. faces[ i ].color.fromArray( morphColors, i * 3 );
  20285. }
  20286. }
  20287. }
  20288. function parseAnimations( json, geometry ) {
  20289. var outputAnimations = [];
  20290. // parse old style Bone/Hierarchy animations
  20291. var animations = [];
  20292. if ( json.animation !== undefined ) {
  20293. animations.push( json.animation );
  20294. }
  20295. if ( json.animations !== undefined ) {
  20296. if ( json.animations.length ) {
  20297. animations = animations.concat( json.animations );
  20298. } else {
  20299. animations.push( json.animations );
  20300. }
  20301. }
  20302. for ( var i = 0; i < animations.length; i ++ ) {
  20303. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  20304. if ( clip ) outputAnimations.push( clip );
  20305. }
  20306. // parse implicit morph animations
  20307. if ( geometry.morphTargets ) {
  20308. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  20309. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  20310. outputAnimations = outputAnimations.concat( morphAnimationClips );
  20311. }
  20312. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  20313. }
  20314. return function ( json, texturePath ) {
  20315. if ( json.data !== undefined ) {
  20316. // Geometry 4.0 spec
  20317. json = json.data;
  20318. }
  20319. if ( json.scale !== undefined ) {
  20320. json.scale = 1.0 / json.scale;
  20321. } else {
  20322. json.scale = 1.0;
  20323. }
  20324. var geometry = new Geometry();
  20325. parseModel( json, geometry );
  20326. parseSkin( json, geometry );
  20327. parseMorphing( json, geometry );
  20328. parseAnimations( json, geometry );
  20329. geometry.computeFaceNormals();
  20330. geometry.computeBoundingSphere();
  20331. if ( json.materials === undefined || json.materials.length === 0 ) {
  20332. return { geometry: geometry };
  20333. } else {
  20334. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  20335. return { geometry: geometry, materials: materials };
  20336. }
  20337. };
  20338. } )()
  20339. } );
  20340. /**
  20341. * @author mrdoob / http://mrdoob.com/
  20342. */
  20343. function ObjectLoader( manager ) {
  20344. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  20345. this.texturePath = '';
  20346. }
  20347. Object.assign( ObjectLoader.prototype, {
  20348. load: function ( url, onLoad, onProgress, onError ) {
  20349. if ( this.texturePath === '' ) {
  20350. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  20351. }
  20352. var scope = this;
  20353. var loader = new FileLoader( scope.manager );
  20354. loader.load( url, function ( text ) {
  20355. var json = null;
  20356. try {
  20357. json = JSON.parse( text );
  20358. } catch ( error ) {
  20359. if ( onError !== undefined ) onError( error );
  20360. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  20361. return;
  20362. }
  20363. var metadata = json.metadata;
  20364. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  20365. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  20366. return;
  20367. }
  20368. scope.parse( json, onLoad );
  20369. }, onProgress, onError );
  20370. },
  20371. setTexturePath: function ( value ) {
  20372. this.texturePath = value;
  20373. },
  20374. setCrossOrigin: function ( value ) {
  20375. this.crossOrigin = value;
  20376. },
  20377. parse: function ( json, onLoad ) {
  20378. var geometries = this.parseGeometries( json.geometries );
  20379. var images = this.parseImages( json.images, function () {
  20380. if ( onLoad !== undefined ) onLoad( object );
  20381. } );
  20382. var textures = this.parseTextures( json.textures, images );
  20383. var materials = this.parseMaterials( json.materials, textures );
  20384. var object = this.parseObject( json.object, geometries, materials );
  20385. if ( json.animations ) {
  20386. object.animations = this.parseAnimations( json.animations );
  20387. }
  20388. if ( json.images === undefined || json.images.length === 0 ) {
  20389. if ( onLoad !== undefined ) onLoad( object );
  20390. }
  20391. return object;
  20392. },
  20393. parseGeometries: function ( json ) {
  20394. var geometries = {};
  20395. if ( json !== undefined ) {
  20396. var geometryLoader = new JSONLoader();
  20397. var bufferGeometryLoader = new BufferGeometryLoader();
  20398. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20399. var geometry;
  20400. var data = json[ i ];
  20401. switch ( data.type ) {
  20402. case 'PlaneGeometry':
  20403. case 'PlaneBufferGeometry':
  20404. geometry = new Geometries[ data.type ](
  20405. data.width,
  20406. data.height,
  20407. data.widthSegments,
  20408. data.heightSegments
  20409. );
  20410. break;
  20411. case 'BoxGeometry':
  20412. case 'BoxBufferGeometry':
  20413. case 'CubeGeometry': // backwards compatible
  20414. geometry = new Geometries[ data.type ](
  20415. data.width,
  20416. data.height,
  20417. data.depth,
  20418. data.widthSegments,
  20419. data.heightSegments,
  20420. data.depthSegments
  20421. );
  20422. break;
  20423. case 'CircleGeometry':
  20424. case 'CircleBufferGeometry':
  20425. geometry = new Geometries[ data.type ](
  20426. data.radius,
  20427. data.segments,
  20428. data.thetaStart,
  20429. data.thetaLength
  20430. );
  20431. break;
  20432. case 'CylinderGeometry':
  20433. case 'CylinderBufferGeometry':
  20434. geometry = new Geometries[ data.type ](
  20435. data.radiusTop,
  20436. data.radiusBottom,
  20437. data.height,
  20438. data.radialSegments,
  20439. data.heightSegments,
  20440. data.openEnded,
  20441. data.thetaStart,
  20442. data.thetaLength
  20443. );
  20444. break;
  20445. case 'ConeGeometry':
  20446. case 'ConeBufferGeometry':
  20447. geometry = new Geometries[ data.type ](
  20448. data.radius,
  20449. data.height,
  20450. data.radialSegments,
  20451. data.heightSegments,
  20452. data.openEnded,
  20453. data.thetaStart,
  20454. data.thetaLength
  20455. );
  20456. break;
  20457. case 'SphereGeometry':
  20458. case 'SphereBufferGeometry':
  20459. geometry = new Geometries[ data.type ](
  20460. data.radius,
  20461. data.widthSegments,
  20462. data.heightSegments,
  20463. data.phiStart,
  20464. data.phiLength,
  20465. data.thetaStart,
  20466. data.thetaLength
  20467. );
  20468. break;
  20469. case 'DodecahedronGeometry':
  20470. case 'IcosahedronGeometry':
  20471. case 'OctahedronGeometry':
  20472. case 'TetrahedronGeometry':
  20473. geometry = new Geometries[ data.type ](
  20474. data.radius,
  20475. data.detail
  20476. );
  20477. break;
  20478. case 'RingGeometry':
  20479. case 'RingBufferGeometry':
  20480. geometry = new Geometries[ data.type ](
  20481. data.innerRadius,
  20482. data.outerRadius,
  20483. data.thetaSegments,
  20484. data.phiSegments,
  20485. data.thetaStart,
  20486. data.thetaLength
  20487. );
  20488. break;
  20489. case 'TorusGeometry':
  20490. case 'TorusBufferGeometry':
  20491. geometry = new Geometries[ data.type ](
  20492. data.radius,
  20493. data.tube,
  20494. data.radialSegments,
  20495. data.tubularSegments,
  20496. data.arc
  20497. );
  20498. break;
  20499. case 'TorusKnotGeometry':
  20500. case 'TorusKnotBufferGeometry':
  20501. geometry = new Geometries[ data.type ](
  20502. data.radius,
  20503. data.tube,
  20504. data.tubularSegments,
  20505. data.radialSegments,
  20506. data.p,
  20507. data.q
  20508. );
  20509. break;
  20510. case 'LatheGeometry':
  20511. case 'LatheBufferGeometry':
  20512. geometry = new Geometries[ data.type ](
  20513. data.points,
  20514. data.segments,
  20515. data.phiStart,
  20516. data.phiLength
  20517. );
  20518. break;
  20519. case 'BufferGeometry':
  20520. geometry = bufferGeometryLoader.parse( data );
  20521. break;
  20522. case 'Geometry':
  20523. geometry = geometryLoader.parse( data, this.texturePath ).geometry;
  20524. break;
  20525. default:
  20526. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  20527. continue;
  20528. }
  20529. geometry.uuid = data.uuid;
  20530. if ( data.name !== undefined ) geometry.name = data.name;
  20531. geometries[ data.uuid ] = geometry;
  20532. }
  20533. }
  20534. return geometries;
  20535. },
  20536. parseMaterials: function ( json, textures ) {
  20537. var materials = {};
  20538. if ( json !== undefined ) {
  20539. var loader = new MaterialLoader();
  20540. loader.setTextures( textures );
  20541. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20542. var data = json[ i ];
  20543. if ( data.type === 'MultiMaterial' ) {
  20544. // Deprecated
  20545. var array = [];
  20546. for ( var j = 0; j < data.materials.length; j ++ ) {
  20547. array.push( loader.parse( data.materials[ j ] ) );
  20548. }
  20549. materials[ data.uuid ] = array;
  20550. } else {
  20551. materials[ data.uuid ] = loader.parse( data );
  20552. }
  20553. }
  20554. }
  20555. return materials;
  20556. },
  20557. parseAnimations: function ( json ) {
  20558. var animations = [];
  20559. for ( var i = 0; i < json.length; i ++ ) {
  20560. var clip = AnimationClip.parse( json[ i ] );
  20561. animations.push( clip );
  20562. }
  20563. return animations;
  20564. },
  20565. parseImages: function ( json, onLoad ) {
  20566. var scope = this;
  20567. var images = {};
  20568. function loadImage( url ) {
  20569. scope.manager.itemStart( url );
  20570. return loader.load( url, function () {
  20571. scope.manager.itemEnd( url );
  20572. }, undefined, function () {
  20573. scope.manager.itemEnd( url );
  20574. scope.manager.itemError( url );
  20575. } );
  20576. }
  20577. if ( json !== undefined && json.length > 0 ) {
  20578. var manager = new LoadingManager( onLoad );
  20579. var loader = new ImageLoader( manager );
  20580. loader.setCrossOrigin( this.crossOrigin );
  20581. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20582. var image = json[ i ];
  20583. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  20584. images[ image.uuid ] = loadImage( path );
  20585. }
  20586. }
  20587. return images;
  20588. },
  20589. parseTextures: function ( json, images ) {
  20590. function parseConstant( value, type ) {
  20591. if ( typeof( value ) === 'number' ) return value;
  20592. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  20593. return type[ value ];
  20594. }
  20595. var textures = {};
  20596. if ( json !== undefined ) {
  20597. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20598. var data = json[ i ];
  20599. if ( data.image === undefined ) {
  20600. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  20601. }
  20602. if ( images[ data.image ] === undefined ) {
  20603. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  20604. }
  20605. var texture = new Texture( images[ data.image ] );
  20606. texture.needsUpdate = true;
  20607. texture.uuid = data.uuid;
  20608. if ( data.name !== undefined ) texture.name = data.name;
  20609. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  20610. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  20611. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  20612. if ( data.wrap !== undefined ) {
  20613. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  20614. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  20615. }
  20616. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  20617. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  20618. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  20619. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  20620. textures[ data.uuid ] = texture;
  20621. }
  20622. }
  20623. return textures;
  20624. },
  20625. parseObject: function () {
  20626. var matrix = new Matrix4();
  20627. return function parseObject( data, geometries, materials ) {
  20628. var object;
  20629. function getGeometry( name ) {
  20630. if ( geometries[ name ] === undefined ) {
  20631. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  20632. }
  20633. return geometries[ name ];
  20634. }
  20635. function getMaterial( name ) {
  20636. if ( name === undefined ) return undefined;
  20637. if ( Array.isArray( name ) ) {
  20638. var array = [];
  20639. for ( var i = 0, l = name.length; i < l; i ++ ) {
  20640. var uuid = name[ i ];
  20641. if ( materials[ uuid ] === undefined ) {
  20642. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  20643. }
  20644. array.push( materials[ uuid ] );
  20645. }
  20646. return array;
  20647. }
  20648. if ( materials[ name ] === undefined ) {
  20649. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  20650. }
  20651. return materials[ name ];
  20652. }
  20653. switch ( data.type ) {
  20654. case 'Scene':
  20655. object = new Scene();
  20656. if ( data.background !== undefined ) {
  20657. if ( Number.isInteger( data.background ) ) {
  20658. object.background = new Color( data.background );
  20659. }
  20660. }
  20661. if ( data.fog !== undefined ) {
  20662. if ( data.fog.type === 'Fog' ) {
  20663. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  20664. } else if ( data.fog.type === 'FogExp2' ) {
  20665. object.fog = new FogExp2( data.fog.color, data.fog.density );
  20666. }
  20667. }
  20668. break;
  20669. case 'PerspectiveCamera':
  20670. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  20671. if ( data.focus !== undefined ) object.focus = data.focus;
  20672. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  20673. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  20674. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  20675. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  20676. break;
  20677. case 'OrthographicCamera':
  20678. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  20679. break;
  20680. case 'AmbientLight':
  20681. object = new AmbientLight( data.color, data.intensity );
  20682. break;
  20683. case 'DirectionalLight':
  20684. object = new DirectionalLight( data.color, data.intensity );
  20685. break;
  20686. case 'PointLight':
  20687. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  20688. break;
  20689. case 'RectAreaLight':
  20690. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  20691. break;
  20692. case 'SpotLight':
  20693. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  20694. break;
  20695. case 'HemisphereLight':
  20696. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  20697. break;
  20698. case 'SkinnedMesh':
  20699. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  20700. case 'Mesh':
  20701. var geometry = getGeometry( data.geometry );
  20702. var material = getMaterial( data.material );
  20703. if ( geometry.bones && geometry.bones.length > 0 ) {
  20704. object = new SkinnedMesh( geometry, material );
  20705. } else {
  20706. object = new Mesh( geometry, material );
  20707. }
  20708. break;
  20709. case 'LOD':
  20710. object = new LOD();
  20711. break;
  20712. case 'Line':
  20713. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  20714. break;
  20715. case 'LineLoop':
  20716. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  20717. break;
  20718. case 'LineSegments':
  20719. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  20720. break;
  20721. case 'PointCloud':
  20722. case 'Points':
  20723. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  20724. break;
  20725. case 'Sprite':
  20726. object = new Sprite( getMaterial( data.material ) );
  20727. break;
  20728. case 'Group':
  20729. object = new Group();
  20730. break;
  20731. default:
  20732. object = new Object3D();
  20733. }
  20734. object.uuid = data.uuid;
  20735. if ( data.name !== undefined ) object.name = data.name;
  20736. if ( data.matrix !== undefined ) {
  20737. matrix.fromArray( data.matrix );
  20738. matrix.decompose( object.position, object.quaternion, object.scale );
  20739. } else {
  20740. if ( data.position !== undefined ) object.position.fromArray( data.position );
  20741. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  20742. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  20743. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  20744. }
  20745. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  20746. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  20747. if ( data.shadow ) {
  20748. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  20749. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  20750. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  20751. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  20752. }
  20753. if ( data.visible !== undefined ) object.visible = data.visible;
  20754. if ( data.userData !== undefined ) object.userData = data.userData;
  20755. if ( data.children !== undefined ) {
  20756. var children = data.children;
  20757. for ( var i = 0; i < children.length; i ++ ) {
  20758. object.add( this.parseObject( children[ i ], geometries, materials ) );
  20759. }
  20760. }
  20761. if ( data.type === 'LOD' ) {
  20762. var levels = data.levels;
  20763. for ( var l = 0; l < levels.length; l ++ ) {
  20764. var level = levels[ l ];
  20765. var child = object.getObjectByProperty( 'uuid', level.object );
  20766. if ( child !== undefined ) {
  20767. object.addLevel( child, level.distance );
  20768. }
  20769. }
  20770. }
  20771. return object;
  20772. };
  20773. }()
  20774. } );
  20775. var TEXTURE_MAPPING = {
  20776. UVMapping: UVMapping,
  20777. CubeReflectionMapping: CubeReflectionMapping,
  20778. CubeRefractionMapping: CubeRefractionMapping,
  20779. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  20780. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  20781. SphericalReflectionMapping: SphericalReflectionMapping,
  20782. CubeUVReflectionMapping: CubeUVReflectionMapping,
  20783. CubeUVRefractionMapping: CubeUVRefractionMapping
  20784. };
  20785. var TEXTURE_WRAPPING = {
  20786. RepeatWrapping: RepeatWrapping,
  20787. ClampToEdgeWrapping: ClampToEdgeWrapping,
  20788. MirroredRepeatWrapping: MirroredRepeatWrapping
  20789. };
  20790. var TEXTURE_FILTER = {
  20791. NearestFilter: NearestFilter,
  20792. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  20793. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  20794. LinearFilter: LinearFilter,
  20795. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  20796. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  20797. };
  20798. /**
  20799. * @author zz85 / http://www.lab4games.net/zz85/blog
  20800. *
  20801. * Bezier Curves formulas obtained from
  20802. * http://en.wikipedia.org/wiki/Bézier_curve
  20803. */
  20804. function CatmullRom( t, p0, p1, p2, p3 ) {
  20805. var v0 = ( p2 - p0 ) * 0.5;
  20806. var v1 = ( p3 - p1 ) * 0.5;
  20807. var t2 = t * t;
  20808. var t3 = t * t2;
  20809. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20810. }
  20811. //
  20812. function QuadraticBezierP0( t, p ) {
  20813. var k = 1 - t;
  20814. return k * k * p;
  20815. }
  20816. function QuadraticBezierP1( t, p ) {
  20817. return 2 * ( 1 - t ) * t * p;
  20818. }
  20819. function QuadraticBezierP2( t, p ) {
  20820. return t * t * p;
  20821. }
  20822. function QuadraticBezier( t, p0, p1, p2 ) {
  20823. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  20824. QuadraticBezierP2( t, p2 );
  20825. }
  20826. //
  20827. function CubicBezierP0( t, p ) {
  20828. var k = 1 - t;
  20829. return k * k * k * p;
  20830. }
  20831. function CubicBezierP1( t, p ) {
  20832. var k = 1 - t;
  20833. return 3 * k * k * t * p;
  20834. }
  20835. function CubicBezierP2( t, p ) {
  20836. return 3 * ( 1 - t ) * t * t * p;
  20837. }
  20838. function CubicBezierP3( t, p ) {
  20839. return t * t * t * p;
  20840. }
  20841. function CubicBezier( t, p0, p1, p2, p3 ) {
  20842. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  20843. CubicBezierP3( t, p3 );
  20844. }
  20845. /**
  20846. * @author zz85 / http://www.lab4games.net/zz85/blog
  20847. * Extensible curve object
  20848. *
  20849. * Some common of curve methods:
  20850. * .getPoint(t), getTangent(t)
  20851. * .getPointAt(u), getTangentAt(u)
  20852. * .getPoints(), .getSpacedPoints()
  20853. * .getLength()
  20854. * .updateArcLengths()
  20855. *
  20856. * This following curves inherit from THREE.Curve:
  20857. *
  20858. * -- 2D curves --
  20859. * THREE.ArcCurve
  20860. * THREE.CubicBezierCurve
  20861. * THREE.EllipseCurve
  20862. * THREE.LineCurve
  20863. * THREE.QuadraticBezierCurve
  20864. * THREE.SplineCurve
  20865. *
  20866. * -- 3D curves --
  20867. * THREE.CatmullRomCurve3
  20868. * THREE.CubicBezierCurve3
  20869. * THREE.LineCurve3
  20870. * THREE.QuadraticBezierCurve3
  20871. *
  20872. * A series of curves can be represented as a THREE.CurvePath.
  20873. *
  20874. **/
  20875. /**************************************************************
  20876. * Abstract Curve base class
  20877. **************************************************************/
  20878. function Curve() {
  20879. this.arcLengthDivisions = 200;
  20880. }
  20881. Object.assign( Curve.prototype, {
  20882. // Virtual base class method to overwrite and implement in subclasses
  20883. // - t [0 .. 1]
  20884. getPoint: function () {
  20885. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  20886. return null;
  20887. },
  20888. // Get point at relative position in curve according to arc length
  20889. // - u [0 .. 1]
  20890. getPointAt: function ( u ) {
  20891. var t = this.getUtoTmapping( u );
  20892. return this.getPoint( t );
  20893. },
  20894. // Get sequence of points using getPoint( t )
  20895. getPoints: function ( divisions ) {
  20896. if ( divisions === undefined ) divisions = 5;
  20897. var points = [];
  20898. for ( var d = 0; d <= divisions; d ++ ) {
  20899. points.push( this.getPoint( d / divisions ) );
  20900. }
  20901. return points;
  20902. },
  20903. // Get sequence of points using getPointAt( u )
  20904. getSpacedPoints: function ( divisions ) {
  20905. if ( divisions === undefined ) divisions = 5;
  20906. var points = [];
  20907. for ( var d = 0; d <= divisions; d ++ ) {
  20908. points.push( this.getPointAt( d / divisions ) );
  20909. }
  20910. return points;
  20911. },
  20912. // Get total curve arc length
  20913. getLength: function () {
  20914. var lengths = this.getLengths();
  20915. return lengths[ lengths.length - 1 ];
  20916. },
  20917. // Get list of cumulative segment lengths
  20918. getLengths: function ( divisions ) {
  20919. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  20920. if ( this.cacheArcLengths &&
  20921. ( this.cacheArcLengths.length === divisions + 1 ) &&
  20922. ! this.needsUpdate ) {
  20923. return this.cacheArcLengths;
  20924. }
  20925. this.needsUpdate = false;
  20926. var cache = [];
  20927. var current, last = this.getPoint( 0 );
  20928. var p, sum = 0;
  20929. cache.push( 0 );
  20930. for ( p = 1; p <= divisions; p ++ ) {
  20931. current = this.getPoint( p / divisions );
  20932. sum += current.distanceTo( last );
  20933. cache.push( sum );
  20934. last = current;
  20935. }
  20936. this.cacheArcLengths = cache;
  20937. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  20938. },
  20939. updateArcLengths: function () {
  20940. this.needsUpdate = true;
  20941. this.getLengths();
  20942. },
  20943. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20944. getUtoTmapping: function ( u, distance ) {
  20945. var arcLengths = this.getLengths();
  20946. var i = 0, il = arcLengths.length;
  20947. var targetArcLength; // The targeted u distance value to get
  20948. if ( distance ) {
  20949. targetArcLength = distance;
  20950. } else {
  20951. targetArcLength = u * arcLengths[ il - 1 ];
  20952. }
  20953. // binary search for the index with largest value smaller than target u distance
  20954. var low = 0, high = il - 1, comparison;
  20955. while ( low <= high ) {
  20956. i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats
  20957. comparison = arcLengths[ i ] - targetArcLength;
  20958. if ( comparison < 0 ) {
  20959. low = i + 1;
  20960. } else if ( comparison > 0 ) {
  20961. high = i - 1;
  20962. } else {
  20963. high = i;
  20964. break;
  20965. // DONE
  20966. }
  20967. }
  20968. i = high;
  20969. if ( arcLengths[ i ] === targetArcLength ) {
  20970. return i / ( il - 1 );
  20971. }
  20972. // we could get finer grain at lengths, or use simple interpolation between two points
  20973. var lengthBefore = arcLengths[ i ];
  20974. var lengthAfter = arcLengths[ i + 1 ];
  20975. var segmentLength = lengthAfter - lengthBefore;
  20976. // determine where we are between the 'before' and 'after' points
  20977. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20978. // add that fractional amount to t
  20979. var t = ( i + segmentFraction ) / ( il - 1 );
  20980. return t;
  20981. },
  20982. // Returns a unit vector tangent at t
  20983. // In case any sub curve does not implement its tangent derivation,
  20984. // 2 points a small delta apart will be used to find its gradient
  20985. // which seems to give a reasonable approximation
  20986. getTangent: function ( t ) {
  20987. var delta = 0.0001;
  20988. var t1 = t - delta;
  20989. var t2 = t + delta;
  20990. // Capping in case of danger
  20991. if ( t1 < 0 ) t1 = 0;
  20992. if ( t2 > 1 ) t2 = 1;
  20993. var pt1 = this.getPoint( t1 );
  20994. var pt2 = this.getPoint( t2 );
  20995. var vec = pt2.clone().sub( pt1 );
  20996. return vec.normalize();
  20997. },
  20998. getTangentAt: function ( u ) {
  20999. var t = this.getUtoTmapping( u );
  21000. return this.getTangent( t );
  21001. },
  21002. computeFrenetFrames: function ( segments, closed ) {
  21003. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  21004. var normal = new Vector3();
  21005. var tangents = [];
  21006. var normals = [];
  21007. var binormals = [];
  21008. var vec = new Vector3();
  21009. var mat = new Matrix4();
  21010. var i, u, theta;
  21011. // compute the tangent vectors for each segment on the curve
  21012. for ( i = 0; i <= segments; i ++ ) {
  21013. u = i / segments;
  21014. tangents[ i ] = this.getTangentAt( u );
  21015. tangents[ i ].normalize();
  21016. }
  21017. // select an initial normal vector perpendicular to the first tangent vector,
  21018. // and in the direction of the minimum tangent xyz component
  21019. normals[ 0 ] = new Vector3();
  21020. binormals[ 0 ] = new Vector3();
  21021. var min = Number.MAX_VALUE;
  21022. var tx = Math.abs( tangents[ 0 ].x );
  21023. var ty = Math.abs( tangents[ 0 ].y );
  21024. var tz = Math.abs( tangents[ 0 ].z );
  21025. if ( tx <= min ) {
  21026. min = tx;
  21027. normal.set( 1, 0, 0 );
  21028. }
  21029. if ( ty <= min ) {
  21030. min = ty;
  21031. normal.set( 0, 1, 0 );
  21032. }
  21033. if ( tz <= min ) {
  21034. normal.set( 0, 0, 1 );
  21035. }
  21036. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  21037. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  21038. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  21039. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  21040. for ( i = 1; i <= segments; i ++ ) {
  21041. normals[ i ] = normals[ i - 1 ].clone();
  21042. binormals[ i ] = binormals[ i - 1 ].clone();
  21043. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  21044. if ( vec.length() > Number.EPSILON ) {
  21045. vec.normalize();
  21046. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  21047. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  21048. }
  21049. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21050. }
  21051. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  21052. if ( closed === true ) {
  21053. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  21054. theta /= segments;
  21055. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  21056. theta = - theta;
  21057. }
  21058. for ( i = 1; i <= segments; i ++ ) {
  21059. // twist a little...
  21060. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  21061. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21062. }
  21063. }
  21064. return {
  21065. tangents: tangents,
  21066. normals: normals,
  21067. binormals: binormals
  21068. };
  21069. }
  21070. } );
  21071. function LineCurve( v1, v2 ) {
  21072. Curve.call( this );
  21073. this.v1 = v1;
  21074. this.v2 = v2;
  21075. }
  21076. LineCurve.prototype = Object.create( Curve.prototype );
  21077. LineCurve.prototype.constructor = LineCurve;
  21078. LineCurve.prototype.isLineCurve = true;
  21079. LineCurve.prototype.getPoint = function ( t ) {
  21080. if ( t === 1 ) {
  21081. return this.v2.clone();
  21082. }
  21083. var point = this.v2.clone().sub( this.v1 );
  21084. point.multiplyScalar( t ).add( this.v1 );
  21085. return point;
  21086. };
  21087. // Line curve is linear, so we can overwrite default getPointAt
  21088. LineCurve.prototype.getPointAt = function ( u ) {
  21089. return this.getPoint( u );
  21090. };
  21091. LineCurve.prototype.getTangent = function ( t ) {
  21092. var tangent = this.v2.clone().sub( this.v1 );
  21093. return tangent.normalize();
  21094. };
  21095. /**
  21096. * @author zz85 / http://www.lab4games.net/zz85/blog
  21097. *
  21098. **/
  21099. /**************************************************************
  21100. * Curved Path - a curve path is simply a array of connected
  21101. * curves, but retains the api of a curve
  21102. **************************************************************/
  21103. function CurvePath() {
  21104. Curve.call( this );
  21105. this.curves = [];
  21106. this.autoClose = false; // Automatically closes the path
  21107. }
  21108. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  21109. constructor: CurvePath,
  21110. add: function ( curve ) {
  21111. this.curves.push( curve );
  21112. },
  21113. closePath: function () {
  21114. // Add a line curve if start and end of lines are not connected
  21115. var startPoint = this.curves[ 0 ].getPoint( 0 );
  21116. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  21117. if ( ! startPoint.equals( endPoint ) ) {
  21118. this.curves.push( new LineCurve( endPoint, startPoint ) );
  21119. }
  21120. },
  21121. // To get accurate point with reference to
  21122. // entire path distance at time t,
  21123. // following has to be done:
  21124. // 1. Length of each sub path have to be known
  21125. // 2. Locate and identify type of curve
  21126. // 3. Get t for the curve
  21127. // 4. Return curve.getPointAt(t')
  21128. getPoint: function ( t ) {
  21129. var d = t * this.getLength();
  21130. var curveLengths = this.getCurveLengths();
  21131. var i = 0;
  21132. // To think about boundaries points.
  21133. while ( i < curveLengths.length ) {
  21134. if ( curveLengths[ i ] >= d ) {
  21135. var diff = curveLengths[ i ] - d;
  21136. var curve = this.curves[ i ];
  21137. var segmentLength = curve.getLength();
  21138. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21139. return curve.getPointAt( u );
  21140. }
  21141. i ++;
  21142. }
  21143. return null;
  21144. // loop where sum != 0, sum > d , sum+1 <d
  21145. },
  21146. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21147. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21148. // getPoint() depends on getLength
  21149. getLength: function () {
  21150. var lens = this.getCurveLengths();
  21151. return lens[ lens.length - 1 ];
  21152. },
  21153. // cacheLengths must be recalculated.
  21154. updateArcLengths: function () {
  21155. this.needsUpdate = true;
  21156. this.cacheLengths = null;
  21157. this.getCurveLengths();
  21158. },
  21159. // Compute lengths and cache them
  21160. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21161. getCurveLengths: function () {
  21162. // We use cache values if curves and cache array are same length
  21163. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  21164. return this.cacheLengths;
  21165. }
  21166. // Get length of sub-curve
  21167. // Push sums into cached array
  21168. var lengths = [], sums = 0;
  21169. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  21170. sums += this.curves[ i ].getLength();
  21171. lengths.push( sums );
  21172. }
  21173. this.cacheLengths = lengths;
  21174. return lengths;
  21175. },
  21176. getSpacedPoints: function ( divisions ) {
  21177. if ( divisions === undefined ) divisions = 40;
  21178. var points = [];
  21179. for ( var i = 0; i <= divisions; i ++ ) {
  21180. points.push( this.getPoint( i / divisions ) );
  21181. }
  21182. if ( this.autoClose ) {
  21183. points.push( points[ 0 ] );
  21184. }
  21185. return points;
  21186. },
  21187. getPoints: function ( divisions ) {
  21188. divisions = divisions || 12;
  21189. var points = [], last;
  21190. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  21191. var curve = curves[ i ];
  21192. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  21193. : (curve && curve.isLineCurve) ? 1
  21194. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  21195. : divisions;
  21196. var pts = curve.getPoints( resolution );
  21197. for ( var j = 0; j < pts.length; j++ ) {
  21198. var point = pts[ j ];
  21199. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  21200. points.push( point );
  21201. last = point;
  21202. }
  21203. }
  21204. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  21205. points.push( points[ 0 ] );
  21206. }
  21207. return points;
  21208. },
  21209. /**************************************************************
  21210. * Create Geometries Helpers
  21211. **************************************************************/
  21212. /// Generate geometry from path points (for Line or Points objects)
  21213. createPointsGeometry: function ( divisions ) {
  21214. var pts = this.getPoints( divisions );
  21215. return this.createGeometry( pts );
  21216. },
  21217. // Generate geometry from equidistant sampling along the path
  21218. createSpacedPointsGeometry: function ( divisions ) {
  21219. var pts = this.getSpacedPoints( divisions );
  21220. return this.createGeometry( pts );
  21221. },
  21222. createGeometry: function ( points ) {
  21223. var geometry = new Geometry();
  21224. for ( var i = 0, l = points.length; i < l; i ++ ) {
  21225. var point = points[ i ];
  21226. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  21227. }
  21228. return geometry;
  21229. }
  21230. } );
  21231. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21232. Curve.call( this );
  21233. this.aX = aX;
  21234. this.aY = aY;
  21235. this.xRadius = xRadius;
  21236. this.yRadius = yRadius;
  21237. this.aStartAngle = aStartAngle;
  21238. this.aEndAngle = aEndAngle;
  21239. this.aClockwise = aClockwise;
  21240. this.aRotation = aRotation || 0;
  21241. }
  21242. EllipseCurve.prototype = Object.create( Curve.prototype );
  21243. EllipseCurve.prototype.constructor = EllipseCurve;
  21244. EllipseCurve.prototype.isEllipseCurve = true;
  21245. EllipseCurve.prototype.getPoint = function ( t ) {
  21246. var twoPi = Math.PI * 2;
  21247. var deltaAngle = this.aEndAngle - this.aStartAngle;
  21248. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  21249. // ensures that deltaAngle is 0 .. 2 PI
  21250. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  21251. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  21252. if ( deltaAngle < Number.EPSILON ) {
  21253. if ( samePoints ) {
  21254. deltaAngle = 0;
  21255. } else {
  21256. deltaAngle = twoPi;
  21257. }
  21258. }
  21259. if ( this.aClockwise === true && ! samePoints ) {
  21260. if ( deltaAngle === twoPi ) {
  21261. deltaAngle = - twoPi;
  21262. } else {
  21263. deltaAngle = deltaAngle - twoPi;
  21264. }
  21265. }
  21266. var angle = this.aStartAngle + t * deltaAngle;
  21267. var x = this.aX + this.xRadius * Math.cos( angle );
  21268. var y = this.aY + this.yRadius * Math.sin( angle );
  21269. if ( this.aRotation !== 0 ) {
  21270. var cos = Math.cos( this.aRotation );
  21271. var sin = Math.sin( this.aRotation );
  21272. var tx = x - this.aX;
  21273. var ty = y - this.aY;
  21274. // Rotate the point about the center of the ellipse.
  21275. x = tx * cos - ty * sin + this.aX;
  21276. y = tx * sin + ty * cos + this.aY;
  21277. }
  21278. return new Vector2( x, y );
  21279. };
  21280. function SplineCurve( points /* array of Vector2 */ ) {
  21281. Curve.call( this );
  21282. this.points = ( points === undefined ) ? [] : points;
  21283. }
  21284. SplineCurve.prototype = Object.create( Curve.prototype );
  21285. SplineCurve.prototype.constructor = SplineCurve;
  21286. SplineCurve.prototype.isSplineCurve = true;
  21287. SplineCurve.prototype.getPoint = function ( t ) {
  21288. var points = this.points;
  21289. var point = ( points.length - 1 ) * t;
  21290. var intPoint = Math.floor( point );
  21291. var weight = point - intPoint;
  21292. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  21293. var point1 = points[ intPoint ];
  21294. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21295. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21296. return new Vector2(
  21297. CatmullRom( weight, point0.x, point1.x, point2.x, point3.x ),
  21298. CatmullRom( weight, point0.y, point1.y, point2.y, point3.y )
  21299. );
  21300. };
  21301. function CubicBezierCurve( v0, v1, v2, v3 ) {
  21302. Curve.call( this );
  21303. this.v0 = v0;
  21304. this.v1 = v1;
  21305. this.v2 = v2;
  21306. this.v3 = v3;
  21307. }
  21308. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  21309. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  21310. CubicBezierCurve.prototype.getPoint = function ( t ) {
  21311. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21312. return new Vector2(
  21313. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21314. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  21315. );
  21316. };
  21317. function QuadraticBezierCurve( v0, v1, v2 ) {
  21318. Curve.call( this );
  21319. this.v0 = v0;
  21320. this.v1 = v1;
  21321. this.v2 = v2;
  21322. }
  21323. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  21324. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  21325. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  21326. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21327. return new Vector2(
  21328. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21329. QuadraticBezier( t, v0.y, v1.y, v2.y )
  21330. );
  21331. };
  21332. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  21333. fromPoints: function ( vectors ) {
  21334. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  21335. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  21336. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  21337. }
  21338. },
  21339. moveTo: function ( x, y ) {
  21340. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  21341. },
  21342. lineTo: function ( x, y ) {
  21343. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  21344. this.curves.push( curve );
  21345. this.currentPoint.set( x, y );
  21346. },
  21347. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  21348. var curve = new QuadraticBezierCurve(
  21349. this.currentPoint.clone(),
  21350. new Vector2( aCPx, aCPy ),
  21351. new Vector2( aX, aY )
  21352. );
  21353. this.curves.push( curve );
  21354. this.currentPoint.set( aX, aY );
  21355. },
  21356. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21357. var curve = new CubicBezierCurve(
  21358. this.currentPoint.clone(),
  21359. new Vector2( aCP1x, aCP1y ),
  21360. new Vector2( aCP2x, aCP2y ),
  21361. new Vector2( aX, aY )
  21362. );
  21363. this.curves.push( curve );
  21364. this.currentPoint.set( aX, aY );
  21365. },
  21366. splineThru: function ( pts /*Array of Vector*/ ) {
  21367. var npts = [ this.currentPoint.clone() ].concat( pts );
  21368. var curve = new SplineCurve( npts );
  21369. this.curves.push( curve );
  21370. this.currentPoint.copy( pts[ pts.length - 1 ] );
  21371. },
  21372. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21373. var x0 = this.currentPoint.x;
  21374. var y0 = this.currentPoint.y;
  21375. this.absarc( aX + x0, aY + y0, aRadius,
  21376. aStartAngle, aEndAngle, aClockwise );
  21377. },
  21378. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21379. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21380. },
  21381. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21382. var x0 = this.currentPoint.x;
  21383. var y0 = this.currentPoint.y;
  21384. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21385. },
  21386. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21387. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21388. if ( this.curves.length > 0 ) {
  21389. // if a previous curve is present, attempt to join
  21390. var firstPoint = curve.getPoint( 0 );
  21391. if ( ! firstPoint.equals( this.currentPoint ) ) {
  21392. this.lineTo( firstPoint.x, firstPoint.y );
  21393. }
  21394. }
  21395. this.curves.push( curve );
  21396. var lastPoint = curve.getPoint( 1 );
  21397. this.currentPoint.copy( lastPoint );
  21398. }
  21399. } );
  21400. /**
  21401. * @author zz85 / http://www.lab4games.net/zz85/blog
  21402. * Creates free form 2d path using series of points, lines or curves.
  21403. **/
  21404. function Path( points ) {
  21405. CurvePath.call( this );
  21406. this.currentPoint = new Vector2();
  21407. if ( points ) {
  21408. this.fromPoints( points );
  21409. }
  21410. }
  21411. Path.prototype = PathPrototype;
  21412. PathPrototype.constructor = Path;
  21413. /**
  21414. * @author zz85 / http://www.lab4games.net/zz85/blog
  21415. * Defines a 2d shape plane using paths.
  21416. **/
  21417. // STEP 1 Create a path.
  21418. // STEP 2 Turn path into shape.
  21419. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  21420. // STEP 3a - Extract points from each shape, turn to vertices
  21421. // STEP 3b - Triangulate each shape, add faces.
  21422. function Shape() {
  21423. Path.apply( this, arguments );
  21424. this.holes = [];
  21425. }
  21426. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  21427. constructor: Shape,
  21428. getPointsHoles: function ( divisions ) {
  21429. var holesPts = [];
  21430. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  21431. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  21432. }
  21433. return holesPts;
  21434. },
  21435. // Get points of shape and holes (keypoints based on segments parameter)
  21436. extractAllPoints: function ( divisions ) {
  21437. return {
  21438. shape: this.getPoints( divisions ),
  21439. holes: this.getPointsHoles( divisions )
  21440. };
  21441. },
  21442. extractPoints: function ( divisions ) {
  21443. return this.extractAllPoints( divisions );
  21444. }
  21445. } );
  21446. /**
  21447. * @author zz85 / http://www.lab4games.net/zz85/blog
  21448. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  21449. **/
  21450. function ShapePath() {
  21451. this.subPaths = [];
  21452. this.currentPath = null;
  21453. }
  21454. Object.assign( ShapePath.prototype, {
  21455. moveTo: function ( x, y ) {
  21456. this.currentPath = new Path();
  21457. this.subPaths.push( this.currentPath );
  21458. this.currentPath.moveTo( x, y );
  21459. },
  21460. lineTo: function ( x, y ) {
  21461. this.currentPath.lineTo( x, y );
  21462. },
  21463. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  21464. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21465. },
  21466. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21467. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21468. },
  21469. splineThru: function ( pts ) {
  21470. this.currentPath.splineThru( pts );
  21471. },
  21472. toShapes: function ( isCCW, noHoles ) {
  21473. function toShapesNoHoles( inSubpaths ) {
  21474. var shapes = [];
  21475. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21476. var tmpPath = inSubpaths[ i ];
  21477. var tmpShape = new Shape();
  21478. tmpShape.curves = tmpPath.curves;
  21479. shapes.push( tmpShape );
  21480. }
  21481. return shapes;
  21482. }
  21483. function isPointInsidePolygon( inPt, inPolygon ) {
  21484. var polyLen = inPolygon.length;
  21485. // inPt on polygon contour => immediate success or
  21486. // toggling of inside/outside at every single! intersection point of an edge
  21487. // with the horizontal line through inPt, left of inPt
  21488. // not counting lowerY endpoints of edges and whole edges on that line
  21489. var inside = false;
  21490. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21491. var edgeLowPt = inPolygon[ p ];
  21492. var edgeHighPt = inPolygon[ q ];
  21493. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  21494. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  21495. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21496. // not parallel
  21497. if ( edgeDy < 0 ) {
  21498. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21499. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21500. }
  21501. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21502. if ( inPt.y === edgeLowPt.y ) {
  21503. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21504. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21505. } else {
  21506. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21507. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21508. if ( perpEdge < 0 ) continue;
  21509. inside = ! inside; // true intersection left of inPt
  21510. }
  21511. } else {
  21512. // parallel or collinear
  21513. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21514. // edge lies on the same horizontal line as inPt
  21515. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21516. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21517. // continue;
  21518. }
  21519. }
  21520. return inside;
  21521. }
  21522. var isClockWise = ShapeUtils.isClockWise;
  21523. var subPaths = this.subPaths;
  21524. if ( subPaths.length === 0 ) return [];
  21525. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  21526. var solid, tmpPath, tmpShape, shapes = [];
  21527. if ( subPaths.length === 1 ) {
  21528. tmpPath = subPaths[ 0 ];
  21529. tmpShape = new Shape();
  21530. tmpShape.curves = tmpPath.curves;
  21531. shapes.push( tmpShape );
  21532. return shapes;
  21533. }
  21534. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21535. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21536. // console.log("Holes first", holesFirst);
  21537. var betterShapeHoles = [];
  21538. var newShapes = [];
  21539. var newShapeHoles = [];
  21540. var mainIdx = 0;
  21541. var tmpPoints;
  21542. newShapes[ mainIdx ] = undefined;
  21543. newShapeHoles[ mainIdx ] = [];
  21544. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  21545. tmpPath = subPaths[ i ];
  21546. tmpPoints = tmpPath.getPoints();
  21547. solid = isClockWise( tmpPoints );
  21548. solid = isCCW ? ! solid : solid;
  21549. if ( solid ) {
  21550. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21551. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21552. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21553. if ( holesFirst ) mainIdx ++;
  21554. newShapeHoles[ mainIdx ] = [];
  21555. //console.log('cw', i);
  21556. } else {
  21557. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21558. //console.log('ccw', i);
  21559. }
  21560. }
  21561. // only Holes? -> probably all Shapes with wrong orientation
  21562. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21563. if ( newShapes.length > 1 ) {
  21564. var ambiguous = false;
  21565. var toChange = [];
  21566. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21567. betterShapeHoles[ sIdx ] = [];
  21568. }
  21569. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21570. var sho = newShapeHoles[ sIdx ];
  21571. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21572. var ho = sho[ hIdx ];
  21573. var hole_unassigned = true;
  21574. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21575. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21576. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  21577. if ( hole_unassigned ) {
  21578. hole_unassigned = false;
  21579. betterShapeHoles[ s2Idx ].push( ho );
  21580. } else {
  21581. ambiguous = true;
  21582. }
  21583. }
  21584. }
  21585. if ( hole_unassigned ) {
  21586. betterShapeHoles[ sIdx ].push( ho );
  21587. }
  21588. }
  21589. }
  21590. // console.log("ambiguous: ", ambiguous);
  21591. if ( toChange.length > 0 ) {
  21592. // console.log("to change: ", toChange);
  21593. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  21594. }
  21595. }
  21596. var tmpHoles;
  21597. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  21598. tmpShape = newShapes[ i ].s;
  21599. shapes.push( tmpShape );
  21600. tmpHoles = newShapeHoles[ i ];
  21601. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21602. tmpShape.holes.push( tmpHoles[ j ].h );
  21603. }
  21604. }
  21605. //console.log("shape", shapes);
  21606. return shapes;
  21607. }
  21608. } );
  21609. /**
  21610. * @author zz85 / http://www.lab4games.net/zz85/blog
  21611. * @author mrdoob / http://mrdoob.com/
  21612. */
  21613. function Font( data ) {
  21614. this.data = data;
  21615. }
  21616. Object.assign( Font.prototype, {
  21617. isFont: true,
  21618. generateShapes: function ( text, size, divisions ) {
  21619. function createPaths( text ) {
  21620. var chars = String( text ).split( '' );
  21621. var scale = size / data.resolution;
  21622. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  21623. var offsetX = 0, offsetY = 0;
  21624. var paths = [];
  21625. for ( var i = 0; i < chars.length; i ++ ) {
  21626. var char = chars[ i ];
  21627. if ( char === '\n' ) {
  21628. offsetX = 0;
  21629. offsetY -= line_height;
  21630. } else {
  21631. var ret = createPath( char, scale, offsetX, offsetY );
  21632. offsetX += ret.offsetX;
  21633. paths.push( ret.path );
  21634. }
  21635. }
  21636. return paths;
  21637. }
  21638. function createPath( c, scale, offsetX, offsetY ) {
  21639. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  21640. if ( ! glyph ) return;
  21641. var path = new ShapePath();
  21642. var pts = [];
  21643. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  21644. if ( glyph.o ) {
  21645. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  21646. for ( var i = 0, l = outline.length; i < l; ) {
  21647. var action = outline[ i ++ ];
  21648. switch ( action ) {
  21649. case 'm': // moveTo
  21650. x = outline[ i ++ ] * scale + offsetX;
  21651. y = outline[ i ++ ] * scale + offsetY;
  21652. path.moveTo( x, y );
  21653. break;
  21654. case 'l': // lineTo
  21655. x = outline[ i ++ ] * scale + offsetX;
  21656. y = outline[ i ++ ] * scale + offsetY;
  21657. path.lineTo( x, y );
  21658. break;
  21659. case 'q': // quadraticCurveTo
  21660. cpx = outline[ i ++ ] * scale + offsetX;
  21661. cpy = outline[ i ++ ] * scale + offsetY;
  21662. cpx1 = outline[ i ++ ] * scale + offsetX;
  21663. cpy1 = outline[ i ++ ] * scale + offsetY;
  21664. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  21665. laste = pts[ pts.length - 1 ];
  21666. if ( laste ) {
  21667. cpx0 = laste.x;
  21668. cpy0 = laste.y;
  21669. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21670. var t = i2 / divisions;
  21671. QuadraticBezier( t, cpx0, cpx1, cpx );
  21672. QuadraticBezier( t, cpy0, cpy1, cpy );
  21673. }
  21674. }
  21675. break;
  21676. case 'b': // bezierCurveTo
  21677. cpx = outline[ i ++ ] * scale + offsetX;
  21678. cpy = outline[ i ++ ] * scale + offsetY;
  21679. cpx1 = outline[ i ++ ] * scale + offsetX;
  21680. cpy1 = outline[ i ++ ] * scale + offsetY;
  21681. cpx2 = outline[ i ++ ] * scale + offsetX;
  21682. cpy2 = outline[ i ++ ] * scale + offsetY;
  21683. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  21684. laste = pts[ pts.length - 1 ];
  21685. if ( laste ) {
  21686. cpx0 = laste.x;
  21687. cpy0 = laste.y;
  21688. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21689. var t = i2 / divisions;
  21690. CubicBezier( t, cpx0, cpx1, cpx2, cpx );
  21691. CubicBezier( t, cpy0, cpy1, cpy2, cpy );
  21692. }
  21693. }
  21694. break;
  21695. }
  21696. }
  21697. }
  21698. return { offsetX: glyph.ha * scale, path: path };
  21699. }
  21700. //
  21701. if ( size === undefined ) size = 100;
  21702. if ( divisions === undefined ) divisions = 4;
  21703. var data = this.data;
  21704. var paths = createPaths( text );
  21705. var shapes = [];
  21706. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  21707. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  21708. }
  21709. return shapes;
  21710. }
  21711. } );
  21712. /**
  21713. * @author mrdoob / http://mrdoob.com/
  21714. */
  21715. function FontLoader( manager ) {
  21716. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21717. }
  21718. Object.assign( FontLoader.prototype, {
  21719. load: function ( url, onLoad, onProgress, onError ) {
  21720. var scope = this;
  21721. var loader = new FileLoader( this.manager );
  21722. loader.load( url, function ( text ) {
  21723. var json;
  21724. try {
  21725. json = JSON.parse( text );
  21726. } catch ( e ) {
  21727. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  21728. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  21729. }
  21730. var font = scope.parse( json );
  21731. if ( onLoad ) onLoad( font );
  21732. }, onProgress, onError );
  21733. },
  21734. parse: function ( json ) {
  21735. return new Font( json );
  21736. }
  21737. } );
  21738. var context;
  21739. var AudioContext = {
  21740. getContext: function () {
  21741. if ( context === undefined ) {
  21742. context = new ( window.AudioContext || window.webkitAudioContext )();
  21743. }
  21744. return context;
  21745. },
  21746. setContext: function ( value ) {
  21747. context = value;
  21748. }
  21749. };
  21750. /**
  21751. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21752. */
  21753. function AudioLoader( manager ) {
  21754. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21755. }
  21756. Object.assign( AudioLoader.prototype, {
  21757. load: function ( url, onLoad, onProgress, onError ) {
  21758. var loader = new FileLoader( this.manager );
  21759. loader.setResponseType( 'arraybuffer' );
  21760. loader.load( url, function ( buffer ) {
  21761. var context = AudioContext.getContext();
  21762. context.decodeAudioData( buffer, function ( audioBuffer ) {
  21763. onLoad( audioBuffer );
  21764. } );
  21765. }, onProgress, onError );
  21766. }
  21767. } );
  21768. /**
  21769. * @author mrdoob / http://mrdoob.com/
  21770. */
  21771. function StereoCamera() {
  21772. this.type = 'StereoCamera';
  21773. this.aspect = 1;
  21774. this.eyeSep = 0.064;
  21775. this.cameraL = new PerspectiveCamera();
  21776. this.cameraL.layers.enable( 1 );
  21777. this.cameraL.matrixAutoUpdate = false;
  21778. this.cameraR = new PerspectiveCamera();
  21779. this.cameraR.layers.enable( 2 );
  21780. this.cameraR.matrixAutoUpdate = false;
  21781. }
  21782. Object.assign( StereoCamera.prototype, {
  21783. update: ( function () {
  21784. var instance, focus, fov, aspect, near, far, zoom, eyeSep;
  21785. var eyeRight = new Matrix4();
  21786. var eyeLeft = new Matrix4();
  21787. return function update( camera ) {
  21788. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  21789. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  21790. far !== camera.far || zoom !== camera.zoom || eyeSep !== this.eyeSep;
  21791. if ( needsUpdate ) {
  21792. instance = this;
  21793. focus = camera.focus;
  21794. fov = camera.fov;
  21795. aspect = camera.aspect * this.aspect;
  21796. near = camera.near;
  21797. far = camera.far;
  21798. zoom = camera.zoom;
  21799. // Off-axis stereoscopic effect based on
  21800. // http://paulbourke.net/stereographics/stereorender/
  21801. var projectionMatrix = camera.projectionMatrix.clone();
  21802. eyeSep = this.eyeSep / 2;
  21803. var eyeSepOnProjection = eyeSep * near / focus;
  21804. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  21805. var xmin, xmax;
  21806. // translate xOffset
  21807. eyeLeft.elements[ 12 ] = - eyeSep;
  21808. eyeRight.elements[ 12 ] = eyeSep;
  21809. // for left eye
  21810. xmin = - ymax * aspect + eyeSepOnProjection;
  21811. xmax = ymax * aspect + eyeSepOnProjection;
  21812. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21813. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21814. this.cameraL.projectionMatrix.copy( projectionMatrix );
  21815. // for right eye
  21816. xmin = - ymax * aspect - eyeSepOnProjection;
  21817. xmax = ymax * aspect - eyeSepOnProjection;
  21818. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21819. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21820. this.cameraR.projectionMatrix.copy( projectionMatrix );
  21821. }
  21822. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  21823. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  21824. };
  21825. } )()
  21826. } );
  21827. /**
  21828. * Camera for rendering cube maps
  21829. * - renders scene into axis-aligned cube
  21830. *
  21831. * @author alteredq / http://alteredqualia.com/
  21832. */
  21833. function CubeCamera( near, far, cubeResolution ) {
  21834. Object3D.call( this );
  21835. this.type = 'CubeCamera';
  21836. var fov = 90, aspect = 1;
  21837. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  21838. cameraPX.up.set( 0, - 1, 0 );
  21839. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  21840. this.add( cameraPX );
  21841. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  21842. cameraNX.up.set( 0, - 1, 0 );
  21843. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  21844. this.add( cameraNX );
  21845. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  21846. cameraPY.up.set( 0, 0, 1 );
  21847. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  21848. this.add( cameraPY );
  21849. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  21850. cameraNY.up.set( 0, 0, - 1 );
  21851. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  21852. this.add( cameraNY );
  21853. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  21854. cameraPZ.up.set( 0, - 1, 0 );
  21855. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  21856. this.add( cameraPZ );
  21857. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  21858. cameraNZ.up.set( 0, - 1, 0 );
  21859. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  21860. this.add( cameraNZ );
  21861. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  21862. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  21863. this.renderTarget.texture.name = "CubeCamera";
  21864. this.updateCubeMap = function ( renderer, scene ) {
  21865. if ( this.parent === null ) this.updateMatrixWorld();
  21866. var renderTarget = this.renderTarget;
  21867. var generateMipmaps = renderTarget.texture.generateMipmaps;
  21868. renderTarget.texture.generateMipmaps = false;
  21869. renderTarget.activeCubeFace = 0;
  21870. renderer.render( scene, cameraPX, renderTarget );
  21871. renderTarget.activeCubeFace = 1;
  21872. renderer.render( scene, cameraNX, renderTarget );
  21873. renderTarget.activeCubeFace = 2;
  21874. renderer.render( scene, cameraPY, renderTarget );
  21875. renderTarget.activeCubeFace = 3;
  21876. renderer.render( scene, cameraNY, renderTarget );
  21877. renderTarget.activeCubeFace = 4;
  21878. renderer.render( scene, cameraPZ, renderTarget );
  21879. renderTarget.texture.generateMipmaps = generateMipmaps;
  21880. renderTarget.activeCubeFace = 5;
  21881. renderer.render( scene, cameraNZ, renderTarget );
  21882. renderer.setRenderTarget( null );
  21883. };
  21884. }
  21885. CubeCamera.prototype = Object.create( Object3D.prototype );
  21886. CubeCamera.prototype.constructor = CubeCamera;
  21887. /**
  21888. * @author mrdoob / http://mrdoob.com/
  21889. */
  21890. function AudioListener() {
  21891. Object3D.call( this );
  21892. this.type = 'AudioListener';
  21893. this.context = AudioContext.getContext();
  21894. this.gain = this.context.createGain();
  21895. this.gain.connect( this.context.destination );
  21896. this.filter = null;
  21897. }
  21898. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21899. constructor: AudioListener,
  21900. getInput: function () {
  21901. return this.gain;
  21902. },
  21903. removeFilter: function ( ) {
  21904. if ( this.filter !== null ) {
  21905. this.gain.disconnect( this.filter );
  21906. this.filter.disconnect( this.context.destination );
  21907. this.gain.connect( this.context.destination );
  21908. this.filter = null;
  21909. }
  21910. },
  21911. getFilter: function () {
  21912. return this.filter;
  21913. },
  21914. setFilter: function ( value ) {
  21915. if ( this.filter !== null ) {
  21916. this.gain.disconnect( this.filter );
  21917. this.filter.disconnect( this.context.destination );
  21918. } else {
  21919. this.gain.disconnect( this.context.destination );
  21920. }
  21921. this.filter = value;
  21922. this.gain.connect( this.filter );
  21923. this.filter.connect( this.context.destination );
  21924. },
  21925. getMasterVolume: function () {
  21926. return this.gain.gain.value;
  21927. },
  21928. setMasterVolume: function ( value ) {
  21929. this.gain.gain.value = value;
  21930. },
  21931. updateMatrixWorld: ( function () {
  21932. var position = new Vector3();
  21933. var quaternion = new Quaternion();
  21934. var scale = new Vector3();
  21935. var orientation = new Vector3();
  21936. return function updateMatrixWorld( force ) {
  21937. Object3D.prototype.updateMatrixWorld.call( this, force );
  21938. var listener = this.context.listener;
  21939. var up = this.up;
  21940. this.matrixWorld.decompose( position, quaternion, scale );
  21941. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  21942. if ( listener.positionX ) {
  21943. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  21944. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  21945. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  21946. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  21947. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  21948. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  21949. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  21950. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  21951. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  21952. } else {
  21953. listener.setPosition( position.x, position.y, position.z );
  21954. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  21955. }
  21956. };
  21957. } )()
  21958. } );
  21959. /**
  21960. * @author mrdoob / http://mrdoob.com/
  21961. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21962. */
  21963. function Audio( listener ) {
  21964. Object3D.call( this );
  21965. this.type = 'Audio';
  21966. this.context = listener.context;
  21967. this.gain = this.context.createGain();
  21968. this.gain.connect( listener.getInput() );
  21969. this.autoplay = false;
  21970. this.buffer = null;
  21971. this.loop = false;
  21972. this.startTime = 0;
  21973. this.playbackRate = 1;
  21974. this.isPlaying = false;
  21975. this.hasPlaybackControl = true;
  21976. this.sourceType = 'empty';
  21977. this.filters = [];
  21978. }
  21979. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21980. constructor: Audio,
  21981. getOutput: function () {
  21982. return this.gain;
  21983. },
  21984. setNodeSource: function ( audioNode ) {
  21985. this.hasPlaybackControl = false;
  21986. this.sourceType = 'audioNode';
  21987. this.source = audioNode;
  21988. this.connect();
  21989. return this;
  21990. },
  21991. setBuffer: function ( audioBuffer ) {
  21992. this.buffer = audioBuffer;
  21993. this.sourceType = 'buffer';
  21994. if ( this.autoplay ) this.play();
  21995. return this;
  21996. },
  21997. play: function () {
  21998. if ( this.isPlaying === true ) {
  21999. console.warn( 'THREE.Audio: Audio is already playing.' );
  22000. return;
  22001. }
  22002. if ( this.hasPlaybackControl === false ) {
  22003. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22004. return;
  22005. }
  22006. var source = this.context.createBufferSource();
  22007. source.buffer = this.buffer;
  22008. source.loop = this.loop;
  22009. source.onended = this.onEnded.bind( this );
  22010. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  22011. source.start( 0, this.startTime );
  22012. this.isPlaying = true;
  22013. this.source = source;
  22014. return this.connect();
  22015. },
  22016. pause: function () {
  22017. if ( this.hasPlaybackControl === false ) {
  22018. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22019. return;
  22020. }
  22021. this.source.stop();
  22022. this.startTime = this.context.currentTime;
  22023. this.isPlaying = false;
  22024. return this;
  22025. },
  22026. stop: function () {
  22027. if ( this.hasPlaybackControl === false ) {
  22028. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22029. return;
  22030. }
  22031. this.source.stop();
  22032. this.startTime = 0;
  22033. this.isPlaying = false;
  22034. return this;
  22035. },
  22036. connect: function () {
  22037. if ( this.filters.length > 0 ) {
  22038. this.source.connect( this.filters[ 0 ] );
  22039. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  22040. this.filters[ i - 1 ].connect( this.filters[ i ] );
  22041. }
  22042. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  22043. } else {
  22044. this.source.connect( this.getOutput() );
  22045. }
  22046. return this;
  22047. },
  22048. disconnect: function () {
  22049. if ( this.filters.length > 0 ) {
  22050. this.source.disconnect( this.filters[ 0 ] );
  22051. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  22052. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  22053. }
  22054. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  22055. } else {
  22056. this.source.disconnect( this.getOutput() );
  22057. }
  22058. return this;
  22059. },
  22060. getFilters: function () {
  22061. return this.filters;
  22062. },
  22063. setFilters: function ( value ) {
  22064. if ( ! value ) value = [];
  22065. if ( this.isPlaying === true ) {
  22066. this.disconnect();
  22067. this.filters = value;
  22068. this.connect();
  22069. } else {
  22070. this.filters = value;
  22071. }
  22072. return this;
  22073. },
  22074. getFilter: function () {
  22075. return this.getFilters()[ 0 ];
  22076. },
  22077. setFilter: function ( filter ) {
  22078. return this.setFilters( filter ? [ filter ] : [] );
  22079. },
  22080. setPlaybackRate: function ( value ) {
  22081. if ( this.hasPlaybackControl === false ) {
  22082. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22083. return;
  22084. }
  22085. this.playbackRate = value;
  22086. if ( this.isPlaying === true ) {
  22087. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  22088. }
  22089. return this;
  22090. },
  22091. getPlaybackRate: function () {
  22092. return this.playbackRate;
  22093. },
  22094. onEnded: function () {
  22095. this.isPlaying = false;
  22096. },
  22097. getLoop: function () {
  22098. if ( this.hasPlaybackControl === false ) {
  22099. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22100. return false;
  22101. }
  22102. return this.loop;
  22103. },
  22104. setLoop: function ( value ) {
  22105. if ( this.hasPlaybackControl === false ) {
  22106. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22107. return;
  22108. }
  22109. this.loop = value;
  22110. if ( this.isPlaying === true ) {
  22111. this.source.loop = this.loop;
  22112. }
  22113. return this;
  22114. },
  22115. getVolume: function () {
  22116. return this.gain.gain.value;
  22117. },
  22118. setVolume: function ( value ) {
  22119. this.gain.gain.value = value;
  22120. return this;
  22121. }
  22122. } );
  22123. /**
  22124. * @author mrdoob / http://mrdoob.com/
  22125. */
  22126. function PositionalAudio( listener ) {
  22127. Audio.call( this, listener );
  22128. this.panner = this.context.createPanner();
  22129. this.panner.connect( this.gain );
  22130. }
  22131. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  22132. constructor: PositionalAudio,
  22133. getOutput: function () {
  22134. return this.panner;
  22135. },
  22136. getRefDistance: function () {
  22137. return this.panner.refDistance;
  22138. },
  22139. setRefDistance: function ( value ) {
  22140. this.panner.refDistance = value;
  22141. },
  22142. getRolloffFactor: function () {
  22143. return this.panner.rolloffFactor;
  22144. },
  22145. setRolloffFactor: function ( value ) {
  22146. this.panner.rolloffFactor = value;
  22147. },
  22148. getDistanceModel: function () {
  22149. return this.panner.distanceModel;
  22150. },
  22151. setDistanceModel: function ( value ) {
  22152. this.panner.distanceModel = value;
  22153. },
  22154. getMaxDistance: function () {
  22155. return this.panner.maxDistance;
  22156. },
  22157. setMaxDistance: function ( value ) {
  22158. this.panner.maxDistance = value;
  22159. },
  22160. updateMatrixWorld: ( function () {
  22161. var position = new Vector3();
  22162. return function updateMatrixWorld( force ) {
  22163. Object3D.prototype.updateMatrixWorld.call( this, force );
  22164. position.setFromMatrixPosition( this.matrixWorld );
  22165. this.panner.setPosition( position.x, position.y, position.z );
  22166. };
  22167. } )()
  22168. } );
  22169. /**
  22170. * @author mrdoob / http://mrdoob.com/
  22171. */
  22172. function AudioAnalyser( audio, fftSize ) {
  22173. this.analyser = audio.context.createAnalyser();
  22174. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  22175. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  22176. audio.getOutput().connect( this.analyser );
  22177. }
  22178. Object.assign( AudioAnalyser.prototype, {
  22179. getFrequencyData: function () {
  22180. this.analyser.getByteFrequencyData( this.data );
  22181. return this.data;
  22182. },
  22183. getAverageFrequency: function () {
  22184. var value = 0, data = this.getFrequencyData();
  22185. for ( var i = 0; i < data.length; i ++ ) {
  22186. value += data[ i ];
  22187. }
  22188. return value / data.length;
  22189. }
  22190. } );
  22191. /**
  22192. *
  22193. * Buffered scene graph property that allows weighted accumulation.
  22194. *
  22195. *
  22196. * @author Ben Houston / http://clara.io/
  22197. * @author David Sarno / http://lighthaus.us/
  22198. * @author tschw
  22199. */
  22200. function PropertyMixer( binding, typeName, valueSize ) {
  22201. this.binding = binding;
  22202. this.valueSize = valueSize;
  22203. var bufferType = Float64Array,
  22204. mixFunction;
  22205. switch ( typeName ) {
  22206. case 'quaternion':
  22207. mixFunction = this._slerp;
  22208. break;
  22209. case 'string':
  22210. case 'bool':
  22211. bufferType = Array;
  22212. mixFunction = this._select;
  22213. break;
  22214. default:
  22215. mixFunction = this._lerp;
  22216. }
  22217. this.buffer = new bufferType( valueSize * 4 );
  22218. // layout: [ incoming | accu0 | accu1 | orig ]
  22219. //
  22220. // interpolators can use .buffer as their .result
  22221. // the data then goes to 'incoming'
  22222. //
  22223. // 'accu0' and 'accu1' are used frame-interleaved for
  22224. // the cumulative result and are compared to detect
  22225. // changes
  22226. //
  22227. // 'orig' stores the original state of the property
  22228. this._mixBufferRegion = mixFunction;
  22229. this.cumulativeWeight = 0;
  22230. this.useCount = 0;
  22231. this.referenceCount = 0;
  22232. }
  22233. Object.assign( PropertyMixer.prototype, {
  22234. // accumulate data in the 'incoming' region into 'accu<i>'
  22235. accumulate: function ( accuIndex, weight ) {
  22236. // note: happily accumulating nothing when weight = 0, the caller knows
  22237. // the weight and shouldn't have made the call in the first place
  22238. var buffer = this.buffer,
  22239. stride = this.valueSize,
  22240. offset = accuIndex * stride + stride,
  22241. currentWeight = this.cumulativeWeight;
  22242. if ( currentWeight === 0 ) {
  22243. // accuN := incoming * weight
  22244. for ( var i = 0; i !== stride; ++ i ) {
  22245. buffer[ offset + i ] = buffer[ i ];
  22246. }
  22247. currentWeight = weight;
  22248. } else {
  22249. // accuN := accuN + incoming * weight
  22250. currentWeight += weight;
  22251. var mix = weight / currentWeight;
  22252. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  22253. }
  22254. this.cumulativeWeight = currentWeight;
  22255. },
  22256. // apply the state of 'accu<i>' to the binding when accus differ
  22257. apply: function ( accuIndex ) {
  22258. var stride = this.valueSize,
  22259. buffer = this.buffer,
  22260. offset = accuIndex * stride + stride,
  22261. weight = this.cumulativeWeight,
  22262. binding = this.binding;
  22263. this.cumulativeWeight = 0;
  22264. if ( weight < 1 ) {
  22265. // accuN := accuN + original * ( 1 - cumulativeWeight )
  22266. var originalValueOffset = stride * 3;
  22267. this._mixBufferRegion(
  22268. buffer, offset, originalValueOffset, 1 - weight, stride );
  22269. }
  22270. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  22271. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  22272. // value has changed -> update scene graph
  22273. binding.setValue( buffer, offset );
  22274. break;
  22275. }
  22276. }
  22277. },
  22278. // remember the state of the bound property and copy it to both accus
  22279. saveOriginalState: function () {
  22280. var binding = this.binding;
  22281. var buffer = this.buffer,
  22282. stride = this.valueSize,
  22283. originalValueOffset = stride * 3;
  22284. binding.getValue( buffer, originalValueOffset );
  22285. // accu[0..1] := orig -- initially detect changes against the original
  22286. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  22287. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  22288. }
  22289. this.cumulativeWeight = 0;
  22290. },
  22291. // apply the state previously taken via 'saveOriginalState' to the binding
  22292. restoreOriginalState: function () {
  22293. var originalValueOffset = this.valueSize * 3;
  22294. this.binding.setValue( this.buffer, originalValueOffset );
  22295. },
  22296. // mix functions
  22297. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  22298. if ( t >= 0.5 ) {
  22299. for ( var i = 0; i !== stride; ++ i ) {
  22300. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  22301. }
  22302. }
  22303. },
  22304. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  22305. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  22306. },
  22307. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  22308. var s = 1 - t;
  22309. for ( var i = 0; i !== stride; ++ i ) {
  22310. var j = dstOffset + i;
  22311. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  22312. }
  22313. }
  22314. } );
  22315. /**
  22316. *
  22317. * A reference to a real property in the scene graph.
  22318. *
  22319. *
  22320. * @author Ben Houston / http://clara.io/
  22321. * @author David Sarno / http://lighthaus.us/
  22322. * @author tschw
  22323. */
  22324. function Composite( targetGroup, path, optionalParsedPath ) {
  22325. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  22326. this._targetGroup = targetGroup;
  22327. this._bindings = targetGroup.subscribe_( path, parsedPath );
  22328. }
  22329. Object.assign( Composite.prototype, {
  22330. getValue: function ( array, offset ) {
  22331. this.bind(); // bind all binding
  22332. var firstValidIndex = this._targetGroup.nCachedObjects_,
  22333. binding = this._bindings[ firstValidIndex ];
  22334. // and only call .getValue on the first
  22335. if ( binding !== undefined ) binding.getValue( array, offset );
  22336. },
  22337. setValue: function ( array, offset ) {
  22338. var bindings = this._bindings;
  22339. for ( var i = this._targetGroup.nCachedObjects_,
  22340. n = bindings.length; i !== n; ++ i ) {
  22341. bindings[ i ].setValue( array, offset );
  22342. }
  22343. },
  22344. bind: function () {
  22345. var bindings = this._bindings;
  22346. for ( var i = this._targetGroup.nCachedObjects_,
  22347. n = bindings.length; i !== n; ++ i ) {
  22348. bindings[ i ].bind();
  22349. }
  22350. },
  22351. unbind: function () {
  22352. var bindings = this._bindings;
  22353. for ( var i = this._targetGroup.nCachedObjects_,
  22354. n = bindings.length; i !== n; ++ i ) {
  22355. bindings[ i ].unbind();
  22356. }
  22357. }
  22358. } );
  22359. function PropertyBinding( rootNode, path, parsedPath ) {
  22360. this.path = path;
  22361. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  22362. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  22363. this.rootNode = rootNode;
  22364. }
  22365. Object.assign( PropertyBinding, {
  22366. Composite: Composite,
  22367. create: function ( root, path, parsedPath ) {
  22368. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  22369. return new PropertyBinding( root, path, parsedPath );
  22370. } else {
  22371. return new PropertyBinding.Composite( root, path, parsedPath );
  22372. }
  22373. },
  22374. /**
  22375. * Replaces spaces with underscores and removes unsupported characters from
  22376. * node names, to ensure compatibility with parseTrackName().
  22377. *
  22378. * @param {string} name Node name to be sanitized.
  22379. * @return {string}
  22380. */
  22381. sanitizeNodeName: function ( name ) {
  22382. return name.replace( /\s/g, '_' ).replace( /[^\w-]/g, '' );
  22383. },
  22384. parseTrackName: function () {
  22385. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  22386. // be matched to parse the rest of the track name.
  22387. var directoryRe = /((?:[\w-]+[\/:])*)/;
  22388. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  22389. var nodeRe = /([\w-\.]+)?/;
  22390. // Object on target node, and accessor. Name may contain only word
  22391. // characters. Accessor may contain any character except closing bracket.
  22392. var objectRe = /(?:\.([\w-]+)(?:\[(.+)\])?)?/;
  22393. // Property and accessor. May contain only word characters. Accessor may
  22394. // contain any non-bracket characters.
  22395. var propertyRe = /\.([\w-]+)(?:\[(.+)\])?/;
  22396. var trackRe = new RegExp(''
  22397. + '^'
  22398. + directoryRe.source
  22399. + nodeRe.source
  22400. + objectRe.source
  22401. + propertyRe.source
  22402. + '$'
  22403. );
  22404. var supportedObjectNames = [ 'material', 'materials', 'bones' ];
  22405. return function ( trackName ) {
  22406. var matches = trackRe.exec( trackName );
  22407. if ( ! matches ) {
  22408. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  22409. }
  22410. var results = {
  22411. // directoryName: matches[ 1 ], // (tschw) currently unused
  22412. nodeName: matches[ 2 ],
  22413. objectName: matches[ 3 ],
  22414. objectIndex: matches[ 4 ],
  22415. propertyName: matches[ 5 ], // required
  22416. propertyIndex: matches[ 6 ]
  22417. };
  22418. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  22419. if ( lastDot !== undefined && lastDot !== -1 ) {
  22420. var objectName = results.nodeName.substring( lastDot + 1 );
  22421. // Object names must be checked against a whitelist. Otherwise, there
  22422. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  22423. // 'bar' could be the objectName, or part of a nodeName (which can
  22424. // include '.' characters).
  22425. if ( supportedObjectNames.indexOf( objectName ) !== -1 ) {
  22426. results.nodeName = results.nodeName.substring( 0, lastDot );
  22427. results.objectName = objectName;
  22428. }
  22429. }
  22430. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  22431. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  22432. }
  22433. return results;
  22434. };
  22435. }(),
  22436. findNode: function ( root, nodeName ) {
  22437. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  22438. return root;
  22439. }
  22440. // search into skeleton bones.
  22441. if ( root.skeleton ) {
  22442. var searchSkeleton = function ( skeleton ) {
  22443. for ( var i = 0; i < skeleton.bones.length; i ++ ) {
  22444. var bone = skeleton.bones[ i ];
  22445. if ( bone.name === nodeName ) {
  22446. return bone;
  22447. }
  22448. }
  22449. return null;
  22450. };
  22451. var bone = searchSkeleton( root.skeleton );
  22452. if ( bone ) {
  22453. return bone;
  22454. }
  22455. }
  22456. // search into node subtree.
  22457. if ( root.children ) {
  22458. var searchNodeSubtree = function ( children ) {
  22459. for ( var i = 0; i < children.length; i ++ ) {
  22460. var childNode = children[ i ];
  22461. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  22462. return childNode;
  22463. }
  22464. var result = searchNodeSubtree( childNode.children );
  22465. if ( result ) return result;
  22466. }
  22467. return null;
  22468. };
  22469. var subTreeNode = searchNodeSubtree( root.children );
  22470. if ( subTreeNode ) {
  22471. return subTreeNode;
  22472. }
  22473. }
  22474. return null;
  22475. }
  22476. } );
  22477. Object.assign( PropertyBinding.prototype, { // prototype, continued
  22478. // these are used to "bind" a nonexistent property
  22479. _getValue_unavailable: function () {},
  22480. _setValue_unavailable: function () {},
  22481. BindingType: {
  22482. Direct: 0,
  22483. EntireArray: 1,
  22484. ArrayElement: 2,
  22485. HasFromToArray: 3
  22486. },
  22487. Versioning: {
  22488. None: 0,
  22489. NeedsUpdate: 1,
  22490. MatrixWorldNeedsUpdate: 2
  22491. },
  22492. GetterByBindingType: [
  22493. function getValue_direct( buffer, offset ) {
  22494. buffer[ offset ] = this.node[ this.propertyName ];
  22495. },
  22496. function getValue_array( buffer, offset ) {
  22497. var source = this.resolvedProperty;
  22498. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  22499. buffer[ offset ++ ] = source[ i ];
  22500. }
  22501. },
  22502. function getValue_arrayElement( buffer, offset ) {
  22503. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  22504. },
  22505. function getValue_toArray( buffer, offset ) {
  22506. this.resolvedProperty.toArray( buffer, offset );
  22507. }
  22508. ],
  22509. SetterByBindingTypeAndVersioning: [
  22510. [
  22511. // Direct
  22512. function setValue_direct( buffer, offset ) {
  22513. this.node[ this.propertyName ] = buffer[ offset ];
  22514. },
  22515. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  22516. this.node[ this.propertyName ] = buffer[ offset ];
  22517. this.targetObject.needsUpdate = true;
  22518. },
  22519. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22520. this.node[ this.propertyName ] = buffer[ offset ];
  22521. this.targetObject.matrixWorldNeedsUpdate = true;
  22522. }
  22523. ], [
  22524. // EntireArray
  22525. function setValue_array( buffer, offset ) {
  22526. var dest = this.resolvedProperty;
  22527. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22528. dest[ i ] = buffer[ offset ++ ];
  22529. }
  22530. },
  22531. function setValue_array_setNeedsUpdate( buffer, offset ) {
  22532. var dest = this.resolvedProperty;
  22533. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22534. dest[ i ] = buffer[ offset ++ ];
  22535. }
  22536. this.targetObject.needsUpdate = true;
  22537. },
  22538. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22539. var dest = this.resolvedProperty;
  22540. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22541. dest[ i ] = buffer[ offset ++ ];
  22542. }
  22543. this.targetObject.matrixWorldNeedsUpdate = true;
  22544. }
  22545. ], [
  22546. // ArrayElement
  22547. function setValue_arrayElement( buffer, offset ) {
  22548. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22549. },
  22550. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  22551. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22552. this.targetObject.needsUpdate = true;
  22553. },
  22554. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22555. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22556. this.targetObject.matrixWorldNeedsUpdate = true;
  22557. }
  22558. ], [
  22559. // HasToFromArray
  22560. function setValue_fromArray( buffer, offset ) {
  22561. this.resolvedProperty.fromArray( buffer, offset );
  22562. },
  22563. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  22564. this.resolvedProperty.fromArray( buffer, offset );
  22565. this.targetObject.needsUpdate = true;
  22566. },
  22567. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22568. this.resolvedProperty.fromArray( buffer, offset );
  22569. this.targetObject.matrixWorldNeedsUpdate = true;
  22570. }
  22571. ]
  22572. ],
  22573. getValue: function getValue_unbound( targetArray, offset ) {
  22574. this.bind();
  22575. this.getValue( targetArray, offset );
  22576. // Note: This class uses a State pattern on a per-method basis:
  22577. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  22578. // prototype version of these methods with one that represents
  22579. // the bound state. When the property is not found, the methods
  22580. // become no-ops.
  22581. },
  22582. setValue: function getValue_unbound( sourceArray, offset ) {
  22583. this.bind();
  22584. this.setValue( sourceArray, offset );
  22585. },
  22586. // create getter / setter pair for a property in the scene graph
  22587. bind: function () {
  22588. var targetObject = this.node,
  22589. parsedPath = this.parsedPath,
  22590. objectName = parsedPath.objectName,
  22591. propertyName = parsedPath.propertyName,
  22592. propertyIndex = parsedPath.propertyIndex;
  22593. if ( ! targetObject ) {
  22594. targetObject = PropertyBinding.findNode(
  22595. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  22596. this.node = targetObject;
  22597. }
  22598. // set fail state so we can just 'return' on error
  22599. this.getValue = this._getValue_unavailable;
  22600. this.setValue = this._setValue_unavailable;
  22601. // ensure there is a value node
  22602. if ( ! targetObject ) {
  22603. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  22604. return;
  22605. }
  22606. if ( objectName ) {
  22607. var objectIndex = parsedPath.objectIndex;
  22608. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  22609. switch ( objectName ) {
  22610. case 'materials':
  22611. if ( ! targetObject.material ) {
  22612. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  22613. return;
  22614. }
  22615. if ( ! targetObject.material.materials ) {
  22616. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  22617. return;
  22618. }
  22619. targetObject = targetObject.material.materials;
  22620. break;
  22621. case 'bones':
  22622. if ( ! targetObject.skeleton ) {
  22623. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  22624. return;
  22625. }
  22626. // potential future optimization: skip this if propertyIndex is already an integer
  22627. // and convert the integer string to a true integer.
  22628. targetObject = targetObject.skeleton.bones;
  22629. // support resolving morphTarget names into indices.
  22630. for ( var i = 0; i < targetObject.length; i ++ ) {
  22631. if ( targetObject[ i ].name === objectIndex ) {
  22632. objectIndex = i;
  22633. break;
  22634. }
  22635. }
  22636. break;
  22637. default:
  22638. if ( targetObject[ objectName ] === undefined ) {
  22639. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  22640. return;
  22641. }
  22642. targetObject = targetObject[ objectName ];
  22643. }
  22644. if ( objectIndex !== undefined ) {
  22645. if ( targetObject[ objectIndex ] === undefined ) {
  22646. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  22647. return;
  22648. }
  22649. targetObject = targetObject[ objectIndex ];
  22650. }
  22651. }
  22652. // resolve property
  22653. var nodeProperty = targetObject[ propertyName ];
  22654. if ( nodeProperty === undefined ) {
  22655. var nodeName = parsedPath.nodeName;
  22656. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  22657. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  22658. return;
  22659. }
  22660. // determine versioning scheme
  22661. var versioning = this.Versioning.None;
  22662. if ( targetObject.needsUpdate !== undefined ) { // material
  22663. versioning = this.Versioning.NeedsUpdate;
  22664. this.targetObject = targetObject;
  22665. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  22666. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  22667. this.targetObject = targetObject;
  22668. }
  22669. // determine how the property gets bound
  22670. var bindingType = this.BindingType.Direct;
  22671. if ( propertyIndex !== undefined ) {
  22672. // access a sub element of the property array (only primitives are supported right now)
  22673. if ( propertyName === "morphTargetInfluences" ) {
  22674. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  22675. // support resolving morphTarget names into indices.
  22676. if ( ! targetObject.geometry ) {
  22677. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  22678. return;
  22679. }
  22680. if ( targetObject.geometry.isBufferGeometry ) {
  22681. if ( ! targetObject.geometry.morphAttributes ) {
  22682. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  22683. return;
  22684. }
  22685. for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {
  22686. if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {
  22687. propertyIndex = i;
  22688. break;
  22689. }
  22690. }
  22691. } else {
  22692. if ( ! targetObject.geometry.morphTargets ) {
  22693. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
  22694. return;
  22695. }
  22696. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  22697. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  22698. propertyIndex = i;
  22699. break;
  22700. }
  22701. }
  22702. }
  22703. }
  22704. bindingType = this.BindingType.ArrayElement;
  22705. this.resolvedProperty = nodeProperty;
  22706. this.propertyIndex = propertyIndex;
  22707. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  22708. // must use copy for Object3D.Euler/Quaternion
  22709. bindingType = this.BindingType.HasFromToArray;
  22710. this.resolvedProperty = nodeProperty;
  22711. } else if ( Array.isArray( nodeProperty ) ) {
  22712. bindingType = this.BindingType.EntireArray;
  22713. this.resolvedProperty = nodeProperty;
  22714. } else {
  22715. this.propertyName = propertyName;
  22716. }
  22717. // select getter / setter
  22718. this.getValue = this.GetterByBindingType[ bindingType ];
  22719. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  22720. },
  22721. unbind: function () {
  22722. this.node = null;
  22723. // back to the prototype version of getValue / setValue
  22724. // note: avoiding to mutate the shape of 'this' via 'delete'
  22725. this.getValue = this._getValue_unbound;
  22726. this.setValue = this._setValue_unbound;
  22727. }
  22728. } );
  22729. //!\ DECLARE ALIAS AFTER assign prototype !
  22730. Object.assign( PropertyBinding.prototype, {
  22731. // initial state of these methods that calls 'bind'
  22732. _getValue_unbound: PropertyBinding.prototype.getValue,
  22733. _setValue_unbound: PropertyBinding.prototype.setValue,
  22734. } );
  22735. /**
  22736. *
  22737. * A group of objects that receives a shared animation state.
  22738. *
  22739. * Usage:
  22740. *
  22741. * - Add objects you would otherwise pass as 'root' to the
  22742. * constructor or the .clipAction method of AnimationMixer.
  22743. *
  22744. * - Instead pass this object as 'root'.
  22745. *
  22746. * - You can also add and remove objects later when the mixer
  22747. * is running.
  22748. *
  22749. * Note:
  22750. *
  22751. * Objects of this class appear as one object to the mixer,
  22752. * so cache control of the individual objects must be done
  22753. * on the group.
  22754. *
  22755. * Limitation:
  22756. *
  22757. * - The animated properties must be compatible among the
  22758. * all objects in the group.
  22759. *
  22760. * - A single property can either be controlled through a
  22761. * target group or directly, but not both.
  22762. *
  22763. * @author tschw
  22764. */
  22765. function AnimationObjectGroup( var_args ) {
  22766. this.uuid = _Math.generateUUID();
  22767. // cached objects followed by the active ones
  22768. this._objects = Array.prototype.slice.call( arguments );
  22769. this.nCachedObjects_ = 0; // threshold
  22770. // note: read by PropertyBinding.Composite
  22771. var indices = {};
  22772. this._indicesByUUID = indices; // for bookkeeping
  22773. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22774. indices[ arguments[ i ].uuid ] = i;
  22775. }
  22776. this._paths = []; // inside: string
  22777. this._parsedPaths = []; // inside: { we don't care, here }
  22778. this._bindings = []; // inside: Array< PropertyBinding >
  22779. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  22780. var scope = this;
  22781. this.stats = {
  22782. objects: {
  22783. get total() { return scope._objects.length; },
  22784. get inUse() { return this.total - scope.nCachedObjects_; }
  22785. },
  22786. get bindingsPerObject() { return scope._bindings.length; }
  22787. };
  22788. }
  22789. Object.assign( AnimationObjectGroup.prototype, {
  22790. isAnimationObjectGroup: true,
  22791. add: function( var_args ) {
  22792. var objects = this._objects,
  22793. nObjects = objects.length,
  22794. nCachedObjects = this.nCachedObjects_,
  22795. indicesByUUID = this._indicesByUUID,
  22796. paths = this._paths,
  22797. parsedPaths = this._parsedPaths,
  22798. bindings = this._bindings,
  22799. nBindings = bindings.length;
  22800. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22801. var object = arguments[ i ],
  22802. uuid = object.uuid,
  22803. index = indicesByUUID[ uuid ],
  22804. knownObject = undefined;
  22805. if ( index === undefined ) {
  22806. // unknown object -> add it to the ACTIVE region
  22807. index = nObjects ++;
  22808. indicesByUUID[ uuid ] = index;
  22809. objects.push( object );
  22810. // accounting is done, now do the same for all bindings
  22811. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22812. bindings[ j ].push(
  22813. new PropertyBinding(
  22814. object, paths[ j ], parsedPaths[ j ] ) );
  22815. }
  22816. } else if ( index < nCachedObjects ) {
  22817. knownObject = objects[ index ];
  22818. // move existing object to the ACTIVE region
  22819. var firstActiveIndex = -- nCachedObjects,
  22820. lastCachedObject = objects[ firstActiveIndex ];
  22821. indicesByUUID[ lastCachedObject.uuid ] = index;
  22822. objects[ index ] = lastCachedObject;
  22823. indicesByUUID[ uuid ] = firstActiveIndex;
  22824. objects[ firstActiveIndex ] = object;
  22825. // accounting is done, now do the same for all bindings
  22826. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22827. var bindingsForPath = bindings[ j ],
  22828. lastCached = bindingsForPath[ firstActiveIndex ],
  22829. binding = bindingsForPath[ index ];
  22830. bindingsForPath[ index ] = lastCached;
  22831. if ( binding === undefined ) {
  22832. // since we do not bother to create new bindings
  22833. // for objects that are cached, the binding may
  22834. // or may not exist
  22835. binding = new PropertyBinding(
  22836. object, paths[ j ], parsedPaths[ j ] );
  22837. }
  22838. bindingsForPath[ firstActiveIndex ] = binding;
  22839. }
  22840. } else if ( objects[ index ] !== knownObject ) {
  22841. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  22842. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  22843. } // else the object is already where we want it to be
  22844. } // for arguments
  22845. this.nCachedObjects_ = nCachedObjects;
  22846. },
  22847. remove: function( var_args ) {
  22848. var objects = this._objects,
  22849. nCachedObjects = this.nCachedObjects_,
  22850. indicesByUUID = this._indicesByUUID,
  22851. bindings = this._bindings,
  22852. nBindings = bindings.length;
  22853. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22854. var object = arguments[ i ],
  22855. uuid = object.uuid,
  22856. index = indicesByUUID[ uuid ];
  22857. if ( index !== undefined && index >= nCachedObjects ) {
  22858. // move existing object into the CACHED region
  22859. var lastCachedIndex = nCachedObjects ++,
  22860. firstActiveObject = objects[ lastCachedIndex ];
  22861. indicesByUUID[ firstActiveObject.uuid ] = index;
  22862. objects[ index ] = firstActiveObject;
  22863. indicesByUUID[ uuid ] = lastCachedIndex;
  22864. objects[ lastCachedIndex ] = object;
  22865. // accounting is done, now do the same for all bindings
  22866. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22867. var bindingsForPath = bindings[ j ],
  22868. firstActive = bindingsForPath[ lastCachedIndex ],
  22869. binding = bindingsForPath[ index ];
  22870. bindingsForPath[ index ] = firstActive;
  22871. bindingsForPath[ lastCachedIndex ] = binding;
  22872. }
  22873. }
  22874. } // for arguments
  22875. this.nCachedObjects_ = nCachedObjects;
  22876. },
  22877. // remove & forget
  22878. uncache: function( var_args ) {
  22879. var objects = this._objects,
  22880. nObjects = objects.length,
  22881. nCachedObjects = this.nCachedObjects_,
  22882. indicesByUUID = this._indicesByUUID,
  22883. bindings = this._bindings,
  22884. nBindings = bindings.length;
  22885. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22886. var object = arguments[ i ],
  22887. uuid = object.uuid,
  22888. index = indicesByUUID[ uuid ];
  22889. if ( index !== undefined ) {
  22890. delete indicesByUUID[ uuid ];
  22891. if ( index < nCachedObjects ) {
  22892. // object is cached, shrink the CACHED region
  22893. var firstActiveIndex = -- nCachedObjects,
  22894. lastCachedObject = objects[ firstActiveIndex ],
  22895. lastIndex = -- nObjects,
  22896. lastObject = objects[ lastIndex ];
  22897. // last cached object takes this object's place
  22898. indicesByUUID[ lastCachedObject.uuid ] = index;
  22899. objects[ index ] = lastCachedObject;
  22900. // last object goes to the activated slot and pop
  22901. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  22902. objects[ firstActiveIndex ] = lastObject;
  22903. objects.pop();
  22904. // accounting is done, now do the same for all bindings
  22905. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22906. var bindingsForPath = bindings[ j ],
  22907. lastCached = bindingsForPath[ firstActiveIndex ],
  22908. last = bindingsForPath[ lastIndex ];
  22909. bindingsForPath[ index ] = lastCached;
  22910. bindingsForPath[ firstActiveIndex ] = last;
  22911. bindingsForPath.pop();
  22912. }
  22913. } else {
  22914. // object is active, just swap with the last and pop
  22915. var lastIndex = -- nObjects,
  22916. lastObject = objects[ lastIndex ];
  22917. indicesByUUID[ lastObject.uuid ] = index;
  22918. objects[ index ] = lastObject;
  22919. objects.pop();
  22920. // accounting is done, now do the same for all bindings
  22921. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22922. var bindingsForPath = bindings[ j ];
  22923. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  22924. bindingsForPath.pop();
  22925. }
  22926. } // cached or active
  22927. } // if object is known
  22928. } // for arguments
  22929. this.nCachedObjects_ = nCachedObjects;
  22930. },
  22931. // Internal interface used by befriended PropertyBinding.Composite:
  22932. subscribe_: function ( path, parsedPath ) {
  22933. // returns an array of bindings for the given path that is changed
  22934. // according to the contained objects in the group
  22935. var indicesByPath = this._bindingsIndicesByPath,
  22936. index = indicesByPath[ path ],
  22937. bindings = this._bindings;
  22938. if ( index !== undefined ) return bindings[ index ];
  22939. var paths = this._paths,
  22940. parsedPaths = this._parsedPaths,
  22941. objects = this._objects,
  22942. nObjects = objects.length,
  22943. nCachedObjects = this.nCachedObjects_,
  22944. bindingsForPath = new Array( nObjects );
  22945. index = bindings.length;
  22946. indicesByPath[ path ] = index;
  22947. paths.push( path );
  22948. parsedPaths.push( parsedPath );
  22949. bindings.push( bindingsForPath );
  22950. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  22951. var object = objects[ i ];
  22952. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  22953. }
  22954. return bindingsForPath;
  22955. },
  22956. unsubscribe_: function ( path ) {
  22957. // tells the group to forget about a property path and no longer
  22958. // update the array previously obtained with 'subscribe_'
  22959. var indicesByPath = this._bindingsIndicesByPath,
  22960. index = indicesByPath[ path ];
  22961. if ( index !== undefined ) {
  22962. var paths = this._paths,
  22963. parsedPaths = this._parsedPaths,
  22964. bindings = this._bindings,
  22965. lastBindingsIndex = bindings.length - 1,
  22966. lastBindings = bindings[ lastBindingsIndex ],
  22967. lastBindingsPath = path[ lastBindingsIndex ];
  22968. indicesByPath[ lastBindingsPath ] = index;
  22969. bindings[ index ] = lastBindings;
  22970. bindings.pop();
  22971. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  22972. parsedPaths.pop();
  22973. paths[ index ] = paths[ lastBindingsIndex ];
  22974. paths.pop();
  22975. }
  22976. }
  22977. } );
  22978. /**
  22979. *
  22980. * Action provided by AnimationMixer for scheduling clip playback on specific
  22981. * objects.
  22982. *
  22983. * @author Ben Houston / http://clara.io/
  22984. * @author David Sarno / http://lighthaus.us/
  22985. * @author tschw
  22986. *
  22987. */
  22988. function AnimationAction( mixer, clip, localRoot ) {
  22989. this._mixer = mixer;
  22990. this._clip = clip;
  22991. this._localRoot = localRoot || null;
  22992. var tracks = clip.tracks,
  22993. nTracks = tracks.length,
  22994. interpolants = new Array( nTracks );
  22995. var interpolantSettings = {
  22996. endingStart: ZeroCurvatureEnding,
  22997. endingEnd: ZeroCurvatureEnding
  22998. };
  22999. for ( var i = 0; i !== nTracks; ++ i ) {
  23000. var interpolant = tracks[ i ].createInterpolant( null );
  23001. interpolants[ i ] = interpolant;
  23002. interpolant.settings = interpolantSettings;
  23003. }
  23004. this._interpolantSettings = interpolantSettings;
  23005. this._interpolants = interpolants; // bound by the mixer
  23006. // inside: PropertyMixer (managed by the mixer)
  23007. this._propertyBindings = new Array( nTracks );
  23008. this._cacheIndex = null; // for the memory manager
  23009. this._byClipCacheIndex = null; // for the memory manager
  23010. this._timeScaleInterpolant = null;
  23011. this._weightInterpolant = null;
  23012. this.loop = LoopRepeat;
  23013. this._loopCount = -1;
  23014. // global mixer time when the action is to be started
  23015. // it's set back to 'null' upon start of the action
  23016. this._startTime = null;
  23017. // scaled local time of the action
  23018. // gets clamped or wrapped to 0..clip.duration according to loop
  23019. this.time = 0;
  23020. this.timeScale = 1;
  23021. this._effectiveTimeScale = 1;
  23022. this.weight = 1;
  23023. this._effectiveWeight = 1;
  23024. this.repetitions = Infinity; // no. of repetitions when looping
  23025. this.paused = false; // true -> zero effective time scale
  23026. this.enabled = true; // false -> zero effective weight
  23027. this.clampWhenFinished = false; // keep feeding the last frame?
  23028. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  23029. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  23030. }
  23031. Object.assign( AnimationAction.prototype, {
  23032. // State & Scheduling
  23033. play: function() {
  23034. this._mixer._activateAction( this );
  23035. return this;
  23036. },
  23037. stop: function() {
  23038. this._mixer._deactivateAction( this );
  23039. return this.reset();
  23040. },
  23041. reset: function() {
  23042. this.paused = false;
  23043. this.enabled = true;
  23044. this.time = 0; // restart clip
  23045. this._loopCount = -1; // forget previous loops
  23046. this._startTime = null; // forget scheduling
  23047. return this.stopFading().stopWarping();
  23048. },
  23049. isRunning: function() {
  23050. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  23051. this._startTime === null && this._mixer._isActiveAction( this );
  23052. },
  23053. // return true when play has been called
  23054. isScheduled: function() {
  23055. return this._mixer._isActiveAction( this );
  23056. },
  23057. startAt: function( time ) {
  23058. this._startTime = time;
  23059. return this;
  23060. },
  23061. setLoop: function( mode, repetitions ) {
  23062. this.loop = mode;
  23063. this.repetitions = repetitions;
  23064. return this;
  23065. },
  23066. // Weight
  23067. // set the weight stopping any scheduled fading
  23068. // although .enabled = false yields an effective weight of zero, this
  23069. // method does *not* change .enabled, because it would be confusing
  23070. setEffectiveWeight: function( weight ) {
  23071. this.weight = weight;
  23072. // note: same logic as when updated at runtime
  23073. this._effectiveWeight = this.enabled ? weight : 0;
  23074. return this.stopFading();
  23075. },
  23076. // return the weight considering fading and .enabled
  23077. getEffectiveWeight: function() {
  23078. return this._effectiveWeight;
  23079. },
  23080. fadeIn: function( duration ) {
  23081. return this._scheduleFading( duration, 0, 1 );
  23082. },
  23083. fadeOut: function( duration ) {
  23084. return this._scheduleFading( duration, 1, 0 );
  23085. },
  23086. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  23087. fadeOutAction.fadeOut( duration );
  23088. this.fadeIn( duration );
  23089. if( warp ) {
  23090. var fadeInDuration = this._clip.duration,
  23091. fadeOutDuration = fadeOutAction._clip.duration,
  23092. startEndRatio = fadeOutDuration / fadeInDuration,
  23093. endStartRatio = fadeInDuration / fadeOutDuration;
  23094. fadeOutAction.warp( 1.0, startEndRatio, duration );
  23095. this.warp( endStartRatio, 1.0, duration );
  23096. }
  23097. return this;
  23098. },
  23099. crossFadeTo: function( fadeInAction, duration, warp ) {
  23100. return fadeInAction.crossFadeFrom( this, duration, warp );
  23101. },
  23102. stopFading: function() {
  23103. var weightInterpolant = this._weightInterpolant;
  23104. if ( weightInterpolant !== null ) {
  23105. this._weightInterpolant = null;
  23106. this._mixer._takeBackControlInterpolant( weightInterpolant );
  23107. }
  23108. return this;
  23109. },
  23110. // Time Scale Control
  23111. // set the time scale stopping any scheduled warping
  23112. // although .paused = true yields an effective time scale of zero, this
  23113. // method does *not* change .paused, because it would be confusing
  23114. setEffectiveTimeScale: function( timeScale ) {
  23115. this.timeScale = timeScale;
  23116. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  23117. return this.stopWarping();
  23118. },
  23119. // return the time scale considering warping and .paused
  23120. getEffectiveTimeScale: function() {
  23121. return this._effectiveTimeScale;
  23122. },
  23123. setDuration: function( duration ) {
  23124. this.timeScale = this._clip.duration / duration;
  23125. return this.stopWarping();
  23126. },
  23127. syncWith: function( action ) {
  23128. this.time = action.time;
  23129. this.timeScale = action.timeScale;
  23130. return this.stopWarping();
  23131. },
  23132. halt: function( duration ) {
  23133. return this.warp( this._effectiveTimeScale, 0, duration );
  23134. },
  23135. warp: function( startTimeScale, endTimeScale, duration ) {
  23136. var mixer = this._mixer, now = mixer.time,
  23137. interpolant = this._timeScaleInterpolant,
  23138. timeScale = this.timeScale;
  23139. if ( interpolant === null ) {
  23140. interpolant = mixer._lendControlInterpolant();
  23141. this._timeScaleInterpolant = interpolant;
  23142. }
  23143. var times = interpolant.parameterPositions,
  23144. values = interpolant.sampleValues;
  23145. times[ 0 ] = now;
  23146. times[ 1 ] = now + duration;
  23147. values[ 0 ] = startTimeScale / timeScale;
  23148. values[ 1 ] = endTimeScale / timeScale;
  23149. return this;
  23150. },
  23151. stopWarping: function() {
  23152. var timeScaleInterpolant = this._timeScaleInterpolant;
  23153. if ( timeScaleInterpolant !== null ) {
  23154. this._timeScaleInterpolant = null;
  23155. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  23156. }
  23157. return this;
  23158. },
  23159. // Object Accessors
  23160. getMixer: function() {
  23161. return this._mixer;
  23162. },
  23163. getClip: function() {
  23164. return this._clip;
  23165. },
  23166. getRoot: function() {
  23167. return this._localRoot || this._mixer._root;
  23168. },
  23169. // Interna
  23170. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  23171. // called by the mixer
  23172. if ( ! this.enabled ) {
  23173. // call ._updateWeight() to update ._effectiveWeight
  23174. this._updateWeight( time );
  23175. return;
  23176. }
  23177. var startTime = this._startTime;
  23178. if ( startTime !== null ) {
  23179. // check for scheduled start of action
  23180. var timeRunning = ( time - startTime ) * timeDirection;
  23181. if ( timeRunning < 0 || timeDirection === 0 ) {
  23182. return; // yet to come / don't decide when delta = 0
  23183. }
  23184. // start
  23185. this._startTime = null; // unschedule
  23186. deltaTime = timeDirection * timeRunning;
  23187. }
  23188. // apply time scale and advance time
  23189. deltaTime *= this._updateTimeScale( time );
  23190. var clipTime = this._updateTime( deltaTime );
  23191. // note: _updateTime may disable the action resulting in
  23192. // an effective weight of 0
  23193. var weight = this._updateWeight( time );
  23194. if ( weight > 0 ) {
  23195. var interpolants = this._interpolants;
  23196. var propertyMixers = this._propertyBindings;
  23197. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  23198. interpolants[ j ].evaluate( clipTime );
  23199. propertyMixers[ j ].accumulate( accuIndex, weight );
  23200. }
  23201. }
  23202. },
  23203. _updateWeight: function( time ) {
  23204. var weight = 0;
  23205. if ( this.enabled ) {
  23206. weight = this.weight;
  23207. var interpolant = this._weightInterpolant;
  23208. if ( interpolant !== null ) {
  23209. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  23210. weight *= interpolantValue;
  23211. if ( time > interpolant.parameterPositions[ 1 ] ) {
  23212. this.stopFading();
  23213. if ( interpolantValue === 0 ) {
  23214. // faded out, disable
  23215. this.enabled = false;
  23216. }
  23217. }
  23218. }
  23219. }
  23220. this._effectiveWeight = weight;
  23221. return weight;
  23222. },
  23223. _updateTimeScale: function( time ) {
  23224. var timeScale = 0;
  23225. if ( ! this.paused ) {
  23226. timeScale = this.timeScale;
  23227. var interpolant = this._timeScaleInterpolant;
  23228. if ( interpolant !== null ) {
  23229. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  23230. timeScale *= interpolantValue;
  23231. if ( time > interpolant.parameterPositions[ 1 ] ) {
  23232. this.stopWarping();
  23233. if ( timeScale === 0 ) {
  23234. // motion has halted, pause
  23235. this.paused = true;
  23236. } else {
  23237. // warp done - apply final time scale
  23238. this.timeScale = timeScale;
  23239. }
  23240. }
  23241. }
  23242. }
  23243. this._effectiveTimeScale = timeScale;
  23244. return timeScale;
  23245. },
  23246. _updateTime: function( deltaTime ) {
  23247. var time = this.time + deltaTime;
  23248. if ( deltaTime === 0 ) return time;
  23249. var duration = this._clip.duration,
  23250. loop = this.loop,
  23251. loopCount = this._loopCount;
  23252. if ( loop === LoopOnce ) {
  23253. if ( loopCount === -1 ) {
  23254. // just started
  23255. this._loopCount = 0;
  23256. this._setEndings( true, true, false );
  23257. }
  23258. handle_stop: {
  23259. if ( time >= duration ) {
  23260. time = duration;
  23261. } else if ( time < 0 ) {
  23262. time = 0;
  23263. } else break handle_stop;
  23264. if ( this.clampWhenFinished ) this.paused = true;
  23265. else this.enabled = false;
  23266. this._mixer.dispatchEvent( {
  23267. type: 'finished', action: this,
  23268. direction: deltaTime < 0 ? -1 : 1
  23269. } );
  23270. }
  23271. } else { // repetitive Repeat or PingPong
  23272. var pingPong = ( loop === LoopPingPong );
  23273. if ( loopCount === -1 ) {
  23274. // just started
  23275. if ( deltaTime >= 0 ) {
  23276. loopCount = 0;
  23277. this._setEndings(
  23278. true, this.repetitions === 0, pingPong );
  23279. } else {
  23280. // when looping in reverse direction, the initial
  23281. // transition through zero counts as a repetition,
  23282. // so leave loopCount at -1
  23283. this._setEndings(
  23284. this.repetitions === 0, true, pingPong );
  23285. }
  23286. }
  23287. if ( time >= duration || time < 0 ) {
  23288. // wrap around
  23289. var loopDelta = Math.floor( time / duration ); // signed
  23290. time -= duration * loopDelta;
  23291. loopCount += Math.abs( loopDelta );
  23292. var pending = this.repetitions - loopCount;
  23293. if ( pending < 0 ) {
  23294. // have to stop (switch state, clamp time, fire event)
  23295. if ( this.clampWhenFinished ) this.paused = true;
  23296. else this.enabled = false;
  23297. time = deltaTime > 0 ? duration : 0;
  23298. this._mixer.dispatchEvent( {
  23299. type: 'finished', action: this,
  23300. direction: deltaTime > 0 ? 1 : -1
  23301. } );
  23302. } else {
  23303. // keep running
  23304. if ( pending === 0 ) {
  23305. // entering the last round
  23306. var atStart = deltaTime < 0;
  23307. this._setEndings( atStart, ! atStart, pingPong );
  23308. } else {
  23309. this._setEndings( false, false, pingPong );
  23310. }
  23311. this._loopCount = loopCount;
  23312. this._mixer.dispatchEvent( {
  23313. type: 'loop', action: this, loopDelta: loopDelta
  23314. } );
  23315. }
  23316. }
  23317. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  23318. // invert time for the "pong round"
  23319. this.time = time;
  23320. return duration - time;
  23321. }
  23322. }
  23323. this.time = time;
  23324. return time;
  23325. },
  23326. _setEndings: function( atStart, atEnd, pingPong ) {
  23327. var settings = this._interpolantSettings;
  23328. if ( pingPong ) {
  23329. settings.endingStart = ZeroSlopeEnding;
  23330. settings.endingEnd = ZeroSlopeEnding;
  23331. } else {
  23332. // assuming for LoopOnce atStart == atEnd == true
  23333. if ( atStart ) {
  23334. settings.endingStart = this.zeroSlopeAtStart ?
  23335. ZeroSlopeEnding : ZeroCurvatureEnding;
  23336. } else {
  23337. settings.endingStart = WrapAroundEnding;
  23338. }
  23339. if ( atEnd ) {
  23340. settings.endingEnd = this.zeroSlopeAtEnd ?
  23341. ZeroSlopeEnding : ZeroCurvatureEnding;
  23342. } else {
  23343. settings.endingEnd = WrapAroundEnding;
  23344. }
  23345. }
  23346. },
  23347. _scheduleFading: function( duration, weightNow, weightThen ) {
  23348. var mixer = this._mixer, now = mixer.time,
  23349. interpolant = this._weightInterpolant;
  23350. if ( interpolant === null ) {
  23351. interpolant = mixer._lendControlInterpolant();
  23352. this._weightInterpolant = interpolant;
  23353. }
  23354. var times = interpolant.parameterPositions,
  23355. values = interpolant.sampleValues;
  23356. times[ 0 ] = now; values[ 0 ] = weightNow;
  23357. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  23358. return this;
  23359. }
  23360. } );
  23361. /**
  23362. *
  23363. * Player for AnimationClips.
  23364. *
  23365. *
  23366. * @author Ben Houston / http://clara.io/
  23367. * @author David Sarno / http://lighthaus.us/
  23368. * @author tschw
  23369. */
  23370. function AnimationMixer( root ) {
  23371. this._root = root;
  23372. this._initMemoryManager();
  23373. this._accuIndex = 0;
  23374. this.time = 0;
  23375. this.timeScale = 1.0;
  23376. }
  23377. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, {
  23378. _bindAction: function ( action, prototypeAction ) {
  23379. var root = action._localRoot || this._root,
  23380. tracks = action._clip.tracks,
  23381. nTracks = tracks.length,
  23382. bindings = action._propertyBindings,
  23383. interpolants = action._interpolants,
  23384. rootUuid = root.uuid,
  23385. bindingsByRoot = this._bindingsByRootAndName,
  23386. bindingsByName = bindingsByRoot[ rootUuid ];
  23387. if ( bindingsByName === undefined ) {
  23388. bindingsByName = {};
  23389. bindingsByRoot[ rootUuid ] = bindingsByName;
  23390. }
  23391. for ( var i = 0; i !== nTracks; ++ i ) {
  23392. var track = tracks[ i ],
  23393. trackName = track.name,
  23394. binding = bindingsByName[ trackName ];
  23395. if ( binding !== undefined ) {
  23396. bindings[ i ] = binding;
  23397. } else {
  23398. binding = bindings[ i ];
  23399. if ( binding !== undefined ) {
  23400. // existing binding, make sure the cache knows
  23401. if ( binding._cacheIndex === null ) {
  23402. ++ binding.referenceCount;
  23403. this._addInactiveBinding( binding, rootUuid, trackName );
  23404. }
  23405. continue;
  23406. }
  23407. var path = prototypeAction && prototypeAction.
  23408. _propertyBindings[ i ].binding.parsedPath;
  23409. binding = new PropertyMixer(
  23410. PropertyBinding.create( root, trackName, path ),
  23411. track.ValueTypeName, track.getValueSize() );
  23412. ++ binding.referenceCount;
  23413. this._addInactiveBinding( binding, rootUuid, trackName );
  23414. bindings[ i ] = binding;
  23415. }
  23416. interpolants[ i ].resultBuffer = binding.buffer;
  23417. }
  23418. },
  23419. _activateAction: function ( action ) {
  23420. if ( ! this._isActiveAction( action ) ) {
  23421. if ( action._cacheIndex === null ) {
  23422. // this action has been forgotten by the cache, but the user
  23423. // appears to be still using it -> rebind
  23424. var rootUuid = ( action._localRoot || this._root ).uuid,
  23425. clipUuid = action._clip.uuid,
  23426. actionsForClip = this._actionsByClip[ clipUuid ];
  23427. this._bindAction( action,
  23428. actionsForClip && actionsForClip.knownActions[ 0 ] );
  23429. this._addInactiveAction( action, clipUuid, rootUuid );
  23430. }
  23431. var bindings = action._propertyBindings;
  23432. // increment reference counts / sort out state
  23433. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23434. var binding = bindings[ i ];
  23435. if ( binding.useCount ++ === 0 ) {
  23436. this._lendBinding( binding );
  23437. binding.saveOriginalState();
  23438. }
  23439. }
  23440. this._lendAction( action );
  23441. }
  23442. },
  23443. _deactivateAction: function ( action ) {
  23444. if ( this._isActiveAction( action ) ) {
  23445. var bindings = action._propertyBindings;
  23446. // decrement reference counts / sort out state
  23447. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23448. var binding = bindings[ i ];
  23449. if ( -- binding.useCount === 0 ) {
  23450. binding.restoreOriginalState();
  23451. this._takeBackBinding( binding );
  23452. }
  23453. }
  23454. this._takeBackAction( action );
  23455. }
  23456. },
  23457. // Memory manager
  23458. _initMemoryManager: function () {
  23459. this._actions = []; // 'nActiveActions' followed by inactive ones
  23460. this._nActiveActions = 0;
  23461. this._actionsByClip = {};
  23462. // inside:
  23463. // {
  23464. // knownActions: Array< AnimationAction > - used as prototypes
  23465. // actionByRoot: AnimationAction - lookup
  23466. // }
  23467. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  23468. this._nActiveBindings = 0;
  23469. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  23470. this._controlInterpolants = []; // same game as above
  23471. this._nActiveControlInterpolants = 0;
  23472. var scope = this;
  23473. this.stats = {
  23474. actions: {
  23475. get total() { return scope._actions.length; },
  23476. get inUse() { return scope._nActiveActions; }
  23477. },
  23478. bindings: {
  23479. get total() { return scope._bindings.length; },
  23480. get inUse() { return scope._nActiveBindings; }
  23481. },
  23482. controlInterpolants: {
  23483. get total() { return scope._controlInterpolants.length; },
  23484. get inUse() { return scope._nActiveControlInterpolants; }
  23485. }
  23486. };
  23487. },
  23488. // Memory management for AnimationAction objects
  23489. _isActiveAction: function ( action ) {
  23490. var index = action._cacheIndex;
  23491. return index !== null && index < this._nActiveActions;
  23492. },
  23493. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  23494. var actions = this._actions,
  23495. actionsByClip = this._actionsByClip,
  23496. actionsForClip = actionsByClip[ clipUuid ];
  23497. if ( actionsForClip === undefined ) {
  23498. actionsForClip = {
  23499. knownActions: [ action ],
  23500. actionByRoot: {}
  23501. };
  23502. action._byClipCacheIndex = 0;
  23503. actionsByClip[ clipUuid ] = actionsForClip;
  23504. } else {
  23505. var knownActions = actionsForClip.knownActions;
  23506. action._byClipCacheIndex = knownActions.length;
  23507. knownActions.push( action );
  23508. }
  23509. action._cacheIndex = actions.length;
  23510. actions.push( action );
  23511. actionsForClip.actionByRoot[ rootUuid ] = action;
  23512. },
  23513. _removeInactiveAction: function ( action ) {
  23514. var actions = this._actions,
  23515. lastInactiveAction = actions[ actions.length - 1 ],
  23516. cacheIndex = action._cacheIndex;
  23517. lastInactiveAction._cacheIndex = cacheIndex;
  23518. actions[ cacheIndex ] = lastInactiveAction;
  23519. actions.pop();
  23520. action._cacheIndex = null;
  23521. var clipUuid = action._clip.uuid,
  23522. actionsByClip = this._actionsByClip,
  23523. actionsForClip = actionsByClip[ clipUuid ],
  23524. knownActionsForClip = actionsForClip.knownActions,
  23525. lastKnownAction =
  23526. knownActionsForClip[ knownActionsForClip.length - 1 ],
  23527. byClipCacheIndex = action._byClipCacheIndex;
  23528. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  23529. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  23530. knownActionsForClip.pop();
  23531. action._byClipCacheIndex = null;
  23532. var actionByRoot = actionsForClip.actionByRoot,
  23533. rootUuid = ( action._localRoot || this._root ).uuid;
  23534. delete actionByRoot[ rootUuid ];
  23535. if ( knownActionsForClip.length === 0 ) {
  23536. delete actionsByClip[ clipUuid ];
  23537. }
  23538. this._removeInactiveBindingsForAction( action );
  23539. },
  23540. _removeInactiveBindingsForAction: function ( action ) {
  23541. var bindings = action._propertyBindings;
  23542. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23543. var binding = bindings[ i ];
  23544. if ( -- binding.referenceCount === 0 ) {
  23545. this._removeInactiveBinding( binding );
  23546. }
  23547. }
  23548. },
  23549. _lendAction: function ( action ) {
  23550. // [ active actions | inactive actions ]
  23551. // [ active actions >| inactive actions ]
  23552. // s a
  23553. // <-swap->
  23554. // a s
  23555. var actions = this._actions,
  23556. prevIndex = action._cacheIndex,
  23557. lastActiveIndex = this._nActiveActions ++,
  23558. firstInactiveAction = actions[ lastActiveIndex ];
  23559. action._cacheIndex = lastActiveIndex;
  23560. actions[ lastActiveIndex ] = action;
  23561. firstInactiveAction._cacheIndex = prevIndex;
  23562. actions[ prevIndex ] = firstInactiveAction;
  23563. },
  23564. _takeBackAction: function ( action ) {
  23565. // [ active actions | inactive actions ]
  23566. // [ active actions |< inactive actions ]
  23567. // a s
  23568. // <-swap->
  23569. // s a
  23570. var actions = this._actions,
  23571. prevIndex = action._cacheIndex,
  23572. firstInactiveIndex = -- this._nActiveActions,
  23573. lastActiveAction = actions[ firstInactiveIndex ];
  23574. action._cacheIndex = firstInactiveIndex;
  23575. actions[ firstInactiveIndex ] = action;
  23576. lastActiveAction._cacheIndex = prevIndex;
  23577. actions[ prevIndex ] = lastActiveAction;
  23578. },
  23579. // Memory management for PropertyMixer objects
  23580. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  23581. var bindingsByRoot = this._bindingsByRootAndName,
  23582. bindingByName = bindingsByRoot[ rootUuid ],
  23583. bindings = this._bindings;
  23584. if ( bindingByName === undefined ) {
  23585. bindingByName = {};
  23586. bindingsByRoot[ rootUuid ] = bindingByName;
  23587. }
  23588. bindingByName[ trackName ] = binding;
  23589. binding._cacheIndex = bindings.length;
  23590. bindings.push( binding );
  23591. },
  23592. _removeInactiveBinding: function ( binding ) {
  23593. var bindings = this._bindings,
  23594. propBinding = binding.binding,
  23595. rootUuid = propBinding.rootNode.uuid,
  23596. trackName = propBinding.path,
  23597. bindingsByRoot = this._bindingsByRootAndName,
  23598. bindingByName = bindingsByRoot[ rootUuid ],
  23599. lastInactiveBinding = bindings[ bindings.length - 1 ],
  23600. cacheIndex = binding._cacheIndex;
  23601. lastInactiveBinding._cacheIndex = cacheIndex;
  23602. bindings[ cacheIndex ] = lastInactiveBinding;
  23603. bindings.pop();
  23604. delete bindingByName[ trackName ];
  23605. remove_empty_map: {
  23606. for ( var _ in bindingByName ) break remove_empty_map;
  23607. delete bindingsByRoot[ rootUuid ];
  23608. }
  23609. },
  23610. _lendBinding: function ( binding ) {
  23611. var bindings = this._bindings,
  23612. prevIndex = binding._cacheIndex,
  23613. lastActiveIndex = this._nActiveBindings ++,
  23614. firstInactiveBinding = bindings[ lastActiveIndex ];
  23615. binding._cacheIndex = lastActiveIndex;
  23616. bindings[ lastActiveIndex ] = binding;
  23617. firstInactiveBinding._cacheIndex = prevIndex;
  23618. bindings[ prevIndex ] = firstInactiveBinding;
  23619. },
  23620. _takeBackBinding: function ( binding ) {
  23621. var bindings = this._bindings,
  23622. prevIndex = binding._cacheIndex,
  23623. firstInactiveIndex = -- this._nActiveBindings,
  23624. lastActiveBinding = bindings[ firstInactiveIndex ];
  23625. binding._cacheIndex = firstInactiveIndex;
  23626. bindings[ firstInactiveIndex ] = binding;
  23627. lastActiveBinding._cacheIndex = prevIndex;
  23628. bindings[ prevIndex ] = lastActiveBinding;
  23629. },
  23630. // Memory management of Interpolants for weight and time scale
  23631. _lendControlInterpolant: function () {
  23632. var interpolants = this._controlInterpolants,
  23633. lastActiveIndex = this._nActiveControlInterpolants ++,
  23634. interpolant = interpolants[ lastActiveIndex ];
  23635. if ( interpolant === undefined ) {
  23636. interpolant = new LinearInterpolant(
  23637. new Float32Array( 2 ), new Float32Array( 2 ),
  23638. 1, this._controlInterpolantsResultBuffer );
  23639. interpolant.__cacheIndex = lastActiveIndex;
  23640. interpolants[ lastActiveIndex ] = interpolant;
  23641. }
  23642. return interpolant;
  23643. },
  23644. _takeBackControlInterpolant: function ( interpolant ) {
  23645. var interpolants = this._controlInterpolants,
  23646. prevIndex = interpolant.__cacheIndex,
  23647. firstInactiveIndex = -- this._nActiveControlInterpolants,
  23648. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  23649. interpolant.__cacheIndex = firstInactiveIndex;
  23650. interpolants[ firstInactiveIndex ] = interpolant;
  23651. lastActiveInterpolant.__cacheIndex = prevIndex;
  23652. interpolants[ prevIndex ] = lastActiveInterpolant;
  23653. },
  23654. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  23655. // return an action for a clip optionally using a custom root target
  23656. // object (this method allocates a lot of dynamic memory in case a
  23657. // previously unknown clip/root combination is specified)
  23658. clipAction: function ( clip, optionalRoot ) {
  23659. var root = optionalRoot || this._root,
  23660. rootUuid = root.uuid,
  23661. clipObject = typeof clip === 'string' ?
  23662. AnimationClip.findByName( root, clip ) : clip,
  23663. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  23664. actionsForClip = this._actionsByClip[ clipUuid ],
  23665. prototypeAction = null;
  23666. if ( actionsForClip !== undefined ) {
  23667. var existingAction =
  23668. actionsForClip.actionByRoot[ rootUuid ];
  23669. if ( existingAction !== undefined ) {
  23670. return existingAction;
  23671. }
  23672. // we know the clip, so we don't have to parse all
  23673. // the bindings again but can just copy
  23674. prototypeAction = actionsForClip.knownActions[ 0 ];
  23675. // also, take the clip from the prototype action
  23676. if ( clipObject === null )
  23677. clipObject = prototypeAction._clip;
  23678. }
  23679. // clip must be known when specified via string
  23680. if ( clipObject === null ) return null;
  23681. // allocate all resources required to run it
  23682. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  23683. this._bindAction( newAction, prototypeAction );
  23684. // and make the action known to the memory manager
  23685. this._addInactiveAction( newAction, clipUuid, rootUuid );
  23686. return newAction;
  23687. },
  23688. // get an existing action
  23689. existingAction: function ( clip, optionalRoot ) {
  23690. var root = optionalRoot || this._root,
  23691. rootUuid = root.uuid,
  23692. clipObject = typeof clip === 'string' ?
  23693. AnimationClip.findByName( root, clip ) : clip,
  23694. clipUuid = clipObject ? clipObject.uuid : clip,
  23695. actionsForClip = this._actionsByClip[ clipUuid ];
  23696. if ( actionsForClip !== undefined ) {
  23697. return actionsForClip.actionByRoot[ rootUuid ] || null;
  23698. }
  23699. return null;
  23700. },
  23701. // deactivates all previously scheduled actions
  23702. stopAllAction: function () {
  23703. var actions = this._actions,
  23704. nActions = this._nActiveActions,
  23705. bindings = this._bindings,
  23706. nBindings = this._nActiveBindings;
  23707. this._nActiveActions = 0;
  23708. this._nActiveBindings = 0;
  23709. for ( var i = 0; i !== nActions; ++ i ) {
  23710. actions[ i ].reset();
  23711. }
  23712. for ( var i = 0; i !== nBindings; ++ i ) {
  23713. bindings[ i ].useCount = 0;
  23714. }
  23715. return this;
  23716. },
  23717. // advance the time and update apply the animation
  23718. update: function ( deltaTime ) {
  23719. deltaTime *= this.timeScale;
  23720. var actions = this._actions,
  23721. nActions = this._nActiveActions,
  23722. time = this.time += deltaTime,
  23723. timeDirection = Math.sign( deltaTime ),
  23724. accuIndex = this._accuIndex ^= 1;
  23725. // run active actions
  23726. for ( var i = 0; i !== nActions; ++ i ) {
  23727. var action = actions[ i ];
  23728. action._update( time, deltaTime, timeDirection, accuIndex );
  23729. }
  23730. // update scene graph
  23731. var bindings = this._bindings,
  23732. nBindings = this._nActiveBindings;
  23733. for ( var i = 0; i !== nBindings; ++ i ) {
  23734. bindings[ i ].apply( accuIndex );
  23735. }
  23736. return this;
  23737. },
  23738. // return this mixer's root target object
  23739. getRoot: function () {
  23740. return this._root;
  23741. },
  23742. // free all resources specific to a particular clip
  23743. uncacheClip: function ( clip ) {
  23744. var actions = this._actions,
  23745. clipUuid = clip.uuid,
  23746. actionsByClip = this._actionsByClip,
  23747. actionsForClip = actionsByClip[ clipUuid ];
  23748. if ( actionsForClip !== undefined ) {
  23749. // note: just calling _removeInactiveAction would mess up the
  23750. // iteration state and also require updating the state we can
  23751. // just throw away
  23752. var actionsToRemove = actionsForClip.knownActions;
  23753. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  23754. var action = actionsToRemove[ i ];
  23755. this._deactivateAction( action );
  23756. var cacheIndex = action._cacheIndex,
  23757. lastInactiveAction = actions[ actions.length - 1 ];
  23758. action._cacheIndex = null;
  23759. action._byClipCacheIndex = null;
  23760. lastInactiveAction._cacheIndex = cacheIndex;
  23761. actions[ cacheIndex ] = lastInactiveAction;
  23762. actions.pop();
  23763. this._removeInactiveBindingsForAction( action );
  23764. }
  23765. delete actionsByClip[ clipUuid ];
  23766. }
  23767. },
  23768. // free all resources specific to a particular root target object
  23769. uncacheRoot: function ( root ) {
  23770. var rootUuid = root.uuid,
  23771. actionsByClip = this._actionsByClip;
  23772. for ( var clipUuid in actionsByClip ) {
  23773. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  23774. action = actionByRoot[ rootUuid ];
  23775. if ( action !== undefined ) {
  23776. this._deactivateAction( action );
  23777. this._removeInactiveAction( action );
  23778. }
  23779. }
  23780. var bindingsByRoot = this._bindingsByRootAndName,
  23781. bindingByName = bindingsByRoot[ rootUuid ];
  23782. if ( bindingByName !== undefined ) {
  23783. for ( var trackName in bindingByName ) {
  23784. var binding = bindingByName[ trackName ];
  23785. binding.restoreOriginalState();
  23786. this._removeInactiveBinding( binding );
  23787. }
  23788. }
  23789. },
  23790. // remove a targeted clip from the cache
  23791. uncacheAction: function ( clip, optionalRoot ) {
  23792. var action = this.existingAction( clip, optionalRoot );
  23793. if ( action !== null ) {
  23794. this._deactivateAction( action );
  23795. this._removeInactiveAction( action );
  23796. }
  23797. }
  23798. } );
  23799. /**
  23800. * @author mrdoob / http://mrdoob.com/
  23801. */
  23802. function Uniform( value ) {
  23803. if ( typeof value === 'string' ) {
  23804. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  23805. value = arguments[ 1 ];
  23806. }
  23807. this.value = value;
  23808. }
  23809. Uniform.prototype.clone = function () {
  23810. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  23811. };
  23812. /**
  23813. * @author benaadams / https://twitter.com/ben_a_adams
  23814. */
  23815. function InstancedBufferGeometry() {
  23816. BufferGeometry.call( this );
  23817. this.type = 'InstancedBufferGeometry';
  23818. this.maxInstancedCount = undefined;
  23819. }
  23820. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  23821. constructor: InstancedBufferGeometry,
  23822. isInstancedBufferGeometry: true,
  23823. addGroup: function ( start, count, materialIndex ) {
  23824. this.groups.push( {
  23825. start: start,
  23826. count: count,
  23827. materialIndex: materialIndex
  23828. } );
  23829. },
  23830. copy: function ( source ) {
  23831. var index = source.index;
  23832. if ( index !== null ) {
  23833. this.setIndex( index.clone() );
  23834. }
  23835. var attributes = source.attributes;
  23836. for ( var name in attributes ) {
  23837. var attribute = attributes[ name ];
  23838. this.addAttribute( name, attribute.clone() );
  23839. }
  23840. var groups = source.groups;
  23841. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  23842. var group = groups[ i ];
  23843. this.addGroup( group.start, group.count, group.materialIndex );
  23844. }
  23845. return this;
  23846. }
  23847. } );
  23848. /**
  23849. * @author benaadams / https://twitter.com/ben_a_adams
  23850. */
  23851. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  23852. this.uuid = _Math.generateUUID();
  23853. this.data = interleavedBuffer;
  23854. this.itemSize = itemSize;
  23855. this.offset = offset;
  23856. this.normalized = normalized === true;
  23857. }
  23858. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  23859. count: {
  23860. get: function () {
  23861. return this.data.count;
  23862. }
  23863. },
  23864. array: {
  23865. get: function () {
  23866. return this.data.array;
  23867. }
  23868. }
  23869. } );
  23870. Object.assign( InterleavedBufferAttribute.prototype, {
  23871. isInterleavedBufferAttribute: true,
  23872. setX: function ( index, x ) {
  23873. this.data.array[ index * this.data.stride + this.offset ] = x;
  23874. return this;
  23875. },
  23876. setY: function ( index, y ) {
  23877. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  23878. return this;
  23879. },
  23880. setZ: function ( index, z ) {
  23881. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  23882. return this;
  23883. },
  23884. setW: function ( index, w ) {
  23885. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  23886. return this;
  23887. },
  23888. getX: function ( index ) {
  23889. return this.data.array[ index * this.data.stride + this.offset ];
  23890. },
  23891. getY: function ( index ) {
  23892. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  23893. },
  23894. getZ: function ( index ) {
  23895. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  23896. },
  23897. getW: function ( index ) {
  23898. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  23899. },
  23900. setXY: function ( index, x, y ) {
  23901. index = index * this.data.stride + this.offset;
  23902. this.data.array[ index + 0 ] = x;
  23903. this.data.array[ index + 1 ] = y;
  23904. return this;
  23905. },
  23906. setXYZ: function ( index, x, y, z ) {
  23907. index = index * this.data.stride + this.offset;
  23908. this.data.array[ index + 0 ] = x;
  23909. this.data.array[ index + 1 ] = y;
  23910. this.data.array[ index + 2 ] = z;
  23911. return this;
  23912. },
  23913. setXYZW: function ( index, x, y, z, w ) {
  23914. index = index * this.data.stride + this.offset;
  23915. this.data.array[ index + 0 ] = x;
  23916. this.data.array[ index + 1 ] = y;
  23917. this.data.array[ index + 2 ] = z;
  23918. this.data.array[ index + 3 ] = w;
  23919. return this;
  23920. }
  23921. } );
  23922. /**
  23923. * @author benaadams / https://twitter.com/ben_a_adams
  23924. */
  23925. function InterleavedBuffer( array, stride ) {
  23926. this.uuid = _Math.generateUUID();
  23927. this.array = array;
  23928. this.stride = stride;
  23929. this.count = array !== undefined ? array.length / stride : 0;
  23930. this.dynamic = false;
  23931. this.updateRange = { offset: 0, count: - 1 };
  23932. this.onUploadCallback = function () {};
  23933. this.version = 0;
  23934. }
  23935. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  23936. set: function ( value ) {
  23937. if ( value === true ) this.version ++;
  23938. }
  23939. } );
  23940. Object.assign( InterleavedBuffer.prototype, {
  23941. isInterleavedBuffer: true,
  23942. setArray: function ( array ) {
  23943. if ( Array.isArray( array ) ) {
  23944. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  23945. }
  23946. this.count = array !== undefined ? array.length / this.stride : 0;
  23947. this.array = array;
  23948. },
  23949. setDynamic: function ( value ) {
  23950. this.dynamic = value;
  23951. return this;
  23952. },
  23953. copy: function ( source ) {
  23954. this.array = new source.array.constructor( source.array );
  23955. this.count = source.count;
  23956. this.stride = source.stride;
  23957. this.dynamic = source.dynamic;
  23958. return this;
  23959. },
  23960. copyAt: function ( index1, attribute, index2 ) {
  23961. index1 *= this.stride;
  23962. index2 *= attribute.stride;
  23963. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  23964. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  23965. }
  23966. return this;
  23967. },
  23968. set: function ( value, offset ) {
  23969. if ( offset === undefined ) offset = 0;
  23970. this.array.set( value, offset );
  23971. return this;
  23972. },
  23973. clone: function () {
  23974. return new this.constructor().copy( this );
  23975. },
  23976. onUpload: function ( callback ) {
  23977. this.onUploadCallback = callback;
  23978. return this;
  23979. }
  23980. } );
  23981. /**
  23982. * @author benaadams / https://twitter.com/ben_a_adams
  23983. */
  23984. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  23985. InterleavedBuffer.call( this, array, stride );
  23986. this.meshPerAttribute = meshPerAttribute || 1;
  23987. }
  23988. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  23989. constructor: InstancedInterleavedBuffer,
  23990. isInstancedInterleavedBuffer: true,
  23991. copy: function ( source ) {
  23992. InterleavedBuffer.prototype.copy.call( this, source );
  23993. this.meshPerAttribute = source.meshPerAttribute;
  23994. return this;
  23995. }
  23996. } );
  23997. /**
  23998. * @author benaadams / https://twitter.com/ben_a_adams
  23999. */
  24000. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  24001. BufferAttribute.call( this, array, itemSize );
  24002. this.meshPerAttribute = meshPerAttribute || 1;
  24003. }
  24004. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  24005. constructor: InstancedBufferAttribute,
  24006. isInstancedBufferAttribute: true,
  24007. copy: function ( source ) {
  24008. BufferAttribute.prototype.copy.call( this, source );
  24009. this.meshPerAttribute = source.meshPerAttribute;
  24010. return this;
  24011. }
  24012. } );
  24013. /**
  24014. * @author mrdoob / http://mrdoob.com/
  24015. * @author bhouston / http://clara.io/
  24016. * @author stephomi / http://stephaneginier.com/
  24017. */
  24018. function Raycaster( origin, direction, near, far ) {
  24019. this.ray = new Ray( origin, direction );
  24020. // direction is assumed to be normalized (for accurate distance calculations)
  24021. this.near = near || 0;
  24022. this.far = far || Infinity;
  24023. this.params = {
  24024. Mesh: {},
  24025. Line: {},
  24026. LOD: {},
  24027. Points: { threshold: 1 },
  24028. Sprite: {}
  24029. };
  24030. Object.defineProperties( this.params, {
  24031. PointCloud: {
  24032. get: function () {
  24033. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  24034. return this.Points;
  24035. }
  24036. }
  24037. } );
  24038. }
  24039. function ascSort( a, b ) {
  24040. return a.distance - b.distance;
  24041. }
  24042. function intersectObject( object, raycaster, intersects, recursive ) {
  24043. if ( object.visible === false ) return;
  24044. object.raycast( raycaster, intersects );
  24045. if ( recursive === true ) {
  24046. var children = object.children;
  24047. for ( var i = 0, l = children.length; i < l; i ++ ) {
  24048. intersectObject( children[ i ], raycaster, intersects, true );
  24049. }
  24050. }
  24051. }
  24052. Object.assign( Raycaster.prototype, {
  24053. linePrecision: 1,
  24054. set: function ( origin, direction ) {
  24055. // direction is assumed to be normalized (for accurate distance calculations)
  24056. this.ray.set( origin, direction );
  24057. },
  24058. setFromCamera: function ( coords, camera ) {
  24059. if ( ( camera && camera.isPerspectiveCamera ) ) {
  24060. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  24061. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  24062. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  24063. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  24064. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  24065. } else {
  24066. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  24067. }
  24068. },
  24069. intersectObject: function ( object, recursive ) {
  24070. var intersects = [];
  24071. intersectObject( object, this, intersects, recursive );
  24072. intersects.sort( ascSort );
  24073. return intersects;
  24074. },
  24075. intersectObjects: function ( objects, recursive ) {
  24076. var intersects = [];
  24077. if ( Array.isArray( objects ) === false ) {
  24078. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  24079. return intersects;
  24080. }
  24081. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  24082. intersectObject( objects[ i ], this, intersects, recursive );
  24083. }
  24084. intersects.sort( ascSort );
  24085. return intersects;
  24086. }
  24087. } );
  24088. /**
  24089. * @author alteredq / http://alteredqualia.com/
  24090. */
  24091. function Clock( autoStart ) {
  24092. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  24093. this.startTime = 0;
  24094. this.oldTime = 0;
  24095. this.elapsedTime = 0;
  24096. this.running = false;
  24097. }
  24098. Object.assign( Clock.prototype, {
  24099. start: function () {
  24100. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  24101. this.oldTime = this.startTime;
  24102. this.elapsedTime = 0;
  24103. this.running = true;
  24104. },
  24105. stop: function () {
  24106. this.getElapsedTime();
  24107. this.running = false;
  24108. this.autoStart = false;
  24109. },
  24110. getElapsedTime: function () {
  24111. this.getDelta();
  24112. return this.elapsedTime;
  24113. },
  24114. getDelta: function () {
  24115. var diff = 0;
  24116. if ( this.autoStart && ! this.running ) {
  24117. this.start();
  24118. return 0;
  24119. }
  24120. if ( this.running ) {
  24121. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  24122. diff = ( newTime - this.oldTime ) / 1000;
  24123. this.oldTime = newTime;
  24124. this.elapsedTime += diff;
  24125. }
  24126. return diff;
  24127. }
  24128. } );
  24129. /**
  24130. * @author bhouston / http://clara.io
  24131. * @author WestLangley / http://github.com/WestLangley
  24132. *
  24133. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  24134. *
  24135. * The poles (phi) are at the positive and negative y axis.
  24136. * The equator starts at positive z.
  24137. */
  24138. function Spherical( radius, phi, theta ) {
  24139. this.radius = ( radius !== undefined ) ? radius : 1.0;
  24140. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  24141. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  24142. return this;
  24143. }
  24144. Object.assign( Spherical.prototype, {
  24145. set: function ( radius, phi, theta ) {
  24146. this.radius = radius;
  24147. this.phi = phi;
  24148. this.theta = theta;
  24149. return this;
  24150. },
  24151. clone: function () {
  24152. return new this.constructor().copy( this );
  24153. },
  24154. copy: function ( other ) {
  24155. this.radius = other.radius;
  24156. this.phi = other.phi;
  24157. this.theta = other.theta;
  24158. return this;
  24159. },
  24160. // restrict phi to be betwee EPS and PI-EPS
  24161. makeSafe: function() {
  24162. var EPS = 0.000001;
  24163. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  24164. return this;
  24165. },
  24166. setFromVector3: function( vec3 ) {
  24167. this.radius = vec3.length();
  24168. if ( this.radius === 0 ) {
  24169. this.theta = 0;
  24170. this.phi = 0;
  24171. } else {
  24172. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  24173. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  24174. }
  24175. return this;
  24176. }
  24177. } );
  24178. /**
  24179. * @author Mugen87 / https://github.com/Mugen87
  24180. *
  24181. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  24182. *
  24183. */
  24184. function Cylindrical( radius, theta, y ) {
  24185. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  24186. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  24187. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  24188. return this;
  24189. }
  24190. Object.assign( Cylindrical.prototype, {
  24191. set: function ( radius, theta, y ) {
  24192. this.radius = radius;
  24193. this.theta = theta;
  24194. this.y = y;
  24195. return this;
  24196. },
  24197. clone: function () {
  24198. return new this.constructor().copy( this );
  24199. },
  24200. copy: function ( other ) {
  24201. this.radius = other.radius;
  24202. this.theta = other.theta;
  24203. this.y = other.y;
  24204. return this;
  24205. },
  24206. setFromVector3: function( vec3 ) {
  24207. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  24208. this.theta = Math.atan2( vec3.x, vec3.z );
  24209. this.y = vec3.y;
  24210. return this;
  24211. }
  24212. } );
  24213. /**
  24214. * @author alteredq / http://alteredqualia.com/
  24215. */
  24216. function MorphBlendMesh( geometry, material ) {
  24217. Mesh.call( this, geometry, material );
  24218. this.animationsMap = {};
  24219. this.animationsList = [];
  24220. // prepare default animation
  24221. // (all frames played together in 1 second)
  24222. var numFrames = this.geometry.morphTargets.length;
  24223. var name = "__default";
  24224. var startFrame = 0;
  24225. var endFrame = numFrames - 1;
  24226. var fps = numFrames / 1;
  24227. this.createAnimation( name, startFrame, endFrame, fps );
  24228. this.setAnimationWeight( name, 1 );
  24229. }
  24230. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  24231. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  24232. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  24233. var animation = {
  24234. start: start,
  24235. end: end,
  24236. length: end - start + 1,
  24237. fps: fps,
  24238. duration: ( end - start ) / fps,
  24239. lastFrame: 0,
  24240. currentFrame: 0,
  24241. active: false,
  24242. time: 0,
  24243. direction: 1,
  24244. weight: 1,
  24245. directionBackwards: false,
  24246. mirroredLoop: false
  24247. };
  24248. this.animationsMap[ name ] = animation;
  24249. this.animationsList.push( animation );
  24250. };
  24251. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  24252. var pattern = /([a-z]+)_?(\d+)/i;
  24253. var firstAnimation, frameRanges = {};
  24254. var geometry = this.geometry;
  24255. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  24256. var morph = geometry.morphTargets[ i ];
  24257. var chunks = morph.name.match( pattern );
  24258. if ( chunks && chunks.length > 1 ) {
  24259. var name = chunks[ 1 ];
  24260. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  24261. var range = frameRanges[ name ];
  24262. if ( i < range.start ) range.start = i;
  24263. if ( i > range.end ) range.end = i;
  24264. if ( ! firstAnimation ) firstAnimation = name;
  24265. }
  24266. }
  24267. for ( var name in frameRanges ) {
  24268. var range = frameRanges[ name ];
  24269. this.createAnimation( name, range.start, range.end, fps );
  24270. }
  24271. this.firstAnimation = firstAnimation;
  24272. };
  24273. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  24274. var animation = this.animationsMap[ name ];
  24275. if ( animation ) {
  24276. animation.direction = 1;
  24277. animation.directionBackwards = false;
  24278. }
  24279. };
  24280. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  24281. var animation = this.animationsMap[ name ];
  24282. if ( animation ) {
  24283. animation.direction = - 1;
  24284. animation.directionBackwards = true;
  24285. }
  24286. };
  24287. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  24288. var animation = this.animationsMap[ name ];
  24289. if ( animation ) {
  24290. animation.fps = fps;
  24291. animation.duration = ( animation.end - animation.start ) / animation.fps;
  24292. }
  24293. };
  24294. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  24295. var animation = this.animationsMap[ name ];
  24296. if ( animation ) {
  24297. animation.duration = duration;
  24298. animation.fps = ( animation.end - animation.start ) / animation.duration;
  24299. }
  24300. };
  24301. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  24302. var animation = this.animationsMap[ name ];
  24303. if ( animation ) {
  24304. animation.weight = weight;
  24305. }
  24306. };
  24307. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  24308. var animation = this.animationsMap[ name ];
  24309. if ( animation ) {
  24310. animation.time = time;
  24311. }
  24312. };
  24313. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  24314. var time = 0;
  24315. var animation = this.animationsMap[ name ];
  24316. if ( animation ) {
  24317. time = animation.time;
  24318. }
  24319. return time;
  24320. };
  24321. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  24322. var duration = - 1;
  24323. var animation = this.animationsMap[ name ];
  24324. if ( animation ) {
  24325. duration = animation.duration;
  24326. }
  24327. return duration;
  24328. };
  24329. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  24330. var animation = this.animationsMap[ name ];
  24331. if ( animation ) {
  24332. animation.time = 0;
  24333. animation.active = true;
  24334. } else {
  24335. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  24336. }
  24337. };
  24338. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  24339. var animation = this.animationsMap[ name ];
  24340. if ( animation ) {
  24341. animation.active = false;
  24342. }
  24343. };
  24344. MorphBlendMesh.prototype.update = function ( delta ) {
  24345. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  24346. var animation = this.animationsList[ i ];
  24347. if ( ! animation.active ) continue;
  24348. var frameTime = animation.duration / animation.length;
  24349. animation.time += animation.direction * delta;
  24350. if ( animation.mirroredLoop ) {
  24351. if ( animation.time > animation.duration || animation.time < 0 ) {
  24352. animation.direction *= - 1;
  24353. if ( animation.time > animation.duration ) {
  24354. animation.time = animation.duration;
  24355. animation.directionBackwards = true;
  24356. }
  24357. if ( animation.time < 0 ) {
  24358. animation.time = 0;
  24359. animation.directionBackwards = false;
  24360. }
  24361. }
  24362. } else {
  24363. animation.time = animation.time % animation.duration;
  24364. if ( animation.time < 0 ) animation.time += animation.duration;
  24365. }
  24366. var keyframe = animation.start + _Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  24367. var weight = animation.weight;
  24368. if ( keyframe !== animation.currentFrame ) {
  24369. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  24370. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  24371. this.morphTargetInfluences[ keyframe ] = 0;
  24372. animation.lastFrame = animation.currentFrame;
  24373. animation.currentFrame = keyframe;
  24374. }
  24375. var mix = ( animation.time % frameTime ) / frameTime;
  24376. if ( animation.directionBackwards ) mix = 1 - mix;
  24377. if ( animation.currentFrame !== animation.lastFrame ) {
  24378. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  24379. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  24380. } else {
  24381. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  24382. }
  24383. }
  24384. };
  24385. /**
  24386. * @author alteredq / http://alteredqualia.com/
  24387. */
  24388. function ImmediateRenderObject( material ) {
  24389. Object3D.call( this );
  24390. this.material = material;
  24391. this.render = function ( renderCallback ) {};
  24392. }
  24393. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  24394. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  24395. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  24396. /**
  24397. * @author mrdoob / http://mrdoob.com/
  24398. * @author WestLangley / http://github.com/WestLangley
  24399. */
  24400. function VertexNormalsHelper( object, size, hex, linewidth ) {
  24401. this.object = object;
  24402. this.size = ( size !== undefined ) ? size : 1;
  24403. var color = ( hex !== undefined ) ? hex : 0xff0000;
  24404. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24405. //
  24406. var nNormals = 0;
  24407. var objGeometry = this.object.geometry;
  24408. if ( objGeometry && objGeometry.isGeometry ) {
  24409. nNormals = objGeometry.faces.length * 3;
  24410. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24411. nNormals = objGeometry.attributes.normal.count;
  24412. }
  24413. //
  24414. var geometry = new BufferGeometry();
  24415. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24416. geometry.addAttribute( 'position', positions );
  24417. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24418. //
  24419. this.matrixAutoUpdate = false;
  24420. this.update();
  24421. }
  24422. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24423. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  24424. VertexNormalsHelper.prototype.update = ( function () {
  24425. var v1 = new Vector3();
  24426. var v2 = new Vector3();
  24427. var normalMatrix = new Matrix3();
  24428. return function update() {
  24429. var keys = [ 'a', 'b', 'c' ];
  24430. this.object.updateMatrixWorld( true );
  24431. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24432. var matrixWorld = this.object.matrixWorld;
  24433. var position = this.geometry.attributes.position;
  24434. //
  24435. var objGeometry = this.object.geometry;
  24436. if ( objGeometry && objGeometry.isGeometry ) {
  24437. var vertices = objGeometry.vertices;
  24438. var faces = objGeometry.faces;
  24439. var idx = 0;
  24440. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24441. var face = faces[ i ];
  24442. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  24443. var vertex = vertices[ face[ keys[ j ] ] ];
  24444. var normal = face.vertexNormals[ j ];
  24445. v1.copy( vertex ).applyMatrix4( matrixWorld );
  24446. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24447. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24448. idx = idx + 1;
  24449. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24450. idx = idx + 1;
  24451. }
  24452. }
  24453. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24454. var objPos = objGeometry.attributes.position;
  24455. var objNorm = objGeometry.attributes.normal;
  24456. var idx = 0;
  24457. // for simplicity, ignore index and drawcalls, and render every normal
  24458. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  24459. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  24460. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  24461. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24462. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24463. idx = idx + 1;
  24464. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24465. idx = idx + 1;
  24466. }
  24467. }
  24468. position.needsUpdate = true;
  24469. };
  24470. }() );
  24471. /**
  24472. * @author alteredq / http://alteredqualia.com/
  24473. * @author mrdoob / http://mrdoob.com/
  24474. * @author WestLangley / http://github.com/WestLangley
  24475. */
  24476. function SpotLightHelper( light, color ) {
  24477. Object3D.call( this );
  24478. this.light = light;
  24479. this.light.updateMatrixWorld();
  24480. this.matrix = light.matrixWorld;
  24481. this.matrixAutoUpdate = false;
  24482. this.color = color;
  24483. var geometry = new BufferGeometry();
  24484. var positions = [
  24485. 0, 0, 0, 0, 0, 1,
  24486. 0, 0, 0, 1, 0, 1,
  24487. 0, 0, 0, - 1, 0, 1,
  24488. 0, 0, 0, 0, 1, 1,
  24489. 0, 0, 0, 0, - 1, 1
  24490. ];
  24491. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  24492. var p1 = ( i / l ) * Math.PI * 2;
  24493. var p2 = ( j / l ) * Math.PI * 2;
  24494. positions.push(
  24495. Math.cos( p1 ), Math.sin( p1 ), 1,
  24496. Math.cos( p2 ), Math.sin( p2 ), 1
  24497. );
  24498. }
  24499. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  24500. var material = new LineBasicMaterial( { fog: false } );
  24501. this.cone = new LineSegments( geometry, material );
  24502. this.add( this.cone );
  24503. this.update();
  24504. }
  24505. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  24506. SpotLightHelper.prototype.constructor = SpotLightHelper;
  24507. SpotLightHelper.prototype.dispose = function () {
  24508. this.cone.geometry.dispose();
  24509. this.cone.material.dispose();
  24510. };
  24511. SpotLightHelper.prototype.update = function () {
  24512. var vector = new Vector3();
  24513. var vector2 = new Vector3();
  24514. return function update() {
  24515. this.light.updateMatrixWorld();
  24516. var coneLength = this.light.distance ? this.light.distance : 1000;
  24517. var coneWidth = coneLength * Math.tan( this.light.angle );
  24518. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  24519. vector.setFromMatrixPosition( this.light.matrixWorld );
  24520. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24521. this.cone.lookAt( vector2.sub( vector ) );
  24522. if ( this.color !== undefined ) {
  24523. this.cone.material.color.set( this.color );
  24524. } else {
  24525. this.cone.material.color.copy( this.light.color );
  24526. }
  24527. };
  24528. }();
  24529. /**
  24530. * @author Sean Griffin / http://twitter.com/sgrif
  24531. * @author Michael Guerrero / http://realitymeltdown.com
  24532. * @author mrdoob / http://mrdoob.com/
  24533. * @author ikerr / http://verold.com
  24534. * @author Mugen87 / https://github.com/Mugen87
  24535. */
  24536. function getBoneList( object ) {
  24537. var boneList = [];
  24538. if ( object && object.isBone ) {
  24539. boneList.push( object );
  24540. }
  24541. for ( var i = 0; i < object.children.length; i ++ ) {
  24542. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  24543. }
  24544. return boneList;
  24545. }
  24546. function SkeletonHelper( object ) {
  24547. var bones = getBoneList( object );
  24548. var geometry = new BufferGeometry();
  24549. var vertices = [];
  24550. var colors = [];
  24551. var color1 = new Color( 0, 0, 1 );
  24552. var color2 = new Color( 0, 1, 0 );
  24553. for ( var i = 0; i < bones.length; i ++ ) {
  24554. var bone = bones[ i ];
  24555. if ( bone.parent && bone.parent.isBone ) {
  24556. vertices.push( 0, 0, 0 );
  24557. vertices.push( 0, 0, 0 );
  24558. colors.push( color1.r, color1.g, color1.b );
  24559. colors.push( color2.r, color2.g, color2.b );
  24560. }
  24561. }
  24562. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24563. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24564. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  24565. LineSegments.call( this, geometry, material );
  24566. this.root = object;
  24567. this.bones = bones;
  24568. this.matrix = object.matrixWorld;
  24569. this.matrixAutoUpdate = false;
  24570. this.onBeforeRender();
  24571. }
  24572. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  24573. SkeletonHelper.prototype.constructor = SkeletonHelper;
  24574. SkeletonHelper.prototype.onBeforeRender = function () {
  24575. var vector = new Vector3();
  24576. var boneMatrix = new Matrix4();
  24577. var matrixWorldInv = new Matrix4();
  24578. return function onBeforeRender() {
  24579. var bones = this.bones;
  24580. var geometry = this.geometry;
  24581. var position = geometry.getAttribute( 'position' );
  24582. matrixWorldInv.getInverse( this.root.matrixWorld );
  24583. for ( var i = 0, j = 0; i < bones.length; i ++ ) {
  24584. var bone = bones[ i ];
  24585. if ( bone.parent && bone.parent.isBone ) {
  24586. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  24587. vector.setFromMatrixPosition( boneMatrix );
  24588. position.setXYZ( j, vector.x, vector.y, vector.z );
  24589. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  24590. vector.setFromMatrixPosition( boneMatrix );
  24591. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  24592. j += 2;
  24593. }
  24594. }
  24595. geometry.getAttribute( 'position' ).needsUpdate = true;
  24596. };
  24597. }();
  24598. /**
  24599. * @author alteredq / http://alteredqualia.com/
  24600. * @author mrdoob / http://mrdoob.com/
  24601. */
  24602. function PointLightHelper( light, sphereSize, color ) {
  24603. this.light = light;
  24604. this.light.updateMatrixWorld();
  24605. this.color = color;
  24606. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  24607. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  24608. Mesh.call( this, geometry, material );
  24609. this.matrix = this.light.matrixWorld;
  24610. this.matrixAutoUpdate = false;
  24611. this.update();
  24612. /*
  24613. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  24614. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  24615. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  24616. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  24617. var d = light.distance;
  24618. if ( d === 0.0 ) {
  24619. this.lightDistance.visible = false;
  24620. } else {
  24621. this.lightDistance.scale.set( d, d, d );
  24622. }
  24623. this.add( this.lightDistance );
  24624. */
  24625. }
  24626. PointLightHelper.prototype = Object.create( Mesh.prototype );
  24627. PointLightHelper.prototype.constructor = PointLightHelper;
  24628. PointLightHelper.prototype.dispose = function () {
  24629. this.geometry.dispose();
  24630. this.material.dispose();
  24631. };
  24632. PointLightHelper.prototype.update = function () {
  24633. if ( this.color !== undefined ) {
  24634. this.material.color.set( this.color );
  24635. } else {
  24636. this.material.color.copy( this.light.color );
  24637. }
  24638. /*
  24639. var d = this.light.distance;
  24640. if ( d === 0.0 ) {
  24641. this.lightDistance.visible = false;
  24642. } else {
  24643. this.lightDistance.visible = true;
  24644. this.lightDistance.scale.set( d, d, d );
  24645. }
  24646. */
  24647. };
  24648. /**
  24649. * @author abelnation / http://github.com/abelnation
  24650. * @author Mugen87 / http://github.com/Mugen87
  24651. * @author WestLangley / http://github.com/WestLangley
  24652. */
  24653. function RectAreaLightHelper( light, color ) {
  24654. Object3D.call( this );
  24655. this.light = light;
  24656. this.light.updateMatrixWorld();
  24657. this.matrix = light.matrixWorld;
  24658. this.matrixAutoUpdate = false;
  24659. this.color = color;
  24660. var material = new LineBasicMaterial( { fog: false } );
  24661. var geometry = new BufferGeometry();
  24662. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 5 * 3 ), 3 ) );
  24663. this.line = new Line( geometry, material );
  24664. this.add( this.line );
  24665. this.update();
  24666. }
  24667. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  24668. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  24669. RectAreaLightHelper.prototype.dispose = function () {
  24670. this.children[ 0 ].geometry.dispose();
  24671. this.children[ 0 ].material.dispose();
  24672. };
  24673. RectAreaLightHelper.prototype.update = function () {
  24674. // calculate new dimensions of the helper
  24675. var hx = this.light.width * 0.5;
  24676. var hy = this.light.height * 0.5;
  24677. var position = this.line.geometry.attributes.position;
  24678. var array = position.array;
  24679. // update vertices
  24680. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  24681. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  24682. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  24683. array[ 9 ] = - hx; array[ 10 ] = - hy; array[ 11 ] = 0;
  24684. array[ 12 ] = hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  24685. position.needsUpdate = true;
  24686. if ( this.color !== undefined ) {
  24687. this.line.material.color.set( this.color );
  24688. } else {
  24689. this.line.material.color.copy( this.light.color );
  24690. }
  24691. };
  24692. /**
  24693. * @author alteredq / http://alteredqualia.com/
  24694. * @author mrdoob / http://mrdoob.com/
  24695. * @author Mugen87 / https://github.com/Mugen87
  24696. */
  24697. function HemisphereLightHelper( light, size, color ) {
  24698. Object3D.call( this );
  24699. this.light = light;
  24700. this.light.updateMatrixWorld();
  24701. this.matrix = light.matrixWorld;
  24702. this.matrixAutoUpdate = false;
  24703. this.color = color;
  24704. var geometry = new OctahedronBufferGeometry( size );
  24705. geometry.rotateY( Math.PI * 0.5 );
  24706. this.material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  24707. if ( this.color === undefined ) this.material.vertexColors = VertexColors;
  24708. var position = geometry.getAttribute( 'position' );
  24709. var colors = new Float32Array( position.count * 3 );
  24710. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  24711. this.add( new Mesh( geometry, this.material ) );
  24712. this.update();
  24713. }
  24714. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  24715. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  24716. HemisphereLightHelper.prototype.dispose = function () {
  24717. this.children[ 0 ].geometry.dispose();
  24718. this.children[ 0 ].material.dispose();
  24719. };
  24720. HemisphereLightHelper.prototype.update = function () {
  24721. var vector = new Vector3();
  24722. var color1 = new Color();
  24723. var color2 = new Color();
  24724. return function update() {
  24725. var mesh = this.children[ 0 ];
  24726. if ( this.color !== undefined ) {
  24727. this.material.color.set( this.color );
  24728. } else {
  24729. var colors = mesh.geometry.getAttribute( 'color' );
  24730. color1.copy( this.light.color );
  24731. color2.copy( this.light.groundColor );
  24732. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  24733. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  24734. colors.setXYZ( i, color.r, color.g, color.b );
  24735. }
  24736. colors.needsUpdate = true;
  24737. }
  24738. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  24739. };
  24740. }();
  24741. /**
  24742. * @author mrdoob / http://mrdoob.com/
  24743. */
  24744. function GridHelper( size, divisions, color1, color2 ) {
  24745. size = size || 10;
  24746. divisions = divisions || 10;
  24747. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24748. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24749. var center = divisions / 2;
  24750. var step = size / divisions;
  24751. var halfSize = size / 2;
  24752. var vertices = [], colors = [];
  24753. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  24754. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  24755. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  24756. var color = i === center ? color1 : color2;
  24757. color.toArray( colors, j ); j += 3;
  24758. color.toArray( colors, j ); j += 3;
  24759. color.toArray( colors, j ); j += 3;
  24760. color.toArray( colors, j ); j += 3;
  24761. }
  24762. var geometry = new BufferGeometry();
  24763. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24764. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24765. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24766. LineSegments.call( this, geometry, material );
  24767. }
  24768. GridHelper.prototype = Object.create( LineSegments.prototype );
  24769. GridHelper.prototype.constructor = GridHelper;
  24770. /**
  24771. * @author mrdoob / http://mrdoob.com/
  24772. * @author Mugen87 / http://github.com/Mugen87
  24773. * @author Hectate / http://www.github.com/Hectate
  24774. */
  24775. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  24776. radius = radius || 10;
  24777. radials = radials || 16;
  24778. circles = circles || 8;
  24779. divisions = divisions || 64;
  24780. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24781. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24782. var vertices = [];
  24783. var colors = [];
  24784. var x, z;
  24785. var v, i, j, r, color;
  24786. // create the radials
  24787. for ( i = 0; i <= radials; i ++ ) {
  24788. v = ( i / radials ) * ( Math.PI * 2 );
  24789. x = Math.sin( v ) * radius;
  24790. z = Math.cos( v ) * radius;
  24791. vertices.push( 0, 0, 0 );
  24792. vertices.push( x, 0, z );
  24793. color = ( i & 1 ) ? color1 : color2;
  24794. colors.push( color.r, color.g, color.b );
  24795. colors.push( color.r, color.g, color.b );
  24796. }
  24797. // create the circles
  24798. for ( i = 0; i <= circles; i ++ ) {
  24799. color = ( i & 1 ) ? color1 : color2;
  24800. r = radius - ( radius / circles * i );
  24801. for ( j = 0; j < divisions; j ++ ) {
  24802. // first vertex
  24803. v = ( j / divisions ) * ( Math.PI * 2 );
  24804. x = Math.sin( v ) * r;
  24805. z = Math.cos( v ) * r;
  24806. vertices.push( x, 0, z );
  24807. colors.push( color.r, color.g, color.b );
  24808. // second vertex
  24809. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  24810. x = Math.sin( v ) * r;
  24811. z = Math.cos( v ) * r;
  24812. vertices.push( x, 0, z );
  24813. colors.push( color.r, color.g, color.b );
  24814. }
  24815. }
  24816. var geometry = new BufferGeometry();
  24817. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24818. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24819. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24820. LineSegments.call( this, geometry, material );
  24821. }
  24822. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  24823. PolarGridHelper.prototype.constructor = PolarGridHelper;
  24824. /**
  24825. * @author mrdoob / http://mrdoob.com/
  24826. * @author WestLangley / http://github.com/WestLangley
  24827. */
  24828. function FaceNormalsHelper( object, size, hex, linewidth ) {
  24829. // FaceNormalsHelper only supports THREE.Geometry
  24830. this.object = object;
  24831. this.size = ( size !== undefined ) ? size : 1;
  24832. var color = ( hex !== undefined ) ? hex : 0xffff00;
  24833. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24834. //
  24835. var nNormals = 0;
  24836. var objGeometry = this.object.geometry;
  24837. if ( objGeometry && objGeometry.isGeometry ) {
  24838. nNormals = objGeometry.faces.length;
  24839. } else {
  24840. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  24841. }
  24842. //
  24843. var geometry = new BufferGeometry();
  24844. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24845. geometry.addAttribute( 'position', positions );
  24846. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24847. //
  24848. this.matrixAutoUpdate = false;
  24849. this.update();
  24850. }
  24851. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24852. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  24853. FaceNormalsHelper.prototype.update = ( function () {
  24854. var v1 = new Vector3();
  24855. var v2 = new Vector3();
  24856. var normalMatrix = new Matrix3();
  24857. return function update() {
  24858. this.object.updateMatrixWorld( true );
  24859. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24860. var matrixWorld = this.object.matrixWorld;
  24861. var position = this.geometry.attributes.position;
  24862. //
  24863. var objGeometry = this.object.geometry;
  24864. var vertices = objGeometry.vertices;
  24865. var faces = objGeometry.faces;
  24866. var idx = 0;
  24867. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24868. var face = faces[ i ];
  24869. var normal = face.normal;
  24870. v1.copy( vertices[ face.a ] )
  24871. .add( vertices[ face.b ] )
  24872. .add( vertices[ face.c ] )
  24873. .divideScalar( 3 )
  24874. .applyMatrix4( matrixWorld );
  24875. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24876. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24877. idx = idx + 1;
  24878. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24879. idx = idx + 1;
  24880. }
  24881. position.needsUpdate = true;
  24882. };
  24883. }() );
  24884. /**
  24885. * @author alteredq / http://alteredqualia.com/
  24886. * @author mrdoob / http://mrdoob.com/
  24887. * @author WestLangley / http://github.com/WestLangley
  24888. */
  24889. function DirectionalLightHelper( light, size, color ) {
  24890. Object3D.call( this );
  24891. this.light = light;
  24892. this.light.updateMatrixWorld();
  24893. this.matrix = light.matrixWorld;
  24894. this.matrixAutoUpdate = false;
  24895. this.color = color;
  24896. if ( size === undefined ) size = 1;
  24897. var geometry = new BufferGeometry();
  24898. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  24899. - size, size, 0,
  24900. size, size, 0,
  24901. size, - size, 0,
  24902. - size, - size, 0,
  24903. - size, size, 0
  24904. ], 3 ) );
  24905. var material = new LineBasicMaterial( { fog: false } );
  24906. this.lightPlane = new Line( geometry, material );
  24907. this.add( this.lightPlane );
  24908. geometry = new BufferGeometry();
  24909. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  24910. this.targetLine = new Line( geometry, material );
  24911. this.add( this.targetLine );
  24912. this.update();
  24913. }
  24914. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  24915. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  24916. DirectionalLightHelper.prototype.dispose = function () {
  24917. this.lightPlane.geometry.dispose();
  24918. this.lightPlane.material.dispose();
  24919. this.targetLine.geometry.dispose();
  24920. this.targetLine.material.dispose();
  24921. };
  24922. DirectionalLightHelper.prototype.update = function () {
  24923. var v1 = new Vector3();
  24924. var v2 = new Vector3();
  24925. var v3 = new Vector3();
  24926. return function update() {
  24927. v1.setFromMatrixPosition( this.light.matrixWorld );
  24928. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  24929. v3.subVectors( v2, v1 );
  24930. this.lightPlane.lookAt( v3 );
  24931. if ( this.color !== undefined ) {
  24932. this.lightPlane.material.color.set( this.color );
  24933. this.targetLine.material.color.set( this.color );
  24934. } else {
  24935. this.lightPlane.material.color.copy( this.light.color );
  24936. this.targetLine.material.color.copy( this.light.color );
  24937. }
  24938. this.targetLine.lookAt( v3 );
  24939. this.targetLine.scale.z = v3.length();
  24940. };
  24941. }();
  24942. /**
  24943. * @author alteredq / http://alteredqualia.com/
  24944. * @author Mugen87 / https://github.com/Mugen87
  24945. *
  24946. * - shows frustum, line of sight and up of the camera
  24947. * - suitable for fast updates
  24948. * - based on frustum visualization in lightgl.js shadowmap example
  24949. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  24950. */
  24951. function CameraHelper( camera ) {
  24952. var geometry = new BufferGeometry();
  24953. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  24954. var vertices = [];
  24955. var colors = [];
  24956. var pointMap = {};
  24957. // colors
  24958. var colorFrustum = new Color( 0xffaa00 );
  24959. var colorCone = new Color( 0xff0000 );
  24960. var colorUp = new Color( 0x00aaff );
  24961. var colorTarget = new Color( 0xffffff );
  24962. var colorCross = new Color( 0x333333 );
  24963. // near
  24964. addLine( "n1", "n2", colorFrustum );
  24965. addLine( "n2", "n4", colorFrustum );
  24966. addLine( "n4", "n3", colorFrustum );
  24967. addLine( "n3", "n1", colorFrustum );
  24968. // far
  24969. addLine( "f1", "f2", colorFrustum );
  24970. addLine( "f2", "f4", colorFrustum );
  24971. addLine( "f4", "f3", colorFrustum );
  24972. addLine( "f3", "f1", colorFrustum );
  24973. // sides
  24974. addLine( "n1", "f1", colorFrustum );
  24975. addLine( "n2", "f2", colorFrustum );
  24976. addLine( "n3", "f3", colorFrustum );
  24977. addLine( "n4", "f4", colorFrustum );
  24978. // cone
  24979. addLine( "p", "n1", colorCone );
  24980. addLine( "p", "n2", colorCone );
  24981. addLine( "p", "n3", colorCone );
  24982. addLine( "p", "n4", colorCone );
  24983. // up
  24984. addLine( "u1", "u2", colorUp );
  24985. addLine( "u2", "u3", colorUp );
  24986. addLine( "u3", "u1", colorUp );
  24987. // target
  24988. addLine( "c", "t", colorTarget );
  24989. addLine( "p", "c", colorCross );
  24990. // cross
  24991. addLine( "cn1", "cn2", colorCross );
  24992. addLine( "cn3", "cn4", colorCross );
  24993. addLine( "cf1", "cf2", colorCross );
  24994. addLine( "cf3", "cf4", colorCross );
  24995. function addLine( a, b, color ) {
  24996. addPoint( a, color );
  24997. addPoint( b, color );
  24998. }
  24999. function addPoint( id, color ) {
  25000. vertices.push( 0, 0, 0 );
  25001. colors.push( color.r, color.g, color.b );
  25002. if ( pointMap[ id ] === undefined ) {
  25003. pointMap[ id ] = [];
  25004. }
  25005. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  25006. }
  25007. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25008. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  25009. LineSegments.call( this, geometry, material );
  25010. this.camera = camera;
  25011. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  25012. this.matrix = camera.matrixWorld;
  25013. this.matrixAutoUpdate = false;
  25014. this.pointMap = pointMap;
  25015. this.update();
  25016. }
  25017. CameraHelper.prototype = Object.create( LineSegments.prototype );
  25018. CameraHelper.prototype.constructor = CameraHelper;
  25019. CameraHelper.prototype.update = function () {
  25020. var geometry, pointMap;
  25021. var vector = new Vector3();
  25022. var camera = new Camera();
  25023. function setPoint( point, x, y, z ) {
  25024. vector.set( x, y, z ).unproject( camera );
  25025. var points = pointMap[ point ];
  25026. if ( points !== undefined ) {
  25027. var position = geometry.getAttribute( 'position' );
  25028. for ( var i = 0, l = points.length; i < l; i ++ ) {
  25029. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  25030. }
  25031. }
  25032. }
  25033. return function update() {
  25034. geometry = this.geometry;
  25035. pointMap = this.pointMap;
  25036. var w = 1, h = 1;
  25037. // we need just camera projection matrix
  25038. // world matrix must be identity
  25039. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  25040. // center / target
  25041. setPoint( "c", 0, 0, - 1 );
  25042. setPoint( "t", 0, 0, 1 );
  25043. // near
  25044. setPoint( "n1", - w, - h, - 1 );
  25045. setPoint( "n2", w, - h, - 1 );
  25046. setPoint( "n3", - w, h, - 1 );
  25047. setPoint( "n4", w, h, - 1 );
  25048. // far
  25049. setPoint( "f1", - w, - h, 1 );
  25050. setPoint( "f2", w, - h, 1 );
  25051. setPoint( "f3", - w, h, 1 );
  25052. setPoint( "f4", w, h, 1 );
  25053. // up
  25054. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  25055. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  25056. setPoint( "u3", 0, h * 2, - 1 );
  25057. // cross
  25058. setPoint( "cf1", - w, 0, 1 );
  25059. setPoint( "cf2", w, 0, 1 );
  25060. setPoint( "cf3", 0, - h, 1 );
  25061. setPoint( "cf4", 0, h, 1 );
  25062. setPoint( "cn1", - w, 0, - 1 );
  25063. setPoint( "cn2", w, 0, - 1 );
  25064. setPoint( "cn3", 0, - h, - 1 );
  25065. setPoint( "cn4", 0, h, - 1 );
  25066. geometry.getAttribute( 'position' ).needsUpdate = true;
  25067. };
  25068. }();
  25069. /**
  25070. * @author mrdoob / http://mrdoob.com/
  25071. * @author Mugen87 / http://github.com/Mugen87
  25072. */
  25073. function BoxHelper( object, color ) {
  25074. this.object = object;
  25075. if ( color === undefined ) color = 0xffff00;
  25076. var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  25077. var positions = new Float32Array( 8 * 3 );
  25078. var geometry = new BufferGeometry();
  25079. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  25080. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  25081. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  25082. this.matrixAutoUpdate = false;
  25083. this.update();
  25084. }
  25085. BoxHelper.prototype = Object.create( LineSegments.prototype );
  25086. BoxHelper.prototype.constructor = BoxHelper;
  25087. BoxHelper.prototype.update = ( function () {
  25088. var box = new Box3();
  25089. return function update( object ) {
  25090. if ( object !== undefined ) {
  25091. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  25092. }
  25093. if ( this.object !== undefined ) {
  25094. box.setFromObject( this.object );
  25095. }
  25096. if ( box.isEmpty() ) return;
  25097. var min = box.min;
  25098. var max = box.max;
  25099. /*
  25100. 5____4
  25101. 1/___0/|
  25102. | 6__|_7
  25103. 2/___3/
  25104. 0: max.x, max.y, max.z
  25105. 1: min.x, max.y, max.z
  25106. 2: min.x, min.y, max.z
  25107. 3: max.x, min.y, max.z
  25108. 4: max.x, max.y, min.z
  25109. 5: min.x, max.y, min.z
  25110. 6: min.x, min.y, min.z
  25111. 7: max.x, min.y, min.z
  25112. */
  25113. var position = this.geometry.attributes.position;
  25114. var array = position.array;
  25115. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  25116. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  25117. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  25118. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  25119. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  25120. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  25121. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  25122. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  25123. position.needsUpdate = true;
  25124. this.geometry.computeBoundingSphere();
  25125. };
  25126. } )();
  25127. BoxHelper.prototype.setFromObject = function ( object ) {
  25128. this.object = object;
  25129. this.update();
  25130. return this;
  25131. };
  25132. /**
  25133. * @author WestLangley / http://github.com/WestLangley
  25134. */
  25135. function Box3Helper( box, hex ) {
  25136. this.type = 'Box3Helper';
  25137. this.box = box;
  25138. var color = ( hex !== undefined ) ? hex : 0xffff00;
  25139. var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  25140. var positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];
  25141. var geometry = new BufferGeometry();
  25142. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  25143. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  25144. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  25145. this.geometry.computeBoundingSphere();
  25146. this.onBeforeRender();
  25147. }
  25148. Box3Helper.prototype = Object.create( LineSegments.prototype );
  25149. Box3Helper.prototype.constructor = Box3Helper;
  25150. Box3Helper.prototype.onBeforeRender = function () {
  25151. var box = this.box;
  25152. if ( box.isEmpty() ) return;
  25153. box.getCenter( this.position );
  25154. box.getSize( this.scale );
  25155. this.scale.multiplyScalar( 0.5 );
  25156. };
  25157. /**
  25158. * @author WestLangley / http://github.com/WestLangley
  25159. */
  25160. function PlaneHelper( plane, size, hex ) {
  25161. this.type = 'PlaneHelper';
  25162. this.plane = plane;
  25163. this.size = ( size === undefined ) ? 1 : size;
  25164. var color = ( hex !== undefined ) ? hex : 0xffff00;
  25165. var positions = [ 1, - 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 ];
  25166. var geometry = new BufferGeometry();
  25167. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  25168. geometry.computeBoundingSphere();
  25169. Line.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  25170. //
  25171. var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  25172. var geometry2 = new BufferGeometry();
  25173. geometry2.addAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  25174. geometry2.computeBoundingSphere();
  25175. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false } ) ) );
  25176. //
  25177. this.onBeforeRender();
  25178. }
  25179. PlaneHelper.prototype = Object.create( Line.prototype );
  25180. PlaneHelper.prototype.constructor = PlaneHelper;
  25181. PlaneHelper.prototype.onBeforeRender = function () {
  25182. var scale = - this.plane.constant;
  25183. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  25184. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  25185. this.lookAt( this.plane.normal );
  25186. this.updateMatrixWorld();
  25187. };
  25188. /**
  25189. * @author WestLangley / http://github.com/WestLangley
  25190. * @author zz85 / http://github.com/zz85
  25191. * @author bhouston / http://clara.io
  25192. *
  25193. * Creates an arrow for visualizing directions
  25194. *
  25195. * Parameters:
  25196. * dir - Vector3
  25197. * origin - Vector3
  25198. * length - Number
  25199. * color - color in hex value
  25200. * headLength - Number
  25201. * headWidth - Number
  25202. */
  25203. var lineGeometry;
  25204. var coneGeometry;
  25205. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  25206. // dir is assumed to be normalized
  25207. Object3D.call( this );
  25208. if ( color === undefined ) color = 0xffff00;
  25209. if ( length === undefined ) length = 1;
  25210. if ( headLength === undefined ) headLength = 0.2 * length;
  25211. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  25212. if ( lineGeometry === undefined ) {
  25213. lineGeometry = new BufferGeometry();
  25214. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  25215. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  25216. coneGeometry.translate( 0, - 0.5, 0 );
  25217. }
  25218. this.position.copy( origin );
  25219. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  25220. this.line.matrixAutoUpdate = false;
  25221. this.add( this.line );
  25222. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  25223. this.cone.matrixAutoUpdate = false;
  25224. this.add( this.cone );
  25225. this.setDirection( dir );
  25226. this.setLength( length, headLength, headWidth );
  25227. }
  25228. ArrowHelper.prototype = Object.create( Object3D.prototype );
  25229. ArrowHelper.prototype.constructor = ArrowHelper;
  25230. ArrowHelper.prototype.setDirection = ( function () {
  25231. var axis = new Vector3();
  25232. var radians;
  25233. return function setDirection( dir ) {
  25234. // dir is assumed to be normalized
  25235. if ( dir.y > 0.99999 ) {
  25236. this.quaternion.set( 0, 0, 0, 1 );
  25237. } else if ( dir.y < - 0.99999 ) {
  25238. this.quaternion.set( 1, 0, 0, 0 );
  25239. } else {
  25240. axis.set( dir.z, 0, - dir.x ).normalize();
  25241. radians = Math.acos( dir.y );
  25242. this.quaternion.setFromAxisAngle( axis, radians );
  25243. }
  25244. };
  25245. }() );
  25246. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  25247. if ( headLength === undefined ) headLength = 0.2 * length;
  25248. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  25249. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  25250. this.line.updateMatrix();
  25251. this.cone.scale.set( headWidth, headLength, headWidth );
  25252. this.cone.position.y = length;
  25253. this.cone.updateMatrix();
  25254. };
  25255. ArrowHelper.prototype.setColor = function ( color ) {
  25256. this.line.material.color.copy( color );
  25257. this.cone.material.color.copy( color );
  25258. };
  25259. /**
  25260. * @author sroucheray / http://sroucheray.org/
  25261. * @author mrdoob / http://mrdoob.com/
  25262. */
  25263. function AxisHelper( size ) {
  25264. size = size || 1;
  25265. var vertices = [
  25266. 0, 0, 0, size, 0, 0,
  25267. 0, 0, 0, 0, size, 0,
  25268. 0, 0, 0, 0, 0, size
  25269. ];
  25270. var colors = [
  25271. 1, 0, 0, 1, 0.6, 0,
  25272. 0, 1, 0, 0.6, 1, 0,
  25273. 0, 0, 1, 0, 0.6, 1
  25274. ];
  25275. var geometry = new BufferGeometry();
  25276. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25277. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  25278. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  25279. LineSegments.call( this, geometry, material );
  25280. }
  25281. AxisHelper.prototype = Object.create( LineSegments.prototype );
  25282. AxisHelper.prototype.constructor = AxisHelper;
  25283. /**
  25284. * @author zz85 https://github.com/zz85
  25285. *
  25286. * Centripetal CatmullRom Curve - which is useful for avoiding
  25287. * cusps and self-intersections in non-uniform catmull rom curves.
  25288. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  25289. *
  25290. * curve.type accepts centripetal(default), chordal and catmullrom
  25291. * curve.tension is used for catmullrom which defaults to 0.5
  25292. */
  25293. /*
  25294. Based on an optimized c++ solution in
  25295. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  25296. - http://ideone.com/NoEbVM
  25297. This CubicPoly class could be used for reusing some variables and calculations,
  25298. but for three.js curve use, it could be possible inlined and flatten into a single function call
  25299. which can be placed in CurveUtils.
  25300. */
  25301. function CubicPoly() {
  25302. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  25303. /*
  25304. * Compute coefficients for a cubic polynomial
  25305. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  25306. * such that
  25307. * p(0) = x0, p(1) = x1
  25308. * and
  25309. * p'(0) = t0, p'(1) = t1.
  25310. */
  25311. function init( x0, x1, t0, t1 ) {
  25312. c0 = x0;
  25313. c1 = t0;
  25314. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  25315. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  25316. }
  25317. return {
  25318. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  25319. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  25320. },
  25321. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  25322. // compute tangents when parameterized in [t1,t2]
  25323. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  25324. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  25325. // rescale tangents for parametrization in [0,1]
  25326. t1 *= dt1;
  25327. t2 *= dt1;
  25328. init( x1, x2, t1, t2 );
  25329. },
  25330. calc: function ( t ) {
  25331. var t2 = t * t;
  25332. var t3 = t2 * t;
  25333. return c0 + c1 * t + c2 * t2 + c3 * t3;
  25334. }
  25335. };
  25336. }
  25337. //
  25338. var tmp = new Vector3();
  25339. var px = new CubicPoly();
  25340. var py = new CubicPoly();
  25341. var pz = new CubicPoly();
  25342. function CatmullRomCurve3( points ) {
  25343. Curve.call( this );
  25344. if ( points.length < 2 ) console.warn( 'THREE.CatmullRomCurve3: Points array needs at least two entries.' );
  25345. this.points = points || [];
  25346. this.closed = false;
  25347. }
  25348. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  25349. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  25350. CatmullRomCurve3.prototype.getPoint = function ( t ) {
  25351. var points = this.points;
  25352. var l = points.length;
  25353. var point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  25354. var intPoint = Math.floor( point );
  25355. var weight = point - intPoint;
  25356. if ( this.closed ) {
  25357. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  25358. } else if ( weight === 0 && intPoint === l - 1 ) {
  25359. intPoint = l - 2;
  25360. weight = 1;
  25361. }
  25362. var p0, p1, p2, p3; // 4 points
  25363. if ( this.closed || intPoint > 0 ) {
  25364. p0 = points[ ( intPoint - 1 ) % l ];
  25365. } else {
  25366. // extrapolate first point
  25367. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  25368. p0 = tmp;
  25369. }
  25370. p1 = points[ intPoint % l ];
  25371. p2 = points[ ( intPoint + 1 ) % l ];
  25372. if ( this.closed || intPoint + 2 < l ) {
  25373. p3 = points[ ( intPoint + 2 ) % l ];
  25374. } else {
  25375. // extrapolate last point
  25376. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  25377. p3 = tmp;
  25378. }
  25379. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  25380. // init Centripetal / Chordal Catmull-Rom
  25381. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  25382. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  25383. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  25384. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  25385. // safety check for repeated points
  25386. if ( dt1 < 1e-4 ) dt1 = 1.0;
  25387. if ( dt0 < 1e-4 ) dt0 = dt1;
  25388. if ( dt2 < 1e-4 ) dt2 = dt1;
  25389. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  25390. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  25391. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  25392. } else if ( this.type === 'catmullrom' ) {
  25393. var tension = this.tension !== undefined ? this.tension : 0.5;
  25394. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  25395. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  25396. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  25397. }
  25398. return new Vector3( px.calc( weight ), py.calc( weight ), pz.calc( weight ) );
  25399. };
  25400. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  25401. Curve.call( this );
  25402. this.v0 = v0;
  25403. this.v1 = v1;
  25404. this.v2 = v2;
  25405. this.v3 = v3;
  25406. }
  25407. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  25408. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  25409. CubicBezierCurve3.prototype.getPoint = function ( t ) {
  25410. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  25411. return new Vector3(
  25412. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  25413. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  25414. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  25415. );
  25416. };
  25417. function QuadraticBezierCurve3( v0, v1, v2 ) {
  25418. Curve.call( this );
  25419. this.v0 = v0;
  25420. this.v1 = v1;
  25421. this.v2 = v2;
  25422. }
  25423. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  25424. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  25425. QuadraticBezierCurve3.prototype.getPoint = function ( t ) {
  25426. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  25427. return new Vector3(
  25428. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  25429. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  25430. QuadraticBezier( t, v0.z, v1.z, v2.z )
  25431. );
  25432. };
  25433. function LineCurve3( v1, v2 ) {
  25434. Curve.call( this );
  25435. this.v1 = v1;
  25436. this.v2 = v2;
  25437. }
  25438. LineCurve3.prototype = Object.create( Curve.prototype );
  25439. LineCurve3.prototype.constructor = LineCurve3;
  25440. LineCurve3.prototype.getPoint = function ( t ) {
  25441. if ( t === 1 ) {
  25442. return this.v2.clone();
  25443. }
  25444. var vector = new Vector3();
  25445. vector.subVectors( this.v2, this.v1 ); // diff
  25446. vector.multiplyScalar( t );
  25447. vector.add( this.v1 );
  25448. return vector;
  25449. };
  25450. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25451. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25452. }
  25453. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  25454. ArcCurve.prototype.constructor = ArcCurve;
  25455. /**
  25456. * @author alteredq / http://alteredqualia.com/
  25457. */
  25458. var SceneUtils = {
  25459. createMultiMaterialObject: function ( geometry, materials ) {
  25460. var group = new Group();
  25461. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  25462. group.add( new Mesh( geometry, materials[ i ] ) );
  25463. }
  25464. return group;
  25465. },
  25466. detach: function ( child, parent, scene ) {
  25467. child.applyMatrix( parent.matrixWorld );
  25468. parent.remove( child );
  25469. scene.add( child );
  25470. },
  25471. attach: function ( child, scene, parent ) {
  25472. child.applyMatrix( new Matrix4().getInverse( parent.matrixWorld ) );
  25473. scene.remove( child );
  25474. parent.add( child );
  25475. }
  25476. };
  25477. /**
  25478. * @author mrdoob / http://mrdoob.com/
  25479. */
  25480. function Face4( a, b, c, d, normal, color, materialIndex ) {
  25481. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  25482. return new Face3( a, b, c, normal, color, materialIndex );
  25483. }
  25484. var LineStrip = 0;
  25485. var LinePieces = 1;
  25486. function MeshFaceMaterial( materials ) {
  25487. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  25488. return materials;
  25489. }
  25490. function MultiMaterial( materials ) {
  25491. if ( materials === undefined ) materials = [];
  25492. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  25493. materials.isMultiMaterial = true;
  25494. materials.materials = materials;
  25495. materials.clone = function () {
  25496. return materials.slice();
  25497. };
  25498. return materials;
  25499. }
  25500. function PointCloud( geometry, material ) {
  25501. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  25502. return new Points( geometry, material );
  25503. }
  25504. function Particle( material ) {
  25505. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  25506. return new Sprite( material );
  25507. }
  25508. function ParticleSystem( geometry, material ) {
  25509. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  25510. return new Points( geometry, material );
  25511. }
  25512. function PointCloudMaterial( parameters ) {
  25513. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  25514. return new PointsMaterial( parameters );
  25515. }
  25516. function ParticleBasicMaterial( parameters ) {
  25517. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  25518. return new PointsMaterial( parameters );
  25519. }
  25520. function ParticleSystemMaterial( parameters ) {
  25521. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  25522. return new PointsMaterial( parameters );
  25523. }
  25524. function Vertex( x, y, z ) {
  25525. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  25526. return new Vector3( x, y, z );
  25527. }
  25528. //
  25529. function DynamicBufferAttribute( array, itemSize ) {
  25530. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  25531. return new BufferAttribute( array, itemSize ).setDynamic( true );
  25532. }
  25533. function Int8Attribute( array, itemSize ) {
  25534. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  25535. return new Int8BufferAttribute( array, itemSize );
  25536. }
  25537. function Uint8Attribute( array, itemSize ) {
  25538. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  25539. return new Uint8BufferAttribute( array, itemSize );
  25540. }
  25541. function Uint8ClampedAttribute( array, itemSize ) {
  25542. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  25543. return new Uint8ClampedBufferAttribute( array, itemSize );
  25544. }
  25545. function Int16Attribute( array, itemSize ) {
  25546. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  25547. return new Int16BufferAttribute( array, itemSize );
  25548. }
  25549. function Uint16Attribute( array, itemSize ) {
  25550. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  25551. return new Uint16BufferAttribute( array, itemSize );
  25552. }
  25553. function Int32Attribute( array, itemSize ) {
  25554. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  25555. return new Int32BufferAttribute( array, itemSize );
  25556. }
  25557. function Uint32Attribute( array, itemSize ) {
  25558. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  25559. return new Uint32BufferAttribute( array, itemSize );
  25560. }
  25561. function Float32Attribute( array, itemSize ) {
  25562. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  25563. return new Float32BufferAttribute( array, itemSize );
  25564. }
  25565. function Float64Attribute( array, itemSize ) {
  25566. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  25567. return new Float64BufferAttribute( array, itemSize );
  25568. }
  25569. //
  25570. Curve.create = function ( construct, getPoint ) {
  25571. console.log( 'THREE.Curve.create() has been deprecated' );
  25572. construct.prototype = Object.create( Curve.prototype );
  25573. construct.prototype.constructor = construct;
  25574. construct.prototype.getPoint = getPoint;
  25575. return construct;
  25576. };
  25577. //
  25578. function ClosedSplineCurve3( points ) {
  25579. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25580. CatmullRomCurve3.call( this, points );
  25581. this.type = 'catmullrom';
  25582. this.closed = true;
  25583. }
  25584. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25585. //
  25586. function SplineCurve3( points ) {
  25587. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25588. CatmullRomCurve3.call( this, points );
  25589. this.type = 'catmullrom';
  25590. }
  25591. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25592. //
  25593. function Spline( points ) {
  25594. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  25595. CatmullRomCurve3.call( this, points );
  25596. this.type = 'catmullrom';
  25597. }
  25598. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  25599. Object.assign( Spline.prototype, {
  25600. initFromArray: function ( a ) {
  25601. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  25602. },
  25603. getControlPointsArray: function ( optionalTarget ) {
  25604. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  25605. },
  25606. reparametrizeByArcLength: function ( samplingCoef ) {
  25607. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  25608. }
  25609. } );
  25610. //
  25611. function BoundingBoxHelper( object, color ) {
  25612. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  25613. return new BoxHelper( object, color );
  25614. }
  25615. function EdgesHelper( object, hex ) {
  25616. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  25617. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25618. }
  25619. GridHelper.prototype.setColors = function () {
  25620. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  25621. };
  25622. SkeletonHelper.prototype.update = function () {
  25623. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  25624. };
  25625. function WireframeHelper( object, hex ) {
  25626. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  25627. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25628. }
  25629. //
  25630. function XHRLoader( manager ) {
  25631. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  25632. return new FileLoader( manager );
  25633. }
  25634. function BinaryTextureLoader( manager ) {
  25635. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  25636. return new DataTextureLoader( manager );
  25637. }
  25638. //
  25639. Object.assign( Box2.prototype, {
  25640. center: function ( optionalTarget ) {
  25641. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  25642. return this.getCenter( optionalTarget );
  25643. },
  25644. empty: function () {
  25645. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  25646. return this.isEmpty();
  25647. },
  25648. isIntersectionBox: function ( box ) {
  25649. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25650. return this.intersectsBox( box );
  25651. },
  25652. size: function ( optionalTarget ) {
  25653. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  25654. return this.getSize( optionalTarget );
  25655. }
  25656. } );
  25657. Object.assign( Box3.prototype, {
  25658. center: function ( optionalTarget ) {
  25659. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  25660. return this.getCenter( optionalTarget );
  25661. },
  25662. empty: function () {
  25663. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  25664. return this.isEmpty();
  25665. },
  25666. isIntersectionBox: function ( box ) {
  25667. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25668. return this.intersectsBox( box );
  25669. },
  25670. isIntersectionSphere: function ( sphere ) {
  25671. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25672. return this.intersectsSphere( sphere );
  25673. },
  25674. size: function ( optionalTarget ) {
  25675. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  25676. return this.getSize( optionalTarget );
  25677. }
  25678. } );
  25679. Line3.prototype.center = function ( optionalTarget ) {
  25680. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  25681. return this.getCenter( optionalTarget );
  25682. };
  25683. _Math.random16 = function () {
  25684. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  25685. return Math.random();
  25686. };
  25687. Object.assign( Matrix3.prototype, {
  25688. flattenToArrayOffset: function ( array, offset ) {
  25689. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25690. return this.toArray( array, offset );
  25691. },
  25692. multiplyVector3: function ( vector ) {
  25693. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  25694. return vector.applyMatrix3( this );
  25695. },
  25696. multiplyVector3Array: function ( a ) {
  25697. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  25698. },
  25699. applyToBuffer: function( buffer, offset, length ) {
  25700. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25701. return this.applyToBufferAttribute( buffer );
  25702. },
  25703. applyToVector3Array: function( array, offset, length ) {
  25704. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  25705. }
  25706. } );
  25707. Object.assign( Matrix4.prototype, {
  25708. extractPosition: function ( m ) {
  25709. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  25710. return this.copyPosition( m );
  25711. },
  25712. flattenToArrayOffset: function ( array, offset ) {
  25713. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25714. return this.toArray( array, offset );
  25715. },
  25716. getPosition: function () {
  25717. var v1;
  25718. return function getPosition() {
  25719. if ( v1 === undefined ) v1 = new Vector3();
  25720. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  25721. return v1.setFromMatrixColumn( this, 3 );
  25722. };
  25723. }(),
  25724. setRotationFromQuaternion: function ( q ) {
  25725. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  25726. return this.makeRotationFromQuaternion( q );
  25727. },
  25728. multiplyToArray: function () {
  25729. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  25730. },
  25731. multiplyVector3: function ( vector ) {
  25732. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25733. return vector.applyMatrix4( this );
  25734. },
  25735. multiplyVector4: function ( vector ) {
  25736. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25737. return vector.applyMatrix4( this );
  25738. },
  25739. multiplyVector3Array: function ( a ) {
  25740. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  25741. },
  25742. rotateAxis: function ( v ) {
  25743. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  25744. v.transformDirection( this );
  25745. },
  25746. crossVector: function ( vector ) {
  25747. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25748. return vector.applyMatrix4( this );
  25749. },
  25750. translate: function () {
  25751. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  25752. },
  25753. rotateX: function () {
  25754. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  25755. },
  25756. rotateY: function () {
  25757. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  25758. },
  25759. rotateZ: function () {
  25760. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  25761. },
  25762. rotateByAxis: function () {
  25763. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  25764. },
  25765. applyToBuffer: function( buffer, offset, length ) {
  25766. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25767. return this.applyToBufferAttribute( buffer );
  25768. },
  25769. applyToVector3Array: function( array, offset, length ) {
  25770. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  25771. },
  25772. makeFrustum: function( left, right, bottom, top, near, far ) {
  25773. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  25774. return this.makePerspective( left, right, top, bottom, near, far );
  25775. }
  25776. } );
  25777. Plane.prototype.isIntersectionLine = function ( line ) {
  25778. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  25779. return this.intersectsLine( line );
  25780. };
  25781. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  25782. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  25783. return vector.applyQuaternion( this );
  25784. };
  25785. Object.assign( Ray.prototype, {
  25786. isIntersectionBox: function ( box ) {
  25787. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25788. return this.intersectsBox( box );
  25789. },
  25790. isIntersectionPlane: function ( plane ) {
  25791. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  25792. return this.intersectsPlane( plane );
  25793. },
  25794. isIntersectionSphere: function ( sphere ) {
  25795. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25796. return this.intersectsSphere( sphere );
  25797. }
  25798. } );
  25799. Object.assign( Shape.prototype, {
  25800. extrude: function ( options ) {
  25801. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  25802. return new ExtrudeGeometry( this, options );
  25803. },
  25804. makeGeometry: function ( options ) {
  25805. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  25806. return new ShapeGeometry( this, options );
  25807. }
  25808. } );
  25809. Object.assign( Vector2.prototype, {
  25810. fromAttribute: function ( attribute, index, offset ) {
  25811. console.error( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25812. return this.fromBufferAttribute( attribute, index, offset );
  25813. }
  25814. } );
  25815. Object.assign( Vector3.prototype, {
  25816. setEulerFromRotationMatrix: function () {
  25817. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  25818. },
  25819. setEulerFromQuaternion: function () {
  25820. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  25821. },
  25822. getPositionFromMatrix: function ( m ) {
  25823. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  25824. return this.setFromMatrixPosition( m );
  25825. },
  25826. getScaleFromMatrix: function ( m ) {
  25827. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  25828. return this.setFromMatrixScale( m );
  25829. },
  25830. getColumnFromMatrix: function ( index, matrix ) {
  25831. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  25832. return this.setFromMatrixColumn( matrix, index );
  25833. },
  25834. applyProjection: function ( m ) {
  25835. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  25836. return this.applyMatrix4( m );
  25837. },
  25838. fromAttribute: function ( attribute, index, offset ) {
  25839. console.error( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25840. return this.fromBufferAttribute( attribute, index, offset );
  25841. }
  25842. } );
  25843. Object.assign( Vector4.prototype, {
  25844. fromAttribute: function ( attribute, index, offset ) {
  25845. console.error( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25846. return this.fromBufferAttribute( attribute, index, offset );
  25847. }
  25848. } );
  25849. //
  25850. Geometry.prototype.computeTangents = function () {
  25851. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  25852. };
  25853. Object.assign( Object3D.prototype, {
  25854. getChildByName: function ( name ) {
  25855. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  25856. return this.getObjectByName( name );
  25857. },
  25858. renderDepth: function () {
  25859. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  25860. },
  25861. translate: function ( distance, axis ) {
  25862. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  25863. return this.translateOnAxis( axis, distance );
  25864. }
  25865. } );
  25866. Object.defineProperties( Object3D.prototype, {
  25867. eulerOrder: {
  25868. get: function () {
  25869. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25870. return this.rotation.order;
  25871. },
  25872. set: function ( value ) {
  25873. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25874. this.rotation.order = value;
  25875. }
  25876. },
  25877. useQuaternion: {
  25878. get: function () {
  25879. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25880. },
  25881. set: function () {
  25882. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25883. }
  25884. }
  25885. } );
  25886. Object.defineProperties( LOD.prototype, {
  25887. objects: {
  25888. get: function () {
  25889. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  25890. return this.levels;
  25891. }
  25892. }
  25893. } );
  25894. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  25895. get: function () {
  25896. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  25897. },
  25898. set: function () {
  25899. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  25900. }
  25901. } );
  25902. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  25903. get: function () {
  25904. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  25905. return this.arcLengthDivisions;
  25906. },
  25907. set: function ( value ) {
  25908. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  25909. this.arcLengthDivisions = value;
  25910. }
  25911. } );
  25912. //
  25913. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  25914. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  25915. "Use .setFocalLength and .filmGauge for a photographic setup." );
  25916. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  25917. this.setFocalLength( focalLength );
  25918. };
  25919. //
  25920. Object.defineProperties( Light.prototype, {
  25921. onlyShadow: {
  25922. set: function () {
  25923. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  25924. }
  25925. },
  25926. shadowCameraFov: {
  25927. set: function ( value ) {
  25928. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  25929. this.shadow.camera.fov = value;
  25930. }
  25931. },
  25932. shadowCameraLeft: {
  25933. set: function ( value ) {
  25934. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  25935. this.shadow.camera.left = value;
  25936. }
  25937. },
  25938. shadowCameraRight: {
  25939. set: function ( value ) {
  25940. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  25941. this.shadow.camera.right = value;
  25942. }
  25943. },
  25944. shadowCameraTop: {
  25945. set: function ( value ) {
  25946. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  25947. this.shadow.camera.top = value;
  25948. }
  25949. },
  25950. shadowCameraBottom: {
  25951. set: function ( value ) {
  25952. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  25953. this.shadow.camera.bottom = value;
  25954. }
  25955. },
  25956. shadowCameraNear: {
  25957. set: function ( value ) {
  25958. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  25959. this.shadow.camera.near = value;
  25960. }
  25961. },
  25962. shadowCameraFar: {
  25963. set: function ( value ) {
  25964. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  25965. this.shadow.camera.far = value;
  25966. }
  25967. },
  25968. shadowCameraVisible: {
  25969. set: function () {
  25970. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  25971. }
  25972. },
  25973. shadowBias: {
  25974. set: function ( value ) {
  25975. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  25976. this.shadow.bias = value;
  25977. }
  25978. },
  25979. shadowDarkness: {
  25980. set: function () {
  25981. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  25982. }
  25983. },
  25984. shadowMapWidth: {
  25985. set: function ( value ) {
  25986. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  25987. this.shadow.mapSize.width = value;
  25988. }
  25989. },
  25990. shadowMapHeight: {
  25991. set: function ( value ) {
  25992. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  25993. this.shadow.mapSize.height = value;
  25994. }
  25995. }
  25996. } );
  25997. //
  25998. Object.defineProperties( BufferAttribute.prototype, {
  25999. length: {
  26000. get: function () {
  26001. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  26002. return this.array.length;
  26003. }
  26004. }
  26005. } );
  26006. Object.assign( BufferGeometry.prototype, {
  26007. addIndex: function ( index ) {
  26008. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  26009. this.setIndex( index );
  26010. },
  26011. addDrawCall: function ( start, count, indexOffset ) {
  26012. if ( indexOffset !== undefined ) {
  26013. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  26014. }
  26015. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  26016. this.addGroup( start, count );
  26017. },
  26018. clearDrawCalls: function () {
  26019. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  26020. this.clearGroups();
  26021. },
  26022. computeTangents: function () {
  26023. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  26024. },
  26025. computeOffsets: function () {
  26026. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  26027. }
  26028. } );
  26029. Object.defineProperties( BufferGeometry.prototype, {
  26030. drawcalls: {
  26031. get: function () {
  26032. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  26033. return this.groups;
  26034. }
  26035. },
  26036. offsets: {
  26037. get: function () {
  26038. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  26039. return this.groups;
  26040. }
  26041. }
  26042. } );
  26043. //
  26044. Object.defineProperties( Uniform.prototype, {
  26045. dynamic: {
  26046. set: function () {
  26047. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  26048. }
  26049. },
  26050. onUpdate: {
  26051. value: function () {
  26052. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  26053. return this;
  26054. }
  26055. }
  26056. } );
  26057. //
  26058. Object.defineProperties( Material.prototype, {
  26059. wrapAround: {
  26060. get: function () {
  26061. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  26062. },
  26063. set: function () {
  26064. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  26065. }
  26066. },
  26067. wrapRGB: {
  26068. get: function () {
  26069. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  26070. return new Color();
  26071. }
  26072. },
  26073. shading: {
  26074. get: function () {
  26075. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  26076. },
  26077. set: function ( value ) {
  26078. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  26079. this.flatShading = ( value === THREE.FlatShading ) ? true : false;
  26080. }
  26081. }
  26082. } );
  26083. Object.defineProperties( MeshPhongMaterial.prototype, {
  26084. metal: {
  26085. get: function () {
  26086. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  26087. return false;
  26088. },
  26089. set: function () {
  26090. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  26091. }
  26092. }
  26093. } );
  26094. Object.defineProperties( ShaderMaterial.prototype, {
  26095. derivatives: {
  26096. get: function () {
  26097. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  26098. return this.extensions.derivatives;
  26099. },
  26100. set: function ( value ) {
  26101. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  26102. this.extensions.derivatives = value;
  26103. }
  26104. }
  26105. } );
  26106. //
  26107. Object.assign( WebGLRenderer.prototype, {
  26108. getCurrentRenderTarget: function () {
  26109. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  26110. return this.getRenderTarget();
  26111. },
  26112. getMaxAnisotropy: function () {
  26113. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  26114. return this.capabilities.getMaxAnisotropy();
  26115. },
  26116. getPrecision: function () {
  26117. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  26118. return this.capabilities.precision;
  26119. },
  26120. supportsFloatTextures: function () {
  26121. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  26122. return this.extensions.get( 'OES_texture_float' );
  26123. },
  26124. supportsHalfFloatTextures: function () {
  26125. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  26126. return this.extensions.get( 'OES_texture_half_float' );
  26127. },
  26128. supportsStandardDerivatives: function () {
  26129. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  26130. return this.extensions.get( 'OES_standard_derivatives' );
  26131. },
  26132. supportsCompressedTextureS3TC: function () {
  26133. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  26134. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  26135. },
  26136. supportsCompressedTexturePVRTC: function () {
  26137. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  26138. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  26139. },
  26140. supportsBlendMinMax: function () {
  26141. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  26142. return this.extensions.get( 'EXT_blend_minmax' );
  26143. },
  26144. supportsVertexTextures: function () {
  26145. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  26146. return this.capabilities.vertexTextures;
  26147. },
  26148. supportsInstancedArrays: function () {
  26149. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  26150. return this.extensions.get( 'ANGLE_instanced_arrays' );
  26151. },
  26152. enableScissorTest: function ( boolean ) {
  26153. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  26154. this.setScissorTest( boolean );
  26155. },
  26156. initMaterial: function () {
  26157. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  26158. },
  26159. addPrePlugin: function () {
  26160. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  26161. },
  26162. addPostPlugin: function () {
  26163. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  26164. },
  26165. updateShadowMap: function () {
  26166. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  26167. }
  26168. } );
  26169. Object.defineProperties( WebGLRenderer.prototype, {
  26170. shadowMapEnabled: {
  26171. get: function () {
  26172. return this.shadowMap.enabled;
  26173. },
  26174. set: function ( value ) {
  26175. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  26176. this.shadowMap.enabled = value;
  26177. }
  26178. },
  26179. shadowMapType: {
  26180. get: function () {
  26181. return this.shadowMap.type;
  26182. },
  26183. set: function ( value ) {
  26184. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  26185. this.shadowMap.type = value;
  26186. }
  26187. },
  26188. shadowMapCullFace: {
  26189. get: function () {
  26190. return this.shadowMap.cullFace;
  26191. },
  26192. set: function ( value ) {
  26193. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  26194. this.shadowMap.cullFace = value;
  26195. }
  26196. }
  26197. } );
  26198. Object.defineProperties( WebGLShadowMap.prototype, {
  26199. cullFace: {
  26200. get: function () {
  26201. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  26202. },
  26203. set: function ( cullFace ) {
  26204. var value = ( cullFace !== CullFaceBack );
  26205. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  26206. this.renderReverseSided = value;
  26207. }
  26208. }
  26209. } );
  26210. //
  26211. Object.defineProperties( WebGLRenderTarget.prototype, {
  26212. wrapS: {
  26213. get: function () {
  26214. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  26215. return this.texture.wrapS;
  26216. },
  26217. set: function ( value ) {
  26218. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  26219. this.texture.wrapS = value;
  26220. }
  26221. },
  26222. wrapT: {
  26223. get: function () {
  26224. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  26225. return this.texture.wrapT;
  26226. },
  26227. set: function ( value ) {
  26228. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  26229. this.texture.wrapT = value;
  26230. }
  26231. },
  26232. magFilter: {
  26233. get: function () {
  26234. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  26235. return this.texture.magFilter;
  26236. },
  26237. set: function ( value ) {
  26238. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  26239. this.texture.magFilter = value;
  26240. }
  26241. },
  26242. minFilter: {
  26243. get: function () {
  26244. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  26245. return this.texture.minFilter;
  26246. },
  26247. set: function ( value ) {
  26248. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  26249. this.texture.minFilter = value;
  26250. }
  26251. },
  26252. anisotropy: {
  26253. get: function () {
  26254. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  26255. return this.texture.anisotropy;
  26256. },
  26257. set: function ( value ) {
  26258. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  26259. this.texture.anisotropy = value;
  26260. }
  26261. },
  26262. offset: {
  26263. get: function () {
  26264. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  26265. return this.texture.offset;
  26266. },
  26267. set: function ( value ) {
  26268. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  26269. this.texture.offset = value;
  26270. }
  26271. },
  26272. repeat: {
  26273. get: function () {
  26274. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  26275. return this.texture.repeat;
  26276. },
  26277. set: function ( value ) {
  26278. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  26279. this.texture.repeat = value;
  26280. }
  26281. },
  26282. format: {
  26283. get: function () {
  26284. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  26285. return this.texture.format;
  26286. },
  26287. set: function ( value ) {
  26288. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  26289. this.texture.format = value;
  26290. }
  26291. },
  26292. type: {
  26293. get: function () {
  26294. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  26295. return this.texture.type;
  26296. },
  26297. set: function ( value ) {
  26298. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  26299. this.texture.type = value;
  26300. }
  26301. },
  26302. generateMipmaps: {
  26303. get: function () {
  26304. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  26305. return this.texture.generateMipmaps;
  26306. },
  26307. set: function ( value ) {
  26308. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  26309. this.texture.generateMipmaps = value;
  26310. }
  26311. }
  26312. } );
  26313. //
  26314. Audio.prototype.load = function ( file ) {
  26315. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  26316. var scope = this;
  26317. var audioLoader = new AudioLoader();
  26318. audioLoader.load( file, function ( buffer ) {
  26319. scope.setBuffer( buffer );
  26320. } );
  26321. return this;
  26322. };
  26323. AudioAnalyser.prototype.getData = function () {
  26324. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  26325. return this.getFrequencyData();
  26326. };
  26327. //
  26328. var GeometryUtils = {
  26329. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  26330. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  26331. var matrix;
  26332. if ( geometry2.isMesh ) {
  26333. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  26334. matrix = geometry2.matrix;
  26335. geometry2 = geometry2.geometry;
  26336. }
  26337. geometry1.merge( geometry2, matrix, materialIndexOffset );
  26338. },
  26339. center: function ( geometry ) {
  26340. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  26341. return geometry.center();
  26342. }
  26343. };
  26344. var ImageUtils = {
  26345. crossOrigin: undefined,
  26346. loadTexture: function ( url, mapping, onLoad, onError ) {
  26347. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  26348. var loader = new TextureLoader();
  26349. loader.setCrossOrigin( this.crossOrigin );
  26350. var texture = loader.load( url, onLoad, undefined, onError );
  26351. if ( mapping ) texture.mapping = mapping;
  26352. return texture;
  26353. },
  26354. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  26355. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  26356. var loader = new CubeTextureLoader();
  26357. loader.setCrossOrigin( this.crossOrigin );
  26358. var texture = loader.load( urls, onLoad, undefined, onError );
  26359. if ( mapping ) texture.mapping = mapping;
  26360. return texture;
  26361. },
  26362. loadCompressedTexture: function () {
  26363. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  26364. },
  26365. loadCompressedTextureCube: function () {
  26366. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  26367. }
  26368. };
  26369. //
  26370. function Projector() {
  26371. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  26372. this.projectVector = function ( vector, camera ) {
  26373. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  26374. vector.project( camera );
  26375. };
  26376. this.unprojectVector = function ( vector, camera ) {
  26377. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  26378. vector.unproject( camera );
  26379. };
  26380. this.pickingRay = function () {
  26381. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  26382. };
  26383. }
  26384. //
  26385. function CanvasRenderer() {
  26386. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  26387. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  26388. this.clear = function () {};
  26389. this.render = function () {};
  26390. this.setClearColor = function () {};
  26391. this.setSize = function () {};
  26392. }
  26393. export { WebGLRenderTargetCube, WebGLRenderTarget, WebGLRenderer, ShaderLib, UniformsLib, UniformsUtils, ShaderChunk, FogExp2, Fog, Scene, LensFlare, Sprite, LOD, SkinnedMesh, Skeleton, Bone, Mesh, LineSegments, LineLoop, Line, Points, Group, VideoTexture, DataTexture, CompressedTexture, CubeTexture, CanvasTexture, DepthTexture, Texture, CompressedTextureLoader, DataTextureLoader, CubeTextureLoader, TextureLoader, ObjectLoader, MaterialLoader, BufferGeometryLoader, DefaultLoadingManager, LoadingManager, JSONLoader, ImageLoader, FontLoader, FileLoader, Loader, Cache, AudioLoader, SpotLightShadow, SpotLight, PointLight, RectAreaLight, HemisphereLight, DirectionalLightShadow, DirectionalLight, AmbientLight, LightShadow, Light, StereoCamera, PerspectiveCamera, OrthographicCamera, CubeCamera, ArrayCamera, Camera, AudioListener, PositionalAudio, AudioContext, AudioAnalyser, Audio, VectorKeyframeTrack, StringKeyframeTrack, QuaternionKeyframeTrack, NumberKeyframeTrack, ColorKeyframeTrack, BooleanKeyframeTrack, PropertyMixer, PropertyBinding, KeyframeTrack, AnimationUtils, AnimationObjectGroup, AnimationMixer, AnimationClip, Uniform, InstancedBufferGeometry, BufferGeometry, GeometryIdCount, Geometry, InterleavedBufferAttribute, InstancedInterleavedBuffer, InterleavedBuffer, InstancedBufferAttribute, Face3, Object3D, Raycaster, Layers, EventDispatcher, Clock, QuaternionLinearInterpolant, LinearInterpolant, DiscreteInterpolant, CubicInterpolant, Interpolant, Triangle, _Math as Math, Spherical, Cylindrical, Plane, Frustum, Sphere, Ray, Matrix4, Matrix3, Box3, Box2, Line3, Euler, Vector4, Vector3, Vector2, Quaternion, Color, MorphBlendMesh, ImmediateRenderObject, VertexNormalsHelper, SpotLightHelper, SkeletonHelper, PointLightHelper, RectAreaLightHelper, HemisphereLightHelper, GridHelper, PolarGridHelper, FaceNormalsHelper, DirectionalLightHelper, CameraHelper, BoxHelper, Box3Helper, PlaneHelper, ArrowHelper, AxisHelper, CatmullRomCurve3, CubicBezierCurve3, QuadraticBezierCurve3, LineCurve3, ArcCurve, EllipseCurve, SplineCurve, CubicBezierCurve, QuadraticBezierCurve, LineCurve, Shape, Path, ShapePath, Font, CurvePath, Curve, ShapeUtils, SceneUtils, WireframeGeometry, ParametricGeometry, ParametricBufferGeometry, TetrahedronGeometry, TetrahedronBufferGeometry, OctahedronGeometry, OctahedronBufferGeometry, IcosahedronGeometry, IcosahedronBufferGeometry, DodecahedronGeometry, DodecahedronBufferGeometry, PolyhedronGeometry, PolyhedronBufferGeometry, TubeGeometry, TubeBufferGeometry, TorusKnotGeometry, TorusKnotBufferGeometry, TorusGeometry, TorusBufferGeometry, TextGeometry, TextBufferGeometry, SphereGeometry, SphereBufferGeometry, RingGeometry, RingBufferGeometry, PlaneGeometry, PlaneBufferGeometry, LatheGeometry, LatheBufferGeometry, ShapeGeometry, ShapeBufferGeometry, ExtrudeGeometry, ExtrudeBufferGeometry, EdgesGeometry, ConeGeometry, ConeBufferGeometry, CylinderGeometry, CylinderBufferGeometry, CircleGeometry, CircleBufferGeometry, BoxGeometry, BoxBufferGeometry, ShadowMaterial, SpriteMaterial, RawShaderMaterial, ShaderMaterial, PointsMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshPhongMaterial, MeshToonMaterial, MeshNormalMaterial, MeshLambertMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshBasicMaterial, LineDashedMaterial, LineBasicMaterial, Material, Float64BufferAttribute, Float32BufferAttribute, Uint32BufferAttribute, Int32BufferAttribute, Uint16BufferAttribute, Int16BufferAttribute, Uint8ClampedBufferAttribute, Uint8BufferAttribute, Int8BufferAttribute, BufferAttribute, REVISION, MOUSE, CullFaceNone, CullFaceBack, CullFaceFront, CullFaceFrontBack, FrontFaceDirectionCW, FrontFaceDirectionCCW, BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, FrontSide, BackSide, DoubleSide, FlatShading, SmoothShading, NoColors, FaceColors, VertexColors, NoBlending, NormalBlending, AdditiveBlending, SubtractiveBlending, MultiplyBlending, CustomBlending, AddEquation, SubtractEquation, ReverseSubtractEquation, MinEquation, MaxEquation, ZeroFactor, OneFactor, SrcColorFactor, OneMinusSrcColorFactor, SrcAlphaFactor, OneMinusSrcAlphaFactor, DstAlphaFactor, OneMinusDstAlphaFactor, DstColorFactor, OneMinusDstColorFactor, SrcAlphaSaturateFactor, NeverDepth, AlwaysDepth, LessDepth, LessEqualDepth, EqualDepth, GreaterEqualDepth, GreaterDepth, NotEqualDepth, MultiplyOperation, MixOperation, AddOperation, NoToneMapping, LinearToneMapping, ReinhardToneMapping, Uncharted2ToneMapping, CineonToneMapping, UVMapping, CubeReflectionMapping, CubeRefractionMapping, EquirectangularReflectionMapping, EquirectangularRefractionMapping, SphericalReflectionMapping, CubeUVReflectionMapping, CubeUVRefractionMapping, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, NearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter, LinearFilter, LinearMipMapNearestFilter, LinearMipMapLinearFilter, UnsignedByteType, ByteType, ShortType, UnsignedShortType, IntType, UnsignedIntType, FloatType, HalfFloatType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShort565Type, UnsignedInt248Type, AlphaFormat, RGBFormat, RGBAFormat, LuminanceFormat, LuminanceAlphaFormat, RGBEFormat, DepthFormat, DepthStencilFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, LoopOnce, LoopRepeat, LoopPingPong, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, ZeroCurvatureEnding, ZeroSlopeEnding, WrapAroundEnding, TrianglesDrawMode, TriangleStripDrawMode, TriangleFanDrawMode, LinearEncoding, sRGBEncoding, GammaEncoding, RGBEEncoding, LogLuvEncoding, RGBM7Encoding, RGBM16Encoding, RGBDEncoding, BasicDepthPacking, RGBADepthPacking, BoxGeometry as CubeGeometry, Face4, LineStrip, LinePieces, MeshFaceMaterial, MultiMaterial, PointCloud, Particle, ParticleSystem, PointCloudMaterial, ParticleBasicMaterial, ParticleSystemMaterial, Vertex, DynamicBufferAttribute, Int8Attribute, Uint8Attribute, Uint8ClampedAttribute, Int16Attribute, Uint16Attribute, Int32Attribute, Uint32Attribute, Float32Attribute, Float64Attribute, ClosedSplineCurve3, SplineCurve3, Spline, BoundingBoxHelper, EdgesHelper, WireframeHelper, XHRLoader, BinaryTextureLoader, GeometryUtils, ImageUtils, Projector, CanvasRenderer };