three.module.js 984 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847
  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 = '87';
  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 instanceof HTMLCanvasElement ) {
  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, 'rebeccapurple': 0x663399, '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 vec3 color;\nuniform 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( color, 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. shadow: {
  3791. uniforms: UniformsUtils.merge( [
  3792. UniformsLib.lights,
  3793. {
  3794. color: { value: new Color( 0x00000 ) },
  3795. opacity: { value: 1.0 }
  3796. },
  3797. ] ),
  3798. vertexShader: ShaderChunk.shadow_vert,
  3799. fragmentShader: ShaderChunk.shadow_frag
  3800. }
  3801. };
  3802. ShaderLib.physical = {
  3803. uniforms: UniformsUtils.merge( [
  3804. ShaderLib.standard.uniforms,
  3805. {
  3806. clearCoat: { value: 0 },
  3807. clearCoatRoughness: { value: 0 }
  3808. }
  3809. ] ),
  3810. vertexShader: ShaderChunk.meshphysical_vert,
  3811. fragmentShader: ShaderChunk.meshphysical_frag
  3812. };
  3813. /**
  3814. * @author bhouston / http://clara.io
  3815. */
  3816. function Box2( min, max ) {
  3817. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  3818. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  3819. }
  3820. Object.assign( Box2.prototype, {
  3821. set: function ( min, max ) {
  3822. this.min.copy( min );
  3823. this.max.copy( max );
  3824. return this;
  3825. },
  3826. setFromPoints: function ( points ) {
  3827. this.makeEmpty();
  3828. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3829. this.expandByPoint( points[ i ] );
  3830. }
  3831. return this;
  3832. },
  3833. setFromCenterAndSize: function () {
  3834. var v1 = new Vector2();
  3835. return function setFromCenterAndSize( center, size ) {
  3836. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  3837. this.min.copy( center ).sub( halfSize );
  3838. this.max.copy( center ).add( halfSize );
  3839. return this;
  3840. };
  3841. }(),
  3842. clone: function () {
  3843. return new this.constructor().copy( this );
  3844. },
  3845. copy: function ( box ) {
  3846. this.min.copy( box.min );
  3847. this.max.copy( box.max );
  3848. return this;
  3849. },
  3850. makeEmpty: function () {
  3851. this.min.x = this.min.y = + Infinity;
  3852. this.max.x = this.max.y = - Infinity;
  3853. return this;
  3854. },
  3855. isEmpty: function () {
  3856. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3857. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  3858. },
  3859. getCenter: function ( optionalTarget ) {
  3860. var result = optionalTarget || new Vector2();
  3861. return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3862. },
  3863. getSize: function ( optionalTarget ) {
  3864. var result = optionalTarget || new Vector2();
  3865. return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min );
  3866. },
  3867. expandByPoint: function ( point ) {
  3868. this.min.min( point );
  3869. this.max.max( point );
  3870. return this;
  3871. },
  3872. expandByVector: function ( vector ) {
  3873. this.min.sub( vector );
  3874. this.max.add( vector );
  3875. return this;
  3876. },
  3877. expandByScalar: function ( scalar ) {
  3878. this.min.addScalar( - scalar );
  3879. this.max.addScalar( scalar );
  3880. return this;
  3881. },
  3882. containsPoint: function ( point ) {
  3883. return point.x < this.min.x || point.x > this.max.x ||
  3884. point.y < this.min.y || point.y > this.max.y ? false : true;
  3885. },
  3886. containsBox: function ( box ) {
  3887. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3888. this.min.y <= box.min.y && box.max.y <= this.max.y;
  3889. },
  3890. getParameter: function ( point, optionalTarget ) {
  3891. // This can potentially have a divide by zero if the box
  3892. // has a size dimension of 0.
  3893. var result = optionalTarget || new Vector2();
  3894. return result.set(
  3895. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3896. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  3897. );
  3898. },
  3899. intersectsBox: function ( box ) {
  3900. // using 4 splitting planes to rule out intersections
  3901. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3902. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  3903. },
  3904. clampPoint: function ( point, optionalTarget ) {
  3905. var result = optionalTarget || new Vector2();
  3906. return result.copy( point ).clamp( this.min, this.max );
  3907. },
  3908. distanceToPoint: function () {
  3909. var v1 = new Vector2();
  3910. return function distanceToPoint( point ) {
  3911. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  3912. return clampedPoint.sub( point ).length();
  3913. };
  3914. }(),
  3915. intersect: function ( box ) {
  3916. this.min.max( box.min );
  3917. this.max.min( box.max );
  3918. return this;
  3919. },
  3920. union: function ( box ) {
  3921. this.min.min( box.min );
  3922. this.max.max( box.max );
  3923. return this;
  3924. },
  3925. translate: function ( offset ) {
  3926. this.min.add( offset );
  3927. this.max.add( offset );
  3928. return this;
  3929. },
  3930. equals: function ( box ) {
  3931. return box.min.equals( this.min ) && box.max.equals( this.max );
  3932. }
  3933. } );
  3934. /**
  3935. * @author mikael emtinger / http://gomo.se/
  3936. * @author alteredq / http://alteredqualia.com/
  3937. */
  3938. function WebGLFlareRenderer( renderer, gl, state, textures, capabilities ) {
  3939. var vertexBuffer, elementBuffer;
  3940. var shader, program, attributes, uniforms;
  3941. var tempTexture, occlusionTexture;
  3942. function init() {
  3943. var vertices = new Float32Array( [
  3944. - 1, - 1, 0, 0,
  3945. 1, - 1, 1, 0,
  3946. 1, 1, 1, 1,
  3947. - 1, 1, 0, 1
  3948. ] );
  3949. var faces = new Uint16Array( [
  3950. 0, 1, 2,
  3951. 0, 2, 3
  3952. ] );
  3953. // buffers
  3954. vertexBuffer = gl.createBuffer();
  3955. elementBuffer = gl.createBuffer();
  3956. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  3957. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  3958. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  3959. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  3960. // textures
  3961. tempTexture = gl.createTexture();
  3962. occlusionTexture = gl.createTexture();
  3963. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  3964. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  3965. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3966. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3967. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3968. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3969. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  3970. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  3971. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3972. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3973. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3974. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3975. shader = {
  3976. vertexShader: [
  3977. "uniform lowp int renderType;",
  3978. "uniform vec3 screenPosition;",
  3979. "uniform vec2 scale;",
  3980. "uniform float rotation;",
  3981. "uniform sampler2D occlusionMap;",
  3982. "attribute vec2 position;",
  3983. "attribute vec2 uv;",
  3984. "varying vec2 vUV;",
  3985. "varying float vVisibility;",
  3986. "void main() {",
  3987. "vUV = uv;",
  3988. "vec2 pos = position;",
  3989. "if ( renderType == 2 ) {",
  3990. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  3991. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  3992. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  3993. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  3994. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  3995. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  3996. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  3997. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  3998. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  3999. "vVisibility = visibility.r / 9.0;",
  4000. "vVisibility *= 1.0 - visibility.g / 9.0;",
  4001. "vVisibility *= visibility.b / 9.0;",
  4002. "vVisibility *= 1.0 - visibility.a / 9.0;",
  4003. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  4004. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  4005. "}",
  4006. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  4007. "}"
  4008. ].join( "\n" ),
  4009. fragmentShader: [
  4010. "uniform lowp int renderType;",
  4011. "uniform sampler2D map;",
  4012. "uniform float opacity;",
  4013. "uniform vec3 color;",
  4014. "varying vec2 vUV;",
  4015. "varying float vVisibility;",
  4016. "void main() {",
  4017. // pink square
  4018. "if ( renderType == 0 ) {",
  4019. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  4020. // restore
  4021. "} else if ( renderType == 1 ) {",
  4022. "gl_FragColor = texture2D( map, vUV );",
  4023. // flare
  4024. "} else {",
  4025. "vec4 texture = texture2D( map, vUV );",
  4026. "texture.a *= opacity * vVisibility;",
  4027. "gl_FragColor = texture;",
  4028. "gl_FragColor.rgb *= color;",
  4029. "}",
  4030. "}"
  4031. ].join( "\n" )
  4032. };
  4033. program = createProgram( shader );
  4034. attributes = {
  4035. vertex: gl.getAttribLocation ( program, "position" ),
  4036. uv: gl.getAttribLocation ( program, "uv" )
  4037. };
  4038. uniforms = {
  4039. renderType: gl.getUniformLocation( program, "renderType" ),
  4040. map: gl.getUniformLocation( program, "map" ),
  4041. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  4042. opacity: gl.getUniformLocation( program, "opacity" ),
  4043. color: gl.getUniformLocation( program, "color" ),
  4044. scale: gl.getUniformLocation( program, "scale" ),
  4045. rotation: gl.getUniformLocation( program, "rotation" ),
  4046. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  4047. };
  4048. }
  4049. /*
  4050. * Render lens flares
  4051. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  4052. * reads these back and calculates occlusion.
  4053. */
  4054. this.render = function ( flares, scene, camera, viewport ) {
  4055. if ( flares.length === 0 ) return;
  4056. var tempPosition = new Vector3();
  4057. var invAspect = viewport.w / viewport.z,
  4058. halfViewportWidth = viewport.z * 0.5,
  4059. halfViewportHeight = viewport.w * 0.5;
  4060. var size = 16 / viewport.w,
  4061. scale = new Vector2( size * invAspect, size );
  4062. var screenPosition = new Vector3( 1, 1, 0 ),
  4063. screenPositionPixels = new Vector2( 1, 1 );
  4064. var validArea = new Box2();
  4065. validArea.min.set( viewport.x, viewport.y );
  4066. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  4067. if ( program === undefined ) {
  4068. init();
  4069. }
  4070. state.useProgram( program );
  4071. state.initAttributes();
  4072. state.enableAttribute( attributes.vertex );
  4073. state.enableAttribute( attributes.uv );
  4074. state.disableUnusedAttributes();
  4075. // loop through all lens flares to update their occlusion and positions
  4076. // setup gl and common used attribs/uniforms
  4077. gl.uniform1i( uniforms.occlusionMap, 0 );
  4078. gl.uniform1i( uniforms.map, 1 );
  4079. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4080. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  4081. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4082. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4083. state.disable( gl.CULL_FACE );
  4084. state.buffers.depth.setMask( false );
  4085. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  4086. size = 16 / viewport.w;
  4087. scale.set( size * invAspect, size );
  4088. // calc object screen position
  4089. var flare = flares[ i ];
  4090. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  4091. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  4092. tempPosition.applyMatrix4( camera.projectionMatrix );
  4093. // setup arrays for gl programs
  4094. screenPosition.copy( tempPosition );
  4095. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  4096. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  4097. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  4098. // screen cull
  4099. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  4100. // save current RGB to temp texture
  4101. state.activeTexture( gl.TEXTURE0 );
  4102. state.bindTexture( gl.TEXTURE_2D, null );
  4103. state.activeTexture( gl.TEXTURE1 );
  4104. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4105. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4106. // render pink quad
  4107. gl.uniform1i( uniforms.renderType, 0 );
  4108. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4109. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4110. state.disable( gl.BLEND );
  4111. state.enable( gl.DEPTH_TEST );
  4112. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4113. // copy result to occlusionMap
  4114. state.activeTexture( gl.TEXTURE0 );
  4115. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  4116. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4117. // restore graphics
  4118. gl.uniform1i( uniforms.renderType, 1 );
  4119. state.disable( gl.DEPTH_TEST );
  4120. state.activeTexture( gl.TEXTURE1 );
  4121. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4122. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4123. // update object positions
  4124. flare.positionScreen.copy( screenPosition );
  4125. if ( flare.customUpdateCallback ) {
  4126. flare.customUpdateCallback( flare );
  4127. } else {
  4128. flare.updateLensFlares();
  4129. }
  4130. // render flares
  4131. gl.uniform1i( uniforms.renderType, 2 );
  4132. state.enable( gl.BLEND );
  4133. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  4134. var sprite = flare.lensFlares[ j ];
  4135. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  4136. screenPosition.x = sprite.x;
  4137. screenPosition.y = sprite.y;
  4138. screenPosition.z = sprite.z;
  4139. size = sprite.size * sprite.scale / viewport.w;
  4140. scale.x = size * invAspect;
  4141. scale.y = size;
  4142. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4143. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4144. gl.uniform1f( uniforms.rotation, sprite.rotation );
  4145. gl.uniform1f( uniforms.opacity, sprite.opacity );
  4146. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  4147. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  4148. textures.setTexture2D( sprite.texture, 1 );
  4149. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4150. }
  4151. }
  4152. }
  4153. }
  4154. // restore gl
  4155. state.enable( gl.CULL_FACE );
  4156. state.enable( gl.DEPTH_TEST );
  4157. state.buffers.depth.setMask( true );
  4158. state.reset();
  4159. };
  4160. function createProgram( shader ) {
  4161. var program = gl.createProgram();
  4162. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4163. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4164. var prefix = "precision " + capabilities.precision + " float;\n";
  4165. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  4166. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  4167. gl.compileShader( fragmentShader );
  4168. gl.compileShader( vertexShader );
  4169. gl.attachShader( program, fragmentShader );
  4170. gl.attachShader( program, vertexShader );
  4171. gl.linkProgram( program );
  4172. return program;
  4173. }
  4174. }
  4175. /**
  4176. * @author mrdoob / http://mrdoob.com/
  4177. */
  4178. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  4179. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  4180. this.needsUpdate = true;
  4181. }
  4182. CanvasTexture.prototype = Object.create( Texture.prototype );
  4183. CanvasTexture.prototype.constructor = CanvasTexture;
  4184. /**
  4185. * @author mikael emtinger / http://gomo.se/
  4186. * @author alteredq / http://alteredqualia.com/
  4187. */
  4188. function WebGLSpriteRenderer( renderer, gl, state, textures, capabilities ) {
  4189. var vertexBuffer, elementBuffer;
  4190. var program, attributes, uniforms;
  4191. var texture;
  4192. // decompose matrixWorld
  4193. var spritePosition = new Vector3();
  4194. var spriteRotation = new Quaternion();
  4195. var spriteScale = new Vector3();
  4196. function init() {
  4197. var vertices = new Float32Array( [
  4198. - 0.5, - 0.5, 0, 0,
  4199. 0.5, - 0.5, 1, 0,
  4200. 0.5, 0.5, 1, 1,
  4201. - 0.5, 0.5, 0, 1
  4202. ] );
  4203. var faces = new Uint16Array( [
  4204. 0, 1, 2,
  4205. 0, 2, 3
  4206. ] );
  4207. vertexBuffer = gl.createBuffer();
  4208. elementBuffer = gl.createBuffer();
  4209. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4210. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  4211. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4212. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  4213. program = createProgram();
  4214. attributes = {
  4215. position: gl.getAttribLocation ( program, 'position' ),
  4216. uv: gl.getAttribLocation ( program, 'uv' )
  4217. };
  4218. uniforms = {
  4219. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  4220. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  4221. rotation: gl.getUniformLocation( program, 'rotation' ),
  4222. scale: gl.getUniformLocation( program, 'scale' ),
  4223. color: gl.getUniformLocation( program, 'color' ),
  4224. map: gl.getUniformLocation( program, 'map' ),
  4225. opacity: gl.getUniformLocation( program, 'opacity' ),
  4226. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  4227. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  4228. fogType: gl.getUniformLocation( program, 'fogType' ),
  4229. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  4230. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  4231. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  4232. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  4233. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  4234. };
  4235. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  4236. canvas.width = 8;
  4237. canvas.height = 8;
  4238. var context = canvas.getContext( '2d' );
  4239. context.fillStyle = 'white';
  4240. context.fillRect( 0, 0, 8, 8 );
  4241. texture = new CanvasTexture( canvas );
  4242. }
  4243. this.render = function ( sprites, scene, camera ) {
  4244. if ( sprites.length === 0 ) return;
  4245. // setup gl
  4246. if ( program === undefined ) {
  4247. init();
  4248. }
  4249. state.useProgram( program );
  4250. state.initAttributes();
  4251. state.enableAttribute( attributes.position );
  4252. state.enableAttribute( attributes.uv );
  4253. state.disableUnusedAttributes();
  4254. state.disable( gl.CULL_FACE );
  4255. state.enable( gl.BLEND );
  4256. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4257. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  4258. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4259. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4260. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  4261. state.activeTexture( gl.TEXTURE0 );
  4262. gl.uniform1i( uniforms.map, 0 );
  4263. var oldFogType = 0;
  4264. var sceneFogType = 0;
  4265. var fog = scene.fog;
  4266. if ( fog ) {
  4267. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  4268. if ( fog.isFog ) {
  4269. gl.uniform1f( uniforms.fogNear, fog.near );
  4270. gl.uniform1f( uniforms.fogFar, fog.far );
  4271. gl.uniform1i( uniforms.fogType, 1 );
  4272. oldFogType = 1;
  4273. sceneFogType = 1;
  4274. } else if ( fog.isFogExp2 ) {
  4275. gl.uniform1f( uniforms.fogDensity, fog.density );
  4276. gl.uniform1i( uniforms.fogType, 2 );
  4277. oldFogType = 2;
  4278. sceneFogType = 2;
  4279. }
  4280. } else {
  4281. gl.uniform1i( uniforms.fogType, 0 );
  4282. oldFogType = 0;
  4283. sceneFogType = 0;
  4284. }
  4285. // update positions and sort
  4286. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4287. var sprite = sprites[ i ];
  4288. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  4289. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  4290. }
  4291. sprites.sort( painterSortStable );
  4292. // render all sprites
  4293. var scale = [];
  4294. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4295. var sprite = sprites[ i ];
  4296. var material = sprite.material;
  4297. if ( material.visible === false ) continue;
  4298. sprite.onBeforeRender( renderer, scene, camera, undefined, material, undefined );
  4299. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  4300. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  4301. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  4302. scale[ 0 ] = spriteScale.x;
  4303. scale[ 1 ] = spriteScale.y;
  4304. var fogType = 0;
  4305. if ( scene.fog && material.fog ) {
  4306. fogType = sceneFogType;
  4307. }
  4308. if ( oldFogType !== fogType ) {
  4309. gl.uniform1i( uniforms.fogType, fogType );
  4310. oldFogType = fogType;
  4311. }
  4312. if ( material.map !== null ) {
  4313. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  4314. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  4315. } else {
  4316. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  4317. gl.uniform2f( uniforms.uvScale, 1, 1 );
  4318. }
  4319. gl.uniform1f( uniforms.opacity, material.opacity );
  4320. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  4321. gl.uniform1f( uniforms.rotation, material.rotation );
  4322. gl.uniform2fv( uniforms.scale, scale );
  4323. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  4324. state.buffers.depth.setTest( material.depthTest );
  4325. state.buffers.depth.setMask( material.depthWrite );
  4326. textures.setTexture2D( material.map || texture, 0 );
  4327. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4328. sprite.onAfterRender( renderer, scene, camera, undefined, material, undefined );
  4329. }
  4330. // restore gl
  4331. state.enable( gl.CULL_FACE );
  4332. state.reset();
  4333. };
  4334. function createProgram() {
  4335. var program = gl.createProgram();
  4336. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4337. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4338. gl.shaderSource( vertexShader, [
  4339. 'precision ' + capabilities.precision + ' float;',
  4340. '#define SHADER_NAME ' + 'SpriteMaterial',
  4341. 'uniform mat4 modelViewMatrix;',
  4342. 'uniform mat4 projectionMatrix;',
  4343. 'uniform float rotation;',
  4344. 'uniform vec2 scale;',
  4345. 'uniform vec2 uvOffset;',
  4346. 'uniform vec2 uvScale;',
  4347. 'attribute vec2 position;',
  4348. 'attribute vec2 uv;',
  4349. 'varying vec2 vUV;',
  4350. 'void main() {',
  4351. 'vUV = uvOffset + uv * uvScale;',
  4352. 'vec2 alignedPosition = position * scale;',
  4353. 'vec2 rotatedPosition;',
  4354. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  4355. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  4356. 'vec4 finalPosition;',
  4357. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  4358. 'finalPosition.xy += rotatedPosition;',
  4359. 'finalPosition = projectionMatrix * finalPosition;',
  4360. 'gl_Position = finalPosition;',
  4361. '}'
  4362. ].join( '\n' ) );
  4363. gl.shaderSource( fragmentShader, [
  4364. 'precision ' + capabilities.precision + ' float;',
  4365. '#define SHADER_NAME ' + 'SpriteMaterial',
  4366. 'uniform vec3 color;',
  4367. 'uniform sampler2D map;',
  4368. 'uniform float opacity;',
  4369. 'uniform int fogType;',
  4370. 'uniform vec3 fogColor;',
  4371. 'uniform float fogDensity;',
  4372. 'uniform float fogNear;',
  4373. 'uniform float fogFar;',
  4374. 'uniform float alphaTest;',
  4375. 'varying vec2 vUV;',
  4376. 'void main() {',
  4377. 'vec4 texture = texture2D( map, vUV );',
  4378. 'if ( texture.a < alphaTest ) discard;',
  4379. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  4380. 'if ( fogType > 0 ) {',
  4381. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  4382. 'float fogFactor = 0.0;',
  4383. 'if ( fogType == 1 ) {',
  4384. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  4385. '} else {',
  4386. 'const float LOG2 = 1.442695;',
  4387. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  4388. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  4389. '}',
  4390. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  4391. '}',
  4392. '}'
  4393. ].join( '\n' ) );
  4394. gl.compileShader( vertexShader );
  4395. gl.compileShader( fragmentShader );
  4396. gl.attachShader( program, vertexShader );
  4397. gl.attachShader( program, fragmentShader );
  4398. gl.linkProgram( program );
  4399. return program;
  4400. }
  4401. function painterSortStable( a, b ) {
  4402. if ( a.renderOrder !== b.renderOrder ) {
  4403. return a.renderOrder - b.renderOrder;
  4404. } else if ( a.z !== b.z ) {
  4405. return b.z - a.z;
  4406. } else {
  4407. return b.id - a.id;
  4408. }
  4409. }
  4410. }
  4411. /**
  4412. * @author mrdoob / http://mrdoob.com/
  4413. * @author alteredq / http://alteredqualia.com/
  4414. */
  4415. var materialId = 0;
  4416. function Material() {
  4417. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4418. this.uuid = _Math.generateUUID();
  4419. this.name = '';
  4420. this.type = 'Material';
  4421. this.fog = true;
  4422. this.lights = true;
  4423. this.blending = NormalBlending;
  4424. this.side = FrontSide;
  4425. this.flatShading = false;
  4426. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  4427. this.opacity = 1;
  4428. this.transparent = false;
  4429. this.blendSrc = SrcAlphaFactor;
  4430. this.blendDst = OneMinusSrcAlphaFactor;
  4431. this.blendEquation = AddEquation;
  4432. this.blendSrcAlpha = null;
  4433. this.blendDstAlpha = null;
  4434. this.blendEquationAlpha = null;
  4435. this.depthFunc = LessEqualDepth;
  4436. this.depthTest = true;
  4437. this.depthWrite = true;
  4438. this.clippingPlanes = null;
  4439. this.clipIntersection = false;
  4440. this.clipShadows = false;
  4441. this.colorWrite = true;
  4442. this.precision = null; // override the renderer's default precision for this material
  4443. this.polygonOffset = false;
  4444. this.polygonOffsetFactor = 0;
  4445. this.polygonOffsetUnits = 0;
  4446. this.dithering = false;
  4447. this.alphaTest = 0;
  4448. this.premultipliedAlpha = false;
  4449. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  4450. this.visible = true;
  4451. this.userData = {};
  4452. this.needsUpdate = true;
  4453. }
  4454. Object.assign( Material.prototype, EventDispatcher.prototype, {
  4455. isMaterial: true,
  4456. onBeforeCompile: function () {},
  4457. setValues: function ( values ) {
  4458. if ( values === undefined ) return;
  4459. for ( var key in values ) {
  4460. var newValue = values[ key ];
  4461. if ( newValue === undefined ) {
  4462. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  4463. continue;
  4464. }
  4465. // for backward compatability if shading is set in the constructor
  4466. if ( key === 'shading' ) {
  4467. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  4468. this.flatShading = ( newValue === FlatShading ) ? true : false;
  4469. continue;
  4470. }
  4471. var currentValue = this[ key ];
  4472. if ( currentValue === undefined ) {
  4473. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  4474. continue;
  4475. }
  4476. if ( currentValue && currentValue.isColor ) {
  4477. currentValue.set( newValue );
  4478. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4479. currentValue.copy( newValue );
  4480. } else if ( key === 'overdraw' ) {
  4481. // ensure overdraw is backwards-compatible with legacy boolean type
  4482. this[ key ] = Number( newValue );
  4483. } else {
  4484. this[ key ] = newValue;
  4485. }
  4486. }
  4487. },
  4488. toJSON: function ( meta ) {
  4489. var isRoot = meta === undefined;
  4490. if ( isRoot ) {
  4491. meta = {
  4492. textures: {},
  4493. images: {}
  4494. };
  4495. }
  4496. var data = {
  4497. metadata: {
  4498. version: 4.5,
  4499. type: 'Material',
  4500. generator: 'Material.toJSON'
  4501. }
  4502. };
  4503. // standard Material serialization
  4504. data.uuid = this.uuid;
  4505. data.type = this.type;
  4506. if ( this.name !== '' ) data.name = this.name;
  4507. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4508. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4509. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4510. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4511. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4512. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4513. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  4514. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  4515. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4516. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4517. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4518. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4519. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4520. data.bumpScale = this.bumpScale;
  4521. }
  4522. if ( this.normalMap && this.normalMap.isTexture ) {
  4523. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4524. data.normalScale = this.normalScale.toArray();
  4525. }
  4526. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4527. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4528. data.displacementScale = this.displacementScale;
  4529. data.displacementBias = this.displacementBias;
  4530. }
  4531. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4532. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4533. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4534. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4535. if ( this.envMap && this.envMap.isTexture ) {
  4536. data.envMap = this.envMap.toJSON( meta ).uuid;
  4537. data.reflectivity = this.reflectivity; // Scale behind envMap
  4538. }
  4539. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4540. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4541. }
  4542. if ( this.size !== undefined ) data.size = this.size;
  4543. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4544. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4545. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  4546. if ( this.side !== FrontSide ) data.side = this.side;
  4547. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  4548. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4549. if ( this.transparent === true ) data.transparent = this.transparent;
  4550. data.depthFunc = this.depthFunc;
  4551. data.depthTest = this.depthTest;
  4552. data.depthWrite = this.depthWrite;
  4553. if ( this.dithering === true ) data.dithering = true;
  4554. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4555. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4556. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4557. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4558. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4559. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4560. if ( this.morphTargets === true ) data.morphTargets = true;
  4561. if ( this.skinning === true ) data.skinning = true;
  4562. if ( this.visible === false ) data.visible = false;
  4563. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  4564. // TODO: Copied from Object3D.toJSON
  4565. function extractFromCache( cache ) {
  4566. var values = [];
  4567. for ( var key in cache ) {
  4568. var data = cache[ key ];
  4569. delete data.metadata;
  4570. values.push( data );
  4571. }
  4572. return values;
  4573. }
  4574. if ( isRoot ) {
  4575. var textures = extractFromCache( meta.textures );
  4576. var images = extractFromCache( meta.images );
  4577. if ( textures.length > 0 ) data.textures = textures;
  4578. if ( images.length > 0 ) data.images = images;
  4579. }
  4580. return data;
  4581. },
  4582. clone: function () {
  4583. return new this.constructor().copy( this );
  4584. },
  4585. copy: function ( source ) {
  4586. this.name = source.name;
  4587. this.fog = source.fog;
  4588. this.lights = source.lights;
  4589. this.blending = source.blending;
  4590. this.side = source.side;
  4591. this.flatShading = source.flatShading;
  4592. this.vertexColors = source.vertexColors;
  4593. this.opacity = source.opacity;
  4594. this.transparent = source.transparent;
  4595. this.blendSrc = source.blendSrc;
  4596. this.blendDst = source.blendDst;
  4597. this.blendEquation = source.blendEquation;
  4598. this.blendSrcAlpha = source.blendSrcAlpha;
  4599. this.blendDstAlpha = source.blendDstAlpha;
  4600. this.blendEquationAlpha = source.blendEquationAlpha;
  4601. this.depthFunc = source.depthFunc;
  4602. this.depthTest = source.depthTest;
  4603. this.depthWrite = source.depthWrite;
  4604. this.colorWrite = source.colorWrite;
  4605. this.precision = source.precision;
  4606. this.polygonOffset = source.polygonOffset;
  4607. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4608. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4609. this.dithering = source.dithering;
  4610. this.alphaTest = source.alphaTest;
  4611. this.premultipliedAlpha = source.premultipliedAlpha;
  4612. this.overdraw = source.overdraw;
  4613. this.visible = source.visible;
  4614. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4615. this.clipShadows = source.clipShadows;
  4616. this.clipIntersection = source.clipIntersection;
  4617. var srcPlanes = source.clippingPlanes,
  4618. dstPlanes = null;
  4619. if ( srcPlanes !== null ) {
  4620. var n = srcPlanes.length;
  4621. dstPlanes = new Array( n );
  4622. for ( var i = 0; i !== n; ++ i )
  4623. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4624. }
  4625. this.clippingPlanes = dstPlanes;
  4626. return this;
  4627. },
  4628. dispose: function () {
  4629. this.dispatchEvent( { type: 'dispose' } );
  4630. }
  4631. } );
  4632. /**
  4633. * @author alteredq / http://alteredqualia.com/
  4634. *
  4635. * parameters = {
  4636. * defines: { "label" : "value" },
  4637. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  4638. *
  4639. * fragmentShader: <string>,
  4640. * vertexShader: <string>,
  4641. *
  4642. * wireframe: <boolean>,
  4643. * wireframeLinewidth: <float>,
  4644. *
  4645. * lights: <bool>,
  4646. *
  4647. * skinning: <bool>,
  4648. * morphTargets: <bool>,
  4649. * morphNormals: <bool>
  4650. * }
  4651. */
  4652. function ShaderMaterial( parameters ) {
  4653. Material.call( this );
  4654. this.type = 'ShaderMaterial';
  4655. this.defines = {};
  4656. this.uniforms = {};
  4657. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  4658. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  4659. this.linewidth = 1;
  4660. this.wireframe = false;
  4661. this.wireframeLinewidth = 1;
  4662. this.fog = false; // set to use scene fog
  4663. this.lights = false; // set to use scene lights
  4664. this.clipping = false; // set to use user-defined clipping planes
  4665. this.skinning = false; // set to use skinning attribute streams
  4666. this.morphTargets = false; // set to use morph targets
  4667. this.morphNormals = false; // set to use morph normals
  4668. this.extensions = {
  4669. derivatives: false, // set to use derivatives
  4670. fragDepth: false, // set to use fragment depth values
  4671. drawBuffers: false, // set to use draw buffers
  4672. shaderTextureLOD: false // set to use shader texture LOD
  4673. };
  4674. // When rendered geometry doesn't include these attributes but the material does,
  4675. // use these default values in WebGL. This avoids errors when buffer data is missing.
  4676. this.defaultAttributeValues = {
  4677. 'color': [ 1, 1, 1 ],
  4678. 'uv': [ 0, 0 ],
  4679. 'uv2': [ 0, 0 ]
  4680. };
  4681. this.index0AttributeName = undefined;
  4682. if ( parameters !== undefined ) {
  4683. if ( parameters.attributes !== undefined ) {
  4684. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  4685. }
  4686. this.setValues( parameters );
  4687. }
  4688. }
  4689. ShaderMaterial.prototype = Object.create( Material.prototype );
  4690. ShaderMaterial.prototype.constructor = ShaderMaterial;
  4691. ShaderMaterial.prototype.isShaderMaterial = true;
  4692. ShaderMaterial.prototype.copy = function ( source ) {
  4693. Material.prototype.copy.call( this, source );
  4694. this.fragmentShader = source.fragmentShader;
  4695. this.vertexShader = source.vertexShader;
  4696. this.uniforms = UniformsUtils.clone( source.uniforms );
  4697. this.defines = source.defines;
  4698. this.wireframe = source.wireframe;
  4699. this.wireframeLinewidth = source.wireframeLinewidth;
  4700. this.lights = source.lights;
  4701. this.clipping = source.clipping;
  4702. this.skinning = source.skinning;
  4703. this.morphTargets = source.morphTargets;
  4704. this.morphNormals = source.morphNormals;
  4705. this.extensions = source.extensions;
  4706. return this;
  4707. };
  4708. ShaderMaterial.prototype.toJSON = function ( meta ) {
  4709. var data = Material.prototype.toJSON.call( this, meta );
  4710. data.uniforms = this.uniforms;
  4711. data.vertexShader = this.vertexShader;
  4712. data.fragmentShader = this.fragmentShader;
  4713. return data;
  4714. };
  4715. /**
  4716. * @author mrdoob / http://mrdoob.com/
  4717. * @author alteredq / http://alteredqualia.com/
  4718. * @author bhouston / https://clara.io
  4719. * @author WestLangley / http://github.com/WestLangley
  4720. *
  4721. * parameters = {
  4722. *
  4723. * opacity: <float>,
  4724. *
  4725. * map: new THREE.Texture( <Image> ),
  4726. *
  4727. * alphaMap: new THREE.Texture( <Image> ),
  4728. *
  4729. * displacementMap: new THREE.Texture( <Image> ),
  4730. * displacementScale: <float>,
  4731. * displacementBias: <float>,
  4732. *
  4733. * wireframe: <boolean>,
  4734. * wireframeLinewidth: <float>
  4735. * }
  4736. */
  4737. function MeshDepthMaterial( parameters ) {
  4738. Material.call( this );
  4739. this.type = 'MeshDepthMaterial';
  4740. this.depthPacking = BasicDepthPacking;
  4741. this.skinning = false;
  4742. this.morphTargets = false;
  4743. this.map = null;
  4744. this.alphaMap = null;
  4745. this.displacementMap = null;
  4746. this.displacementScale = 1;
  4747. this.displacementBias = 0;
  4748. this.wireframe = false;
  4749. this.wireframeLinewidth = 1;
  4750. this.fog = false;
  4751. this.lights = false;
  4752. this.setValues( parameters );
  4753. }
  4754. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  4755. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  4756. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  4757. MeshDepthMaterial.prototype.copy = function ( source ) {
  4758. Material.prototype.copy.call( this, source );
  4759. this.depthPacking = source.depthPacking;
  4760. this.skinning = source.skinning;
  4761. this.morphTargets = source.morphTargets;
  4762. this.map = source.map;
  4763. this.alphaMap = source.alphaMap;
  4764. this.displacementMap = source.displacementMap;
  4765. this.displacementScale = source.displacementScale;
  4766. this.displacementBias = source.displacementBias;
  4767. this.wireframe = source.wireframe;
  4768. this.wireframeLinewidth = source.wireframeLinewidth;
  4769. return this;
  4770. };
  4771. /**
  4772. * @author WestLangley / http://github.com/WestLangley
  4773. *
  4774. * parameters = {
  4775. *
  4776. * referencePosition: <float>,
  4777. * nearDistance: <float>,
  4778. * farDistance: <float>,
  4779. *
  4780. * skinning: <bool>,
  4781. * morphTargets: <bool>,
  4782. *
  4783. * map: new THREE.Texture( <Image> ),
  4784. *
  4785. * alphaMap: new THREE.Texture( <Image> ),
  4786. *
  4787. * displacementMap: new THREE.Texture( <Image> ),
  4788. * displacementScale: <float>,
  4789. * displacementBias: <float>
  4790. *
  4791. * }
  4792. */
  4793. function MeshDistanceMaterial( parameters ) {
  4794. Material.call( this );
  4795. this.type = 'MeshDistanceMaterial';
  4796. this.referencePosition = new Vector3();
  4797. this.nearDistance = 1;
  4798. this.farDistance = 1000;
  4799. this.skinning = false;
  4800. this.morphTargets = false;
  4801. this.map = null;
  4802. this.alphaMap = null;
  4803. this.displacementMap = null;
  4804. this.displacementScale = 1;
  4805. this.displacementBias = 0;
  4806. this.fog = false;
  4807. this.lights = false;
  4808. this.setValues( parameters );
  4809. }
  4810. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  4811. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  4812. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  4813. MeshDistanceMaterial.prototype.copy = function ( source ) {
  4814. Material.prototype.copy.call( this, source );
  4815. this.referencePosition.copy( source.referencePosition );
  4816. this.nearDistance = source.nearDistance;
  4817. this.farDistance = source.farDistance;
  4818. this.skinning = source.skinning;
  4819. this.morphTargets = source.morphTargets;
  4820. this.map = source.map;
  4821. this.alphaMap = source.alphaMap;
  4822. this.displacementMap = source.displacementMap;
  4823. this.displacementScale = source.displacementScale;
  4824. this.displacementBias = source.displacementBias;
  4825. return this;
  4826. };
  4827. /**
  4828. * @author bhouston / http://clara.io
  4829. * @author WestLangley / http://github.com/WestLangley
  4830. */
  4831. function Box3( min, max ) {
  4832. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  4833. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  4834. }
  4835. Object.assign( Box3.prototype, {
  4836. isBox3: true,
  4837. set: function ( min, max ) {
  4838. this.min.copy( min );
  4839. this.max.copy( max );
  4840. return this;
  4841. },
  4842. setFromArray: function ( array ) {
  4843. var minX = + Infinity;
  4844. var minY = + Infinity;
  4845. var minZ = + Infinity;
  4846. var maxX = - Infinity;
  4847. var maxY = - Infinity;
  4848. var maxZ = - Infinity;
  4849. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  4850. var x = array[ i ];
  4851. var y = array[ i + 1 ];
  4852. var z = array[ i + 2 ];
  4853. if ( x < minX ) minX = x;
  4854. if ( y < minY ) minY = y;
  4855. if ( z < minZ ) minZ = z;
  4856. if ( x > maxX ) maxX = x;
  4857. if ( y > maxY ) maxY = y;
  4858. if ( z > maxZ ) maxZ = z;
  4859. }
  4860. this.min.set( minX, minY, minZ );
  4861. this.max.set( maxX, maxY, maxZ );
  4862. return this;
  4863. },
  4864. setFromBufferAttribute: function ( attribute ) {
  4865. var minX = + Infinity;
  4866. var minY = + Infinity;
  4867. var minZ = + Infinity;
  4868. var maxX = - Infinity;
  4869. var maxY = - Infinity;
  4870. var maxZ = - Infinity;
  4871. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  4872. var x = attribute.getX( i );
  4873. var y = attribute.getY( i );
  4874. var z = attribute.getZ( i );
  4875. if ( x < minX ) minX = x;
  4876. if ( y < minY ) minY = y;
  4877. if ( z < minZ ) minZ = z;
  4878. if ( x > maxX ) maxX = x;
  4879. if ( y > maxY ) maxY = y;
  4880. if ( z > maxZ ) maxZ = z;
  4881. }
  4882. this.min.set( minX, minY, minZ );
  4883. this.max.set( maxX, maxY, maxZ );
  4884. return this;
  4885. },
  4886. setFromPoints: function ( points ) {
  4887. this.makeEmpty();
  4888. for ( var i = 0, il = points.length; i < il; i ++ ) {
  4889. this.expandByPoint( points[ i ] );
  4890. }
  4891. return this;
  4892. },
  4893. setFromCenterAndSize: function () {
  4894. var v1 = new Vector3();
  4895. return function setFromCenterAndSize( center, size ) {
  4896. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  4897. this.min.copy( center ).sub( halfSize );
  4898. this.max.copy( center ).add( halfSize );
  4899. return this;
  4900. };
  4901. }(),
  4902. setFromObject: function ( object ) {
  4903. this.makeEmpty();
  4904. return this.expandByObject( object );
  4905. },
  4906. clone: function () {
  4907. return new this.constructor().copy( this );
  4908. },
  4909. copy: function ( box ) {
  4910. this.min.copy( box.min );
  4911. this.max.copy( box.max );
  4912. return this;
  4913. },
  4914. makeEmpty: function () {
  4915. this.min.x = this.min.y = this.min.z = + Infinity;
  4916. this.max.x = this.max.y = this.max.z = - Infinity;
  4917. return this;
  4918. },
  4919. isEmpty: function () {
  4920. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4921. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  4922. },
  4923. getCenter: function ( optionalTarget ) {
  4924. var result = optionalTarget || new Vector3();
  4925. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  4926. },
  4927. getSize: function ( optionalTarget ) {
  4928. var result = optionalTarget || new Vector3();
  4929. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  4930. },
  4931. expandByPoint: function ( point ) {
  4932. this.min.min( point );
  4933. this.max.max( point );
  4934. return this;
  4935. },
  4936. expandByVector: function ( vector ) {
  4937. this.min.sub( vector );
  4938. this.max.add( vector );
  4939. return this;
  4940. },
  4941. expandByScalar: function ( scalar ) {
  4942. this.min.addScalar( - scalar );
  4943. this.max.addScalar( scalar );
  4944. return this;
  4945. },
  4946. expandByObject: function () {
  4947. // Computes the world-axis-aligned bounding box of an object (including its children),
  4948. // accounting for both the object's, and children's, world transforms
  4949. var v1 = new Vector3();
  4950. return function expandByObject( object ) {
  4951. var scope = this;
  4952. object.updateMatrixWorld( true );
  4953. object.traverse( function ( node ) {
  4954. var i, l;
  4955. var geometry = node.geometry;
  4956. if ( geometry !== undefined ) {
  4957. if ( geometry.isGeometry ) {
  4958. var vertices = geometry.vertices;
  4959. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  4960. v1.copy( vertices[ i ] );
  4961. v1.applyMatrix4( node.matrixWorld );
  4962. scope.expandByPoint( v1 );
  4963. }
  4964. } else if ( geometry.isBufferGeometry ) {
  4965. var attribute = geometry.attributes.position;
  4966. if ( attribute !== undefined ) {
  4967. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  4968. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  4969. scope.expandByPoint( v1 );
  4970. }
  4971. }
  4972. }
  4973. }
  4974. } );
  4975. return this;
  4976. };
  4977. }(),
  4978. containsPoint: function ( point ) {
  4979. return point.x < this.min.x || point.x > this.max.x ||
  4980. point.y < this.min.y || point.y > this.max.y ||
  4981. point.z < this.min.z || point.z > this.max.z ? false : true;
  4982. },
  4983. containsBox: function ( box ) {
  4984. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  4985. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  4986. this.min.z <= box.min.z && box.max.z <= this.max.z;
  4987. },
  4988. getParameter: function ( point, optionalTarget ) {
  4989. // This can potentially have a divide by zero if the box
  4990. // has a size dimension of 0.
  4991. var result = optionalTarget || new Vector3();
  4992. return result.set(
  4993. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  4994. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  4995. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  4996. );
  4997. },
  4998. intersectsBox: function ( box ) {
  4999. // using 6 splitting planes to rule out intersections.
  5000. return box.max.x < this.min.x || box.min.x > this.max.x ||
  5001. box.max.y < this.min.y || box.min.y > this.max.y ||
  5002. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  5003. },
  5004. intersectsSphere: ( function () {
  5005. var closestPoint = new Vector3();
  5006. return function intersectsSphere( sphere ) {
  5007. // Find the point on the AABB closest to the sphere center.
  5008. this.clampPoint( sphere.center, closestPoint );
  5009. // If that point is inside the sphere, the AABB and sphere intersect.
  5010. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  5011. };
  5012. } )(),
  5013. intersectsPlane: function ( plane ) {
  5014. // We compute the minimum and maximum dot product values. If those values
  5015. // are on the same side (back or front) of the plane, then there is no intersection.
  5016. var min, max;
  5017. if ( plane.normal.x > 0 ) {
  5018. min = plane.normal.x * this.min.x;
  5019. max = plane.normal.x * this.max.x;
  5020. } else {
  5021. min = plane.normal.x * this.max.x;
  5022. max = plane.normal.x * this.min.x;
  5023. }
  5024. if ( plane.normal.y > 0 ) {
  5025. min += plane.normal.y * this.min.y;
  5026. max += plane.normal.y * this.max.y;
  5027. } else {
  5028. min += plane.normal.y * this.max.y;
  5029. max += plane.normal.y * this.min.y;
  5030. }
  5031. if ( plane.normal.z > 0 ) {
  5032. min += plane.normal.z * this.min.z;
  5033. max += plane.normal.z * this.max.z;
  5034. } else {
  5035. min += plane.normal.z * this.max.z;
  5036. max += plane.normal.z * this.min.z;
  5037. }
  5038. return ( min <= plane.constant && max >= plane.constant );
  5039. },
  5040. clampPoint: function ( point, optionalTarget ) {
  5041. var result = optionalTarget || new Vector3();
  5042. return result.copy( point ).clamp( this.min, this.max );
  5043. },
  5044. distanceToPoint: function () {
  5045. var v1 = new Vector3();
  5046. return function distanceToPoint( point ) {
  5047. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  5048. return clampedPoint.sub( point ).length();
  5049. };
  5050. }(),
  5051. getBoundingSphere: function () {
  5052. var v1 = new Vector3();
  5053. return function getBoundingSphere( optionalTarget ) {
  5054. var result = optionalTarget || new Sphere();
  5055. this.getCenter( result.center );
  5056. result.radius = this.getSize( v1 ).length() * 0.5;
  5057. return result;
  5058. };
  5059. }(),
  5060. intersect: function ( box ) {
  5061. this.min.max( box.min );
  5062. this.max.min( box.max );
  5063. // 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.
  5064. if( this.isEmpty() ) this.makeEmpty();
  5065. return this;
  5066. },
  5067. union: function ( box ) {
  5068. this.min.min( box.min );
  5069. this.max.max( box.max );
  5070. return this;
  5071. },
  5072. applyMatrix4: function () {
  5073. var points = [
  5074. new Vector3(),
  5075. new Vector3(),
  5076. new Vector3(),
  5077. new Vector3(),
  5078. new Vector3(),
  5079. new Vector3(),
  5080. new Vector3(),
  5081. new Vector3()
  5082. ];
  5083. return function applyMatrix4( matrix ) {
  5084. // transform of empty box is an empty box.
  5085. if( this.isEmpty() ) return this;
  5086. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5087. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  5088. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  5089. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  5090. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  5091. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  5092. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  5093. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  5094. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  5095. this.setFromPoints( points );
  5096. return this;
  5097. };
  5098. }(),
  5099. translate: function ( offset ) {
  5100. this.min.add( offset );
  5101. this.max.add( offset );
  5102. return this;
  5103. },
  5104. equals: function ( box ) {
  5105. return box.min.equals( this.min ) && box.max.equals( this.max );
  5106. }
  5107. } );
  5108. /**
  5109. * @author bhouston / http://clara.io
  5110. * @author mrdoob / http://mrdoob.com/
  5111. */
  5112. function Sphere( center, radius ) {
  5113. this.center = ( center !== undefined ) ? center : new Vector3();
  5114. this.radius = ( radius !== undefined ) ? radius : 0;
  5115. }
  5116. Object.assign( Sphere.prototype, {
  5117. set: function ( center, radius ) {
  5118. this.center.copy( center );
  5119. this.radius = radius;
  5120. return this;
  5121. },
  5122. setFromPoints: function () {
  5123. var box = new Box3();
  5124. return function setFromPoints( points, optionalCenter ) {
  5125. var center = this.center;
  5126. if ( optionalCenter !== undefined ) {
  5127. center.copy( optionalCenter );
  5128. } else {
  5129. box.setFromPoints( points ).getCenter( center );
  5130. }
  5131. var maxRadiusSq = 0;
  5132. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5133. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5134. }
  5135. this.radius = Math.sqrt( maxRadiusSq );
  5136. return this;
  5137. };
  5138. }(),
  5139. clone: function () {
  5140. return new this.constructor().copy( this );
  5141. },
  5142. copy: function ( sphere ) {
  5143. this.center.copy( sphere.center );
  5144. this.radius = sphere.radius;
  5145. return this;
  5146. },
  5147. empty: function () {
  5148. return ( this.radius <= 0 );
  5149. },
  5150. containsPoint: function ( point ) {
  5151. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5152. },
  5153. distanceToPoint: function ( point ) {
  5154. return ( point.distanceTo( this.center ) - this.radius );
  5155. },
  5156. intersectsSphere: function ( sphere ) {
  5157. var radiusSum = this.radius + sphere.radius;
  5158. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5159. },
  5160. intersectsBox: function ( box ) {
  5161. return box.intersectsSphere( this );
  5162. },
  5163. intersectsPlane: function ( plane ) {
  5164. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  5165. },
  5166. clampPoint: function ( point, optionalTarget ) {
  5167. var deltaLengthSq = this.center.distanceToSquared( point );
  5168. var result = optionalTarget || new Vector3();
  5169. result.copy( point );
  5170. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5171. result.sub( this.center ).normalize();
  5172. result.multiplyScalar( this.radius ).add( this.center );
  5173. }
  5174. return result;
  5175. },
  5176. getBoundingBox: function ( optionalTarget ) {
  5177. var box = optionalTarget || new Box3();
  5178. box.set( this.center, this.center );
  5179. box.expandByScalar( this.radius );
  5180. return box;
  5181. },
  5182. applyMatrix4: function ( matrix ) {
  5183. this.center.applyMatrix4( matrix );
  5184. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5185. return this;
  5186. },
  5187. translate: function ( offset ) {
  5188. this.center.add( offset );
  5189. return this;
  5190. },
  5191. equals: function ( sphere ) {
  5192. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  5193. }
  5194. } );
  5195. /**
  5196. * @author alteredq / http://alteredqualia.com/
  5197. * @author WestLangley / http://github.com/WestLangley
  5198. * @author bhouston / http://clara.io
  5199. * @author tschw
  5200. */
  5201. function Matrix3() {
  5202. this.elements = [
  5203. 1, 0, 0,
  5204. 0, 1, 0,
  5205. 0, 0, 1
  5206. ];
  5207. if ( arguments.length > 0 ) {
  5208. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  5209. }
  5210. }
  5211. Object.assign( Matrix3.prototype, {
  5212. isMatrix3: true,
  5213. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  5214. var te = this.elements;
  5215. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  5216. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  5217. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  5218. return this;
  5219. },
  5220. identity: function () {
  5221. this.set(
  5222. 1, 0, 0,
  5223. 0, 1, 0,
  5224. 0, 0, 1
  5225. );
  5226. return this;
  5227. },
  5228. clone: function () {
  5229. return new this.constructor().fromArray( this.elements );
  5230. },
  5231. copy: function ( m ) {
  5232. var te = this.elements;
  5233. var me = m.elements;
  5234. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  5235. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  5236. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  5237. return this;
  5238. },
  5239. setFromMatrix4: function ( m ) {
  5240. var me = m.elements;
  5241. this.set(
  5242. me[ 0 ], me[ 4 ], me[ 8 ],
  5243. me[ 1 ], me[ 5 ], me[ 9 ],
  5244. me[ 2 ], me[ 6 ], me[ 10 ]
  5245. );
  5246. return this;
  5247. },
  5248. applyToBufferAttribute: function () {
  5249. var v1 = new Vector3();
  5250. return function applyToBufferAttribute( attribute ) {
  5251. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  5252. v1.x = attribute.getX( i );
  5253. v1.y = attribute.getY( i );
  5254. v1.z = attribute.getZ( i );
  5255. v1.applyMatrix3( this );
  5256. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  5257. }
  5258. return attribute;
  5259. };
  5260. }(),
  5261. multiply: function ( m ) {
  5262. return this.multiplyMatrices( this, m );
  5263. },
  5264. premultiply: function ( m ) {
  5265. return this.multiplyMatrices( m, this );
  5266. },
  5267. multiplyMatrices: function ( a, b ) {
  5268. var ae = a.elements;
  5269. var be = b.elements;
  5270. var te = this.elements;
  5271. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  5272. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  5273. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  5274. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  5275. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  5276. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  5277. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  5278. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  5279. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  5280. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  5281. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  5282. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  5283. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  5284. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  5285. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  5286. return this;
  5287. },
  5288. multiplyScalar: function ( s ) {
  5289. var te = this.elements;
  5290. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  5291. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  5292. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  5293. return this;
  5294. },
  5295. determinant: function () {
  5296. var te = this.elements;
  5297. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  5298. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  5299. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  5300. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  5301. },
  5302. getInverse: function ( matrix, throwOnDegenerate ) {
  5303. if ( matrix && matrix.isMatrix4 ) {
  5304. console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." );
  5305. }
  5306. var me = matrix.elements,
  5307. te = this.elements,
  5308. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  5309. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  5310. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  5311. t11 = n33 * n22 - n32 * n23,
  5312. t12 = n32 * n13 - n33 * n12,
  5313. t13 = n23 * n12 - n22 * n13,
  5314. det = n11 * t11 + n21 * t12 + n31 * t13;
  5315. if ( det === 0 ) {
  5316. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  5317. if ( throwOnDegenerate === true ) {
  5318. throw new Error( msg );
  5319. } else {
  5320. console.warn( msg );
  5321. }
  5322. return this.identity();
  5323. }
  5324. var detInv = 1 / det;
  5325. te[ 0 ] = t11 * detInv;
  5326. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  5327. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  5328. te[ 3 ] = t12 * detInv;
  5329. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  5330. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  5331. te[ 6 ] = t13 * detInv;
  5332. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  5333. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  5334. return this;
  5335. },
  5336. transpose: function () {
  5337. var tmp, m = this.elements;
  5338. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  5339. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  5340. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  5341. return this;
  5342. },
  5343. getNormalMatrix: function ( matrix4 ) {
  5344. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  5345. },
  5346. transposeIntoArray: function ( r ) {
  5347. var m = this.elements;
  5348. r[ 0 ] = m[ 0 ];
  5349. r[ 1 ] = m[ 3 ];
  5350. r[ 2 ] = m[ 6 ];
  5351. r[ 3 ] = m[ 1 ];
  5352. r[ 4 ] = m[ 4 ];
  5353. r[ 5 ] = m[ 7 ];
  5354. r[ 6 ] = m[ 2 ];
  5355. r[ 7 ] = m[ 5 ];
  5356. r[ 8 ] = m[ 8 ];
  5357. return this;
  5358. },
  5359. equals: function ( matrix ) {
  5360. var te = this.elements;
  5361. var me = matrix.elements;
  5362. for ( var i = 0; i < 9; i ++ ) {
  5363. if ( te[ i ] !== me[ i ] ) return false;
  5364. }
  5365. return true;
  5366. },
  5367. fromArray: function ( array, offset ) {
  5368. if ( offset === undefined ) offset = 0;
  5369. for ( var i = 0; i < 9; i ++ ) {
  5370. this.elements[ i ] = array[ i + offset ];
  5371. }
  5372. return this;
  5373. },
  5374. toArray: function ( array, offset ) {
  5375. if ( array === undefined ) array = [];
  5376. if ( offset === undefined ) offset = 0;
  5377. var te = this.elements;
  5378. array[ offset ] = te[ 0 ];
  5379. array[ offset + 1 ] = te[ 1 ];
  5380. array[ offset + 2 ] = te[ 2 ];
  5381. array[ offset + 3 ] = te[ 3 ];
  5382. array[ offset + 4 ] = te[ 4 ];
  5383. array[ offset + 5 ] = te[ 5 ];
  5384. array[ offset + 6 ] = te[ 6 ];
  5385. array[ offset + 7 ] = te[ 7 ];
  5386. array[ offset + 8 ] = te[ 8 ];
  5387. return array;
  5388. }
  5389. } );
  5390. /**
  5391. * @author bhouston / http://clara.io
  5392. */
  5393. function Plane( normal, constant ) {
  5394. // normal is assumed to be normalized
  5395. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  5396. this.constant = ( constant !== undefined ) ? constant : 0;
  5397. }
  5398. Object.assign( Plane.prototype, {
  5399. set: function ( normal, constant ) {
  5400. this.normal.copy( normal );
  5401. this.constant = constant;
  5402. return this;
  5403. },
  5404. setComponents: function ( x, y, z, w ) {
  5405. this.normal.set( x, y, z );
  5406. this.constant = w;
  5407. return this;
  5408. },
  5409. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  5410. this.normal.copy( normal );
  5411. this.constant = - point.dot( this.normal );
  5412. return this;
  5413. },
  5414. setFromCoplanarPoints: function () {
  5415. var v1 = new Vector3();
  5416. var v2 = new Vector3();
  5417. return function setFromCoplanarPoints( a, b, c ) {
  5418. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  5419. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5420. this.setFromNormalAndCoplanarPoint( normal, a );
  5421. return this;
  5422. };
  5423. }(),
  5424. clone: function () {
  5425. return new this.constructor().copy( this );
  5426. },
  5427. copy: function ( plane ) {
  5428. this.normal.copy( plane.normal );
  5429. this.constant = plane.constant;
  5430. return this;
  5431. },
  5432. normalize: function () {
  5433. // Note: will lead to a divide by zero if the plane is invalid.
  5434. var inverseNormalLength = 1.0 / this.normal.length();
  5435. this.normal.multiplyScalar( inverseNormalLength );
  5436. this.constant *= inverseNormalLength;
  5437. return this;
  5438. },
  5439. negate: function () {
  5440. this.constant *= - 1;
  5441. this.normal.negate();
  5442. return this;
  5443. },
  5444. distanceToPoint: function ( point ) {
  5445. return this.normal.dot( point ) + this.constant;
  5446. },
  5447. distanceToSphere: function ( sphere ) {
  5448. return this.distanceToPoint( sphere.center ) - sphere.radius;
  5449. },
  5450. projectPoint: function ( point, optionalTarget ) {
  5451. var result = optionalTarget || new Vector3();
  5452. return result.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  5453. },
  5454. intersectLine: function () {
  5455. var v1 = new Vector3();
  5456. return function intersectLine( line, optionalTarget ) {
  5457. var result = optionalTarget || new Vector3();
  5458. var direction = line.delta( v1 );
  5459. var denominator = this.normal.dot( direction );
  5460. if ( denominator === 0 ) {
  5461. // line is coplanar, return origin
  5462. if ( this.distanceToPoint( line.start ) === 0 ) {
  5463. return result.copy( line.start );
  5464. }
  5465. // Unsure if this is the correct method to handle this case.
  5466. return undefined;
  5467. }
  5468. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  5469. if ( t < 0 || t > 1 ) {
  5470. return undefined;
  5471. }
  5472. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  5473. };
  5474. }(),
  5475. intersectsLine: function ( line ) {
  5476. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5477. var startSign = this.distanceToPoint( line.start );
  5478. var endSign = this.distanceToPoint( line.end );
  5479. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  5480. },
  5481. intersectsBox: function ( box ) {
  5482. return box.intersectsPlane( this );
  5483. },
  5484. intersectsSphere: function ( sphere ) {
  5485. return sphere.intersectsPlane( this );
  5486. },
  5487. coplanarPoint: function ( optionalTarget ) {
  5488. var result = optionalTarget || new Vector3();
  5489. return result.copy( this.normal ).multiplyScalar( - this.constant );
  5490. },
  5491. applyMatrix4: function () {
  5492. var v1 = new Vector3();
  5493. var m1 = new Matrix3();
  5494. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  5495. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  5496. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  5497. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  5498. this.constant = - referencePoint.dot( normal );
  5499. return this;
  5500. };
  5501. }(),
  5502. translate: function ( offset ) {
  5503. this.constant -= offset.dot( this.normal );
  5504. return this;
  5505. },
  5506. equals: function ( plane ) {
  5507. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  5508. }
  5509. } );
  5510. /**
  5511. * @author mrdoob / http://mrdoob.com/
  5512. * @author alteredq / http://alteredqualia.com/
  5513. * @author bhouston / http://clara.io
  5514. */
  5515. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  5516. this.planes = [
  5517. ( p0 !== undefined ) ? p0 : new Plane(),
  5518. ( p1 !== undefined ) ? p1 : new Plane(),
  5519. ( p2 !== undefined ) ? p2 : new Plane(),
  5520. ( p3 !== undefined ) ? p3 : new Plane(),
  5521. ( p4 !== undefined ) ? p4 : new Plane(),
  5522. ( p5 !== undefined ) ? p5 : new Plane()
  5523. ];
  5524. }
  5525. Object.assign( Frustum.prototype, {
  5526. set: function ( p0, p1, p2, p3, p4, p5 ) {
  5527. var planes = this.planes;
  5528. planes[ 0 ].copy( p0 );
  5529. planes[ 1 ].copy( p1 );
  5530. planes[ 2 ].copy( p2 );
  5531. planes[ 3 ].copy( p3 );
  5532. planes[ 4 ].copy( p4 );
  5533. planes[ 5 ].copy( p5 );
  5534. return this;
  5535. },
  5536. clone: function () {
  5537. return new this.constructor().copy( this );
  5538. },
  5539. copy: function ( frustum ) {
  5540. var planes = this.planes;
  5541. for ( var i = 0; i < 6; i ++ ) {
  5542. planes[ i ].copy( frustum.planes[ i ] );
  5543. }
  5544. return this;
  5545. },
  5546. setFromMatrix: function ( m ) {
  5547. var planes = this.planes;
  5548. var me = m.elements;
  5549. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  5550. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  5551. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  5552. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  5553. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  5554. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  5555. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  5556. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  5557. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  5558. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  5559. return this;
  5560. },
  5561. intersectsObject: function () {
  5562. var sphere = new Sphere();
  5563. return function intersectsObject( object ) {
  5564. var geometry = object.geometry;
  5565. if ( geometry.boundingSphere === null )
  5566. geometry.computeBoundingSphere();
  5567. sphere.copy( geometry.boundingSphere )
  5568. .applyMatrix4( object.matrixWorld );
  5569. return this.intersectsSphere( sphere );
  5570. };
  5571. }(),
  5572. intersectsSprite: function () {
  5573. var sphere = new Sphere();
  5574. return function intersectsSprite( sprite ) {
  5575. sphere.center.set( 0, 0, 0 );
  5576. sphere.radius = 0.7071067811865476;
  5577. sphere.applyMatrix4( sprite.matrixWorld );
  5578. return this.intersectsSphere( sphere );
  5579. };
  5580. }(),
  5581. intersectsSphere: function ( sphere ) {
  5582. var planes = this.planes;
  5583. var center = sphere.center;
  5584. var negRadius = - sphere.radius;
  5585. for ( var i = 0; i < 6; i ++ ) {
  5586. var distance = planes[ i ].distanceToPoint( center );
  5587. if ( distance < negRadius ) {
  5588. return false;
  5589. }
  5590. }
  5591. return true;
  5592. },
  5593. intersectsBox: function () {
  5594. var p1 = new Vector3(),
  5595. p2 = new Vector3();
  5596. return function intersectsBox( box ) {
  5597. var planes = this.planes;
  5598. for ( var i = 0; i < 6; i ++ ) {
  5599. var plane = planes[ i ];
  5600. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  5601. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  5602. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  5603. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  5604. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  5605. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  5606. var d1 = plane.distanceToPoint( p1 );
  5607. var d2 = plane.distanceToPoint( p2 );
  5608. // if both outside plane, no intersection
  5609. if ( d1 < 0 && d2 < 0 ) {
  5610. return false;
  5611. }
  5612. }
  5613. return true;
  5614. };
  5615. }(),
  5616. containsPoint: function ( point ) {
  5617. var planes = this.planes;
  5618. for ( var i = 0; i < 6; i ++ ) {
  5619. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  5620. return false;
  5621. }
  5622. }
  5623. return true;
  5624. }
  5625. } );
  5626. /**
  5627. * @author alteredq / http://alteredqualia.com/
  5628. * @author mrdoob / http://mrdoob.com/
  5629. */
  5630. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  5631. var _frustum = new Frustum(),
  5632. _projScreenMatrix = new Matrix4(),
  5633. _shadowMapSize = new Vector2(),
  5634. _maxShadowMapSize = new Vector2( maxTextureSize, maxTextureSize ),
  5635. _lookTarget = new Vector3(),
  5636. _lightPositionWorld = new Vector3(),
  5637. _MorphingFlag = 1,
  5638. _SkinningFlag = 2,
  5639. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  5640. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  5641. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  5642. _materialCache = {};
  5643. var cubeDirections = [
  5644. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  5645. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  5646. ];
  5647. var cubeUps = [
  5648. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  5649. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  5650. ];
  5651. var cube2DViewPorts = [
  5652. new Vector4(), new Vector4(), new Vector4(),
  5653. new Vector4(), new Vector4(), new Vector4()
  5654. ];
  5655. // init
  5656. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  5657. var useMorphing = ( i & _MorphingFlag ) !== 0;
  5658. var useSkinning = ( i & _SkinningFlag ) !== 0;
  5659. var depthMaterial = new MeshDepthMaterial( {
  5660. depthPacking: RGBADepthPacking,
  5661. morphTargets: useMorphing,
  5662. skinning: useSkinning
  5663. } );
  5664. _depthMaterials[ i ] = depthMaterial;
  5665. //
  5666. var distanceMaterial = new MeshDistanceMaterial( {
  5667. morphTargets: useMorphing,
  5668. skinning: useSkinning
  5669. } );
  5670. _distanceMaterials[ i ] = distanceMaterial;
  5671. }
  5672. //
  5673. var scope = this;
  5674. this.enabled = false;
  5675. this.autoUpdate = true;
  5676. this.needsUpdate = false;
  5677. this.type = PCFShadowMap;
  5678. this.renderReverseSided = true;
  5679. this.renderSingleSided = true;
  5680. this.render = function ( lights, scene, camera ) {
  5681. if ( scope.enabled === false ) return;
  5682. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  5683. if ( lights.length === 0 ) return;
  5684. // TODO Clean up (needed in case of contextlost)
  5685. var _gl = _renderer.context;
  5686. var _state = _renderer.state;
  5687. // Set GL state for depth map.
  5688. _state.disable( _gl.BLEND );
  5689. _state.buffers.color.setClear( 1, 1, 1, 1 );
  5690. _state.buffers.depth.setTest( true );
  5691. _state.setScissorTest( false );
  5692. // render depth map
  5693. var faceCount;
  5694. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  5695. var light = lights[ i ];
  5696. var shadow = light.shadow;
  5697. var isPointLight = light && light.isPointLight;
  5698. if ( shadow === undefined ) {
  5699. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  5700. continue;
  5701. }
  5702. var shadowCamera = shadow.camera;
  5703. _shadowMapSize.copy( shadow.mapSize );
  5704. _shadowMapSize.min( _maxShadowMapSize );
  5705. if ( isPointLight ) {
  5706. var vpWidth = _shadowMapSize.x;
  5707. var vpHeight = _shadowMapSize.y;
  5708. // These viewports map a cube-map onto a 2D texture with the
  5709. // following orientation:
  5710. //
  5711. // xzXZ
  5712. // y Y
  5713. //
  5714. // X - Positive x direction
  5715. // x - Negative x direction
  5716. // Y - Positive y direction
  5717. // y - Negative y direction
  5718. // Z - Positive z direction
  5719. // z - Negative z direction
  5720. // positive X
  5721. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  5722. // negative X
  5723. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  5724. // positive Z
  5725. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  5726. // negative Z
  5727. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  5728. // positive Y
  5729. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  5730. // negative Y
  5731. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  5732. _shadowMapSize.x *= 4.0;
  5733. _shadowMapSize.y *= 2.0;
  5734. }
  5735. if ( shadow.map === null ) {
  5736. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  5737. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  5738. shadow.map.texture.name = light.name + ".shadowMap";
  5739. shadowCamera.updateProjectionMatrix();
  5740. }
  5741. if ( shadow.isSpotLightShadow ) {
  5742. shadow.update( light );
  5743. }
  5744. var shadowMap = shadow.map;
  5745. var shadowMatrix = shadow.matrix;
  5746. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  5747. shadowCamera.position.copy( _lightPositionWorld );
  5748. if ( isPointLight ) {
  5749. faceCount = 6;
  5750. // for point lights we set the shadow matrix to be a translation-only matrix
  5751. // equal to inverse of the light's position
  5752. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  5753. } else {
  5754. faceCount = 1;
  5755. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  5756. shadowCamera.lookAt( _lookTarget );
  5757. shadowCamera.updateMatrixWorld();
  5758. // compute shadow matrix
  5759. shadowMatrix.set(
  5760. 0.5, 0.0, 0.0, 0.5,
  5761. 0.0, 0.5, 0.0, 0.5,
  5762. 0.0, 0.0, 0.5, 0.5,
  5763. 0.0, 0.0, 0.0, 1.0
  5764. );
  5765. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  5766. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  5767. }
  5768. _renderer.setRenderTarget( shadowMap );
  5769. _renderer.clear();
  5770. // render shadow map for each cube face (if omni-directional) or
  5771. // run a single pass if not
  5772. for ( var face = 0; face < faceCount; face ++ ) {
  5773. if ( isPointLight ) {
  5774. _lookTarget.copy( shadowCamera.position );
  5775. _lookTarget.add( cubeDirections[ face ] );
  5776. shadowCamera.up.copy( cubeUps[ face ] );
  5777. shadowCamera.lookAt( _lookTarget );
  5778. shadowCamera.updateMatrixWorld();
  5779. var vpDimensions = cube2DViewPorts[ face ];
  5780. _state.viewport( vpDimensions );
  5781. }
  5782. // update camera matrices and frustum
  5783. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  5784. _frustum.setFromMatrix( _projScreenMatrix );
  5785. // set object matrices & frustum culling
  5786. renderObject( scene, camera, shadowCamera, isPointLight );
  5787. }
  5788. }
  5789. scope.needsUpdate = false;
  5790. };
  5791. function getDepthMaterial( object, material, isPointLight, lightPositionWorld, shadowCameraNear, shadowCameraFar ) {
  5792. var geometry = object.geometry;
  5793. var result = null;
  5794. var materialVariants = _depthMaterials;
  5795. var customMaterial = object.customDepthMaterial;
  5796. if ( isPointLight ) {
  5797. materialVariants = _distanceMaterials;
  5798. customMaterial = object.customDistanceMaterial;
  5799. }
  5800. if ( ! customMaterial ) {
  5801. var useMorphing = false;
  5802. if ( material.morphTargets ) {
  5803. if ( geometry && geometry.isBufferGeometry ) {
  5804. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  5805. } else if ( geometry && geometry.isGeometry ) {
  5806. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  5807. }
  5808. }
  5809. if ( object.isSkinnedMesh && material.skinning === false ) {
  5810. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  5811. }
  5812. var useSkinning = object.isSkinnedMesh && material.skinning;
  5813. var variantIndex = 0;
  5814. if ( useMorphing ) variantIndex |= _MorphingFlag;
  5815. if ( useSkinning ) variantIndex |= _SkinningFlag;
  5816. result = materialVariants[ variantIndex ];
  5817. } else {
  5818. result = customMaterial;
  5819. }
  5820. if ( _renderer.localClippingEnabled &&
  5821. material.clipShadows === true &&
  5822. material.clippingPlanes.length !== 0 ) {
  5823. // in this case we need a unique material instance reflecting the
  5824. // appropriate state
  5825. var keyA = result.uuid, keyB = material.uuid;
  5826. var materialsForVariant = _materialCache[ keyA ];
  5827. if ( materialsForVariant === undefined ) {
  5828. materialsForVariant = {};
  5829. _materialCache[ keyA ] = materialsForVariant;
  5830. }
  5831. var cachedMaterial = materialsForVariant[ keyB ];
  5832. if ( cachedMaterial === undefined ) {
  5833. cachedMaterial = result.clone();
  5834. materialsForVariant[ keyB ] = cachedMaterial;
  5835. }
  5836. result = cachedMaterial;
  5837. }
  5838. result.visible = material.visible;
  5839. result.wireframe = material.wireframe;
  5840. var side = material.side;
  5841. if ( scope.renderSingleSided && side == DoubleSide ) {
  5842. side = FrontSide;
  5843. }
  5844. if ( scope.renderReverseSided ) {
  5845. if ( side === FrontSide ) side = BackSide;
  5846. else if ( side === BackSide ) side = FrontSide;
  5847. }
  5848. result.side = side;
  5849. result.clipShadows = material.clipShadows;
  5850. result.clippingPlanes = material.clippingPlanes;
  5851. result.clipIntersection = material.clipIntersection;
  5852. result.wireframeLinewidth = material.wireframeLinewidth;
  5853. result.linewidth = material.linewidth;
  5854. if ( isPointLight && result.isMeshDistanceMaterial ) {
  5855. result.referencePosition.copy( lightPositionWorld );
  5856. result.nearDistance = shadowCameraNear;
  5857. result.farDistance = shadowCameraFar;
  5858. }
  5859. return result;
  5860. }
  5861. function renderObject( object, camera, shadowCamera, isPointLight ) {
  5862. if ( object.visible === false ) return;
  5863. var visible = object.layers.test( camera.layers );
  5864. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  5865. if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  5866. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  5867. var geometry = _objects.update( object );
  5868. var material = object.material;
  5869. if ( Array.isArray( material ) ) {
  5870. var groups = geometry.groups;
  5871. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  5872. var group = groups[ k ];
  5873. var groupMaterial = material[ group.materialIndex ];
  5874. if ( groupMaterial && groupMaterial.visible ) {
  5875. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  5876. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  5877. }
  5878. }
  5879. } else if ( material.visible ) {
  5880. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  5881. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  5882. }
  5883. }
  5884. }
  5885. var children = object.children;
  5886. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5887. renderObject( children[ i ], camera, shadowCamera, isPointLight );
  5888. }
  5889. }
  5890. }
  5891. /**
  5892. * @author mrdoob / http://mrdoob.com/
  5893. */
  5894. function WebGLAttributes( gl ) {
  5895. var buffers = {};
  5896. function createBuffer( attribute, bufferType ) {
  5897. var array = attribute.array;
  5898. var usage = attribute.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  5899. var buffer = gl.createBuffer();
  5900. gl.bindBuffer( bufferType, buffer );
  5901. gl.bufferData( bufferType, array, usage );
  5902. attribute.onUploadCallback();
  5903. var type = gl.FLOAT;
  5904. if ( array instanceof Float32Array ) {
  5905. type = gl.FLOAT;
  5906. } else if ( array instanceof Float64Array ) {
  5907. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  5908. } else if ( array instanceof Uint16Array ) {
  5909. type = gl.UNSIGNED_SHORT;
  5910. } else if ( array instanceof Int16Array ) {
  5911. type = gl.SHORT;
  5912. } else if ( array instanceof Uint32Array ) {
  5913. type = gl.UNSIGNED_INT;
  5914. } else if ( array instanceof Int32Array ) {
  5915. type = gl.INT;
  5916. } else if ( array instanceof Int8Array ) {
  5917. type = gl.BYTE;
  5918. } else if ( array instanceof Uint8Array ) {
  5919. type = gl.UNSIGNED_BYTE;
  5920. }
  5921. return {
  5922. buffer: buffer,
  5923. type: type,
  5924. bytesPerElement: array.BYTES_PER_ELEMENT,
  5925. version: attribute.version
  5926. };
  5927. }
  5928. function updateBuffer( buffer, attribute, bufferType ) {
  5929. var array = attribute.array;
  5930. var updateRange = attribute.updateRange;
  5931. gl.bindBuffer( bufferType, buffer );
  5932. if ( attribute.dynamic === false ) {
  5933. gl.bufferData( bufferType, array, gl.STATIC_DRAW );
  5934. } else if ( updateRange.count === - 1 ) {
  5935. // Not using update ranges
  5936. gl.bufferSubData( bufferType, 0, array );
  5937. } else if ( updateRange.count === 0 ) {
  5938. 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.' );
  5939. } else {
  5940. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  5941. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  5942. updateRange.count = -1; // reset range
  5943. }
  5944. }
  5945. //
  5946. function get( attribute ) {
  5947. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  5948. return buffers[ attribute.uuid ];
  5949. }
  5950. function remove( attribute ) {
  5951. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  5952. var data = buffers[ attribute.uuid ];
  5953. if ( data ) {
  5954. gl.deleteBuffer( data.buffer );
  5955. delete buffers[ attribute.uuid ];
  5956. }
  5957. }
  5958. function update( attribute, bufferType ) {
  5959. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  5960. var data = buffers[ attribute.uuid ];
  5961. if ( data === undefined ) {
  5962. buffers[ attribute.uuid ] = createBuffer( attribute, bufferType );
  5963. } else if ( data.version < attribute.version ) {
  5964. updateBuffer( data.buffer, attribute, bufferType );
  5965. data.version = attribute.version;
  5966. }
  5967. }
  5968. return {
  5969. get: get,
  5970. remove: remove,
  5971. update: update
  5972. };
  5973. }
  5974. /**
  5975. * @author mrdoob / http://mrdoob.com/
  5976. * @author WestLangley / http://github.com/WestLangley
  5977. * @author bhouston / http://clara.io
  5978. */
  5979. function Euler( x, y, z, order ) {
  5980. this._x = x || 0;
  5981. this._y = y || 0;
  5982. this._z = z || 0;
  5983. this._order = order || Euler.DefaultOrder;
  5984. }
  5985. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  5986. Euler.DefaultOrder = 'XYZ';
  5987. Object.defineProperties( Euler.prototype, {
  5988. x: {
  5989. get: function () {
  5990. return this._x;
  5991. },
  5992. set: function ( value ) {
  5993. this._x = value;
  5994. this.onChangeCallback();
  5995. }
  5996. },
  5997. y: {
  5998. get: function () {
  5999. return this._y;
  6000. },
  6001. set: function ( value ) {
  6002. this._y = value;
  6003. this.onChangeCallback();
  6004. }
  6005. },
  6006. z: {
  6007. get: function () {
  6008. return this._z;
  6009. },
  6010. set: function ( value ) {
  6011. this._z = value;
  6012. this.onChangeCallback();
  6013. }
  6014. },
  6015. order: {
  6016. get: function () {
  6017. return this._order;
  6018. },
  6019. set: function ( value ) {
  6020. this._order = value;
  6021. this.onChangeCallback();
  6022. }
  6023. }
  6024. } );
  6025. Object.assign( Euler.prototype, {
  6026. isEuler: true,
  6027. set: function ( x, y, z, order ) {
  6028. this._x = x;
  6029. this._y = y;
  6030. this._z = z;
  6031. this._order = order || this._order;
  6032. this.onChangeCallback();
  6033. return this;
  6034. },
  6035. clone: function () {
  6036. return new this.constructor( this._x, this._y, this._z, this._order );
  6037. },
  6038. copy: function ( euler ) {
  6039. this._x = euler._x;
  6040. this._y = euler._y;
  6041. this._z = euler._z;
  6042. this._order = euler._order;
  6043. this.onChangeCallback();
  6044. return this;
  6045. },
  6046. setFromRotationMatrix: function ( m, order, update ) {
  6047. var clamp = _Math.clamp;
  6048. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6049. var te = m.elements;
  6050. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  6051. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  6052. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6053. order = order || this._order;
  6054. if ( order === 'XYZ' ) {
  6055. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  6056. if ( Math.abs( m13 ) < 0.99999 ) {
  6057. this._x = Math.atan2( - m23, m33 );
  6058. this._z = Math.atan2( - m12, m11 );
  6059. } else {
  6060. this._x = Math.atan2( m32, m22 );
  6061. this._z = 0;
  6062. }
  6063. } else if ( order === 'YXZ' ) {
  6064. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  6065. if ( Math.abs( m23 ) < 0.99999 ) {
  6066. this._y = Math.atan2( m13, m33 );
  6067. this._z = Math.atan2( m21, m22 );
  6068. } else {
  6069. this._y = Math.atan2( - m31, m11 );
  6070. this._z = 0;
  6071. }
  6072. } else if ( order === 'ZXY' ) {
  6073. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  6074. if ( Math.abs( m32 ) < 0.99999 ) {
  6075. this._y = Math.atan2( - m31, m33 );
  6076. this._z = Math.atan2( - m12, m22 );
  6077. } else {
  6078. this._y = 0;
  6079. this._z = Math.atan2( m21, m11 );
  6080. }
  6081. } else if ( order === 'ZYX' ) {
  6082. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  6083. if ( Math.abs( m31 ) < 0.99999 ) {
  6084. this._x = Math.atan2( m32, m33 );
  6085. this._z = Math.atan2( m21, m11 );
  6086. } else {
  6087. this._x = 0;
  6088. this._z = Math.atan2( - m12, m22 );
  6089. }
  6090. } else if ( order === 'YZX' ) {
  6091. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  6092. if ( Math.abs( m21 ) < 0.99999 ) {
  6093. this._x = Math.atan2( - m23, m22 );
  6094. this._y = Math.atan2( - m31, m11 );
  6095. } else {
  6096. this._x = 0;
  6097. this._y = Math.atan2( m13, m33 );
  6098. }
  6099. } else if ( order === 'XZY' ) {
  6100. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  6101. if ( Math.abs( m12 ) < 0.99999 ) {
  6102. this._x = Math.atan2( m32, m22 );
  6103. this._y = Math.atan2( m13, m11 );
  6104. } else {
  6105. this._x = Math.atan2( - m23, m33 );
  6106. this._y = 0;
  6107. }
  6108. } else {
  6109. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  6110. }
  6111. this._order = order;
  6112. if ( update !== false ) this.onChangeCallback();
  6113. return this;
  6114. },
  6115. setFromQuaternion: function () {
  6116. var matrix = new Matrix4();
  6117. return function setFromQuaternion( q, order, update ) {
  6118. matrix.makeRotationFromQuaternion( q );
  6119. return this.setFromRotationMatrix( matrix, order, update );
  6120. };
  6121. }(),
  6122. setFromVector3: function ( v, order ) {
  6123. return this.set( v.x, v.y, v.z, order || this._order );
  6124. },
  6125. reorder: function () {
  6126. // WARNING: this discards revolution information -bhouston
  6127. var q = new Quaternion();
  6128. return function reorder( newOrder ) {
  6129. q.setFromEuler( this );
  6130. return this.setFromQuaternion( q, newOrder );
  6131. };
  6132. }(),
  6133. equals: function ( euler ) {
  6134. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  6135. },
  6136. fromArray: function ( array ) {
  6137. this._x = array[ 0 ];
  6138. this._y = array[ 1 ];
  6139. this._z = array[ 2 ];
  6140. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  6141. this.onChangeCallback();
  6142. return this;
  6143. },
  6144. toArray: function ( array, offset ) {
  6145. if ( array === undefined ) array = [];
  6146. if ( offset === undefined ) offset = 0;
  6147. array[ offset ] = this._x;
  6148. array[ offset + 1 ] = this._y;
  6149. array[ offset + 2 ] = this._z;
  6150. array[ offset + 3 ] = this._order;
  6151. return array;
  6152. },
  6153. toVector3: function ( optionalResult ) {
  6154. if ( optionalResult ) {
  6155. return optionalResult.set( this._x, this._y, this._z );
  6156. } else {
  6157. return new Vector3( this._x, this._y, this._z );
  6158. }
  6159. },
  6160. onChange: function ( callback ) {
  6161. this.onChangeCallback = callback;
  6162. return this;
  6163. },
  6164. onChangeCallback: function () {}
  6165. } );
  6166. /**
  6167. * @author mrdoob / http://mrdoob.com/
  6168. */
  6169. function Layers() {
  6170. this.mask = 1 | 0;
  6171. }
  6172. Object.assign( Layers.prototype, {
  6173. set: function ( channel ) {
  6174. this.mask = 1 << channel | 0;
  6175. },
  6176. enable: function ( channel ) {
  6177. this.mask |= 1 << channel | 0;
  6178. },
  6179. toggle: function ( channel ) {
  6180. this.mask ^= 1 << channel | 0;
  6181. },
  6182. disable: function ( channel ) {
  6183. this.mask &= ~ ( 1 << channel | 0 );
  6184. },
  6185. test: function ( layers ) {
  6186. return ( this.mask & layers.mask ) !== 0;
  6187. }
  6188. } );
  6189. /**
  6190. * @author mrdoob / http://mrdoob.com/
  6191. * @author mikael emtinger / http://gomo.se/
  6192. * @author alteredq / http://alteredqualia.com/
  6193. * @author WestLangley / http://github.com/WestLangley
  6194. * @author elephantatwork / www.elephantatwork.ch
  6195. */
  6196. var object3DId = 0;
  6197. function Object3D() {
  6198. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  6199. this.uuid = _Math.generateUUID();
  6200. this.name = '';
  6201. this.type = 'Object3D';
  6202. this.parent = null;
  6203. this.children = [];
  6204. this.up = Object3D.DefaultUp.clone();
  6205. var position = new Vector3();
  6206. var rotation = new Euler();
  6207. var quaternion = new Quaternion();
  6208. var scale = new Vector3( 1, 1, 1 );
  6209. function onRotationChange() {
  6210. quaternion.setFromEuler( rotation, false );
  6211. }
  6212. function onQuaternionChange() {
  6213. rotation.setFromQuaternion( quaternion, undefined, false );
  6214. }
  6215. rotation.onChange( onRotationChange );
  6216. quaternion.onChange( onQuaternionChange );
  6217. Object.defineProperties( this, {
  6218. position: {
  6219. enumerable: true,
  6220. value: position
  6221. },
  6222. rotation: {
  6223. enumerable: true,
  6224. value: rotation
  6225. },
  6226. quaternion: {
  6227. enumerable: true,
  6228. value: quaternion
  6229. },
  6230. scale: {
  6231. enumerable: true,
  6232. value: scale
  6233. },
  6234. modelViewMatrix: {
  6235. value: new Matrix4()
  6236. },
  6237. normalMatrix: {
  6238. value: new Matrix3()
  6239. }
  6240. } );
  6241. this.matrix = new Matrix4();
  6242. this.matrixWorld = new Matrix4();
  6243. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  6244. this.matrixWorldNeedsUpdate = false;
  6245. this.layers = new Layers();
  6246. this.visible = true;
  6247. this.castShadow = false;
  6248. this.receiveShadow = false;
  6249. this.frustumCulled = true;
  6250. this.renderOrder = 0;
  6251. this.userData = {};
  6252. }
  6253. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  6254. Object3D.DefaultMatrixAutoUpdate = true;
  6255. Object.assign( Object3D.prototype, EventDispatcher.prototype, {
  6256. isObject3D: true,
  6257. onBeforeRender: function () {},
  6258. onAfterRender: function () {},
  6259. applyMatrix: function ( matrix ) {
  6260. this.matrix.multiplyMatrices( matrix, this.matrix );
  6261. this.matrix.decompose( this.position, this.quaternion, this.scale );
  6262. },
  6263. applyQuaternion: function ( q ) {
  6264. this.quaternion.premultiply( q );
  6265. return this;
  6266. },
  6267. setRotationFromAxisAngle: function ( axis, angle ) {
  6268. // assumes axis is normalized
  6269. this.quaternion.setFromAxisAngle( axis, angle );
  6270. },
  6271. setRotationFromEuler: function ( euler ) {
  6272. this.quaternion.setFromEuler( euler, true );
  6273. },
  6274. setRotationFromMatrix: function ( m ) {
  6275. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6276. this.quaternion.setFromRotationMatrix( m );
  6277. },
  6278. setRotationFromQuaternion: function ( q ) {
  6279. // assumes q is normalized
  6280. this.quaternion.copy( q );
  6281. },
  6282. rotateOnAxis: function () {
  6283. // rotate object on axis in object space
  6284. // axis is assumed to be normalized
  6285. var q1 = new Quaternion();
  6286. return function rotateOnAxis( axis, angle ) {
  6287. q1.setFromAxisAngle( axis, angle );
  6288. this.quaternion.multiply( q1 );
  6289. return this;
  6290. };
  6291. }(),
  6292. rotateX: function () {
  6293. var v1 = new Vector3( 1, 0, 0 );
  6294. return function rotateX( angle ) {
  6295. return this.rotateOnAxis( v1, angle );
  6296. };
  6297. }(),
  6298. rotateY: function () {
  6299. var v1 = new Vector3( 0, 1, 0 );
  6300. return function rotateY( angle ) {
  6301. return this.rotateOnAxis( v1, angle );
  6302. };
  6303. }(),
  6304. rotateZ: function () {
  6305. var v1 = new Vector3( 0, 0, 1 );
  6306. return function rotateZ( angle ) {
  6307. return this.rotateOnAxis( v1, angle );
  6308. };
  6309. }(),
  6310. translateOnAxis: function () {
  6311. // translate object by distance along axis in object space
  6312. // axis is assumed to be normalized
  6313. var v1 = new Vector3();
  6314. return function translateOnAxis( axis, distance ) {
  6315. v1.copy( axis ).applyQuaternion( this.quaternion );
  6316. this.position.add( v1.multiplyScalar( distance ) );
  6317. return this;
  6318. };
  6319. }(),
  6320. translateX: function () {
  6321. var v1 = new Vector3( 1, 0, 0 );
  6322. return function translateX( distance ) {
  6323. return this.translateOnAxis( v1, distance );
  6324. };
  6325. }(),
  6326. translateY: function () {
  6327. var v1 = new Vector3( 0, 1, 0 );
  6328. return function translateY( distance ) {
  6329. return this.translateOnAxis( v1, distance );
  6330. };
  6331. }(),
  6332. translateZ: function () {
  6333. var v1 = new Vector3( 0, 0, 1 );
  6334. return function translateZ( distance ) {
  6335. return this.translateOnAxis( v1, distance );
  6336. };
  6337. }(),
  6338. localToWorld: function ( vector ) {
  6339. return vector.applyMatrix4( this.matrixWorld );
  6340. },
  6341. worldToLocal: function () {
  6342. var m1 = new Matrix4();
  6343. return function worldToLocal( vector ) {
  6344. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  6345. };
  6346. }(),
  6347. lookAt: function () {
  6348. // This method does not support objects with rotated and/or translated parent(s)
  6349. var m1 = new Matrix4();
  6350. return function lookAt( vector ) {
  6351. if ( this.isCamera ) {
  6352. m1.lookAt( this.position, vector, this.up );
  6353. } else {
  6354. m1.lookAt( vector, this.position, this.up );
  6355. }
  6356. this.quaternion.setFromRotationMatrix( m1 );
  6357. };
  6358. }(),
  6359. add: function ( object ) {
  6360. if ( arguments.length > 1 ) {
  6361. for ( var i = 0; i < arguments.length; i ++ ) {
  6362. this.add( arguments[ i ] );
  6363. }
  6364. return this;
  6365. }
  6366. if ( object === this ) {
  6367. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  6368. return this;
  6369. }
  6370. if ( ( object && object.isObject3D ) ) {
  6371. if ( object.parent !== null ) {
  6372. object.parent.remove( object );
  6373. }
  6374. object.parent = this;
  6375. object.dispatchEvent( { type: 'added' } );
  6376. this.children.push( object );
  6377. } else {
  6378. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  6379. }
  6380. return this;
  6381. },
  6382. remove: function ( object ) {
  6383. if ( arguments.length > 1 ) {
  6384. for ( var i = 0; i < arguments.length; i ++ ) {
  6385. this.remove( arguments[ i ] );
  6386. }
  6387. return this;
  6388. }
  6389. var index = this.children.indexOf( object );
  6390. if ( index !== - 1 ) {
  6391. object.parent = null;
  6392. object.dispatchEvent( { type: 'removed' } );
  6393. this.children.splice( index, 1 );
  6394. }
  6395. return this;
  6396. },
  6397. getObjectById: function ( id ) {
  6398. return this.getObjectByProperty( 'id', id );
  6399. },
  6400. getObjectByName: function ( name ) {
  6401. return this.getObjectByProperty( 'name', name );
  6402. },
  6403. getObjectByProperty: function ( name, value ) {
  6404. if ( this[ name ] === value ) return this;
  6405. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6406. var child = this.children[ i ];
  6407. var object = child.getObjectByProperty( name, value );
  6408. if ( object !== undefined ) {
  6409. return object;
  6410. }
  6411. }
  6412. return undefined;
  6413. },
  6414. getWorldPosition: function ( optionalTarget ) {
  6415. var result = optionalTarget || new Vector3();
  6416. this.updateMatrixWorld( true );
  6417. return result.setFromMatrixPosition( this.matrixWorld );
  6418. },
  6419. getWorldQuaternion: function () {
  6420. var position = new Vector3();
  6421. var scale = new Vector3();
  6422. return function getWorldQuaternion( optionalTarget ) {
  6423. var result = optionalTarget || new Quaternion();
  6424. this.updateMatrixWorld( true );
  6425. this.matrixWorld.decompose( position, result, scale );
  6426. return result;
  6427. };
  6428. }(),
  6429. getWorldRotation: function () {
  6430. var quaternion = new Quaternion();
  6431. return function getWorldRotation( optionalTarget ) {
  6432. var result = optionalTarget || new Euler();
  6433. this.getWorldQuaternion( quaternion );
  6434. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  6435. };
  6436. }(),
  6437. getWorldScale: function () {
  6438. var position = new Vector3();
  6439. var quaternion = new Quaternion();
  6440. return function getWorldScale( optionalTarget ) {
  6441. var result = optionalTarget || new Vector3();
  6442. this.updateMatrixWorld( true );
  6443. this.matrixWorld.decompose( position, quaternion, result );
  6444. return result;
  6445. };
  6446. }(),
  6447. getWorldDirection: function () {
  6448. var quaternion = new Quaternion();
  6449. return function getWorldDirection( optionalTarget ) {
  6450. var result = optionalTarget || new Vector3();
  6451. this.getWorldQuaternion( quaternion );
  6452. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  6453. };
  6454. }(),
  6455. raycast: function () {},
  6456. traverse: function ( callback ) {
  6457. callback( this );
  6458. var children = this.children;
  6459. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6460. children[ i ].traverse( callback );
  6461. }
  6462. },
  6463. traverseVisible: function ( callback ) {
  6464. if ( this.visible === false ) return;
  6465. callback( this );
  6466. var children = this.children;
  6467. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6468. children[ i ].traverseVisible( callback );
  6469. }
  6470. },
  6471. traverseAncestors: function ( callback ) {
  6472. var parent = this.parent;
  6473. if ( parent !== null ) {
  6474. callback( parent );
  6475. parent.traverseAncestors( callback );
  6476. }
  6477. },
  6478. updateMatrix: function () {
  6479. this.matrix.compose( this.position, this.quaternion, this.scale );
  6480. this.matrixWorldNeedsUpdate = true;
  6481. },
  6482. updateMatrixWorld: function ( force ) {
  6483. if ( this.matrixAutoUpdate ) this.updateMatrix();
  6484. if ( this.matrixWorldNeedsUpdate || force ) {
  6485. if ( this.parent === null ) {
  6486. this.matrixWorld.copy( this.matrix );
  6487. } else {
  6488. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  6489. }
  6490. this.matrixWorldNeedsUpdate = false;
  6491. force = true;
  6492. }
  6493. // update children
  6494. var children = this.children;
  6495. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6496. children[ i ].updateMatrixWorld( force );
  6497. }
  6498. },
  6499. toJSON: function ( meta ) {
  6500. // meta is '' when called from JSON.stringify
  6501. var isRootObject = ( meta === undefined || meta === '' );
  6502. var output = {};
  6503. // meta is a hash used to collect geometries, materials.
  6504. // not providing it implies that this is the root object
  6505. // being serialized.
  6506. if ( isRootObject ) {
  6507. // initialize meta obj
  6508. meta = {
  6509. geometries: {},
  6510. materials: {},
  6511. textures: {},
  6512. images: {}
  6513. };
  6514. output.metadata = {
  6515. version: 4.5,
  6516. type: 'Object',
  6517. generator: 'Object3D.toJSON'
  6518. };
  6519. }
  6520. // standard Object3D serialization
  6521. var object = {};
  6522. object.uuid = this.uuid;
  6523. object.type = this.type;
  6524. if ( this.name !== '' ) object.name = this.name;
  6525. if ( this.castShadow === true ) object.castShadow = true;
  6526. if ( this.receiveShadow === true ) object.receiveShadow = true;
  6527. if ( this.visible === false ) object.visible = false;
  6528. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  6529. object.matrix = this.matrix.toArray();
  6530. //
  6531. function serialize( library, element ) {
  6532. if ( library[ element.uuid ] === undefined ) {
  6533. library[ element.uuid ] = element.toJSON( meta );
  6534. }
  6535. return element.uuid;
  6536. }
  6537. if ( this.geometry !== undefined ) {
  6538. object.geometry = serialize( meta.geometries, this.geometry );
  6539. }
  6540. if ( this.material !== undefined ) {
  6541. if ( Array.isArray( this.material ) ) {
  6542. var uuids = [];
  6543. for ( var i = 0, l = this.material.length; i < l; i ++ ) {
  6544. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  6545. }
  6546. object.material = uuids;
  6547. } else {
  6548. object.material = serialize( meta.materials, this.material );
  6549. }
  6550. }
  6551. //
  6552. if ( this.children.length > 0 ) {
  6553. object.children = [];
  6554. for ( var i = 0; i < this.children.length; i ++ ) {
  6555. object.children.push( this.children[ i ].toJSON( meta ).object );
  6556. }
  6557. }
  6558. if ( isRootObject ) {
  6559. var geometries = extractFromCache( meta.geometries );
  6560. var materials = extractFromCache( meta.materials );
  6561. var textures = extractFromCache( meta.textures );
  6562. var images = extractFromCache( meta.images );
  6563. if ( geometries.length > 0 ) output.geometries = geometries;
  6564. if ( materials.length > 0 ) output.materials = materials;
  6565. if ( textures.length > 0 ) output.textures = textures;
  6566. if ( images.length > 0 ) output.images = images;
  6567. }
  6568. output.object = object;
  6569. return output;
  6570. // extract data from the cache hash
  6571. // remove metadata on each item
  6572. // and return as array
  6573. function extractFromCache( cache ) {
  6574. var values = [];
  6575. for ( var key in cache ) {
  6576. var data = cache[ key ];
  6577. delete data.metadata;
  6578. values.push( data );
  6579. }
  6580. return values;
  6581. }
  6582. },
  6583. clone: function ( recursive ) {
  6584. return new this.constructor().copy( this, recursive );
  6585. },
  6586. copy: function ( source, recursive ) {
  6587. if ( recursive === undefined ) recursive = true;
  6588. this.name = source.name;
  6589. this.up.copy( source.up );
  6590. this.position.copy( source.position );
  6591. this.quaternion.copy( source.quaternion );
  6592. this.scale.copy( source.scale );
  6593. this.matrix.copy( source.matrix );
  6594. this.matrixWorld.copy( source.matrixWorld );
  6595. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6596. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  6597. this.layers.mask = source.layers.mask;
  6598. this.visible = source.visible;
  6599. this.castShadow = source.castShadow;
  6600. this.receiveShadow = source.receiveShadow;
  6601. this.frustumCulled = source.frustumCulled;
  6602. this.renderOrder = source.renderOrder;
  6603. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6604. if ( recursive === true ) {
  6605. for ( var i = 0; i < source.children.length; i ++ ) {
  6606. var child = source.children[ i ];
  6607. this.add( child.clone() );
  6608. }
  6609. }
  6610. return this;
  6611. }
  6612. } );
  6613. /**
  6614. * @author mrdoob / http://mrdoob.com/
  6615. * @author mikael emtinger / http://gomo.se/
  6616. * @author WestLangley / http://github.com/WestLangley
  6617. */
  6618. function Camera() {
  6619. Object3D.call( this );
  6620. this.type = 'Camera';
  6621. this.matrixWorldInverse = new Matrix4();
  6622. this.projectionMatrix = new Matrix4();
  6623. }
  6624. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  6625. constructor: Camera,
  6626. isCamera: true,
  6627. copy: function ( source, recursive ) {
  6628. Object3D.prototype.copy.call( this, source, recursive );
  6629. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6630. this.projectionMatrix.copy( source.projectionMatrix );
  6631. return this;
  6632. },
  6633. getWorldDirection: function () {
  6634. var quaternion = new Quaternion();
  6635. return function getWorldDirection( optionalTarget ) {
  6636. var result = optionalTarget || new Vector3();
  6637. this.getWorldQuaternion( quaternion );
  6638. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  6639. };
  6640. }(),
  6641. updateMatrixWorld: function ( force ) {
  6642. Object3D.prototype.updateMatrixWorld.call( this, force );
  6643. this.matrixWorldInverse.getInverse( this.matrixWorld );
  6644. },
  6645. clone: function () {
  6646. return new this.constructor().copy( this );
  6647. }
  6648. } );
  6649. /**
  6650. * @author alteredq / http://alteredqualia.com/
  6651. * @author arose / http://github.com/arose
  6652. */
  6653. function OrthographicCamera( left, right, top, bottom, near, far ) {
  6654. Camera.call( this );
  6655. this.type = 'OrthographicCamera';
  6656. this.zoom = 1;
  6657. this.view = null;
  6658. this.left = left;
  6659. this.right = right;
  6660. this.top = top;
  6661. this.bottom = bottom;
  6662. this.near = ( near !== undefined ) ? near : 0.1;
  6663. this.far = ( far !== undefined ) ? far : 2000;
  6664. this.updateProjectionMatrix();
  6665. }
  6666. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  6667. constructor: OrthographicCamera,
  6668. isOrthographicCamera: true,
  6669. copy: function ( source, recursive ) {
  6670. Camera.prototype.copy.call( this, source, recursive );
  6671. this.left = source.left;
  6672. this.right = source.right;
  6673. this.top = source.top;
  6674. this.bottom = source.bottom;
  6675. this.near = source.near;
  6676. this.far = source.far;
  6677. this.zoom = source.zoom;
  6678. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6679. return this;
  6680. },
  6681. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  6682. this.view = {
  6683. fullWidth: fullWidth,
  6684. fullHeight: fullHeight,
  6685. offsetX: x,
  6686. offsetY: y,
  6687. width: width,
  6688. height: height
  6689. };
  6690. this.updateProjectionMatrix();
  6691. },
  6692. clearViewOffset: function() {
  6693. this.view = null;
  6694. this.updateProjectionMatrix();
  6695. },
  6696. updateProjectionMatrix: function () {
  6697. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  6698. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  6699. var cx = ( this.right + this.left ) / 2;
  6700. var cy = ( this.top + this.bottom ) / 2;
  6701. var left = cx - dx;
  6702. var right = cx + dx;
  6703. var top = cy + dy;
  6704. var bottom = cy - dy;
  6705. if ( this.view !== null ) {
  6706. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  6707. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  6708. var scaleW = ( this.right - this.left ) / this.view.width;
  6709. var scaleH = ( this.top - this.bottom ) / this.view.height;
  6710. left += scaleW * ( this.view.offsetX / zoomW );
  6711. right = left + scaleW * ( this.view.width / zoomW );
  6712. top -= scaleH * ( this.view.offsetY / zoomH );
  6713. bottom = top - scaleH * ( this.view.height / zoomH );
  6714. }
  6715. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  6716. },
  6717. toJSON: function ( meta ) {
  6718. var data = Object3D.prototype.toJSON.call( this, meta );
  6719. data.object.zoom = this.zoom;
  6720. data.object.left = this.left;
  6721. data.object.right = this.right;
  6722. data.object.top = this.top;
  6723. data.object.bottom = this.bottom;
  6724. data.object.near = this.near;
  6725. data.object.far = this.far;
  6726. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  6727. return data;
  6728. }
  6729. } );
  6730. /**
  6731. * @author mrdoob / http://mrdoob.com/
  6732. * @author greggman / http://games.greggman.com/
  6733. * @author zz85 / http://www.lab4games.net/zz85/blog
  6734. * @author tschw
  6735. */
  6736. function PerspectiveCamera( fov, aspect, near, far ) {
  6737. Camera.call( this );
  6738. this.type = 'PerspectiveCamera';
  6739. this.fov = fov !== undefined ? fov : 50;
  6740. this.zoom = 1;
  6741. this.near = near !== undefined ? near : 0.1;
  6742. this.far = far !== undefined ? far : 2000;
  6743. this.focus = 10;
  6744. this.aspect = aspect !== undefined ? aspect : 1;
  6745. this.view = null;
  6746. this.filmGauge = 35; // width of the film (default in millimeters)
  6747. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  6748. this.updateProjectionMatrix();
  6749. }
  6750. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  6751. constructor: PerspectiveCamera,
  6752. isPerspectiveCamera: true,
  6753. copy: function ( source, recursive ) {
  6754. Camera.prototype.copy.call( this, source, recursive );
  6755. this.fov = source.fov;
  6756. this.zoom = source.zoom;
  6757. this.near = source.near;
  6758. this.far = source.far;
  6759. this.focus = source.focus;
  6760. this.aspect = source.aspect;
  6761. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6762. this.filmGauge = source.filmGauge;
  6763. this.filmOffset = source.filmOffset;
  6764. return this;
  6765. },
  6766. /**
  6767. * Sets the FOV by focal length in respect to the current .filmGauge.
  6768. *
  6769. * The default film gauge is 35, so that the focal length can be specified for
  6770. * a 35mm (full frame) camera.
  6771. *
  6772. * Values for focal length and film gauge must have the same unit.
  6773. */
  6774. setFocalLength: function ( focalLength ) {
  6775. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  6776. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  6777. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  6778. this.updateProjectionMatrix();
  6779. },
  6780. /**
  6781. * Calculates the focal length from the current .fov and .filmGauge.
  6782. */
  6783. getFocalLength: function () {
  6784. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  6785. return 0.5 * this.getFilmHeight() / vExtentSlope;
  6786. },
  6787. getEffectiveFOV: function () {
  6788. return _Math.RAD2DEG * 2 * Math.atan(
  6789. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  6790. },
  6791. getFilmWidth: function () {
  6792. // film not completely covered in portrait format (aspect < 1)
  6793. return this.filmGauge * Math.min( this.aspect, 1 );
  6794. },
  6795. getFilmHeight: function () {
  6796. // film not completely covered in landscape format (aspect > 1)
  6797. return this.filmGauge / Math.max( this.aspect, 1 );
  6798. },
  6799. /**
  6800. * Sets an offset in a larger frustum. This is useful for multi-window or
  6801. * multi-monitor/multi-machine setups.
  6802. *
  6803. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6804. * the monitors are in grid like this
  6805. *
  6806. * +---+---+---+
  6807. * | A | B | C |
  6808. * +---+---+---+
  6809. * | D | E | F |
  6810. * +---+---+---+
  6811. *
  6812. * then for each monitor you would call it like this
  6813. *
  6814. * var w = 1920;
  6815. * var h = 1080;
  6816. * var fullWidth = w * 3;
  6817. * var fullHeight = h * 2;
  6818. *
  6819. * --A--
  6820. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6821. * --B--
  6822. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6823. * --C--
  6824. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6825. * --D--
  6826. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6827. * --E--
  6828. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6829. * --F--
  6830. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6831. *
  6832. * Note there is no reason monitors have to be the same size or in a grid.
  6833. */
  6834. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  6835. this.aspect = fullWidth / fullHeight;
  6836. this.view = {
  6837. fullWidth: fullWidth,
  6838. fullHeight: fullHeight,
  6839. offsetX: x,
  6840. offsetY: y,
  6841. width: width,
  6842. height: height
  6843. };
  6844. this.updateProjectionMatrix();
  6845. },
  6846. clearViewOffset: function () {
  6847. this.view = null;
  6848. this.updateProjectionMatrix();
  6849. },
  6850. updateProjectionMatrix: function () {
  6851. var near = this.near,
  6852. top = near * Math.tan(
  6853. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  6854. height = 2 * top,
  6855. width = this.aspect * height,
  6856. left = - 0.5 * width,
  6857. view = this.view;
  6858. if ( view !== null ) {
  6859. var fullWidth = view.fullWidth,
  6860. fullHeight = view.fullHeight;
  6861. left += view.offsetX * width / fullWidth;
  6862. top -= view.offsetY * height / fullHeight;
  6863. width *= view.width / fullWidth;
  6864. height *= view.height / fullHeight;
  6865. }
  6866. var skew = this.filmOffset;
  6867. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  6868. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  6869. },
  6870. toJSON: function ( meta ) {
  6871. var data = Object3D.prototype.toJSON.call( this, meta );
  6872. data.object.fov = this.fov;
  6873. data.object.zoom = this.zoom;
  6874. data.object.near = this.near;
  6875. data.object.far = this.far;
  6876. data.object.focus = this.focus;
  6877. data.object.aspect = this.aspect;
  6878. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  6879. data.object.filmGauge = this.filmGauge;
  6880. data.object.filmOffset = this.filmOffset;
  6881. return data;
  6882. }
  6883. } );
  6884. /**
  6885. * @author mrdoob / http://mrdoob.com/
  6886. * @author alteredq / http://alteredqualia.com/
  6887. */
  6888. function Face3( a, b, c, normal, color, materialIndex ) {
  6889. this.a = a;
  6890. this.b = b;
  6891. this.c = c;
  6892. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  6893. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  6894. this.color = ( color && color.isColor ) ? color : new Color();
  6895. this.vertexColors = Array.isArray( color ) ? color : [];
  6896. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6897. }
  6898. Object.assign( Face3.prototype, {
  6899. clone: function () {
  6900. return new this.constructor().copy( this );
  6901. },
  6902. copy: function ( source ) {
  6903. this.a = source.a;
  6904. this.b = source.b;
  6905. this.c = source.c;
  6906. this.normal.copy( source.normal );
  6907. this.color.copy( source.color );
  6908. this.materialIndex = source.materialIndex;
  6909. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  6910. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  6911. }
  6912. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  6913. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  6914. }
  6915. return this;
  6916. }
  6917. } );
  6918. /**
  6919. * @author mrdoob / http://mrdoob.com/
  6920. * @author kile / http://kile.stravaganza.org/
  6921. * @author alteredq / http://alteredqualia.com/
  6922. * @author mikael emtinger / http://gomo.se/
  6923. * @author zz85 / http://www.lab4games.net/zz85/blog
  6924. * @author bhouston / http://clara.io
  6925. */
  6926. var count = 0;
  6927. function GeometryIdCount() { return count++; }
  6928. function Geometry() {
  6929. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  6930. this.uuid = _Math.generateUUID();
  6931. this.name = '';
  6932. this.type = 'Geometry';
  6933. this.vertices = [];
  6934. this.colors = [];
  6935. this.faces = [];
  6936. this.faceVertexUvs = [[]];
  6937. this.morphTargets = [];
  6938. this.morphNormals = [];
  6939. this.skinWeights = [];
  6940. this.skinIndices = [];
  6941. this.lineDistances = [];
  6942. this.boundingBox = null;
  6943. this.boundingSphere = null;
  6944. // update flags
  6945. this.elementsNeedUpdate = false;
  6946. this.verticesNeedUpdate = false;
  6947. this.uvsNeedUpdate = false;
  6948. this.normalsNeedUpdate = false;
  6949. this.colorsNeedUpdate = false;
  6950. this.lineDistancesNeedUpdate = false;
  6951. this.groupsNeedUpdate = false;
  6952. }
  6953. Object.assign( Geometry.prototype, EventDispatcher.prototype, {
  6954. isGeometry: true,
  6955. applyMatrix: function ( matrix ) {
  6956. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6957. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  6958. var vertex = this.vertices[ i ];
  6959. vertex.applyMatrix4( matrix );
  6960. }
  6961. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  6962. var face = this.faces[ i ];
  6963. face.normal.applyMatrix3( normalMatrix ).normalize();
  6964. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  6965. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  6966. }
  6967. }
  6968. if ( this.boundingBox !== null ) {
  6969. this.computeBoundingBox();
  6970. }
  6971. if ( this.boundingSphere !== null ) {
  6972. this.computeBoundingSphere();
  6973. }
  6974. this.verticesNeedUpdate = true;
  6975. this.normalsNeedUpdate = true;
  6976. return this;
  6977. },
  6978. rotateX: function () {
  6979. // rotate geometry around world x-axis
  6980. var m1 = new Matrix4();
  6981. return function rotateX( angle ) {
  6982. m1.makeRotationX( angle );
  6983. this.applyMatrix( m1 );
  6984. return this;
  6985. };
  6986. }(),
  6987. rotateY: function () {
  6988. // rotate geometry around world y-axis
  6989. var m1 = new Matrix4();
  6990. return function rotateY( angle ) {
  6991. m1.makeRotationY( angle );
  6992. this.applyMatrix( m1 );
  6993. return this;
  6994. };
  6995. }(),
  6996. rotateZ: function () {
  6997. // rotate geometry around world z-axis
  6998. var m1 = new Matrix4();
  6999. return function rotateZ( angle ) {
  7000. m1.makeRotationZ( angle );
  7001. this.applyMatrix( m1 );
  7002. return this;
  7003. };
  7004. }(),
  7005. translate: function () {
  7006. // translate geometry
  7007. var m1 = new Matrix4();
  7008. return function translate( x, y, z ) {
  7009. m1.makeTranslation( x, y, z );
  7010. this.applyMatrix( m1 );
  7011. return this;
  7012. };
  7013. }(),
  7014. scale: function () {
  7015. // scale geometry
  7016. var m1 = new Matrix4();
  7017. return function scale( x, y, z ) {
  7018. m1.makeScale( x, y, z );
  7019. this.applyMatrix( m1 );
  7020. return this;
  7021. };
  7022. }(),
  7023. lookAt: function () {
  7024. var obj = new Object3D();
  7025. return function lookAt( vector ) {
  7026. obj.lookAt( vector );
  7027. obj.updateMatrix();
  7028. this.applyMatrix( obj.matrix );
  7029. };
  7030. }(),
  7031. fromBufferGeometry: function ( geometry ) {
  7032. var scope = this;
  7033. var indices = geometry.index !== null ? geometry.index.array : undefined;
  7034. var attributes = geometry.attributes;
  7035. var positions = attributes.position.array;
  7036. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  7037. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  7038. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  7039. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  7040. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  7041. var tempNormals = [];
  7042. var tempUVs = [];
  7043. var tempUVs2 = [];
  7044. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  7045. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  7046. if ( normals !== undefined ) {
  7047. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  7048. }
  7049. if ( colors !== undefined ) {
  7050. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  7051. }
  7052. if ( uvs !== undefined ) {
  7053. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  7054. }
  7055. if ( uvs2 !== undefined ) {
  7056. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  7057. }
  7058. }
  7059. function addFace( a, b, c, materialIndex ) {
  7060. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  7061. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  7062. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  7063. scope.faces.push( face );
  7064. if ( uvs !== undefined ) {
  7065. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  7066. }
  7067. if ( uvs2 !== undefined ) {
  7068. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  7069. }
  7070. }
  7071. var groups = geometry.groups;
  7072. if ( groups.length > 0 ) {
  7073. for ( var i = 0; i < groups.length; i ++ ) {
  7074. var group = groups[ i ];
  7075. var start = group.start;
  7076. var count = group.count;
  7077. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  7078. if ( indices !== undefined ) {
  7079. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  7080. } else {
  7081. addFace( j, j + 1, j + 2, group.materialIndex );
  7082. }
  7083. }
  7084. }
  7085. } else {
  7086. if ( indices !== undefined ) {
  7087. for ( var i = 0; i < indices.length; i += 3 ) {
  7088. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  7089. }
  7090. } else {
  7091. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  7092. addFace( i, i + 1, i + 2 );
  7093. }
  7094. }
  7095. }
  7096. this.computeFaceNormals();
  7097. if ( geometry.boundingBox !== null ) {
  7098. this.boundingBox = geometry.boundingBox.clone();
  7099. }
  7100. if ( geometry.boundingSphere !== null ) {
  7101. this.boundingSphere = geometry.boundingSphere.clone();
  7102. }
  7103. return this;
  7104. },
  7105. center: function () {
  7106. this.computeBoundingBox();
  7107. var offset = this.boundingBox.getCenter().negate();
  7108. this.translate( offset.x, offset.y, offset.z );
  7109. return offset;
  7110. },
  7111. normalize: function () {
  7112. this.computeBoundingSphere();
  7113. var center = this.boundingSphere.center;
  7114. var radius = this.boundingSphere.radius;
  7115. var s = radius === 0 ? 1 : 1.0 / radius;
  7116. var matrix = new Matrix4();
  7117. matrix.set(
  7118. s, 0, 0, - s * center.x,
  7119. 0, s, 0, - s * center.y,
  7120. 0, 0, s, - s * center.z,
  7121. 0, 0, 0, 1
  7122. );
  7123. this.applyMatrix( matrix );
  7124. return this;
  7125. },
  7126. computeFaceNormals: function () {
  7127. var cb = new Vector3(), ab = new Vector3();
  7128. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7129. var face = this.faces[ f ];
  7130. var vA = this.vertices[ face.a ];
  7131. var vB = this.vertices[ face.b ];
  7132. var vC = this.vertices[ face.c ];
  7133. cb.subVectors( vC, vB );
  7134. ab.subVectors( vA, vB );
  7135. cb.cross( ab );
  7136. cb.normalize();
  7137. face.normal.copy( cb );
  7138. }
  7139. },
  7140. computeVertexNormals: function ( areaWeighted ) {
  7141. if ( areaWeighted === undefined ) areaWeighted = true;
  7142. var v, vl, f, fl, face, vertices;
  7143. vertices = new Array( this.vertices.length );
  7144. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7145. vertices[ v ] = new Vector3();
  7146. }
  7147. if ( areaWeighted ) {
  7148. // vertex normals weighted by triangle areas
  7149. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7150. var vA, vB, vC;
  7151. var cb = new Vector3(), ab = new Vector3();
  7152. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7153. face = this.faces[ f ];
  7154. vA = this.vertices[ face.a ];
  7155. vB = this.vertices[ face.b ];
  7156. vC = this.vertices[ face.c ];
  7157. cb.subVectors( vC, vB );
  7158. ab.subVectors( vA, vB );
  7159. cb.cross( ab );
  7160. vertices[ face.a ].add( cb );
  7161. vertices[ face.b ].add( cb );
  7162. vertices[ face.c ].add( cb );
  7163. }
  7164. } else {
  7165. this.computeFaceNormals();
  7166. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7167. face = this.faces[ f ];
  7168. vertices[ face.a ].add( face.normal );
  7169. vertices[ face.b ].add( face.normal );
  7170. vertices[ face.c ].add( face.normal );
  7171. }
  7172. }
  7173. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7174. vertices[ v ].normalize();
  7175. }
  7176. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7177. face = this.faces[ f ];
  7178. var vertexNormals = face.vertexNormals;
  7179. if ( vertexNormals.length === 3 ) {
  7180. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  7181. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  7182. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  7183. } else {
  7184. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  7185. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  7186. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  7187. }
  7188. }
  7189. if ( this.faces.length > 0 ) {
  7190. this.normalsNeedUpdate = true;
  7191. }
  7192. },
  7193. computeFlatVertexNormals: function () {
  7194. var f, fl, face;
  7195. this.computeFaceNormals();
  7196. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7197. face = this.faces[ f ];
  7198. var vertexNormals = face.vertexNormals;
  7199. if ( vertexNormals.length === 3 ) {
  7200. vertexNormals[ 0 ].copy( face.normal );
  7201. vertexNormals[ 1 ].copy( face.normal );
  7202. vertexNormals[ 2 ].copy( face.normal );
  7203. } else {
  7204. vertexNormals[ 0 ] = face.normal.clone();
  7205. vertexNormals[ 1 ] = face.normal.clone();
  7206. vertexNormals[ 2 ] = face.normal.clone();
  7207. }
  7208. }
  7209. if ( this.faces.length > 0 ) {
  7210. this.normalsNeedUpdate = true;
  7211. }
  7212. },
  7213. computeMorphNormals: function () {
  7214. var i, il, f, fl, face;
  7215. // save original normals
  7216. // - create temp variables on first access
  7217. // otherwise just copy (for faster repeated calls)
  7218. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7219. face = this.faces[ f ];
  7220. if ( ! face.__originalFaceNormal ) {
  7221. face.__originalFaceNormal = face.normal.clone();
  7222. } else {
  7223. face.__originalFaceNormal.copy( face.normal );
  7224. }
  7225. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  7226. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  7227. if ( ! face.__originalVertexNormals[ i ] ) {
  7228. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  7229. } else {
  7230. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  7231. }
  7232. }
  7233. }
  7234. // use temp geometry to compute face and vertex normals for each morph
  7235. var tmpGeo = new Geometry();
  7236. tmpGeo.faces = this.faces;
  7237. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  7238. // create on first access
  7239. if ( ! this.morphNormals[ i ] ) {
  7240. this.morphNormals[ i ] = {};
  7241. this.morphNormals[ i ].faceNormals = [];
  7242. this.morphNormals[ i ].vertexNormals = [];
  7243. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  7244. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  7245. var faceNormal, vertexNormals;
  7246. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7247. faceNormal = new Vector3();
  7248. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  7249. dstNormalsFace.push( faceNormal );
  7250. dstNormalsVertex.push( vertexNormals );
  7251. }
  7252. }
  7253. var morphNormals = this.morphNormals[ i ];
  7254. // set vertices to morph target
  7255. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  7256. // compute morph normals
  7257. tmpGeo.computeFaceNormals();
  7258. tmpGeo.computeVertexNormals();
  7259. // store morph normals
  7260. var faceNormal, vertexNormals;
  7261. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7262. face = this.faces[ f ];
  7263. faceNormal = morphNormals.faceNormals[ f ];
  7264. vertexNormals = morphNormals.vertexNormals[ f ];
  7265. faceNormal.copy( face.normal );
  7266. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  7267. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  7268. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  7269. }
  7270. }
  7271. // restore original normals
  7272. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7273. face = this.faces[ f ];
  7274. face.normal = face.__originalFaceNormal;
  7275. face.vertexNormals = face.__originalVertexNormals;
  7276. }
  7277. },
  7278. computeLineDistances: function () {
  7279. var d = 0;
  7280. var vertices = this.vertices;
  7281. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  7282. if ( i > 0 ) {
  7283. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  7284. }
  7285. this.lineDistances[ i ] = d;
  7286. }
  7287. },
  7288. computeBoundingBox: function () {
  7289. if ( this.boundingBox === null ) {
  7290. this.boundingBox = new Box3();
  7291. }
  7292. this.boundingBox.setFromPoints( this.vertices );
  7293. },
  7294. computeBoundingSphere: function () {
  7295. if ( this.boundingSphere === null ) {
  7296. this.boundingSphere = new Sphere();
  7297. }
  7298. this.boundingSphere.setFromPoints( this.vertices );
  7299. },
  7300. merge: function ( geometry, matrix, materialIndexOffset ) {
  7301. if ( ! ( geometry && geometry.isGeometry ) ) {
  7302. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  7303. return;
  7304. }
  7305. var normalMatrix,
  7306. vertexOffset = this.vertices.length,
  7307. vertices1 = this.vertices,
  7308. vertices2 = geometry.vertices,
  7309. faces1 = this.faces,
  7310. faces2 = geometry.faces,
  7311. uvs1 = this.faceVertexUvs[ 0 ],
  7312. uvs2 = geometry.faceVertexUvs[ 0 ],
  7313. colors1 = this.colors,
  7314. colors2 = geometry.colors;
  7315. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  7316. if ( matrix !== undefined ) {
  7317. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7318. }
  7319. // vertices
  7320. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  7321. var vertex = vertices2[ i ];
  7322. var vertexCopy = vertex.clone();
  7323. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  7324. vertices1.push( vertexCopy );
  7325. }
  7326. // colors
  7327. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  7328. colors1.push( colors2[ i ].clone() );
  7329. }
  7330. // faces
  7331. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  7332. var face = faces2[ i ], faceCopy, normal, color,
  7333. faceVertexNormals = face.vertexNormals,
  7334. faceVertexColors = face.vertexColors;
  7335. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  7336. faceCopy.normal.copy( face.normal );
  7337. if ( normalMatrix !== undefined ) {
  7338. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  7339. }
  7340. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  7341. normal = faceVertexNormals[ j ].clone();
  7342. if ( normalMatrix !== undefined ) {
  7343. normal.applyMatrix3( normalMatrix ).normalize();
  7344. }
  7345. faceCopy.vertexNormals.push( normal );
  7346. }
  7347. faceCopy.color.copy( face.color );
  7348. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  7349. color = faceVertexColors[ j ];
  7350. faceCopy.vertexColors.push( color.clone() );
  7351. }
  7352. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  7353. faces1.push( faceCopy );
  7354. }
  7355. // uvs
  7356. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  7357. var uv = uvs2[ i ], uvCopy = [];
  7358. if ( uv === undefined ) {
  7359. continue;
  7360. }
  7361. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  7362. uvCopy.push( uv[ j ].clone() );
  7363. }
  7364. uvs1.push( uvCopy );
  7365. }
  7366. },
  7367. mergeMesh: function ( mesh ) {
  7368. if ( ! ( mesh && mesh.isMesh ) ) {
  7369. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  7370. return;
  7371. }
  7372. mesh.matrixAutoUpdate && mesh.updateMatrix();
  7373. this.merge( mesh.geometry, mesh.matrix );
  7374. },
  7375. /*
  7376. * Checks for duplicate vertices with hashmap.
  7377. * Duplicated vertices are removed
  7378. * and faces' vertices are updated.
  7379. */
  7380. mergeVertices: function () {
  7381. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  7382. var unique = [], changes = [];
  7383. var v, key;
  7384. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  7385. var precision = Math.pow( 10, precisionPoints );
  7386. var i, il, face;
  7387. var indices, j, jl;
  7388. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  7389. v = this.vertices[ i ];
  7390. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  7391. if ( verticesMap[ key ] === undefined ) {
  7392. verticesMap[ key ] = i;
  7393. unique.push( this.vertices[ i ] );
  7394. changes[ i ] = unique.length - 1;
  7395. } else {
  7396. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  7397. changes[ i ] = changes[ verticesMap[ key ] ];
  7398. }
  7399. }
  7400. // if faces are completely degenerate after merging vertices, we
  7401. // have to remove them from the geometry.
  7402. var faceIndicesToRemove = [];
  7403. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  7404. face = this.faces[ i ];
  7405. face.a = changes[ face.a ];
  7406. face.b = changes[ face.b ];
  7407. face.c = changes[ face.c ];
  7408. indices = [ face.a, face.b, face.c ];
  7409. // if any duplicate vertices are found in a Face3
  7410. // we have to remove the face as nothing can be saved
  7411. for ( var n = 0; n < 3; n ++ ) {
  7412. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  7413. faceIndicesToRemove.push( i );
  7414. break;
  7415. }
  7416. }
  7417. }
  7418. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  7419. var idx = faceIndicesToRemove[ i ];
  7420. this.faces.splice( idx, 1 );
  7421. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  7422. this.faceVertexUvs[ j ].splice( idx, 1 );
  7423. }
  7424. }
  7425. // Use unique set of vertices
  7426. var diff = this.vertices.length - unique.length;
  7427. this.vertices = unique;
  7428. return diff;
  7429. },
  7430. sortFacesByMaterialIndex: function () {
  7431. var faces = this.faces;
  7432. var length = faces.length;
  7433. // tag faces
  7434. for ( var i = 0; i < length; i ++ ) {
  7435. faces[ i ]._id = i;
  7436. }
  7437. // sort faces
  7438. function materialIndexSort( a, b ) {
  7439. return a.materialIndex - b.materialIndex;
  7440. }
  7441. faces.sort( materialIndexSort );
  7442. // sort uvs
  7443. var uvs1 = this.faceVertexUvs[ 0 ];
  7444. var uvs2 = this.faceVertexUvs[ 1 ];
  7445. var newUvs1, newUvs2;
  7446. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  7447. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  7448. for ( var i = 0; i < length; i ++ ) {
  7449. var id = faces[ i ]._id;
  7450. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  7451. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  7452. }
  7453. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  7454. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  7455. },
  7456. toJSON: function () {
  7457. var data = {
  7458. metadata: {
  7459. version: 4.5,
  7460. type: 'Geometry',
  7461. generator: 'Geometry.toJSON'
  7462. }
  7463. };
  7464. // standard Geometry serialization
  7465. data.uuid = this.uuid;
  7466. data.type = this.type;
  7467. if ( this.name !== '' ) data.name = this.name;
  7468. if ( this.parameters !== undefined ) {
  7469. var parameters = this.parameters;
  7470. for ( var key in parameters ) {
  7471. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7472. }
  7473. return data;
  7474. }
  7475. var vertices = [];
  7476. for ( var i = 0; i < this.vertices.length; i ++ ) {
  7477. var vertex = this.vertices[ i ];
  7478. vertices.push( vertex.x, vertex.y, vertex.z );
  7479. }
  7480. var faces = [];
  7481. var normals = [];
  7482. var normalsHash = {};
  7483. var colors = [];
  7484. var colorsHash = {};
  7485. var uvs = [];
  7486. var uvsHash = {};
  7487. for ( var i = 0; i < this.faces.length; i ++ ) {
  7488. var face = this.faces[ i ];
  7489. var hasMaterial = true;
  7490. var hasFaceUv = false; // deprecated
  7491. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  7492. var hasFaceNormal = face.normal.length() > 0;
  7493. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  7494. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  7495. var hasFaceVertexColor = face.vertexColors.length > 0;
  7496. var faceType = 0;
  7497. faceType = setBit( faceType, 0, 0 ); // isQuad
  7498. faceType = setBit( faceType, 1, hasMaterial );
  7499. faceType = setBit( faceType, 2, hasFaceUv );
  7500. faceType = setBit( faceType, 3, hasFaceVertexUv );
  7501. faceType = setBit( faceType, 4, hasFaceNormal );
  7502. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  7503. faceType = setBit( faceType, 6, hasFaceColor );
  7504. faceType = setBit( faceType, 7, hasFaceVertexColor );
  7505. faces.push( faceType );
  7506. faces.push( face.a, face.b, face.c );
  7507. faces.push( face.materialIndex );
  7508. if ( hasFaceVertexUv ) {
  7509. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  7510. faces.push(
  7511. getUvIndex( faceVertexUvs[ 0 ] ),
  7512. getUvIndex( faceVertexUvs[ 1 ] ),
  7513. getUvIndex( faceVertexUvs[ 2 ] )
  7514. );
  7515. }
  7516. if ( hasFaceNormal ) {
  7517. faces.push( getNormalIndex( face.normal ) );
  7518. }
  7519. if ( hasFaceVertexNormal ) {
  7520. var vertexNormals = face.vertexNormals;
  7521. faces.push(
  7522. getNormalIndex( vertexNormals[ 0 ] ),
  7523. getNormalIndex( vertexNormals[ 1 ] ),
  7524. getNormalIndex( vertexNormals[ 2 ] )
  7525. );
  7526. }
  7527. if ( hasFaceColor ) {
  7528. faces.push( getColorIndex( face.color ) );
  7529. }
  7530. if ( hasFaceVertexColor ) {
  7531. var vertexColors = face.vertexColors;
  7532. faces.push(
  7533. getColorIndex( vertexColors[ 0 ] ),
  7534. getColorIndex( vertexColors[ 1 ] ),
  7535. getColorIndex( vertexColors[ 2 ] )
  7536. );
  7537. }
  7538. }
  7539. function setBit( value, position, enabled ) {
  7540. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  7541. }
  7542. function getNormalIndex( normal ) {
  7543. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  7544. if ( normalsHash[ hash ] !== undefined ) {
  7545. return normalsHash[ hash ];
  7546. }
  7547. normalsHash[ hash ] = normals.length / 3;
  7548. normals.push( normal.x, normal.y, normal.z );
  7549. return normalsHash[ hash ];
  7550. }
  7551. function getColorIndex( color ) {
  7552. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  7553. if ( colorsHash[ hash ] !== undefined ) {
  7554. return colorsHash[ hash ];
  7555. }
  7556. colorsHash[ hash ] = colors.length;
  7557. colors.push( color.getHex() );
  7558. return colorsHash[ hash ];
  7559. }
  7560. function getUvIndex( uv ) {
  7561. var hash = uv.x.toString() + uv.y.toString();
  7562. if ( uvsHash[ hash ] !== undefined ) {
  7563. return uvsHash[ hash ];
  7564. }
  7565. uvsHash[ hash ] = uvs.length / 2;
  7566. uvs.push( uv.x, uv.y );
  7567. return uvsHash[ hash ];
  7568. }
  7569. data.data = {};
  7570. data.data.vertices = vertices;
  7571. data.data.normals = normals;
  7572. if ( colors.length > 0 ) data.data.colors = colors;
  7573. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  7574. data.data.faces = faces;
  7575. return data;
  7576. },
  7577. clone: function () {
  7578. /*
  7579. // Handle primitives
  7580. var parameters = this.parameters;
  7581. if ( parameters !== undefined ) {
  7582. var values = [];
  7583. for ( var key in parameters ) {
  7584. values.push( parameters[ key ] );
  7585. }
  7586. var geometry = Object.create( this.constructor.prototype );
  7587. this.constructor.apply( geometry, values );
  7588. return geometry;
  7589. }
  7590. return new this.constructor().copy( this );
  7591. */
  7592. return new Geometry().copy( this );
  7593. },
  7594. copy: function ( source ) {
  7595. var i, il, j, jl, k, kl;
  7596. // reset
  7597. this.vertices = [];
  7598. this.colors = [];
  7599. this.faces = [];
  7600. this.faceVertexUvs = [[]];
  7601. this.morphTargets = [];
  7602. this.morphNormals = [];
  7603. this.skinWeights = [];
  7604. this.skinIndices = [];
  7605. this.lineDistances = [];
  7606. this.boundingBox = null;
  7607. this.boundingSphere = null;
  7608. // name
  7609. this.name = source.name;
  7610. // vertices
  7611. var vertices = source.vertices;
  7612. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  7613. this.vertices.push( vertices[ i ].clone() );
  7614. }
  7615. // colors
  7616. var colors = source.colors;
  7617. for ( i = 0, il = colors.length; i < il; i ++ ) {
  7618. this.colors.push( colors[ i ].clone() );
  7619. }
  7620. // faces
  7621. var faces = source.faces;
  7622. for ( i = 0, il = faces.length; i < il; i ++ ) {
  7623. this.faces.push( faces[ i ].clone() );
  7624. }
  7625. // face vertex uvs
  7626. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  7627. var faceVertexUvs = source.faceVertexUvs[ i ];
  7628. if ( this.faceVertexUvs[ i ] === undefined ) {
  7629. this.faceVertexUvs[ i ] = [];
  7630. }
  7631. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  7632. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  7633. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  7634. var uv = uvs[ k ];
  7635. uvsCopy.push( uv.clone() );
  7636. }
  7637. this.faceVertexUvs[ i ].push( uvsCopy );
  7638. }
  7639. }
  7640. // morph targets
  7641. var morphTargets = source.morphTargets;
  7642. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  7643. var morphTarget = {};
  7644. morphTarget.name = morphTargets[ i ].name;
  7645. // vertices
  7646. if ( morphTargets[ i ].vertices !== undefined ) {
  7647. morphTarget.vertices = [];
  7648. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  7649. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  7650. }
  7651. }
  7652. // normals
  7653. if ( morphTargets[ i ].normals !== undefined ) {
  7654. morphTarget.normals = [];
  7655. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  7656. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  7657. }
  7658. }
  7659. this.morphTargets.push( morphTarget );
  7660. }
  7661. // morph normals
  7662. var morphNormals = source.morphNormals;
  7663. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  7664. var morphNormal = {};
  7665. // vertex normals
  7666. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  7667. morphNormal.vertexNormals = [];
  7668. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  7669. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  7670. var destVertexNormal = {};
  7671. destVertexNormal.a = srcVertexNormal.a.clone();
  7672. destVertexNormal.b = srcVertexNormal.b.clone();
  7673. destVertexNormal.c = srcVertexNormal.c.clone();
  7674. morphNormal.vertexNormals.push( destVertexNormal );
  7675. }
  7676. }
  7677. // face normals
  7678. if ( morphNormals[ i ].faceNormals !== undefined ) {
  7679. morphNormal.faceNormals = [];
  7680. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  7681. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  7682. }
  7683. }
  7684. this.morphNormals.push( morphNormal );
  7685. }
  7686. // skin weights
  7687. var skinWeights = source.skinWeights;
  7688. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  7689. this.skinWeights.push( skinWeights[ i ].clone() );
  7690. }
  7691. // skin indices
  7692. var skinIndices = source.skinIndices;
  7693. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  7694. this.skinIndices.push( skinIndices[ i ].clone() );
  7695. }
  7696. // line distances
  7697. var lineDistances = source.lineDistances;
  7698. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  7699. this.lineDistances.push( lineDistances[ i ] );
  7700. }
  7701. // bounding box
  7702. var boundingBox = source.boundingBox;
  7703. if ( boundingBox !== null ) {
  7704. this.boundingBox = boundingBox.clone();
  7705. }
  7706. // bounding sphere
  7707. var boundingSphere = source.boundingSphere;
  7708. if ( boundingSphere !== null ) {
  7709. this.boundingSphere = boundingSphere.clone();
  7710. }
  7711. // update flags
  7712. this.elementsNeedUpdate = source.elementsNeedUpdate;
  7713. this.verticesNeedUpdate = source.verticesNeedUpdate;
  7714. this.uvsNeedUpdate = source.uvsNeedUpdate;
  7715. this.normalsNeedUpdate = source.normalsNeedUpdate;
  7716. this.colorsNeedUpdate = source.colorsNeedUpdate;
  7717. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  7718. this.groupsNeedUpdate = source.groupsNeedUpdate;
  7719. return this;
  7720. },
  7721. dispose: function () {
  7722. this.dispatchEvent( { type: 'dispose' } );
  7723. }
  7724. } );
  7725. /**
  7726. * @author mrdoob / http://mrdoob.com/
  7727. */
  7728. function BufferAttribute( array, itemSize, normalized ) {
  7729. if ( Array.isArray( array ) ) {
  7730. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7731. }
  7732. this.uuid = _Math.generateUUID();
  7733. this.name = '';
  7734. this.array = array;
  7735. this.itemSize = itemSize;
  7736. this.count = array !== undefined ? array.length / itemSize : 0;
  7737. this.normalized = normalized === true;
  7738. this.dynamic = false;
  7739. this.updateRange = { offset: 0, count: - 1 };
  7740. this.onUploadCallback = function () {};
  7741. this.version = 0;
  7742. }
  7743. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  7744. set: function ( value ) {
  7745. if ( value === true ) this.version ++;
  7746. }
  7747. } );
  7748. Object.assign( BufferAttribute.prototype, {
  7749. isBufferAttribute: true,
  7750. setArray: function ( array ) {
  7751. if ( Array.isArray( array ) ) {
  7752. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7753. }
  7754. this.count = array !== undefined ? array.length / this.itemSize : 0;
  7755. this.array = array;
  7756. },
  7757. setDynamic: function ( value ) {
  7758. this.dynamic = value;
  7759. return this;
  7760. },
  7761. copy: function ( source ) {
  7762. this.array = new source.array.constructor( source.array );
  7763. this.itemSize = source.itemSize;
  7764. this.count = source.count;
  7765. this.normalized = source.normalized;
  7766. this.dynamic = source.dynamic;
  7767. return this;
  7768. },
  7769. copyAt: function ( index1, attribute, index2 ) {
  7770. index1 *= this.itemSize;
  7771. index2 *= attribute.itemSize;
  7772. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  7773. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7774. }
  7775. return this;
  7776. },
  7777. copyArray: function ( array ) {
  7778. this.array.set( array );
  7779. return this;
  7780. },
  7781. copyColorsArray: function ( colors ) {
  7782. var array = this.array, offset = 0;
  7783. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  7784. var color = colors[ i ];
  7785. if ( color === undefined ) {
  7786. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  7787. color = new Color();
  7788. }
  7789. array[ offset ++ ] = color.r;
  7790. array[ offset ++ ] = color.g;
  7791. array[ offset ++ ] = color.b;
  7792. }
  7793. return this;
  7794. },
  7795. copyIndicesArray: function ( indices ) {
  7796. var array = this.array, offset = 0;
  7797. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  7798. var index = indices[ i ];
  7799. array[ offset ++ ] = index.a;
  7800. array[ offset ++ ] = index.b;
  7801. array[ offset ++ ] = index.c;
  7802. }
  7803. return this;
  7804. },
  7805. copyVector2sArray: function ( vectors ) {
  7806. var array = this.array, offset = 0;
  7807. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7808. var vector = vectors[ i ];
  7809. if ( vector === undefined ) {
  7810. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  7811. vector = new Vector2();
  7812. }
  7813. array[ offset ++ ] = vector.x;
  7814. array[ offset ++ ] = vector.y;
  7815. }
  7816. return this;
  7817. },
  7818. copyVector3sArray: function ( vectors ) {
  7819. var array = this.array, offset = 0;
  7820. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7821. var vector = vectors[ i ];
  7822. if ( vector === undefined ) {
  7823. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  7824. vector = new Vector3();
  7825. }
  7826. array[ offset ++ ] = vector.x;
  7827. array[ offset ++ ] = vector.y;
  7828. array[ offset ++ ] = vector.z;
  7829. }
  7830. return this;
  7831. },
  7832. copyVector4sArray: function ( vectors ) {
  7833. var array = this.array, offset = 0;
  7834. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7835. var vector = vectors[ i ];
  7836. if ( vector === undefined ) {
  7837. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  7838. vector = new Vector4();
  7839. }
  7840. array[ offset ++ ] = vector.x;
  7841. array[ offset ++ ] = vector.y;
  7842. array[ offset ++ ] = vector.z;
  7843. array[ offset ++ ] = vector.w;
  7844. }
  7845. return this;
  7846. },
  7847. set: function ( value, offset ) {
  7848. if ( offset === undefined ) offset = 0;
  7849. this.array.set( value, offset );
  7850. return this;
  7851. },
  7852. getX: function ( index ) {
  7853. return this.array[ index * this.itemSize ];
  7854. },
  7855. setX: function ( index, x ) {
  7856. this.array[ index * this.itemSize ] = x;
  7857. return this;
  7858. },
  7859. getY: function ( index ) {
  7860. return this.array[ index * this.itemSize + 1 ];
  7861. },
  7862. setY: function ( index, y ) {
  7863. this.array[ index * this.itemSize + 1 ] = y;
  7864. return this;
  7865. },
  7866. getZ: function ( index ) {
  7867. return this.array[ index * this.itemSize + 2 ];
  7868. },
  7869. setZ: function ( index, z ) {
  7870. this.array[ index * this.itemSize + 2 ] = z;
  7871. return this;
  7872. },
  7873. getW: function ( index ) {
  7874. return this.array[ index * this.itemSize + 3 ];
  7875. },
  7876. setW: function ( index, w ) {
  7877. this.array[ index * this.itemSize + 3 ] = w;
  7878. return this;
  7879. },
  7880. setXY: function ( index, x, y ) {
  7881. index *= this.itemSize;
  7882. this.array[ index + 0 ] = x;
  7883. this.array[ index + 1 ] = y;
  7884. return this;
  7885. },
  7886. setXYZ: function ( index, x, y, z ) {
  7887. index *= this.itemSize;
  7888. this.array[ index + 0 ] = x;
  7889. this.array[ index + 1 ] = y;
  7890. this.array[ index + 2 ] = z;
  7891. return this;
  7892. },
  7893. setXYZW: function ( index, x, y, z, w ) {
  7894. index *= this.itemSize;
  7895. this.array[ index + 0 ] = x;
  7896. this.array[ index + 1 ] = y;
  7897. this.array[ index + 2 ] = z;
  7898. this.array[ index + 3 ] = w;
  7899. return this;
  7900. },
  7901. onUpload: function ( callback ) {
  7902. this.onUploadCallback = callback;
  7903. return this;
  7904. },
  7905. clone: function () {
  7906. return new this.constructor( this.array, this.itemSize ).copy( this );
  7907. }
  7908. } );
  7909. //
  7910. function Int8BufferAttribute( array, itemSize ) {
  7911. BufferAttribute.call( this, new Int8Array( array ), itemSize );
  7912. }
  7913. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7914. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7915. function Uint8BufferAttribute( array, itemSize ) {
  7916. BufferAttribute.call( this, new Uint8Array( array ), itemSize );
  7917. }
  7918. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7919. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7920. function Uint8ClampedBufferAttribute( array, itemSize ) {
  7921. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize );
  7922. }
  7923. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7924. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7925. function Int16BufferAttribute( array, itemSize ) {
  7926. BufferAttribute.call( this, new Int16Array( array ), itemSize );
  7927. }
  7928. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7929. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7930. function Uint16BufferAttribute( array, itemSize ) {
  7931. BufferAttribute.call( this, new Uint16Array( array ), itemSize );
  7932. }
  7933. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7934. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7935. function Int32BufferAttribute( array, itemSize ) {
  7936. BufferAttribute.call( this, new Int32Array( array ), itemSize );
  7937. }
  7938. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7939. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7940. function Uint32BufferAttribute( array, itemSize ) {
  7941. BufferAttribute.call( this, new Uint32Array( array ), itemSize );
  7942. }
  7943. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7944. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7945. function Float32BufferAttribute( array, itemSize ) {
  7946. BufferAttribute.call( this, new Float32Array( array ), itemSize );
  7947. }
  7948. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7949. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  7950. function Float64BufferAttribute( array, itemSize ) {
  7951. BufferAttribute.call( this, new Float64Array( array ), itemSize );
  7952. }
  7953. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7954. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  7955. /**
  7956. * @author mrdoob / http://mrdoob.com/
  7957. */
  7958. function DirectGeometry() {
  7959. this.indices = [];
  7960. this.vertices = [];
  7961. this.normals = [];
  7962. this.colors = [];
  7963. this.uvs = [];
  7964. this.uvs2 = [];
  7965. this.groups = [];
  7966. this.morphTargets = {};
  7967. this.skinWeights = [];
  7968. this.skinIndices = [];
  7969. // this.lineDistances = [];
  7970. this.boundingBox = null;
  7971. this.boundingSphere = null;
  7972. // update flags
  7973. this.verticesNeedUpdate = false;
  7974. this.normalsNeedUpdate = false;
  7975. this.colorsNeedUpdate = false;
  7976. this.uvsNeedUpdate = false;
  7977. this.groupsNeedUpdate = false;
  7978. }
  7979. Object.assign( DirectGeometry.prototype, {
  7980. computeGroups: function ( geometry ) {
  7981. var group;
  7982. var groups = [];
  7983. var materialIndex = undefined;
  7984. var faces = geometry.faces;
  7985. for ( var i = 0; i < faces.length; i ++ ) {
  7986. var face = faces[ i ];
  7987. // materials
  7988. if ( face.materialIndex !== materialIndex ) {
  7989. materialIndex = face.materialIndex;
  7990. if ( group !== undefined ) {
  7991. group.count = ( i * 3 ) - group.start;
  7992. groups.push( group );
  7993. }
  7994. group = {
  7995. start: i * 3,
  7996. materialIndex: materialIndex
  7997. };
  7998. }
  7999. }
  8000. if ( group !== undefined ) {
  8001. group.count = ( i * 3 ) - group.start;
  8002. groups.push( group );
  8003. }
  8004. this.groups = groups;
  8005. },
  8006. fromGeometry: function ( geometry ) {
  8007. var faces = geometry.faces;
  8008. var vertices = geometry.vertices;
  8009. var faceVertexUvs = geometry.faceVertexUvs;
  8010. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  8011. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  8012. // morphs
  8013. var morphTargets = geometry.morphTargets;
  8014. var morphTargetsLength = morphTargets.length;
  8015. var morphTargetsPosition;
  8016. if ( morphTargetsLength > 0 ) {
  8017. morphTargetsPosition = [];
  8018. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  8019. morphTargetsPosition[ i ] = [];
  8020. }
  8021. this.morphTargets.position = morphTargetsPosition;
  8022. }
  8023. var morphNormals = geometry.morphNormals;
  8024. var morphNormalsLength = morphNormals.length;
  8025. var morphTargetsNormal;
  8026. if ( morphNormalsLength > 0 ) {
  8027. morphTargetsNormal = [];
  8028. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  8029. morphTargetsNormal[ i ] = [];
  8030. }
  8031. this.morphTargets.normal = morphTargetsNormal;
  8032. }
  8033. // skins
  8034. var skinIndices = geometry.skinIndices;
  8035. var skinWeights = geometry.skinWeights;
  8036. var hasSkinIndices = skinIndices.length === vertices.length;
  8037. var hasSkinWeights = skinWeights.length === vertices.length;
  8038. //
  8039. for ( var i = 0; i < faces.length; i ++ ) {
  8040. var face = faces[ i ];
  8041. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  8042. var vertexNormals = face.vertexNormals;
  8043. if ( vertexNormals.length === 3 ) {
  8044. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  8045. } else {
  8046. var normal = face.normal;
  8047. this.normals.push( normal, normal, normal );
  8048. }
  8049. var vertexColors = face.vertexColors;
  8050. if ( vertexColors.length === 3 ) {
  8051. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  8052. } else {
  8053. var color = face.color;
  8054. this.colors.push( color, color, color );
  8055. }
  8056. if ( hasFaceVertexUv === true ) {
  8057. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  8058. if ( vertexUvs !== undefined ) {
  8059. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  8060. } else {
  8061. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  8062. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  8063. }
  8064. }
  8065. if ( hasFaceVertexUv2 === true ) {
  8066. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  8067. if ( vertexUvs !== undefined ) {
  8068. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  8069. } else {
  8070. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  8071. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  8072. }
  8073. }
  8074. // morphs
  8075. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  8076. var morphTarget = morphTargets[ j ].vertices;
  8077. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  8078. }
  8079. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  8080. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  8081. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  8082. }
  8083. // skins
  8084. if ( hasSkinIndices ) {
  8085. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  8086. }
  8087. if ( hasSkinWeights ) {
  8088. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  8089. }
  8090. }
  8091. this.computeGroups( geometry );
  8092. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  8093. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  8094. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  8095. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  8096. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  8097. return this;
  8098. }
  8099. } );
  8100. /**
  8101. * @author mrdoob / http://mrdoob.com/
  8102. */
  8103. function arrayMax( array ) {
  8104. if ( array.length === 0 ) return - Infinity;
  8105. var max = array[ 0 ];
  8106. for ( var i = 1, l = array.length; i < l; ++ i ) {
  8107. if ( array[ i ] > max ) max = array[ i ];
  8108. }
  8109. return max;
  8110. }
  8111. /**
  8112. * @author alteredq / http://alteredqualia.com/
  8113. * @author mrdoob / http://mrdoob.com/
  8114. */
  8115. function BufferGeometry() {
  8116. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  8117. this.uuid = _Math.generateUUID();
  8118. this.name = '';
  8119. this.type = 'BufferGeometry';
  8120. this.index = null;
  8121. this.attributes = {};
  8122. this.morphAttributes = {};
  8123. this.groups = [];
  8124. this.boundingBox = null;
  8125. this.boundingSphere = null;
  8126. this.drawRange = { start: 0, count: Infinity };
  8127. }
  8128. BufferGeometry.MaxIndex = 65535;
  8129. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, {
  8130. isBufferGeometry: true,
  8131. getIndex: function () {
  8132. return this.index;
  8133. },
  8134. setIndex: function ( index ) {
  8135. if ( Array.isArray( index ) ) {
  8136. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  8137. } else {
  8138. this.index = index;
  8139. }
  8140. },
  8141. addAttribute: function ( name, attribute ) {
  8142. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  8143. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  8144. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  8145. return;
  8146. }
  8147. if ( name === 'index' ) {
  8148. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  8149. this.setIndex( attribute );
  8150. return;
  8151. }
  8152. this.attributes[ name ] = attribute;
  8153. return this;
  8154. },
  8155. getAttribute: function ( name ) {
  8156. return this.attributes[ name ];
  8157. },
  8158. removeAttribute: function ( name ) {
  8159. delete this.attributes[ name ];
  8160. return this;
  8161. },
  8162. addGroup: function ( start, count, materialIndex ) {
  8163. this.groups.push( {
  8164. start: start,
  8165. count: count,
  8166. materialIndex: materialIndex !== undefined ? materialIndex : 0
  8167. } );
  8168. },
  8169. clearGroups: function () {
  8170. this.groups = [];
  8171. },
  8172. setDrawRange: function ( start, count ) {
  8173. this.drawRange.start = start;
  8174. this.drawRange.count = count;
  8175. },
  8176. applyMatrix: function ( matrix ) {
  8177. var position = this.attributes.position;
  8178. if ( position !== undefined ) {
  8179. matrix.applyToBufferAttribute( position );
  8180. position.needsUpdate = true;
  8181. }
  8182. var normal = this.attributes.normal;
  8183. if ( normal !== undefined ) {
  8184. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8185. normalMatrix.applyToBufferAttribute( normal );
  8186. normal.needsUpdate = true;
  8187. }
  8188. if ( this.boundingBox !== null ) {
  8189. this.computeBoundingBox();
  8190. }
  8191. if ( this.boundingSphere !== null ) {
  8192. this.computeBoundingSphere();
  8193. }
  8194. return this;
  8195. },
  8196. rotateX: function () {
  8197. // rotate geometry around world x-axis
  8198. var m1 = new Matrix4();
  8199. return function rotateX( angle ) {
  8200. m1.makeRotationX( angle );
  8201. this.applyMatrix( m1 );
  8202. return this;
  8203. };
  8204. }(),
  8205. rotateY: function () {
  8206. // rotate geometry around world y-axis
  8207. var m1 = new Matrix4();
  8208. return function rotateY( angle ) {
  8209. m1.makeRotationY( angle );
  8210. this.applyMatrix( m1 );
  8211. return this;
  8212. };
  8213. }(),
  8214. rotateZ: function () {
  8215. // rotate geometry around world z-axis
  8216. var m1 = new Matrix4();
  8217. return function rotateZ( angle ) {
  8218. m1.makeRotationZ( angle );
  8219. this.applyMatrix( m1 );
  8220. return this;
  8221. };
  8222. }(),
  8223. translate: function () {
  8224. // translate geometry
  8225. var m1 = new Matrix4();
  8226. return function translate( x, y, z ) {
  8227. m1.makeTranslation( x, y, z );
  8228. this.applyMatrix( m1 );
  8229. return this;
  8230. };
  8231. }(),
  8232. scale: function () {
  8233. // scale geometry
  8234. var m1 = new Matrix4();
  8235. return function scale( x, y, z ) {
  8236. m1.makeScale( x, y, z );
  8237. this.applyMatrix( m1 );
  8238. return this;
  8239. };
  8240. }(),
  8241. lookAt: function () {
  8242. var obj = new Object3D();
  8243. return function lookAt( vector ) {
  8244. obj.lookAt( vector );
  8245. obj.updateMatrix();
  8246. this.applyMatrix( obj.matrix );
  8247. };
  8248. }(),
  8249. center: function () {
  8250. this.computeBoundingBox();
  8251. var offset = this.boundingBox.getCenter().negate();
  8252. this.translate( offset.x, offset.y, offset.z );
  8253. return offset;
  8254. },
  8255. setFromObject: function ( object ) {
  8256. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  8257. var geometry = object.geometry;
  8258. if ( object.isPoints || object.isLine ) {
  8259. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  8260. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  8261. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  8262. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  8263. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  8264. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  8265. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  8266. }
  8267. if ( geometry.boundingSphere !== null ) {
  8268. this.boundingSphere = geometry.boundingSphere.clone();
  8269. }
  8270. if ( geometry.boundingBox !== null ) {
  8271. this.boundingBox = geometry.boundingBox.clone();
  8272. }
  8273. } else if ( object.isMesh ) {
  8274. if ( geometry && geometry.isGeometry ) {
  8275. this.fromGeometry( geometry );
  8276. }
  8277. }
  8278. return this;
  8279. },
  8280. updateFromObject: function ( object ) {
  8281. var geometry = object.geometry;
  8282. if ( object.isMesh ) {
  8283. var direct = geometry.__directGeometry;
  8284. if ( geometry.elementsNeedUpdate === true ) {
  8285. direct = undefined;
  8286. geometry.elementsNeedUpdate = false;
  8287. }
  8288. if ( direct === undefined ) {
  8289. return this.fromGeometry( geometry );
  8290. }
  8291. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  8292. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  8293. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  8294. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  8295. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  8296. geometry.verticesNeedUpdate = false;
  8297. geometry.normalsNeedUpdate = false;
  8298. geometry.colorsNeedUpdate = false;
  8299. geometry.uvsNeedUpdate = false;
  8300. geometry.groupsNeedUpdate = false;
  8301. geometry = direct;
  8302. }
  8303. var attribute;
  8304. if ( geometry.verticesNeedUpdate === true ) {
  8305. attribute = this.attributes.position;
  8306. if ( attribute !== undefined ) {
  8307. attribute.copyVector3sArray( geometry.vertices );
  8308. attribute.needsUpdate = true;
  8309. }
  8310. geometry.verticesNeedUpdate = false;
  8311. }
  8312. if ( geometry.normalsNeedUpdate === true ) {
  8313. attribute = this.attributes.normal;
  8314. if ( attribute !== undefined ) {
  8315. attribute.copyVector3sArray( geometry.normals );
  8316. attribute.needsUpdate = true;
  8317. }
  8318. geometry.normalsNeedUpdate = false;
  8319. }
  8320. if ( geometry.colorsNeedUpdate === true ) {
  8321. attribute = this.attributes.color;
  8322. if ( attribute !== undefined ) {
  8323. attribute.copyColorsArray( geometry.colors );
  8324. attribute.needsUpdate = true;
  8325. }
  8326. geometry.colorsNeedUpdate = false;
  8327. }
  8328. if ( geometry.uvsNeedUpdate ) {
  8329. attribute = this.attributes.uv;
  8330. if ( attribute !== undefined ) {
  8331. attribute.copyVector2sArray( geometry.uvs );
  8332. attribute.needsUpdate = true;
  8333. }
  8334. geometry.uvsNeedUpdate = false;
  8335. }
  8336. if ( geometry.lineDistancesNeedUpdate ) {
  8337. attribute = this.attributes.lineDistance;
  8338. if ( attribute !== undefined ) {
  8339. attribute.copyArray( geometry.lineDistances );
  8340. attribute.needsUpdate = true;
  8341. }
  8342. geometry.lineDistancesNeedUpdate = false;
  8343. }
  8344. if ( geometry.groupsNeedUpdate ) {
  8345. geometry.computeGroups( object.geometry );
  8346. this.groups = geometry.groups;
  8347. geometry.groupsNeedUpdate = false;
  8348. }
  8349. return this;
  8350. },
  8351. fromGeometry: function ( geometry ) {
  8352. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  8353. return this.fromDirectGeometry( geometry.__directGeometry );
  8354. },
  8355. fromDirectGeometry: function ( geometry ) {
  8356. var positions = new Float32Array( geometry.vertices.length * 3 );
  8357. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  8358. if ( geometry.normals.length > 0 ) {
  8359. var normals = new Float32Array( geometry.normals.length * 3 );
  8360. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  8361. }
  8362. if ( geometry.colors.length > 0 ) {
  8363. var colors = new Float32Array( geometry.colors.length * 3 );
  8364. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  8365. }
  8366. if ( geometry.uvs.length > 0 ) {
  8367. var uvs = new Float32Array( geometry.uvs.length * 2 );
  8368. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  8369. }
  8370. if ( geometry.uvs2.length > 0 ) {
  8371. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  8372. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  8373. }
  8374. if ( geometry.indices.length > 0 ) {
  8375. var TypeArray = arrayMax( geometry.indices ) > 65535 ? Uint32Array : Uint16Array;
  8376. var indices = new TypeArray( geometry.indices.length * 3 );
  8377. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  8378. }
  8379. // groups
  8380. this.groups = geometry.groups;
  8381. // morphs
  8382. for ( var name in geometry.morphTargets ) {
  8383. var array = [];
  8384. var morphTargets = geometry.morphTargets[ name ];
  8385. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  8386. var morphTarget = morphTargets[ i ];
  8387. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  8388. array.push( attribute.copyVector3sArray( morphTarget ) );
  8389. }
  8390. this.morphAttributes[ name ] = array;
  8391. }
  8392. // skinning
  8393. if ( geometry.skinIndices.length > 0 ) {
  8394. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  8395. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  8396. }
  8397. if ( geometry.skinWeights.length > 0 ) {
  8398. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  8399. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  8400. }
  8401. //
  8402. if ( geometry.boundingSphere !== null ) {
  8403. this.boundingSphere = geometry.boundingSphere.clone();
  8404. }
  8405. if ( geometry.boundingBox !== null ) {
  8406. this.boundingBox = geometry.boundingBox.clone();
  8407. }
  8408. return this;
  8409. },
  8410. computeBoundingBox: function () {
  8411. if ( this.boundingBox === null ) {
  8412. this.boundingBox = new Box3();
  8413. }
  8414. var position = this.attributes.position;
  8415. if ( position !== undefined ) {
  8416. this.boundingBox.setFromBufferAttribute( position );
  8417. } else {
  8418. this.boundingBox.makeEmpty();
  8419. }
  8420. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  8421. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  8422. }
  8423. },
  8424. computeBoundingSphere: function () {
  8425. var box = new Box3();
  8426. var vector = new Vector3();
  8427. return function computeBoundingSphere() {
  8428. if ( this.boundingSphere === null ) {
  8429. this.boundingSphere = new Sphere();
  8430. }
  8431. var position = this.attributes.position;
  8432. if ( position ) {
  8433. var center = this.boundingSphere.center;
  8434. box.setFromBufferAttribute( position );
  8435. box.getCenter( center );
  8436. // hoping to find a boundingSphere with a radius smaller than the
  8437. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  8438. var maxRadiusSq = 0;
  8439. for ( var i = 0, il = position.count; i < il; i ++ ) {
  8440. vector.x = position.getX( i );
  8441. vector.y = position.getY( i );
  8442. vector.z = position.getZ( i );
  8443. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  8444. }
  8445. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  8446. if ( isNaN( this.boundingSphere.radius ) ) {
  8447. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  8448. }
  8449. }
  8450. };
  8451. }(),
  8452. computeFaceNormals: function () {
  8453. // backwards compatibility
  8454. },
  8455. computeVertexNormals: function () {
  8456. var index = this.index;
  8457. var attributes = this.attributes;
  8458. var groups = this.groups;
  8459. if ( attributes.position ) {
  8460. var positions = attributes.position.array;
  8461. if ( attributes.normal === undefined ) {
  8462. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  8463. } else {
  8464. // reset existing normals to zero
  8465. var array = attributes.normal.array;
  8466. for ( var i = 0, il = array.length; i < il; i ++ ) {
  8467. array[ i ] = 0;
  8468. }
  8469. }
  8470. var normals = attributes.normal.array;
  8471. var vA, vB, vC;
  8472. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  8473. var cb = new Vector3(), ab = new Vector3();
  8474. // indexed elements
  8475. if ( index ) {
  8476. var indices = index.array;
  8477. if ( groups.length === 0 ) {
  8478. this.addGroup( 0, indices.length );
  8479. }
  8480. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  8481. var group = groups[ j ];
  8482. var start = group.start;
  8483. var count = group.count;
  8484. for ( var i = start, il = start + count; i < il; i += 3 ) {
  8485. vA = indices[ i + 0 ] * 3;
  8486. vB = indices[ i + 1 ] * 3;
  8487. vC = indices[ i + 2 ] * 3;
  8488. pA.fromArray( positions, vA );
  8489. pB.fromArray( positions, vB );
  8490. pC.fromArray( positions, vC );
  8491. cb.subVectors( pC, pB );
  8492. ab.subVectors( pA, pB );
  8493. cb.cross( ab );
  8494. normals[ vA ] += cb.x;
  8495. normals[ vA + 1 ] += cb.y;
  8496. normals[ vA + 2 ] += cb.z;
  8497. normals[ vB ] += cb.x;
  8498. normals[ vB + 1 ] += cb.y;
  8499. normals[ vB + 2 ] += cb.z;
  8500. normals[ vC ] += cb.x;
  8501. normals[ vC + 1 ] += cb.y;
  8502. normals[ vC + 2 ] += cb.z;
  8503. }
  8504. }
  8505. } else {
  8506. // non-indexed elements (unconnected triangle soup)
  8507. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  8508. pA.fromArray( positions, i );
  8509. pB.fromArray( positions, i + 3 );
  8510. pC.fromArray( positions, i + 6 );
  8511. cb.subVectors( pC, pB );
  8512. ab.subVectors( pA, pB );
  8513. cb.cross( ab );
  8514. normals[ i ] = cb.x;
  8515. normals[ i + 1 ] = cb.y;
  8516. normals[ i + 2 ] = cb.z;
  8517. normals[ i + 3 ] = cb.x;
  8518. normals[ i + 4 ] = cb.y;
  8519. normals[ i + 5 ] = cb.z;
  8520. normals[ i + 6 ] = cb.x;
  8521. normals[ i + 7 ] = cb.y;
  8522. normals[ i + 8 ] = cb.z;
  8523. }
  8524. }
  8525. this.normalizeNormals();
  8526. attributes.normal.needsUpdate = true;
  8527. }
  8528. },
  8529. merge: function ( geometry, offset ) {
  8530. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  8531. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  8532. return;
  8533. }
  8534. if ( offset === undefined ) offset = 0;
  8535. var attributes = this.attributes;
  8536. for ( var key in attributes ) {
  8537. if ( geometry.attributes[ key ] === undefined ) continue;
  8538. var attribute1 = attributes[ key ];
  8539. var attributeArray1 = attribute1.array;
  8540. var attribute2 = geometry.attributes[ key ];
  8541. var attributeArray2 = attribute2.array;
  8542. var attributeSize = attribute2.itemSize;
  8543. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  8544. attributeArray1[ j ] = attributeArray2[ i ];
  8545. }
  8546. }
  8547. return this;
  8548. },
  8549. normalizeNormals: function () {
  8550. var vector = new Vector3();
  8551. return function normalizeNormals() {
  8552. var normals = this.attributes.normal;
  8553. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  8554. vector.x = normals.getX( i );
  8555. vector.y = normals.getY( i );
  8556. vector.z = normals.getZ( i );
  8557. vector.normalize();
  8558. normals.setXYZ( i, vector.x, vector.y, vector.z );
  8559. }
  8560. };
  8561. }(),
  8562. toNonIndexed: function () {
  8563. if ( this.index === null ) {
  8564. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  8565. return this;
  8566. }
  8567. var geometry2 = new BufferGeometry();
  8568. var indices = this.index.array;
  8569. var attributes = this.attributes;
  8570. for ( var name in attributes ) {
  8571. var attribute = attributes[ name ];
  8572. var array = attribute.array;
  8573. var itemSize = attribute.itemSize;
  8574. var array2 = new array.constructor( indices.length * itemSize );
  8575. var index = 0, index2 = 0;
  8576. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  8577. index = indices[ i ] * itemSize;
  8578. for ( var j = 0; j < itemSize; j ++ ) {
  8579. array2[ index2 ++ ] = array[ index ++ ];
  8580. }
  8581. }
  8582. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  8583. }
  8584. return geometry2;
  8585. },
  8586. toJSON: function () {
  8587. var data = {
  8588. metadata: {
  8589. version: 4.5,
  8590. type: 'BufferGeometry',
  8591. generator: 'BufferGeometry.toJSON'
  8592. }
  8593. };
  8594. // standard BufferGeometry serialization
  8595. data.uuid = this.uuid;
  8596. data.type = this.type;
  8597. if ( this.name !== '' ) data.name = this.name;
  8598. if ( this.parameters !== undefined ) {
  8599. var parameters = this.parameters;
  8600. for ( var key in parameters ) {
  8601. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8602. }
  8603. return data;
  8604. }
  8605. data.data = { attributes: {} };
  8606. var index = this.index;
  8607. if ( index !== null ) {
  8608. var array = Array.prototype.slice.call( index.array );
  8609. data.data.index = {
  8610. type: index.array.constructor.name,
  8611. array: array
  8612. };
  8613. }
  8614. var attributes = this.attributes;
  8615. for ( var key in attributes ) {
  8616. var attribute = attributes[ key ];
  8617. var array = Array.prototype.slice.call( attribute.array );
  8618. data.data.attributes[ key ] = {
  8619. itemSize: attribute.itemSize,
  8620. type: attribute.array.constructor.name,
  8621. array: array,
  8622. normalized: attribute.normalized
  8623. };
  8624. }
  8625. var groups = this.groups;
  8626. if ( groups.length > 0 ) {
  8627. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  8628. }
  8629. var boundingSphere = this.boundingSphere;
  8630. if ( boundingSphere !== null ) {
  8631. data.data.boundingSphere = {
  8632. center: boundingSphere.center.toArray(),
  8633. radius: boundingSphere.radius
  8634. };
  8635. }
  8636. return data;
  8637. },
  8638. clone: function () {
  8639. /*
  8640. // Handle primitives
  8641. var parameters = this.parameters;
  8642. if ( parameters !== undefined ) {
  8643. var values = [];
  8644. for ( var key in parameters ) {
  8645. values.push( parameters[ key ] );
  8646. }
  8647. var geometry = Object.create( this.constructor.prototype );
  8648. this.constructor.apply( geometry, values );
  8649. return geometry;
  8650. }
  8651. return new this.constructor().copy( this );
  8652. */
  8653. return new BufferGeometry().copy( this );
  8654. },
  8655. copy: function ( source ) {
  8656. var name, i, l;
  8657. // reset
  8658. this.index = null;
  8659. this.attributes = {};
  8660. this.morphAttributes = {};
  8661. this.groups = [];
  8662. this.boundingBox = null;
  8663. this.boundingSphere = null;
  8664. // name
  8665. this.name = source.name;
  8666. // index
  8667. var index = source.index;
  8668. if ( index !== null ) {
  8669. this.setIndex( index.clone() );
  8670. }
  8671. // attributes
  8672. var attributes = source.attributes;
  8673. for ( name in attributes ) {
  8674. var attribute = attributes[ name ];
  8675. this.addAttribute( name, attribute.clone() );
  8676. }
  8677. // morph attributes
  8678. var morphAttributes = source.morphAttributes;
  8679. for ( name in morphAttributes ) {
  8680. var array = [];
  8681. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  8682. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  8683. array.push( morphAttribute[ i ].clone() );
  8684. }
  8685. this.morphAttributes[ name ] = array;
  8686. }
  8687. // groups
  8688. var groups = source.groups;
  8689. for ( i = 0, l = groups.length; i < l; i ++ ) {
  8690. var group = groups[ i ];
  8691. this.addGroup( group.start, group.count, group.materialIndex );
  8692. }
  8693. // bounding box
  8694. var boundingBox = source.boundingBox;
  8695. if ( boundingBox !== null ) {
  8696. this.boundingBox = boundingBox.clone();
  8697. }
  8698. // bounding sphere
  8699. var boundingSphere = source.boundingSphere;
  8700. if ( boundingSphere !== null ) {
  8701. this.boundingSphere = boundingSphere.clone();
  8702. }
  8703. // draw range
  8704. this.drawRange.start = source.drawRange.start;
  8705. this.drawRange.count = source.drawRange.count;
  8706. return this;
  8707. },
  8708. dispose: function () {
  8709. this.dispatchEvent( { type: 'dispose' } );
  8710. }
  8711. } );
  8712. /**
  8713. * @author mrdoob / http://mrdoob.com/
  8714. * @author Mugen87 / https://github.com/Mugen87
  8715. */
  8716. // BoxGeometry
  8717. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  8718. Geometry.call( this );
  8719. this.type = 'BoxGeometry';
  8720. this.parameters = {
  8721. width: width,
  8722. height: height,
  8723. depth: depth,
  8724. widthSegments: widthSegments,
  8725. heightSegments: heightSegments,
  8726. depthSegments: depthSegments
  8727. };
  8728. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  8729. this.mergeVertices();
  8730. }
  8731. BoxGeometry.prototype = Object.create( Geometry.prototype );
  8732. BoxGeometry.prototype.constructor = BoxGeometry;
  8733. // BoxBufferGeometry
  8734. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  8735. BufferGeometry.call( this );
  8736. this.type = 'BoxBufferGeometry';
  8737. this.parameters = {
  8738. width: width,
  8739. height: height,
  8740. depth: depth,
  8741. widthSegments: widthSegments,
  8742. heightSegments: heightSegments,
  8743. depthSegments: depthSegments
  8744. };
  8745. var scope = this;
  8746. // segments
  8747. widthSegments = Math.floor( widthSegments ) || 1;
  8748. heightSegments = Math.floor( heightSegments ) || 1;
  8749. depthSegments = Math.floor( depthSegments ) || 1;
  8750. // buffers
  8751. var indices = [];
  8752. var vertices = [];
  8753. var normals = [];
  8754. var uvs = [];
  8755. // helper variables
  8756. var numberOfVertices = 0;
  8757. var groupStart = 0;
  8758. // build each side of the box geometry
  8759. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  8760. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  8761. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  8762. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  8763. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  8764. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  8765. // build geometry
  8766. this.setIndex( indices );
  8767. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8768. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8769. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8770. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  8771. var segmentWidth = width / gridX;
  8772. var segmentHeight = height / gridY;
  8773. var widthHalf = width / 2;
  8774. var heightHalf = height / 2;
  8775. var depthHalf = depth / 2;
  8776. var gridX1 = gridX + 1;
  8777. var gridY1 = gridY + 1;
  8778. var vertexCounter = 0;
  8779. var groupCount = 0;
  8780. var ix, iy;
  8781. var vector = new Vector3();
  8782. // generate vertices, normals and uvs
  8783. for ( iy = 0; iy < gridY1; iy ++ ) {
  8784. var y = iy * segmentHeight - heightHalf;
  8785. for ( ix = 0; ix < gridX1; ix ++ ) {
  8786. var x = ix * segmentWidth - widthHalf;
  8787. // set values to correct vector component
  8788. vector[ u ] = x * udir;
  8789. vector[ v ] = y * vdir;
  8790. vector[ w ] = depthHalf;
  8791. // now apply vector to vertex buffer
  8792. vertices.push( vector.x, vector.y, vector.z );
  8793. // set values to correct vector component
  8794. vector[ u ] = 0;
  8795. vector[ v ] = 0;
  8796. vector[ w ] = depth > 0 ? 1 : - 1;
  8797. // now apply vector to normal buffer
  8798. normals.push( vector.x, vector.y, vector.z );
  8799. // uvs
  8800. uvs.push( ix / gridX );
  8801. uvs.push( 1 - ( iy / gridY ) );
  8802. // counters
  8803. vertexCounter += 1;
  8804. }
  8805. }
  8806. // indices
  8807. // 1. you need three indices to draw a single face
  8808. // 2. a single segment consists of two faces
  8809. // 3. so we need to generate six (2*3) indices per segment
  8810. for ( iy = 0; iy < gridY; iy ++ ) {
  8811. for ( ix = 0; ix < gridX; ix ++ ) {
  8812. var a = numberOfVertices + ix + gridX1 * iy;
  8813. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  8814. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  8815. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  8816. // faces
  8817. indices.push( a, b, d );
  8818. indices.push( b, c, d );
  8819. // increase counter
  8820. groupCount += 6;
  8821. }
  8822. }
  8823. // add a group to the geometry. this will ensure multi material support
  8824. scope.addGroup( groupStart, groupCount, materialIndex );
  8825. // calculate new start value for groups
  8826. groupStart += groupCount;
  8827. // update total number of vertices
  8828. numberOfVertices += vertexCounter;
  8829. }
  8830. }
  8831. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  8832. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  8833. /**
  8834. * @author mrdoob / http://mrdoob.com/
  8835. * @author Mugen87 / https://github.com/Mugen87
  8836. */
  8837. // PlaneGeometry
  8838. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  8839. Geometry.call( this );
  8840. this.type = 'PlaneGeometry';
  8841. this.parameters = {
  8842. width: width,
  8843. height: height,
  8844. widthSegments: widthSegments,
  8845. heightSegments: heightSegments
  8846. };
  8847. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  8848. this.mergeVertices();
  8849. }
  8850. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  8851. PlaneGeometry.prototype.constructor = PlaneGeometry;
  8852. // PlaneBufferGeometry
  8853. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  8854. BufferGeometry.call( this );
  8855. this.type = 'PlaneBufferGeometry';
  8856. this.parameters = {
  8857. width: width,
  8858. height: height,
  8859. widthSegments: widthSegments,
  8860. heightSegments: heightSegments
  8861. };
  8862. var width_half = width / 2;
  8863. var height_half = height / 2;
  8864. var gridX = Math.floor( widthSegments ) || 1;
  8865. var gridY = Math.floor( heightSegments ) || 1;
  8866. var gridX1 = gridX + 1;
  8867. var gridY1 = gridY + 1;
  8868. var segment_width = width / gridX;
  8869. var segment_height = height / gridY;
  8870. var ix, iy;
  8871. // buffers
  8872. var indices = [];
  8873. var vertices = [];
  8874. var normals = [];
  8875. var uvs = [];
  8876. // generate vertices, normals and uvs
  8877. for ( iy = 0; iy < gridY1; iy ++ ) {
  8878. var y = iy * segment_height - height_half;
  8879. for ( ix = 0; ix < gridX1; ix ++ ) {
  8880. var x = ix * segment_width - width_half;
  8881. vertices.push( x, - y, 0 );
  8882. normals.push( 0, 0, 1 );
  8883. uvs.push( ix / gridX );
  8884. uvs.push( 1 - ( iy / gridY ) );
  8885. }
  8886. }
  8887. // indices
  8888. for ( iy = 0; iy < gridY; iy ++ ) {
  8889. for ( ix = 0; ix < gridX; ix ++ ) {
  8890. var a = ix + gridX1 * iy;
  8891. var b = ix + gridX1 * ( iy + 1 );
  8892. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8893. var d = ( ix + 1 ) + gridX1 * iy;
  8894. // faces
  8895. indices.push( a, b, d );
  8896. indices.push( b, c, d );
  8897. }
  8898. }
  8899. // build geometry
  8900. this.setIndex( indices );
  8901. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8902. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8903. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8904. }
  8905. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  8906. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  8907. /**
  8908. * @author mrdoob / http://mrdoob.com/
  8909. * @author alteredq / http://alteredqualia.com/
  8910. *
  8911. * parameters = {
  8912. * color: <hex>,
  8913. * opacity: <float>,
  8914. * map: new THREE.Texture( <Image> ),
  8915. *
  8916. * lightMap: new THREE.Texture( <Image> ),
  8917. * lightMapIntensity: <float>
  8918. *
  8919. * aoMap: new THREE.Texture( <Image> ),
  8920. * aoMapIntensity: <float>
  8921. *
  8922. * specularMap: new THREE.Texture( <Image> ),
  8923. *
  8924. * alphaMap: new THREE.Texture( <Image> ),
  8925. *
  8926. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8927. * combine: THREE.Multiply,
  8928. * reflectivity: <float>,
  8929. * refractionRatio: <float>,
  8930. *
  8931. * depthTest: <bool>,
  8932. * depthWrite: <bool>,
  8933. *
  8934. * wireframe: <boolean>,
  8935. * wireframeLinewidth: <float>,
  8936. *
  8937. * skinning: <bool>,
  8938. * morphTargets: <bool>
  8939. * }
  8940. */
  8941. function MeshBasicMaterial( parameters ) {
  8942. Material.call( this );
  8943. this.type = 'MeshBasicMaterial';
  8944. this.color = new Color( 0xffffff ); // emissive
  8945. this.map = null;
  8946. this.lightMap = null;
  8947. this.lightMapIntensity = 1.0;
  8948. this.aoMap = null;
  8949. this.aoMapIntensity = 1.0;
  8950. this.specularMap = null;
  8951. this.alphaMap = null;
  8952. this.envMap = null;
  8953. this.combine = MultiplyOperation;
  8954. this.reflectivity = 1;
  8955. this.refractionRatio = 0.98;
  8956. this.wireframe = false;
  8957. this.wireframeLinewidth = 1;
  8958. this.wireframeLinecap = 'round';
  8959. this.wireframeLinejoin = 'round';
  8960. this.skinning = false;
  8961. this.morphTargets = false;
  8962. this.lights = false;
  8963. this.setValues( parameters );
  8964. }
  8965. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  8966. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  8967. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  8968. MeshBasicMaterial.prototype.copy = function ( source ) {
  8969. Material.prototype.copy.call( this, source );
  8970. this.color.copy( source.color );
  8971. this.map = source.map;
  8972. this.lightMap = source.lightMap;
  8973. this.lightMapIntensity = source.lightMapIntensity;
  8974. this.aoMap = source.aoMap;
  8975. this.aoMapIntensity = source.aoMapIntensity;
  8976. this.specularMap = source.specularMap;
  8977. this.alphaMap = source.alphaMap;
  8978. this.envMap = source.envMap;
  8979. this.combine = source.combine;
  8980. this.reflectivity = source.reflectivity;
  8981. this.refractionRatio = source.refractionRatio;
  8982. this.wireframe = source.wireframe;
  8983. this.wireframeLinewidth = source.wireframeLinewidth;
  8984. this.wireframeLinecap = source.wireframeLinecap;
  8985. this.wireframeLinejoin = source.wireframeLinejoin;
  8986. this.skinning = source.skinning;
  8987. this.morphTargets = source.morphTargets;
  8988. return this;
  8989. };
  8990. /**
  8991. * @author bhouston / http://clara.io
  8992. */
  8993. function Ray( origin, direction ) {
  8994. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  8995. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  8996. }
  8997. Object.assign( Ray.prototype, {
  8998. set: function ( origin, direction ) {
  8999. this.origin.copy( origin );
  9000. this.direction.copy( direction );
  9001. return this;
  9002. },
  9003. clone: function () {
  9004. return new this.constructor().copy( this );
  9005. },
  9006. copy: function ( ray ) {
  9007. this.origin.copy( ray.origin );
  9008. this.direction.copy( ray.direction );
  9009. return this;
  9010. },
  9011. at: function ( t, optionalTarget ) {
  9012. var result = optionalTarget || new Vector3();
  9013. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  9014. },
  9015. lookAt: function ( v ) {
  9016. this.direction.copy( v ).sub( this.origin ).normalize();
  9017. return this;
  9018. },
  9019. recast: function () {
  9020. var v1 = new Vector3();
  9021. return function recast( t ) {
  9022. this.origin.copy( this.at( t, v1 ) );
  9023. return this;
  9024. };
  9025. }(),
  9026. closestPointToPoint: function ( point, optionalTarget ) {
  9027. var result = optionalTarget || new Vector3();
  9028. result.subVectors( point, this.origin );
  9029. var directionDistance = result.dot( this.direction );
  9030. if ( directionDistance < 0 ) {
  9031. return result.copy( this.origin );
  9032. }
  9033. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  9034. },
  9035. distanceToPoint: function ( point ) {
  9036. return Math.sqrt( this.distanceSqToPoint( point ) );
  9037. },
  9038. distanceSqToPoint: function () {
  9039. var v1 = new Vector3();
  9040. return function distanceSqToPoint( point ) {
  9041. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  9042. // point behind the ray
  9043. if ( directionDistance < 0 ) {
  9044. return this.origin.distanceToSquared( point );
  9045. }
  9046. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  9047. return v1.distanceToSquared( point );
  9048. };
  9049. }(),
  9050. distanceSqToSegment: function () {
  9051. var segCenter = new Vector3();
  9052. var segDir = new Vector3();
  9053. var diff = new Vector3();
  9054. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  9055. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  9056. // It returns the min distance between the ray and the segment
  9057. // defined by v0 and v1
  9058. // It can also set two optional targets :
  9059. // - The closest point on the ray
  9060. // - The closest point on the segment
  9061. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  9062. segDir.copy( v1 ).sub( v0 ).normalize();
  9063. diff.copy( this.origin ).sub( segCenter );
  9064. var segExtent = v0.distanceTo( v1 ) * 0.5;
  9065. var a01 = - this.direction.dot( segDir );
  9066. var b0 = diff.dot( this.direction );
  9067. var b1 = - diff.dot( segDir );
  9068. var c = diff.lengthSq();
  9069. var det = Math.abs( 1 - a01 * a01 );
  9070. var s0, s1, sqrDist, extDet;
  9071. if ( det > 0 ) {
  9072. // The ray and segment are not parallel.
  9073. s0 = a01 * b1 - b0;
  9074. s1 = a01 * b0 - b1;
  9075. extDet = segExtent * det;
  9076. if ( s0 >= 0 ) {
  9077. if ( s1 >= - extDet ) {
  9078. if ( s1 <= extDet ) {
  9079. // region 0
  9080. // Minimum at interior points of ray and segment.
  9081. var invDet = 1 / det;
  9082. s0 *= invDet;
  9083. s1 *= invDet;
  9084. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  9085. } else {
  9086. // region 1
  9087. s1 = segExtent;
  9088. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9089. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9090. }
  9091. } else {
  9092. // region 5
  9093. s1 = - segExtent;
  9094. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9095. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9096. }
  9097. } else {
  9098. if ( s1 <= - extDet ) {
  9099. // region 4
  9100. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  9101. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9102. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9103. } else if ( s1 <= extDet ) {
  9104. // region 3
  9105. s0 = 0;
  9106. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9107. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  9108. } else {
  9109. // region 2
  9110. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  9111. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9112. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9113. }
  9114. }
  9115. } else {
  9116. // Ray and segment are parallel.
  9117. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  9118. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9119. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9120. }
  9121. if ( optionalPointOnRay ) {
  9122. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  9123. }
  9124. if ( optionalPointOnSegment ) {
  9125. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  9126. }
  9127. return sqrDist;
  9128. };
  9129. }(),
  9130. intersectSphere: function () {
  9131. var v1 = new Vector3();
  9132. return function intersectSphere( sphere, optionalTarget ) {
  9133. v1.subVectors( sphere.center, this.origin );
  9134. var tca = v1.dot( this.direction );
  9135. var d2 = v1.dot( v1 ) - tca * tca;
  9136. var radius2 = sphere.radius * sphere.radius;
  9137. if ( d2 > radius2 ) return null;
  9138. var thc = Math.sqrt( radius2 - d2 );
  9139. // t0 = first intersect point - entrance on front of sphere
  9140. var t0 = tca - thc;
  9141. // t1 = second intersect point - exit point on back of sphere
  9142. var t1 = tca + thc;
  9143. // test to see if both t0 and t1 are behind the ray - if so, return null
  9144. if ( t0 < 0 && t1 < 0 ) return null;
  9145. // test to see if t0 is behind the ray:
  9146. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  9147. // in order to always return an intersect point that is in front of the ray.
  9148. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  9149. // else t0 is in front of the ray, so return the first collision point scaled by t0
  9150. return this.at( t0, optionalTarget );
  9151. };
  9152. }(),
  9153. intersectsSphere: function ( sphere ) {
  9154. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  9155. },
  9156. distanceToPlane: function ( plane ) {
  9157. var denominator = plane.normal.dot( this.direction );
  9158. if ( denominator === 0 ) {
  9159. // line is coplanar, return origin
  9160. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  9161. return 0;
  9162. }
  9163. // Null is preferable to undefined since undefined means.... it is undefined
  9164. return null;
  9165. }
  9166. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  9167. // Return if the ray never intersects the plane
  9168. return t >= 0 ? t : null;
  9169. },
  9170. intersectPlane: function ( plane, optionalTarget ) {
  9171. var t = this.distanceToPlane( plane );
  9172. if ( t === null ) {
  9173. return null;
  9174. }
  9175. return this.at( t, optionalTarget );
  9176. },
  9177. intersectsPlane: function ( plane ) {
  9178. // check if the ray lies on the plane first
  9179. var distToPoint = plane.distanceToPoint( this.origin );
  9180. if ( distToPoint === 0 ) {
  9181. return true;
  9182. }
  9183. var denominator = plane.normal.dot( this.direction );
  9184. if ( denominator * distToPoint < 0 ) {
  9185. return true;
  9186. }
  9187. // ray origin is behind the plane (and is pointing behind it)
  9188. return false;
  9189. },
  9190. intersectBox: function ( box, optionalTarget ) {
  9191. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  9192. var invdirx = 1 / this.direction.x,
  9193. invdiry = 1 / this.direction.y,
  9194. invdirz = 1 / this.direction.z;
  9195. var origin = this.origin;
  9196. if ( invdirx >= 0 ) {
  9197. tmin = ( box.min.x - origin.x ) * invdirx;
  9198. tmax = ( box.max.x - origin.x ) * invdirx;
  9199. } else {
  9200. tmin = ( box.max.x - origin.x ) * invdirx;
  9201. tmax = ( box.min.x - origin.x ) * invdirx;
  9202. }
  9203. if ( invdiry >= 0 ) {
  9204. tymin = ( box.min.y - origin.y ) * invdiry;
  9205. tymax = ( box.max.y - origin.y ) * invdiry;
  9206. } else {
  9207. tymin = ( box.max.y - origin.y ) * invdiry;
  9208. tymax = ( box.min.y - origin.y ) * invdiry;
  9209. }
  9210. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  9211. // These lines also handle the case where tmin or tmax is NaN
  9212. // (result of 0 * Infinity). x !== x returns true if x is NaN
  9213. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  9214. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  9215. if ( invdirz >= 0 ) {
  9216. tzmin = ( box.min.z - origin.z ) * invdirz;
  9217. tzmax = ( box.max.z - origin.z ) * invdirz;
  9218. } else {
  9219. tzmin = ( box.max.z - origin.z ) * invdirz;
  9220. tzmax = ( box.min.z - origin.z ) * invdirz;
  9221. }
  9222. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  9223. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  9224. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  9225. //return point closest to the ray (positive side)
  9226. if ( tmax < 0 ) return null;
  9227. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  9228. },
  9229. intersectsBox: ( function () {
  9230. var v = new Vector3();
  9231. return function intersectsBox( box ) {
  9232. return this.intersectBox( box, v ) !== null;
  9233. };
  9234. } )(),
  9235. intersectTriangle: function () {
  9236. // Compute the offset origin, edges, and normal.
  9237. var diff = new Vector3();
  9238. var edge1 = new Vector3();
  9239. var edge2 = new Vector3();
  9240. var normal = new Vector3();
  9241. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  9242. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  9243. edge1.subVectors( b, a );
  9244. edge2.subVectors( c, a );
  9245. normal.crossVectors( edge1, edge2 );
  9246. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  9247. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  9248. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  9249. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  9250. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  9251. var DdN = this.direction.dot( normal );
  9252. var sign;
  9253. if ( DdN > 0 ) {
  9254. if ( backfaceCulling ) return null;
  9255. sign = 1;
  9256. } else if ( DdN < 0 ) {
  9257. sign = - 1;
  9258. DdN = - DdN;
  9259. } else {
  9260. return null;
  9261. }
  9262. diff.subVectors( this.origin, a );
  9263. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  9264. // b1 < 0, no intersection
  9265. if ( DdQxE2 < 0 ) {
  9266. return null;
  9267. }
  9268. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  9269. // b2 < 0, no intersection
  9270. if ( DdE1xQ < 0 ) {
  9271. return null;
  9272. }
  9273. // b1+b2 > 1, no intersection
  9274. if ( DdQxE2 + DdE1xQ > DdN ) {
  9275. return null;
  9276. }
  9277. // Line intersects triangle, check if ray does.
  9278. var QdN = - sign * diff.dot( normal );
  9279. // t < 0, no intersection
  9280. if ( QdN < 0 ) {
  9281. return null;
  9282. }
  9283. // Ray intersects triangle.
  9284. return this.at( QdN / DdN, optionalTarget );
  9285. };
  9286. }(),
  9287. applyMatrix4: function ( matrix4 ) {
  9288. this.origin.applyMatrix4( matrix4 );
  9289. this.direction.transformDirection( matrix4 );
  9290. return this;
  9291. },
  9292. equals: function ( ray ) {
  9293. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  9294. }
  9295. } );
  9296. /**
  9297. * @author bhouston / http://clara.io
  9298. */
  9299. function Line3( start, end ) {
  9300. this.start = ( start !== undefined ) ? start : new Vector3();
  9301. this.end = ( end !== undefined ) ? end : new Vector3();
  9302. }
  9303. Object.assign( Line3.prototype, {
  9304. set: function ( start, end ) {
  9305. this.start.copy( start );
  9306. this.end.copy( end );
  9307. return this;
  9308. },
  9309. clone: function () {
  9310. return new this.constructor().copy( this );
  9311. },
  9312. copy: function ( line ) {
  9313. this.start.copy( line.start );
  9314. this.end.copy( line.end );
  9315. return this;
  9316. },
  9317. getCenter: function ( optionalTarget ) {
  9318. var result = optionalTarget || new Vector3();
  9319. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  9320. },
  9321. delta: function ( optionalTarget ) {
  9322. var result = optionalTarget || new Vector3();
  9323. return result.subVectors( this.end, this.start );
  9324. },
  9325. distanceSq: function () {
  9326. return this.start.distanceToSquared( this.end );
  9327. },
  9328. distance: function () {
  9329. return this.start.distanceTo( this.end );
  9330. },
  9331. at: function ( t, optionalTarget ) {
  9332. var result = optionalTarget || new Vector3();
  9333. return this.delta( result ).multiplyScalar( t ).add( this.start );
  9334. },
  9335. closestPointToPointParameter: function () {
  9336. var startP = new Vector3();
  9337. var startEnd = new Vector3();
  9338. return function closestPointToPointParameter( point, clampToLine ) {
  9339. startP.subVectors( point, this.start );
  9340. startEnd.subVectors( this.end, this.start );
  9341. var startEnd2 = startEnd.dot( startEnd );
  9342. var startEnd_startP = startEnd.dot( startP );
  9343. var t = startEnd_startP / startEnd2;
  9344. if ( clampToLine ) {
  9345. t = _Math.clamp( t, 0, 1 );
  9346. }
  9347. return t;
  9348. };
  9349. }(),
  9350. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  9351. var t = this.closestPointToPointParameter( point, clampToLine );
  9352. var result = optionalTarget || new Vector3();
  9353. return this.delta( result ).multiplyScalar( t ).add( this.start );
  9354. },
  9355. applyMatrix4: function ( matrix ) {
  9356. this.start.applyMatrix4( matrix );
  9357. this.end.applyMatrix4( matrix );
  9358. return this;
  9359. },
  9360. equals: function ( line ) {
  9361. return line.start.equals( this.start ) && line.end.equals( this.end );
  9362. }
  9363. } );
  9364. /**
  9365. * @author bhouston / http://clara.io
  9366. * @author mrdoob / http://mrdoob.com/
  9367. */
  9368. function Triangle( a, b, c ) {
  9369. this.a = ( a !== undefined ) ? a : new Vector3();
  9370. this.b = ( b !== undefined ) ? b : new Vector3();
  9371. this.c = ( c !== undefined ) ? c : new Vector3();
  9372. }
  9373. Object.assign( Triangle, {
  9374. normal: function () {
  9375. var v0 = new Vector3();
  9376. return function normal( a, b, c, optionalTarget ) {
  9377. var result = optionalTarget || new Vector3();
  9378. result.subVectors( c, b );
  9379. v0.subVectors( a, b );
  9380. result.cross( v0 );
  9381. var resultLengthSq = result.lengthSq();
  9382. if ( resultLengthSq > 0 ) {
  9383. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  9384. }
  9385. return result.set( 0, 0, 0 );
  9386. };
  9387. }(),
  9388. // static/instance method to calculate barycentric coordinates
  9389. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  9390. barycoordFromPoint: function () {
  9391. var v0 = new Vector3();
  9392. var v1 = new Vector3();
  9393. var v2 = new Vector3();
  9394. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  9395. v0.subVectors( c, a );
  9396. v1.subVectors( b, a );
  9397. v2.subVectors( point, a );
  9398. var dot00 = v0.dot( v0 );
  9399. var dot01 = v0.dot( v1 );
  9400. var dot02 = v0.dot( v2 );
  9401. var dot11 = v1.dot( v1 );
  9402. var dot12 = v1.dot( v2 );
  9403. var denom = ( dot00 * dot11 - dot01 * dot01 );
  9404. var result = optionalTarget || new Vector3();
  9405. // collinear or singular triangle
  9406. if ( denom === 0 ) {
  9407. // arbitrary location outside of triangle?
  9408. // not sure if this is the best idea, maybe should be returning undefined
  9409. return result.set( - 2, - 1, - 1 );
  9410. }
  9411. var invDenom = 1 / denom;
  9412. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  9413. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  9414. // barycentric coordinates must always sum to 1
  9415. return result.set( 1 - u - v, v, u );
  9416. };
  9417. }(),
  9418. containsPoint: function () {
  9419. var v1 = new Vector3();
  9420. return function containsPoint( point, a, b, c ) {
  9421. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  9422. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  9423. };
  9424. }()
  9425. } );
  9426. Object.assign( Triangle.prototype, {
  9427. set: function ( a, b, c ) {
  9428. this.a.copy( a );
  9429. this.b.copy( b );
  9430. this.c.copy( c );
  9431. return this;
  9432. },
  9433. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  9434. this.a.copy( points[ i0 ] );
  9435. this.b.copy( points[ i1 ] );
  9436. this.c.copy( points[ i2 ] );
  9437. return this;
  9438. },
  9439. clone: function () {
  9440. return new this.constructor().copy( this );
  9441. },
  9442. copy: function ( triangle ) {
  9443. this.a.copy( triangle.a );
  9444. this.b.copy( triangle.b );
  9445. this.c.copy( triangle.c );
  9446. return this;
  9447. },
  9448. area: function () {
  9449. var v0 = new Vector3();
  9450. var v1 = new Vector3();
  9451. return function area() {
  9452. v0.subVectors( this.c, this.b );
  9453. v1.subVectors( this.a, this.b );
  9454. return v0.cross( v1 ).length() * 0.5;
  9455. };
  9456. }(),
  9457. midpoint: function ( optionalTarget ) {
  9458. var result = optionalTarget || new Vector3();
  9459. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  9460. },
  9461. normal: function ( optionalTarget ) {
  9462. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  9463. },
  9464. plane: function ( optionalTarget ) {
  9465. var result = optionalTarget || new Plane();
  9466. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  9467. },
  9468. barycoordFromPoint: function ( point, optionalTarget ) {
  9469. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  9470. },
  9471. containsPoint: function ( point ) {
  9472. return Triangle.containsPoint( point, this.a, this.b, this.c );
  9473. },
  9474. closestPointToPoint: function () {
  9475. var plane = new Plane();
  9476. var edgeList = [ new Line3(), new Line3(), new Line3() ];
  9477. var projectedPoint = new Vector3();
  9478. var closestPoint = new Vector3();
  9479. return function closestPointToPoint( point, optionalTarget ) {
  9480. var result = optionalTarget || new Vector3();
  9481. var minDistance = Infinity;
  9482. // project the point onto the plane of the triangle
  9483. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  9484. plane.projectPoint( point, projectedPoint );
  9485. // check if the projection lies within the triangle
  9486. if( this.containsPoint( projectedPoint ) === true ) {
  9487. // if so, this is the closest point
  9488. result.copy( projectedPoint );
  9489. } else {
  9490. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  9491. edgeList[ 0 ].set( this.a, this.b );
  9492. edgeList[ 1 ].set( this.b, this.c );
  9493. edgeList[ 2 ].set( this.c, this.a );
  9494. for( var i = 0; i < edgeList.length; i ++ ) {
  9495. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  9496. var distance = projectedPoint.distanceToSquared( closestPoint );
  9497. if( distance < minDistance ) {
  9498. minDistance = distance;
  9499. result.copy( closestPoint );
  9500. }
  9501. }
  9502. }
  9503. return result;
  9504. };
  9505. }(),
  9506. equals: function ( triangle ) {
  9507. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  9508. }
  9509. } );
  9510. /**
  9511. * @author mrdoob / http://mrdoob.com/
  9512. * @author alteredq / http://alteredqualia.com/
  9513. * @author mikael emtinger / http://gomo.se/
  9514. * @author jonobr1 / http://jonobr1.com/
  9515. */
  9516. function Mesh( geometry, material ) {
  9517. Object3D.call( this );
  9518. this.type = 'Mesh';
  9519. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  9520. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9521. this.drawMode = TrianglesDrawMode;
  9522. this.updateMorphTargets();
  9523. }
  9524. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  9525. constructor: Mesh,
  9526. isMesh: true,
  9527. setDrawMode: function ( value ) {
  9528. this.drawMode = value;
  9529. },
  9530. copy: function ( source ) {
  9531. Object3D.prototype.copy.call( this, source );
  9532. this.drawMode = source.drawMode;
  9533. return this;
  9534. },
  9535. updateMorphTargets: function () {
  9536. var geometry = this.geometry;
  9537. var m, ml, name;
  9538. if ( geometry.isBufferGeometry ) {
  9539. var morphAttributes = geometry.morphAttributes;
  9540. var keys = Object.keys( morphAttributes );
  9541. if ( keys.length > 0 ) {
  9542. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  9543. if ( morphAttribute !== undefined ) {
  9544. this.morphTargetInfluences = [];
  9545. this.morphTargetDictionary = {};
  9546. for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  9547. name = morphAttribute[ m ].name || String( m );
  9548. this.morphTargetInfluences.push( 0 );
  9549. this.morphTargetDictionary[ name ] = m;
  9550. }
  9551. }
  9552. }
  9553. } else {
  9554. var morphTargets = geometry.morphTargets;
  9555. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  9556. this.morphTargetInfluences = [];
  9557. this.morphTargetDictionary = {};
  9558. for ( m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  9559. name = morphTargets[ m ].name || String( m );
  9560. this.morphTargetInfluences.push( 0 );
  9561. this.morphTargetDictionary[ name ] = m;
  9562. }
  9563. }
  9564. }
  9565. },
  9566. raycast: ( function () {
  9567. var inverseMatrix = new Matrix4();
  9568. var ray = new Ray();
  9569. var sphere = new Sphere();
  9570. var vA = new Vector3();
  9571. var vB = new Vector3();
  9572. var vC = new Vector3();
  9573. var tempA = new Vector3();
  9574. var tempB = new Vector3();
  9575. var tempC = new Vector3();
  9576. var uvA = new Vector2();
  9577. var uvB = new Vector2();
  9578. var uvC = new Vector2();
  9579. var barycoord = new Vector3();
  9580. var intersectionPoint = new Vector3();
  9581. var intersectionPointWorld = new Vector3();
  9582. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  9583. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  9584. uv1.multiplyScalar( barycoord.x );
  9585. uv2.multiplyScalar( barycoord.y );
  9586. uv3.multiplyScalar( barycoord.z );
  9587. uv1.add( uv2 ).add( uv3 );
  9588. return uv1.clone();
  9589. }
  9590. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  9591. var intersect;
  9592. if ( material.side === BackSide ) {
  9593. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  9594. } else {
  9595. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  9596. }
  9597. if ( intersect === null ) return null;
  9598. intersectionPointWorld.copy( point );
  9599. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  9600. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  9601. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  9602. return {
  9603. distance: distance,
  9604. point: intersectionPointWorld.clone(),
  9605. object: object
  9606. };
  9607. }
  9608. function checkBufferGeometryIntersection( object, raycaster, ray, position, uv, a, b, c ) {
  9609. vA.fromBufferAttribute( position, a );
  9610. vB.fromBufferAttribute( position, b );
  9611. vC.fromBufferAttribute( position, c );
  9612. var intersection = checkIntersection( object, object.material, raycaster, ray, vA, vB, vC, intersectionPoint );
  9613. if ( intersection ) {
  9614. if ( uv ) {
  9615. uvA.fromBufferAttribute( uv, a );
  9616. uvB.fromBufferAttribute( uv, b );
  9617. uvC.fromBufferAttribute( uv, c );
  9618. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  9619. }
  9620. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  9621. intersection.faceIndex = a;
  9622. }
  9623. return intersection;
  9624. }
  9625. return function raycast( raycaster, intersects ) {
  9626. var geometry = this.geometry;
  9627. var material = this.material;
  9628. var matrixWorld = this.matrixWorld;
  9629. if ( material === undefined ) return;
  9630. // Checking boundingSphere distance to ray
  9631. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9632. sphere.copy( geometry.boundingSphere );
  9633. sphere.applyMatrix4( matrixWorld );
  9634. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  9635. //
  9636. inverseMatrix.getInverse( matrixWorld );
  9637. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9638. // Check boundingBox before continuing
  9639. if ( geometry.boundingBox !== null ) {
  9640. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  9641. }
  9642. var intersection;
  9643. if ( geometry.isBufferGeometry ) {
  9644. var a, b, c;
  9645. var index = geometry.index;
  9646. var position = geometry.attributes.position;
  9647. var uv = geometry.attributes.uv;
  9648. var i, l;
  9649. if ( index !== null ) {
  9650. // indexed buffer geometry
  9651. for ( i = 0, l = index.count; i < l; i += 3 ) {
  9652. a = index.getX( i );
  9653. b = index.getX( i + 1 );
  9654. c = index.getX( i + 2 );
  9655. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  9656. if ( intersection ) {
  9657. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  9658. intersects.push( intersection );
  9659. }
  9660. }
  9661. } else {
  9662. // non-indexed buffer geometry
  9663. for ( i = 0, l = position.count; i < l; i += 3 ) {
  9664. a = i;
  9665. b = i + 1;
  9666. c = i + 2;
  9667. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  9668. if ( intersection ) {
  9669. intersection.index = a; // triangle number in positions buffer semantics
  9670. intersects.push( intersection );
  9671. }
  9672. }
  9673. }
  9674. } else if ( geometry.isGeometry ) {
  9675. var fvA, fvB, fvC;
  9676. var isMultiMaterial = Array.isArray( material );
  9677. var vertices = geometry.vertices;
  9678. var faces = geometry.faces;
  9679. var uvs;
  9680. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  9681. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  9682. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  9683. var face = faces[ f ];
  9684. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  9685. if ( faceMaterial === undefined ) continue;
  9686. fvA = vertices[ face.a ];
  9687. fvB = vertices[ face.b ];
  9688. fvC = vertices[ face.c ];
  9689. if ( faceMaterial.morphTargets === true ) {
  9690. var morphTargets = geometry.morphTargets;
  9691. var morphInfluences = this.morphTargetInfluences;
  9692. vA.set( 0, 0, 0 );
  9693. vB.set( 0, 0, 0 );
  9694. vC.set( 0, 0, 0 );
  9695. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  9696. var influence = morphInfluences[ t ];
  9697. if ( influence === 0 ) continue;
  9698. var targets = morphTargets[ t ].vertices;
  9699. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  9700. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  9701. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  9702. }
  9703. vA.add( fvA );
  9704. vB.add( fvB );
  9705. vC.add( fvC );
  9706. fvA = vA;
  9707. fvB = vB;
  9708. fvC = vC;
  9709. }
  9710. intersection = checkIntersection( this, faceMaterial, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  9711. if ( intersection ) {
  9712. if ( uvs && uvs[ f ] ) {
  9713. var uvs_f = uvs[ f ];
  9714. uvA.copy( uvs_f[ 0 ] );
  9715. uvB.copy( uvs_f[ 1 ] );
  9716. uvC.copy( uvs_f[ 2 ] );
  9717. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  9718. }
  9719. intersection.face = face;
  9720. intersection.faceIndex = f;
  9721. intersects.push( intersection );
  9722. }
  9723. }
  9724. }
  9725. };
  9726. }() ),
  9727. clone: function () {
  9728. return new this.constructor( this.geometry, this.material ).copy( this );
  9729. }
  9730. } );
  9731. /**
  9732. * @author mrdoob / http://mrdoob.com/
  9733. */
  9734. function WebGLBackground( renderer, state, geometries, premultipliedAlpha ) {
  9735. var clearColor = new Color( 0x000000 );
  9736. var clearAlpha = 0;
  9737. var planeCamera, planeMesh;
  9738. var boxMesh;
  9739. function render( renderList, scene, camera, forceClear ) {
  9740. var background = scene.background;
  9741. if ( background === null ) {
  9742. setClear( clearColor, clearAlpha );
  9743. } else if ( background && background.isColor ) {
  9744. setClear( background, 1 );
  9745. forceClear = true;
  9746. }
  9747. if ( renderer.autoClear || forceClear ) {
  9748. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  9749. }
  9750. if ( background && background.isCubeTexture ) {
  9751. if ( boxMesh === undefined ) {
  9752. boxMesh = new Mesh(
  9753. new BoxBufferGeometry( 1, 1, 1 ),
  9754. new ShaderMaterial( {
  9755. uniforms: ShaderLib.cube.uniforms,
  9756. vertexShader: ShaderLib.cube.vertexShader,
  9757. fragmentShader: ShaderLib.cube.fragmentShader,
  9758. side: BackSide,
  9759. depthTest: true,
  9760. depthWrite: false,
  9761. polygonOffset: true,
  9762. fog: false
  9763. } )
  9764. );
  9765. boxMesh.geometry.removeAttribute( 'normal' );
  9766. boxMesh.geometry.removeAttribute( 'uv' );
  9767. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  9768. var scale = camera.far;
  9769. this.matrixWorld.makeScale( scale, scale, scale );
  9770. this.matrixWorld.copyPosition( camera.matrixWorld );
  9771. this.material.polygonOffsetUnits = scale * 10;
  9772. };
  9773. geometries.update( boxMesh.geometry );
  9774. }
  9775. boxMesh.material.uniforms.tCube.value = background;
  9776. renderList.push( boxMesh, boxMesh.geometry, boxMesh.material, 0, null );
  9777. } else if ( background && background.isTexture ) {
  9778. if ( planeCamera === undefined ) {
  9779. planeCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  9780. planeMesh = new Mesh(
  9781. new PlaneBufferGeometry( 2, 2 ),
  9782. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  9783. );
  9784. geometries.update( planeMesh.geometry );
  9785. }
  9786. planeMesh.material.map = background;
  9787. // TODO Push this to renderList
  9788. renderer.renderBufferDirect( planeCamera, null, planeMesh.geometry, planeMesh.material, planeMesh, null );
  9789. }
  9790. }
  9791. function setClear( color, alpha ) {
  9792. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  9793. }
  9794. return {
  9795. getClearColor: function () {
  9796. return clearColor;
  9797. },
  9798. setClearColor: function ( color, alpha ) {
  9799. clearColor.set( color );
  9800. clearAlpha = alpha !== undefined ? alpha : 1;
  9801. setClear( clearColor, clearAlpha );
  9802. },
  9803. getClearAlpha: function () {
  9804. return clearAlpha;
  9805. },
  9806. setClearAlpha: function ( alpha ) {
  9807. clearAlpha = alpha;
  9808. setClear( clearColor, clearAlpha );
  9809. },
  9810. render: render
  9811. };
  9812. }
  9813. /**
  9814. * @author mrdoob / http://mrdoob.com/
  9815. */
  9816. function painterSortStable( a, b ) {
  9817. if ( a.renderOrder !== b.renderOrder ) {
  9818. return a.renderOrder - b.renderOrder;
  9819. } else if ( a.program && b.program && a.program !== b.program ) {
  9820. return a.program.id - b.program.id;
  9821. } else if ( a.material.id !== b.material.id ) {
  9822. return a.material.id - b.material.id;
  9823. } else if ( a.z !== b.z ) {
  9824. return a.z - b.z;
  9825. } else {
  9826. return a.id - b.id;
  9827. }
  9828. }
  9829. function reversePainterSortStable( a, b ) {
  9830. if ( a.renderOrder !== b.renderOrder ) {
  9831. return a.renderOrder - b.renderOrder;
  9832. } if ( a.z !== b.z ) {
  9833. return b.z - a.z;
  9834. } else {
  9835. return a.id - b.id;
  9836. }
  9837. }
  9838. function WebGLRenderList() {
  9839. var renderItems = [];
  9840. var renderItemsIndex = 0;
  9841. var opaque = [];
  9842. var transparent = [];
  9843. function init() {
  9844. renderItemsIndex = 0;
  9845. opaque.length = 0;
  9846. transparent.length = 0;
  9847. }
  9848. function push( object, geometry, material, z, group ) {
  9849. var renderItem = renderItems[ renderItemsIndex ];
  9850. if ( renderItem === undefined ) {
  9851. renderItem = {
  9852. id: object.id,
  9853. object: object,
  9854. geometry: geometry,
  9855. material: material,
  9856. program: material.program,
  9857. renderOrder: object.renderOrder,
  9858. z: z,
  9859. group: group
  9860. };
  9861. renderItems[ renderItemsIndex ] = renderItem;
  9862. } else {
  9863. renderItem.id = object.id;
  9864. renderItem.object = object;
  9865. renderItem.geometry = geometry;
  9866. renderItem.material = material;
  9867. renderItem.program = material.program;
  9868. renderItem.renderOrder = object.renderOrder;
  9869. renderItem.z = z;
  9870. renderItem.group = group;
  9871. }
  9872. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  9873. renderItemsIndex ++;
  9874. }
  9875. function sort() {
  9876. if ( opaque.length > 1 ) opaque.sort( painterSortStable );
  9877. if ( transparent.length > 1 ) transparent.sort( reversePainterSortStable );
  9878. }
  9879. return {
  9880. opaque: opaque,
  9881. transparent: transparent,
  9882. init: init,
  9883. push: push,
  9884. sort: sort
  9885. };
  9886. }
  9887. function WebGLRenderLists() {
  9888. var lists = {};
  9889. function get( scene, camera ) {
  9890. var hash = scene.id + ',' + camera.id;
  9891. var list = lists[ hash ];
  9892. if ( list === undefined ) {
  9893. // console.log( 'THREE.WebGLRenderLists:', hash );
  9894. list = new WebGLRenderList();
  9895. lists[ hash ] = list;
  9896. }
  9897. return list;
  9898. }
  9899. function dispose() {
  9900. lists = {};
  9901. }
  9902. return {
  9903. get: get,
  9904. dispose: dispose
  9905. };
  9906. }
  9907. /**
  9908. * @author mrdoob / http://mrdoob.com/
  9909. */
  9910. function absNumericalSort( a, b ) {
  9911. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  9912. }
  9913. function WebGLMorphtargets( gl ) {
  9914. var influencesList = {};
  9915. var morphInfluences = new Float32Array( 8 );
  9916. function update( object, geometry, material, program ) {
  9917. var objectInfluences = object.morphTargetInfluences;
  9918. var length = objectInfluences.length;
  9919. var influences = influencesList[ geometry.id ];
  9920. if ( influences === undefined ) {
  9921. // initialise list
  9922. influences = [];
  9923. for ( var i = 0; i < length; i ++ ) {
  9924. influences[ i ] = [ i, 0 ];
  9925. }
  9926. influencesList[ geometry.id ] = influences;
  9927. }
  9928. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  9929. var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  9930. // Remove current morphAttributes
  9931. for ( var i = 0; i < length; i ++ ) {
  9932. var influence = influences[ i ];
  9933. if ( influence[ 1 ] !== 0 ) {
  9934. if ( morphTargets ) geometry.removeAttribute( 'morphTarget' + i );
  9935. if ( morphNormals ) geometry.removeAttribute( 'morphNormal' + i );
  9936. }
  9937. }
  9938. // Collect influences
  9939. for ( var i = 0; i < length; i ++ ) {
  9940. var influence = influences[ i ];
  9941. influence[ 0 ] = i;
  9942. influence[ 1 ] = objectInfluences[ i ];
  9943. }
  9944. influences.sort( absNumericalSort );
  9945. // Add morphAttributes
  9946. for ( var i = 0; i < 8; i ++ ) {
  9947. var influence = influences[ i ];
  9948. if ( influence ) {
  9949. var index = influence[ 0 ];
  9950. var value = influence[ 1 ];
  9951. if ( value ) {
  9952. if ( morphTargets ) geometry.addAttribute( 'morphTarget' + i, morphTargets[ index ] );
  9953. if ( morphNormals ) geometry.addAttribute( 'morphNormal' + i, morphNormals[ index ] );
  9954. morphInfluences[ i ] = value;
  9955. continue;
  9956. }
  9957. }
  9958. morphInfluences[ i ] = 0;
  9959. }
  9960. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  9961. }
  9962. return {
  9963. update: update
  9964. }
  9965. }
  9966. /**
  9967. * @author mrdoob / http://mrdoob.com/
  9968. */
  9969. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  9970. var mode;
  9971. function setMode( value ) {
  9972. mode = value;
  9973. }
  9974. var type, bytesPerElement;
  9975. function setIndex( value ) {
  9976. type = value.type;
  9977. bytesPerElement = value.bytesPerElement;
  9978. }
  9979. function render( start, count ) {
  9980. gl.drawElements( mode, count, type, start * bytesPerElement );
  9981. infoRender.calls ++;
  9982. infoRender.vertices += count;
  9983. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9984. else if ( mode === gl.POINTS ) infoRender.points += count;
  9985. }
  9986. function renderInstances( geometry, start, count ) {
  9987. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9988. if ( extension === null ) {
  9989. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9990. return;
  9991. }
  9992. extension.drawElementsInstancedANGLE( mode, count, type, start * bytesPerElement, geometry.maxInstancedCount );
  9993. infoRender.calls ++;
  9994. infoRender.vertices += count * geometry.maxInstancedCount;
  9995. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9996. else if ( mode === gl.POINTS ) infoRender.points += geometry.maxInstancedCount * count;
  9997. }
  9998. //
  9999. this.setMode = setMode;
  10000. this.setIndex = setIndex;
  10001. this.render = render;
  10002. this.renderInstances = renderInstances;
  10003. }
  10004. /**
  10005. * @author mrdoob / http://mrdoob.com/
  10006. */
  10007. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  10008. var mode;
  10009. function setMode( value ) {
  10010. mode = value;
  10011. }
  10012. function render( start, count ) {
  10013. gl.drawArrays( mode, start, count );
  10014. infoRender.calls ++;
  10015. infoRender.vertices += count;
  10016. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  10017. else if ( mode === gl.POINTS ) infoRender.points += count;
  10018. }
  10019. function renderInstances( geometry, start, count ) {
  10020. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  10021. if ( extension === null ) {
  10022. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10023. return;
  10024. }
  10025. var position = geometry.attributes.position;
  10026. if ( position.isInterleavedBufferAttribute ) {
  10027. count = position.data.count;
  10028. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  10029. } else {
  10030. extension.drawArraysInstancedANGLE( mode, start, count, geometry.maxInstancedCount );
  10031. }
  10032. infoRender.calls ++;
  10033. infoRender.vertices += count * geometry.maxInstancedCount;
  10034. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  10035. else if ( mode === gl.POINTS ) infoRender.points += geometry.maxInstancedCount * count;
  10036. }
  10037. //
  10038. this.setMode = setMode;
  10039. this.render = render;
  10040. this.renderInstances = renderInstances;
  10041. }
  10042. /**
  10043. * @author mrdoob / http://mrdoob.com/
  10044. */
  10045. function WebGLGeometries( gl, attributes, infoMemory ) {
  10046. var geometries = {};
  10047. var wireframeAttributes = {};
  10048. function onGeometryDispose( event ) {
  10049. var geometry = event.target;
  10050. var buffergeometry = geometries[ geometry.id ];
  10051. if ( buffergeometry.index !== null ) {
  10052. attributes.remove( buffergeometry.index );
  10053. }
  10054. for ( var name in buffergeometry.attributes ) {
  10055. attributes.remove( buffergeometry.attributes[ name ] );
  10056. }
  10057. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10058. delete geometries[ geometry.id ];
  10059. // TODO Remove duplicate code
  10060. var attribute = wireframeAttributes[ geometry.id ];
  10061. if ( attribute ) {
  10062. attributes.remove( attribute );
  10063. delete wireframeAttributes[ geometry.id ];
  10064. }
  10065. attribute = wireframeAttributes[ buffergeometry.id ];
  10066. if ( attribute ) {
  10067. attributes.remove( attribute );
  10068. delete wireframeAttributes[ buffergeometry.id ];
  10069. }
  10070. //
  10071. infoMemory.geometries --;
  10072. }
  10073. function get( object, geometry ) {
  10074. var buffergeometry = geometries[ geometry.id ];
  10075. if ( buffergeometry ) return buffergeometry;
  10076. geometry.addEventListener( 'dispose', onGeometryDispose );
  10077. if ( geometry.isBufferGeometry ) {
  10078. buffergeometry = geometry;
  10079. } else if ( geometry.isGeometry ) {
  10080. if ( geometry._bufferGeometry === undefined ) {
  10081. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  10082. }
  10083. buffergeometry = geometry._bufferGeometry;
  10084. }
  10085. geometries[ geometry.id ] = buffergeometry;
  10086. infoMemory.geometries ++;
  10087. return buffergeometry;
  10088. }
  10089. function update( geometry ) {
  10090. var index = geometry.index;
  10091. var geometryAttributes = geometry.attributes;
  10092. if ( index !== null ) {
  10093. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  10094. }
  10095. for ( var name in geometryAttributes ) {
  10096. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  10097. }
  10098. // morph targets
  10099. var morphAttributes = geometry.morphAttributes;
  10100. for ( var name in morphAttributes ) {
  10101. var array = morphAttributes[ name ];
  10102. for ( var i = 0, l = array.length; i < l; i ++ ) {
  10103. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  10104. }
  10105. }
  10106. }
  10107. function getWireframeAttribute( geometry ) {
  10108. var attribute = wireframeAttributes[ geometry.id ];
  10109. if ( attribute ) return attribute;
  10110. var indices = [];
  10111. var geometryIndex = geometry.index;
  10112. var geometryAttributes = geometry.attributes;
  10113. // console.time( 'wireframe' );
  10114. if ( geometryIndex !== null ) {
  10115. var array = geometryIndex.array;
  10116. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  10117. var a = array[ i + 0 ];
  10118. var b = array[ i + 1 ];
  10119. var c = array[ i + 2 ];
  10120. indices.push( a, b, b, c, c, a );
  10121. }
  10122. } else {
  10123. var array = geometryAttributes.position.array;
  10124. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10125. var a = i + 0;
  10126. var b = i + 1;
  10127. var c = i + 2;
  10128. indices.push( a, b, b, c, c, a );
  10129. }
  10130. }
  10131. // console.timeEnd( 'wireframe' );
  10132. attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10133. attributes.update( attribute, gl.ELEMENT_ARRAY_BUFFER );
  10134. wireframeAttributes[ geometry.id ] = attribute;
  10135. return attribute;
  10136. }
  10137. return {
  10138. get: get,
  10139. update: update,
  10140. getWireframeAttribute: getWireframeAttribute
  10141. };
  10142. }
  10143. /**
  10144. * @author mrdoob / http://mrdoob.com/
  10145. */
  10146. function UniformsCache() {
  10147. var lights = {};
  10148. return {
  10149. get: function ( light ) {
  10150. if ( lights[ light.id ] !== undefined ) {
  10151. return lights[ light.id ];
  10152. }
  10153. var uniforms;
  10154. switch ( light.type ) {
  10155. case 'DirectionalLight':
  10156. uniforms = {
  10157. direction: new Vector3(),
  10158. color: new Color(),
  10159. shadow: false,
  10160. shadowBias: 0,
  10161. shadowRadius: 1,
  10162. shadowMapSize: new Vector2()
  10163. };
  10164. break;
  10165. case 'SpotLight':
  10166. uniforms = {
  10167. position: new Vector3(),
  10168. direction: new Vector3(),
  10169. color: new Color(),
  10170. distance: 0,
  10171. coneCos: 0,
  10172. penumbraCos: 0,
  10173. decay: 0,
  10174. shadow: false,
  10175. shadowBias: 0,
  10176. shadowRadius: 1,
  10177. shadowMapSize: new Vector2()
  10178. };
  10179. break;
  10180. case 'PointLight':
  10181. uniforms = {
  10182. position: new Vector3(),
  10183. color: new Color(),
  10184. distance: 0,
  10185. decay: 0,
  10186. shadow: false,
  10187. shadowBias: 0,
  10188. shadowRadius: 1,
  10189. shadowMapSize: new Vector2(),
  10190. shadowCameraNear: 1,
  10191. shadowCameraFar: 1000
  10192. };
  10193. break;
  10194. case 'HemisphereLight':
  10195. uniforms = {
  10196. direction: new Vector3(),
  10197. skyColor: new Color(),
  10198. groundColor: new Color()
  10199. };
  10200. break;
  10201. case 'RectAreaLight':
  10202. uniforms = {
  10203. color: new Color(),
  10204. position: new Vector3(),
  10205. halfWidth: new Vector3(),
  10206. halfHeight: new Vector3()
  10207. // TODO (abelnation): set RectAreaLight shadow uniforms
  10208. };
  10209. break;
  10210. }
  10211. lights[ light.id ] = uniforms;
  10212. return uniforms;
  10213. }
  10214. };
  10215. }
  10216. function WebGLLights() {
  10217. var cache = new UniformsCache();
  10218. var state = {
  10219. hash: '',
  10220. ambient: [ 0, 0, 0 ],
  10221. directional: [],
  10222. directionalShadowMap: [],
  10223. directionalShadowMatrix: [],
  10224. spot: [],
  10225. spotShadowMap: [],
  10226. spotShadowMatrix: [],
  10227. rectArea: [],
  10228. point: [],
  10229. pointShadowMap: [],
  10230. pointShadowMatrix: [],
  10231. hemi: []
  10232. };
  10233. var vector3 = new Vector3();
  10234. var matrix4 = new Matrix4();
  10235. var matrix42 = new Matrix4();
  10236. function setup( lights, shadows, camera ) {
  10237. var r = 0, g = 0, b = 0;
  10238. var directionalLength = 0;
  10239. var pointLength = 0;
  10240. var spotLength = 0;
  10241. var rectAreaLength = 0;
  10242. var hemiLength = 0;
  10243. var viewMatrix = camera.matrixWorldInverse;
  10244. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  10245. var light = lights[ i ];
  10246. var color = light.color;
  10247. var intensity = light.intensity;
  10248. var distance = light.distance;
  10249. var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  10250. if ( light.isAmbientLight ) {
  10251. r += color.r * intensity;
  10252. g += color.g * intensity;
  10253. b += color.b * intensity;
  10254. } else if ( light.isDirectionalLight ) {
  10255. var uniforms = cache.get( light );
  10256. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  10257. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  10258. vector3.setFromMatrixPosition( light.target.matrixWorld );
  10259. uniforms.direction.sub( vector3 );
  10260. uniforms.direction.transformDirection( viewMatrix );
  10261. uniforms.shadow = light.castShadow;
  10262. if ( light.castShadow ) {
  10263. var shadow = light.shadow;
  10264. uniforms.shadowBias = shadow.bias;
  10265. uniforms.shadowRadius = shadow.radius;
  10266. uniforms.shadowMapSize = shadow.mapSize;
  10267. }
  10268. state.directionalShadowMap[ directionalLength ] = shadowMap;
  10269. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  10270. state.directional[ directionalLength ] = uniforms;
  10271. directionalLength ++;
  10272. } else if ( light.isSpotLight ) {
  10273. var uniforms = cache.get( light );
  10274. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  10275. uniforms.position.applyMatrix4( viewMatrix );
  10276. uniforms.color.copy( color ).multiplyScalar( intensity );
  10277. uniforms.distance = distance;
  10278. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  10279. vector3.setFromMatrixPosition( light.target.matrixWorld );
  10280. uniforms.direction.sub( vector3 );
  10281. uniforms.direction.transformDirection( viewMatrix );
  10282. uniforms.coneCos = Math.cos( light.angle );
  10283. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  10284. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  10285. uniforms.shadow = light.castShadow;
  10286. if ( light.castShadow ) {
  10287. var shadow = light.shadow;
  10288. uniforms.shadowBias = shadow.bias;
  10289. uniforms.shadowRadius = shadow.radius;
  10290. uniforms.shadowMapSize = shadow.mapSize;
  10291. }
  10292. state.spotShadowMap[ spotLength ] = shadowMap;
  10293. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  10294. state.spot[ spotLength ] = uniforms;
  10295. spotLength ++;
  10296. } else if ( light.isRectAreaLight ) {
  10297. var uniforms = cache.get( light );
  10298. // (a) intensity controls irradiance of entire light
  10299. uniforms.color
  10300. .copy( color )
  10301. .multiplyScalar( intensity / ( light.width * light.height ) );
  10302. // (b) intensity controls the radiance per light area
  10303. // uniforms.color.copy( color ).multiplyScalar( intensity );
  10304. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  10305. uniforms.position.applyMatrix4( viewMatrix );
  10306. // extract local rotation of light to derive width/height half vectors
  10307. matrix42.identity();
  10308. matrix4.copy( light.matrixWorld );
  10309. matrix4.premultiply( viewMatrix );
  10310. matrix42.extractRotation( matrix4 );
  10311. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  10312. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  10313. uniforms.halfWidth.applyMatrix4( matrix42 );
  10314. uniforms.halfHeight.applyMatrix4( matrix42 );
  10315. // TODO (abelnation): RectAreaLight distance?
  10316. // uniforms.distance = distance;
  10317. state.rectArea[ rectAreaLength ] = uniforms;
  10318. rectAreaLength ++;
  10319. } else if ( light.isPointLight ) {
  10320. var uniforms = cache.get( light );
  10321. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  10322. uniforms.position.applyMatrix4( viewMatrix );
  10323. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  10324. uniforms.distance = light.distance;
  10325. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  10326. uniforms.shadow = light.castShadow;
  10327. if ( light.castShadow ) {
  10328. var shadow = light.shadow;
  10329. uniforms.shadowBias = shadow.bias;
  10330. uniforms.shadowRadius = shadow.radius;
  10331. uniforms.shadowMapSize = shadow.mapSize;
  10332. uniforms.shadowCameraNear = shadow.camera.near;
  10333. uniforms.shadowCameraFar = shadow.camera.far;
  10334. }
  10335. state.pointShadowMap[ pointLength ] = shadowMap;
  10336. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  10337. state.point[ pointLength ] = uniforms;
  10338. pointLength ++;
  10339. } else if ( light.isHemisphereLight ) {
  10340. var uniforms = cache.get( light );
  10341. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  10342. uniforms.direction.transformDirection( viewMatrix );
  10343. uniforms.direction.normalize();
  10344. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  10345. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  10346. state.hemi[ hemiLength ] = uniforms;
  10347. hemiLength ++;
  10348. }
  10349. }
  10350. state.ambient[ 0 ] = r;
  10351. state.ambient[ 1 ] = g;
  10352. state.ambient[ 2 ] = b;
  10353. state.directional.length = directionalLength;
  10354. state.spot.length = spotLength;
  10355. state.rectArea.length = rectAreaLength;
  10356. state.point.length = pointLength;
  10357. state.hemi.length = hemiLength;
  10358. // TODO (sam-g-steel) why aren't we using join
  10359. state.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + shadows.length;
  10360. }
  10361. return {
  10362. setup: setup,
  10363. state: state
  10364. }
  10365. }
  10366. /**
  10367. * @author mrdoob / http://mrdoob.com/
  10368. */
  10369. function WebGLObjects( geometries, infoRender ) {
  10370. var updateList = {};
  10371. function update( object ) {
  10372. var frame = infoRender.frame;
  10373. var geometry = object.geometry;
  10374. var buffergeometry = geometries.get( object, geometry );
  10375. // Update once per frame
  10376. if ( updateList[ buffergeometry.id ] !== frame ) {
  10377. if ( geometry.isGeometry ) {
  10378. buffergeometry.updateFromObject( object );
  10379. }
  10380. geometries.update( buffergeometry );
  10381. updateList[ buffergeometry.id ] = frame;
  10382. }
  10383. return buffergeometry;
  10384. }
  10385. function clear() {
  10386. updateList = {};
  10387. }
  10388. return {
  10389. update: update,
  10390. clear: clear
  10391. };
  10392. }
  10393. /**
  10394. * @author mrdoob / http://mrdoob.com/
  10395. */
  10396. function addLineNumbers( string ) {
  10397. var lines = string.split( '\n' );
  10398. for ( var i = 0; i < lines.length; i ++ ) {
  10399. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  10400. }
  10401. return lines.join( '\n' );
  10402. }
  10403. function WebGLShader( gl, type, string ) {
  10404. var shader = gl.createShader( type );
  10405. gl.shaderSource( shader, string );
  10406. gl.compileShader( shader );
  10407. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  10408. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  10409. }
  10410. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  10411. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  10412. }
  10413. // --enable-privileged-webgl-extension
  10414. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10415. return shader;
  10416. }
  10417. /**
  10418. * @author mrdoob / http://mrdoob.com/
  10419. */
  10420. var programIdCount = 0;
  10421. function getEncodingComponents( encoding ) {
  10422. switch ( encoding ) {
  10423. case LinearEncoding:
  10424. return [ 'Linear','( value )' ];
  10425. case sRGBEncoding:
  10426. return [ 'sRGB','( value )' ];
  10427. case RGBEEncoding:
  10428. return [ 'RGBE','( value )' ];
  10429. case RGBM7Encoding:
  10430. return [ 'RGBM','( value, 7.0 )' ];
  10431. case RGBM16Encoding:
  10432. return [ 'RGBM','( value, 16.0 )' ];
  10433. case RGBDEncoding:
  10434. return [ 'RGBD','( value, 256.0 )' ];
  10435. case GammaEncoding:
  10436. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  10437. default:
  10438. throw new Error( 'unsupported encoding: ' + encoding );
  10439. }
  10440. }
  10441. function getTexelDecodingFunction( functionName, encoding ) {
  10442. var components = getEncodingComponents( encoding );
  10443. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  10444. }
  10445. function getTexelEncodingFunction( functionName, encoding ) {
  10446. var components = getEncodingComponents( encoding );
  10447. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  10448. }
  10449. function getToneMappingFunction( functionName, toneMapping ) {
  10450. var toneMappingName;
  10451. switch ( toneMapping ) {
  10452. case LinearToneMapping:
  10453. toneMappingName = "Linear";
  10454. break;
  10455. case ReinhardToneMapping:
  10456. toneMappingName = "Reinhard";
  10457. break;
  10458. case Uncharted2ToneMapping:
  10459. toneMappingName = "Uncharted2";
  10460. break;
  10461. case CineonToneMapping:
  10462. toneMappingName = "OptimizedCineon";
  10463. break;
  10464. default:
  10465. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  10466. }
  10467. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  10468. }
  10469. function generateExtensions( extensions, parameters, rendererExtensions ) {
  10470. extensions = extensions || {};
  10471. var chunks = [
  10472. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10473. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  10474. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10475. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10476. ];
  10477. return chunks.filter( filterEmptyLine ).join( '\n' );
  10478. }
  10479. function generateDefines( defines ) {
  10480. var chunks = [];
  10481. for ( var name in defines ) {
  10482. var value = defines[ name ];
  10483. if ( value === false ) continue;
  10484. chunks.push( '#define ' + name + ' ' + value );
  10485. }
  10486. return chunks.join( '\n' );
  10487. }
  10488. function fetchAttributeLocations( gl, program, identifiers ) {
  10489. var attributes = {};
  10490. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  10491. for ( var i = 0; i < n; i ++ ) {
  10492. var info = gl.getActiveAttrib( program, i );
  10493. var name = info.name;
  10494. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  10495. attributes[ name ] = gl.getAttribLocation( program, name );
  10496. }
  10497. return attributes;
  10498. }
  10499. function filterEmptyLine( string ) {
  10500. return string !== '';
  10501. }
  10502. function replaceLightNums( string, parameters ) {
  10503. return string
  10504. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10505. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10506. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10507. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10508. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  10509. }
  10510. function parseIncludes( string ) {
  10511. var pattern = /^[ \t]*#include +<([\w\d.]+)>/gm;
  10512. function replace( match, include ) {
  10513. var replace = ShaderChunk[ include ];
  10514. if ( replace === undefined ) {
  10515. throw new Error( 'Can not resolve #include <' + include + '>' );
  10516. }
  10517. return parseIncludes( replace );
  10518. }
  10519. return string.replace( pattern, replace );
  10520. }
  10521. function unrollLoops( string ) {
  10522. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10523. function replace( match, start, end, snippet ) {
  10524. var unroll = '';
  10525. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10526. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  10527. }
  10528. return unroll;
  10529. }
  10530. return string.replace( pattern, replace );
  10531. }
  10532. function WebGLProgram( renderer, extensions, code, material, shader, parameters ) {
  10533. var gl = renderer.context;
  10534. var defines = material.defines;
  10535. var vertexShader = shader.vertexShader;
  10536. var fragmentShader = shader.fragmentShader;
  10537. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10538. if ( parameters.shadowMapType === PCFShadowMap ) {
  10539. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10540. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10541. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10542. }
  10543. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10544. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10545. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10546. if ( parameters.envMap ) {
  10547. switch ( material.envMap.mapping ) {
  10548. case CubeReflectionMapping:
  10549. case CubeRefractionMapping:
  10550. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10551. break;
  10552. case CubeUVReflectionMapping:
  10553. case CubeUVRefractionMapping:
  10554. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10555. break;
  10556. case EquirectangularReflectionMapping:
  10557. case EquirectangularRefractionMapping:
  10558. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  10559. break;
  10560. case SphericalReflectionMapping:
  10561. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  10562. break;
  10563. }
  10564. switch ( material.envMap.mapping ) {
  10565. case CubeRefractionMapping:
  10566. case EquirectangularRefractionMapping:
  10567. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10568. break;
  10569. }
  10570. switch ( material.combine ) {
  10571. case MultiplyOperation:
  10572. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10573. break;
  10574. case MixOperation:
  10575. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10576. break;
  10577. case AddOperation:
  10578. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10579. break;
  10580. }
  10581. }
  10582. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  10583. // console.log( 'building new program ' );
  10584. //
  10585. var customExtensions = generateExtensions( material.extensions, parameters, extensions );
  10586. var customDefines = generateDefines( defines );
  10587. //
  10588. var program = gl.createProgram();
  10589. var prefixVertex, prefixFragment;
  10590. if ( material.isRawShaderMaterial ) {
  10591. prefixVertex = [
  10592. customDefines,
  10593. '\n'
  10594. ].filter( filterEmptyLine ).join( '\n' );
  10595. prefixFragment = [
  10596. customExtensions,
  10597. customDefines,
  10598. '\n'
  10599. ].filter( filterEmptyLine ).join( '\n' );
  10600. } else {
  10601. prefixVertex = [
  10602. 'precision ' + parameters.precision + ' float;',
  10603. 'precision ' + parameters.precision + ' int;',
  10604. '#define SHADER_NAME ' + shader.name,
  10605. customDefines,
  10606. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  10607. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10608. '#define MAX_BONES ' + parameters.maxBones,
  10609. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10610. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  10611. parameters.map ? '#define USE_MAP' : '',
  10612. parameters.envMap ? '#define USE_ENVMAP' : '',
  10613. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10614. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10615. parameters.aoMap ? '#define USE_AOMAP' : '',
  10616. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10617. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10618. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10619. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  10620. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10621. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10622. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10623. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10624. parameters.vertexColors ? '#define USE_COLOR' : '',
  10625. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10626. parameters.skinning ? '#define USE_SKINNING' : '',
  10627. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  10628. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  10629. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  10630. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10631. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10632. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  10633. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10634. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10635. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  10636. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10637. parameters.logarithmicDepthBuffer && extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10638. 'uniform mat4 modelMatrix;',
  10639. 'uniform mat4 modelViewMatrix;',
  10640. 'uniform mat4 projectionMatrix;',
  10641. 'uniform mat4 viewMatrix;',
  10642. 'uniform mat3 normalMatrix;',
  10643. 'uniform vec3 cameraPosition;',
  10644. 'attribute vec3 position;',
  10645. 'attribute vec3 normal;',
  10646. 'attribute vec2 uv;',
  10647. '#ifdef USE_COLOR',
  10648. ' attribute vec3 color;',
  10649. '#endif',
  10650. '#ifdef USE_MORPHTARGETS',
  10651. ' attribute vec3 morphTarget0;',
  10652. ' attribute vec3 morphTarget1;',
  10653. ' attribute vec3 morphTarget2;',
  10654. ' attribute vec3 morphTarget3;',
  10655. ' #ifdef USE_MORPHNORMALS',
  10656. ' attribute vec3 morphNormal0;',
  10657. ' attribute vec3 morphNormal1;',
  10658. ' attribute vec3 morphNormal2;',
  10659. ' attribute vec3 morphNormal3;',
  10660. ' #else',
  10661. ' attribute vec3 morphTarget4;',
  10662. ' attribute vec3 morphTarget5;',
  10663. ' attribute vec3 morphTarget6;',
  10664. ' attribute vec3 morphTarget7;',
  10665. ' #endif',
  10666. '#endif',
  10667. '#ifdef USE_SKINNING',
  10668. ' attribute vec4 skinIndex;',
  10669. ' attribute vec4 skinWeight;',
  10670. '#endif',
  10671. '\n'
  10672. ].filter( filterEmptyLine ).join( '\n' );
  10673. prefixFragment = [
  10674. customExtensions,
  10675. 'precision ' + parameters.precision + ' float;',
  10676. 'precision ' + parameters.precision + ' int;',
  10677. '#define SHADER_NAME ' + shader.name,
  10678. customDefines,
  10679. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  10680. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10681. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10682. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  10683. parameters.map ? '#define USE_MAP' : '',
  10684. parameters.envMap ? '#define USE_ENVMAP' : '',
  10685. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  10686. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10687. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  10688. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10689. parameters.aoMap ? '#define USE_AOMAP' : '',
  10690. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10691. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10692. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10693. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10694. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10695. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10696. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10697. parameters.vertexColors ? '#define USE_COLOR' : '',
  10698. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  10699. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10700. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10701. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10702. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  10703. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  10704. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10705. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10706. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  10707. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  10708. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10709. parameters.logarithmicDepthBuffer && extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10710. parameters.envMap && extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  10711. 'uniform mat4 viewMatrix;',
  10712. 'uniform vec3 cameraPosition;',
  10713. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  10714. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  10715. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  10716. parameters.dithering ? '#define DITHERING' : '',
  10717. ( 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
  10718. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  10719. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  10720. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  10721. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  10722. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  10723. '\n'
  10724. ].filter( filterEmptyLine ).join( '\n' );
  10725. }
  10726. vertexShader = parseIncludes( vertexShader );
  10727. vertexShader = replaceLightNums( vertexShader, parameters );
  10728. fragmentShader = parseIncludes( fragmentShader );
  10729. fragmentShader = replaceLightNums( fragmentShader, parameters );
  10730. if ( ! material.isShaderMaterial ) {
  10731. vertexShader = unrollLoops( vertexShader );
  10732. fragmentShader = unrollLoops( fragmentShader );
  10733. }
  10734. var vertexGlsl = prefixVertex + vertexShader;
  10735. var fragmentGlsl = prefixFragment + fragmentShader;
  10736. // console.log( '*VERTEX*', vertexGlsl );
  10737. // console.log( '*FRAGMENT*', fragmentGlsl );
  10738. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  10739. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  10740. gl.attachShader( program, glVertexShader );
  10741. gl.attachShader( program, glFragmentShader );
  10742. // Force a particular attribute to index 0.
  10743. if ( material.index0AttributeName !== undefined ) {
  10744. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  10745. } else if ( parameters.morphTargets === true ) {
  10746. // programs with morphTargets displace position out of attribute 0
  10747. gl.bindAttribLocation( program, 0, 'position' );
  10748. }
  10749. gl.linkProgram( program );
  10750. var programLog = gl.getProgramInfoLog( program );
  10751. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  10752. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  10753. var runnable = true;
  10754. var haveDiagnostics = true;
  10755. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  10756. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  10757. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  10758. runnable = false;
  10759. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  10760. } else if ( programLog !== '' ) {
  10761. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  10762. } else if ( vertexLog === '' || fragmentLog === '' ) {
  10763. haveDiagnostics = false;
  10764. }
  10765. if ( haveDiagnostics ) {
  10766. this.diagnostics = {
  10767. runnable: runnable,
  10768. material: material,
  10769. programLog: programLog,
  10770. vertexShader: {
  10771. log: vertexLog,
  10772. prefix: prefixVertex
  10773. },
  10774. fragmentShader: {
  10775. log: fragmentLog,
  10776. prefix: prefixFragment
  10777. }
  10778. };
  10779. }
  10780. // clean up
  10781. gl.deleteShader( glVertexShader );
  10782. gl.deleteShader( glFragmentShader );
  10783. // set up caching for uniform locations
  10784. var cachedUniforms;
  10785. this.getUniforms = function () {
  10786. if ( cachedUniforms === undefined ) {
  10787. cachedUniforms = new WebGLUniforms( gl, program, renderer );
  10788. }
  10789. return cachedUniforms;
  10790. };
  10791. // set up caching for attribute locations
  10792. var cachedAttributes;
  10793. this.getAttributes = function () {
  10794. if ( cachedAttributes === undefined ) {
  10795. cachedAttributes = fetchAttributeLocations( gl, program );
  10796. }
  10797. return cachedAttributes;
  10798. };
  10799. // free resource
  10800. this.destroy = function() {
  10801. gl.deleteProgram( program );
  10802. this.program = undefined;
  10803. };
  10804. // DEPRECATED
  10805. Object.defineProperties( this, {
  10806. uniforms: {
  10807. get: function() {
  10808. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  10809. return this.getUniforms();
  10810. }
  10811. },
  10812. attributes: {
  10813. get: function() {
  10814. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  10815. return this.getAttributes();
  10816. }
  10817. }
  10818. } );
  10819. //
  10820. this.id = programIdCount ++;
  10821. this.code = code;
  10822. this.usedTimes = 1;
  10823. this.program = program;
  10824. this.vertexShader = glVertexShader;
  10825. this.fragmentShader = glFragmentShader;
  10826. return this;
  10827. }
  10828. /**
  10829. * @author mrdoob / http://mrdoob.com/
  10830. */
  10831. function WebGLPrograms( renderer, extensions, capabilities ) {
  10832. var programs = [];
  10833. var shaderIDs = {
  10834. MeshDepthMaterial: 'depth',
  10835. MeshDistanceMaterial: 'distanceRGBA',
  10836. MeshNormalMaterial: 'normal',
  10837. MeshBasicMaterial: 'basic',
  10838. MeshLambertMaterial: 'lambert',
  10839. MeshPhongMaterial: 'phong',
  10840. MeshToonMaterial: 'phong',
  10841. MeshStandardMaterial: 'physical',
  10842. MeshPhysicalMaterial: 'physical',
  10843. LineBasicMaterial: 'basic',
  10844. LineDashedMaterial: 'dashed',
  10845. PointsMaterial: 'points',
  10846. ShadowMaterial: 'shadow'
  10847. };
  10848. var parameterNames = [
  10849. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  10850. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  10851. "roughnessMap", "metalnessMap", "gradientMap",
  10852. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  10853. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  10854. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  10855. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  10856. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  10857. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  10858. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering"
  10859. ];
  10860. function allocateBones( object ) {
  10861. var skeleton = object.skeleton;
  10862. var bones = skeleton.bones;
  10863. if ( capabilities.floatVertexTextures ) {
  10864. return 1024;
  10865. } else {
  10866. // default for when object is not specified
  10867. // ( for example when prebuilding shader to be used with multiple objects )
  10868. //
  10869. // - leave some extra space for other uniforms
  10870. // - limit here is ANGLE's 254 max uniform vectors
  10871. // (up to 54 should be safe)
  10872. var nVertexUniforms = capabilities.maxVertexUniforms;
  10873. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  10874. var maxBones = Math.min( nVertexMatrices, bones.length );
  10875. if ( maxBones < bones.length ) {
  10876. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  10877. return 0;
  10878. }
  10879. return maxBones;
  10880. }
  10881. }
  10882. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  10883. var encoding;
  10884. if ( ! map ) {
  10885. encoding = LinearEncoding;
  10886. } else if ( map.isTexture ) {
  10887. encoding = map.encoding;
  10888. } else if ( map.isWebGLRenderTarget ) {
  10889. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  10890. encoding = map.texture.encoding;
  10891. }
  10892. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  10893. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  10894. encoding = GammaEncoding;
  10895. }
  10896. return encoding;
  10897. }
  10898. this.getParameters = function ( material, lights, shadows, fog, nClipPlanes, nClipIntersection, object ) {
  10899. var shaderID = shaderIDs[ material.type ];
  10900. // heuristics to create shader parameters according to lights in the scene
  10901. // (not to blow over maxLights budget)
  10902. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  10903. var precision = capabilities.precision;
  10904. if ( material.precision !== null ) {
  10905. precision = capabilities.getMaxPrecision( material.precision );
  10906. if ( precision !== material.precision ) {
  10907. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  10908. }
  10909. }
  10910. var currentRenderTarget = renderer.getRenderTarget();
  10911. var parameters = {
  10912. shaderID: shaderID,
  10913. precision: precision,
  10914. supportsVertexTextures: capabilities.vertexTextures,
  10915. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  10916. map: !! material.map,
  10917. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  10918. envMap: !! material.envMap,
  10919. envMapMode: material.envMap && material.envMap.mapping,
  10920. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  10921. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  10922. lightMap: !! material.lightMap,
  10923. aoMap: !! material.aoMap,
  10924. emissiveMap: !! material.emissiveMap,
  10925. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  10926. bumpMap: !! material.bumpMap,
  10927. normalMap: !! material.normalMap,
  10928. displacementMap: !! material.displacementMap,
  10929. roughnessMap: !! material.roughnessMap,
  10930. metalnessMap: !! material.metalnessMap,
  10931. specularMap: !! material.specularMap,
  10932. alphaMap: !! material.alphaMap,
  10933. gradientMap: !! material.gradientMap,
  10934. combine: material.combine,
  10935. vertexColors: material.vertexColors,
  10936. fog: !! fog,
  10937. useFog: material.fog,
  10938. fogExp: ( fog && fog.isFogExp2 ),
  10939. flatShading: material.flatShading,
  10940. sizeAttenuation: material.sizeAttenuation,
  10941. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  10942. skinning: material.skinning && maxBones > 0,
  10943. maxBones: maxBones,
  10944. useVertexTexture: capabilities.floatVertexTextures,
  10945. morphTargets: material.morphTargets,
  10946. morphNormals: material.morphNormals,
  10947. maxMorphTargets: renderer.maxMorphTargets,
  10948. maxMorphNormals: renderer.maxMorphNormals,
  10949. numDirLights: lights.directional.length,
  10950. numPointLights: lights.point.length,
  10951. numSpotLights: lights.spot.length,
  10952. numRectAreaLights: lights.rectArea.length,
  10953. numHemiLights: lights.hemi.length,
  10954. numClippingPlanes: nClipPlanes,
  10955. numClipIntersection: nClipIntersection,
  10956. dithering: material.dithering,
  10957. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && shadows.length > 0,
  10958. shadowMapType: renderer.shadowMap.type,
  10959. toneMapping: renderer.toneMapping,
  10960. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10961. premultipliedAlpha: material.premultipliedAlpha,
  10962. alphaTest: material.alphaTest,
  10963. doubleSided: material.side === DoubleSide,
  10964. flipSided: material.side === BackSide,
  10965. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  10966. };
  10967. return parameters;
  10968. };
  10969. this.getProgramCode = function ( material, parameters ) {
  10970. var array = [];
  10971. if ( parameters.shaderID ) {
  10972. array.push( parameters.shaderID );
  10973. } else {
  10974. array.push( material.fragmentShader );
  10975. array.push( material.vertexShader );
  10976. }
  10977. if ( material.defines !== undefined ) {
  10978. for ( var name in material.defines ) {
  10979. array.push( name );
  10980. array.push( material.defines[ name ] );
  10981. }
  10982. }
  10983. for ( var i = 0; i < parameterNames.length; i ++ ) {
  10984. array.push( parameters[ parameterNames[ i ] ] );
  10985. }
  10986. array.push( material.onBeforeCompile.toString() );
  10987. array.push( renderer.gammaOutput );
  10988. return array.join();
  10989. };
  10990. this.acquireProgram = function ( material, shader, parameters, code ) {
  10991. var program;
  10992. // Check if code has been already compiled
  10993. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  10994. var programInfo = programs[ p ];
  10995. if ( programInfo.code === code ) {
  10996. program = programInfo;
  10997. ++ program.usedTimes;
  10998. break;
  10999. }
  11000. }
  11001. if ( program === undefined ) {
  11002. program = new WebGLProgram( renderer, extensions, code, material, shader, parameters );
  11003. programs.push( program );
  11004. }
  11005. return program;
  11006. };
  11007. this.releaseProgram = function ( program ) {
  11008. if ( -- program.usedTimes === 0 ) {
  11009. // Remove from unordered set
  11010. var i = programs.indexOf( program );
  11011. programs[ i ] = programs[ programs.length - 1 ];
  11012. programs.pop();
  11013. // Free WebGL resources
  11014. program.destroy();
  11015. }
  11016. };
  11017. // Exposed for resource monitoring & error feedback via renderer.info:
  11018. this.programs = programs;
  11019. }
  11020. /**
  11021. * @author mrdoob / http://mrdoob.com/
  11022. */
  11023. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, infoMemory ) {
  11024. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  11025. //
  11026. function clampToMaxSize( image, maxSize ) {
  11027. if ( image.width > maxSize || image.height > maxSize ) {
  11028. // Warning: Scaling through the canvas will only work with images that use
  11029. // premultiplied alpha.
  11030. var scale = maxSize / Math.max( image.width, image.height );
  11031. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  11032. canvas.width = Math.floor( image.width * scale );
  11033. canvas.height = Math.floor( image.height * scale );
  11034. var context = canvas.getContext( '2d' );
  11035. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  11036. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  11037. return canvas;
  11038. }
  11039. return image;
  11040. }
  11041. function isPowerOfTwo( image ) {
  11042. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  11043. }
  11044. function makePowerOfTwo( image ) {
  11045. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  11046. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  11047. canvas.width = _Math.nearestPowerOfTwo( image.width );
  11048. canvas.height = _Math.nearestPowerOfTwo( image.height );
  11049. var context = canvas.getContext( '2d' );
  11050. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  11051. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  11052. return canvas;
  11053. }
  11054. return image;
  11055. }
  11056. function textureNeedsPowerOfTwo( texture ) {
  11057. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  11058. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  11059. }
  11060. function textureNeedsGenerateMipmaps( texture, isPowerOfTwo ) {
  11061. return texture.generateMipmaps && isPowerOfTwo &&
  11062. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  11063. }
  11064. // Fallback filters for non-power-of-2 textures
  11065. function filterFallback( f ) {
  11066. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  11067. return _gl.NEAREST;
  11068. }
  11069. return _gl.LINEAR;
  11070. }
  11071. //
  11072. function onTextureDispose( event ) {
  11073. var texture = event.target;
  11074. texture.removeEventListener( 'dispose', onTextureDispose );
  11075. deallocateTexture( texture );
  11076. infoMemory.textures --;
  11077. }
  11078. function onRenderTargetDispose( event ) {
  11079. var renderTarget = event.target;
  11080. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11081. deallocateRenderTarget( renderTarget );
  11082. infoMemory.textures --;
  11083. }
  11084. //
  11085. function deallocateTexture( texture ) {
  11086. var textureProperties = properties.get( texture );
  11087. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  11088. // cube texture
  11089. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  11090. } else {
  11091. // 2D texture
  11092. if ( textureProperties.__webglInit === undefined ) return;
  11093. _gl.deleteTexture( textureProperties.__webglTexture );
  11094. }
  11095. // remove all webgl properties
  11096. properties.remove( texture );
  11097. }
  11098. function deallocateRenderTarget( renderTarget ) {
  11099. var renderTargetProperties = properties.get( renderTarget );
  11100. var textureProperties = properties.get( renderTarget.texture );
  11101. if ( ! renderTarget ) return;
  11102. if ( textureProperties.__webglTexture !== undefined ) {
  11103. _gl.deleteTexture( textureProperties.__webglTexture );
  11104. }
  11105. if ( renderTarget.depthTexture ) {
  11106. renderTarget.depthTexture.dispose();
  11107. }
  11108. if ( renderTarget.isWebGLRenderTargetCube ) {
  11109. for ( var i = 0; i < 6; i ++ ) {
  11110. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  11111. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  11112. }
  11113. } else {
  11114. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  11115. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  11116. }
  11117. properties.remove( renderTarget.texture );
  11118. properties.remove( renderTarget );
  11119. }
  11120. //
  11121. function setTexture2D( texture, slot ) {
  11122. var textureProperties = properties.get( texture );
  11123. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  11124. var image = texture.image;
  11125. if ( image === undefined ) {
  11126. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  11127. } else if ( image.complete === false ) {
  11128. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  11129. } else {
  11130. uploadTexture( textureProperties, texture, slot );
  11131. return;
  11132. }
  11133. }
  11134. state.activeTexture( _gl.TEXTURE0 + slot );
  11135. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  11136. }
  11137. function setTextureCube( texture, slot ) {
  11138. var textureProperties = properties.get( texture );
  11139. if ( texture.image.length === 6 ) {
  11140. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  11141. if ( ! textureProperties.__image__webglTextureCube ) {
  11142. texture.addEventListener( 'dispose', onTextureDispose );
  11143. textureProperties.__image__webglTextureCube = _gl.createTexture();
  11144. infoMemory.textures ++;
  11145. }
  11146. state.activeTexture( _gl.TEXTURE0 + slot );
  11147. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  11148. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  11149. var isCompressed = ( texture && texture.isCompressedTexture );
  11150. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  11151. var cubeImage = [];
  11152. for ( var i = 0; i < 6; i ++ ) {
  11153. if ( ! isCompressed && ! isDataTexture ) {
  11154. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  11155. } else {
  11156. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  11157. }
  11158. }
  11159. var image = cubeImage[ 0 ],
  11160. isPowerOfTwoImage = isPowerOfTwo( image ),
  11161. glFormat = utils.convert( texture.format ),
  11162. glType = utils.convert( texture.type );
  11163. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  11164. for ( var i = 0; i < 6; i ++ ) {
  11165. if ( ! isCompressed ) {
  11166. if ( isDataTexture ) {
  11167. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  11168. } else {
  11169. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  11170. }
  11171. } else {
  11172. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  11173. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  11174. mipmap = mipmaps[ j ];
  11175. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  11176. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  11177. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  11178. } else {
  11179. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  11180. }
  11181. } else {
  11182. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  11183. }
  11184. }
  11185. }
  11186. }
  11187. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) {
  11188. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  11189. }
  11190. textureProperties.__version = texture.version;
  11191. if ( texture.onUpdate ) texture.onUpdate( texture );
  11192. } else {
  11193. state.activeTexture( _gl.TEXTURE0 + slot );
  11194. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  11195. }
  11196. }
  11197. }
  11198. function setTextureCubeDynamic( texture, slot ) {
  11199. state.activeTexture( _gl.TEXTURE0 + slot );
  11200. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  11201. }
  11202. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  11203. var extension;
  11204. if ( isPowerOfTwoImage ) {
  11205. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, utils.convert( texture.wrapS ) );
  11206. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, utils.convert( texture.wrapT ) );
  11207. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, utils.convert( texture.magFilter ) );
  11208. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, utils.convert( texture.minFilter ) );
  11209. } else {
  11210. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  11211. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  11212. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  11213. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  11214. }
  11215. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  11216. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  11217. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  11218. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  11219. }
  11220. }
  11221. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  11222. if ( extension ) {
  11223. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  11224. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  11225. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  11226. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  11227. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  11228. }
  11229. }
  11230. }
  11231. function uploadTexture( textureProperties, texture, slot ) {
  11232. if ( textureProperties.__webglInit === undefined ) {
  11233. textureProperties.__webglInit = true;
  11234. texture.addEventListener( 'dispose', onTextureDispose );
  11235. textureProperties.__webglTexture = _gl.createTexture();
  11236. infoMemory.textures ++;
  11237. }
  11238. state.activeTexture( _gl.TEXTURE0 + slot );
  11239. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  11240. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  11241. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  11242. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  11243. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  11244. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  11245. image = makePowerOfTwo( image );
  11246. }
  11247. var isPowerOfTwoImage = isPowerOfTwo( image ),
  11248. glFormat = utils.convert( texture.format ),
  11249. glType = utils.convert( texture.type );
  11250. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  11251. var mipmap, mipmaps = texture.mipmaps;
  11252. if ( texture.isDepthTexture ) {
  11253. // populate depth texture with dummy data
  11254. var internalFormat = _gl.DEPTH_COMPONENT;
  11255. if ( texture.type === FloatType ) {
  11256. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  11257. internalFormat = _gl.DEPTH_COMPONENT32F;
  11258. } else if ( _isWebGL2 ) {
  11259. // WebGL 2.0 requires signed internalformat for glTexImage2D
  11260. internalFormat = _gl.DEPTH_COMPONENT16;
  11261. }
  11262. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  11263. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  11264. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  11265. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  11266. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  11267. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  11268. texture.type = UnsignedShortType;
  11269. glType = utils.convert( texture.type );
  11270. }
  11271. }
  11272. // Depth stencil textures need the DEPTH_STENCIL internal format
  11273. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  11274. if ( texture.format === DepthStencilFormat ) {
  11275. internalFormat = _gl.DEPTH_STENCIL;
  11276. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  11277. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  11278. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  11279. if ( texture.type !== UnsignedInt248Type ) {
  11280. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  11281. texture.type = UnsignedInt248Type;
  11282. glType = utils.convert( texture.type );
  11283. }
  11284. }
  11285. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  11286. } else if ( texture.isDataTexture ) {
  11287. // use manually created mipmaps if available
  11288. // if there are no manual mipmaps
  11289. // set 0 level mipmap and then use GL to generate other mipmap levels
  11290. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  11291. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  11292. mipmap = mipmaps[ i ];
  11293. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  11294. }
  11295. texture.generateMipmaps = false;
  11296. } else {
  11297. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  11298. }
  11299. } else if ( texture.isCompressedTexture ) {
  11300. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  11301. mipmap = mipmaps[ i ];
  11302. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  11303. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  11304. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  11305. } else {
  11306. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  11307. }
  11308. } else {
  11309. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  11310. }
  11311. }
  11312. } else {
  11313. // regular Texture (image, video, canvas)
  11314. // use manually created mipmaps if available
  11315. // if there are no manual mipmaps
  11316. // set 0 level mipmap and then use GL to generate other mipmap levels
  11317. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  11318. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  11319. mipmap = mipmaps[ i ];
  11320. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  11321. }
  11322. texture.generateMipmaps = false;
  11323. } else {
  11324. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  11325. }
  11326. }
  11327. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) _gl.generateMipmap( _gl.TEXTURE_2D );
  11328. textureProperties.__version = texture.version;
  11329. if ( texture.onUpdate ) texture.onUpdate( texture );
  11330. }
  11331. // Render targets
  11332. // Setup storage for target texture and bind it to correct framebuffer
  11333. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  11334. var glFormat = utils.convert( renderTarget.texture.format );
  11335. var glType = utils.convert( renderTarget.texture.type );
  11336. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  11337. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  11338. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  11339. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  11340. }
  11341. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  11342. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  11343. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  11344. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  11345. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  11346. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  11347. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  11348. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  11349. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  11350. } else {
  11351. // FIXME: We don't support !depth !stencil
  11352. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  11353. }
  11354. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  11355. }
  11356. // Setup resources for a Depth Texture for a FBO (needs an extension)
  11357. function setupDepthTexture( framebuffer, renderTarget ) {
  11358. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  11359. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  11360. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  11361. if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  11362. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  11363. }
  11364. // upload an empty depth texture with framebuffer size
  11365. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  11366. renderTarget.depthTexture.image.width !== renderTarget.width ||
  11367. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  11368. renderTarget.depthTexture.image.width = renderTarget.width;
  11369. renderTarget.depthTexture.image.height = renderTarget.height;
  11370. renderTarget.depthTexture.needsUpdate = true;
  11371. }
  11372. setTexture2D( renderTarget.depthTexture, 0 );
  11373. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  11374. if ( renderTarget.depthTexture.format === DepthFormat ) {
  11375. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  11376. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  11377. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  11378. } else {
  11379. throw new Error( 'Unknown depthTexture format' );
  11380. }
  11381. }
  11382. // Setup GL resources for a non-texture depth buffer
  11383. function setupDepthRenderbuffer( renderTarget ) {
  11384. var renderTargetProperties = properties.get( renderTarget );
  11385. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  11386. if ( renderTarget.depthTexture ) {
  11387. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  11388. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  11389. } else {
  11390. if ( isCube ) {
  11391. renderTargetProperties.__webglDepthbuffer = [];
  11392. for ( var i = 0; i < 6; i ++ ) {
  11393. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  11394. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  11395. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  11396. }
  11397. } else {
  11398. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  11399. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  11400. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  11401. }
  11402. }
  11403. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  11404. }
  11405. // Set up GL resources for the render target
  11406. function setupRenderTarget( renderTarget ) {
  11407. var renderTargetProperties = properties.get( renderTarget );
  11408. var textureProperties = properties.get( renderTarget.texture );
  11409. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  11410. textureProperties.__webglTexture = _gl.createTexture();
  11411. infoMemory.textures ++;
  11412. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  11413. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  11414. // Setup framebuffer
  11415. if ( isCube ) {
  11416. renderTargetProperties.__webglFramebuffer = [];
  11417. for ( var i = 0; i < 6; i ++ ) {
  11418. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  11419. }
  11420. } else {
  11421. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  11422. }
  11423. // Setup color buffer
  11424. if ( isCube ) {
  11425. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  11426. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  11427. for ( var i = 0; i < 6; i ++ ) {
  11428. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  11429. }
  11430. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  11431. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  11432. } else {
  11433. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  11434. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  11435. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  11436. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) _gl.generateMipmap( _gl.TEXTURE_2D );
  11437. state.bindTexture( _gl.TEXTURE_2D, null );
  11438. }
  11439. // Setup depth and stencil buffers
  11440. if ( renderTarget.depthBuffer ) {
  11441. setupDepthRenderbuffer( renderTarget );
  11442. }
  11443. }
  11444. function updateRenderTargetMipmap( renderTarget ) {
  11445. var texture = renderTarget.texture;
  11446. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  11447. if ( textureNeedsGenerateMipmaps( texture, isTargetPowerOfTwo ) ) {
  11448. var target = renderTarget.isWebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  11449. var webglTexture = properties.get( texture ).__webglTexture;
  11450. state.bindTexture( target, webglTexture );
  11451. _gl.generateMipmap( target );
  11452. state.bindTexture( target, null );
  11453. }
  11454. }
  11455. this.setTexture2D = setTexture2D;
  11456. this.setTextureCube = setTextureCube;
  11457. this.setTextureCubeDynamic = setTextureCubeDynamic;
  11458. this.setupRenderTarget = setupRenderTarget;
  11459. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  11460. }
  11461. /**
  11462. * @author fordacious / fordacious.github.io
  11463. */
  11464. function WebGLProperties() {
  11465. var properties = {};
  11466. function get( object ) {
  11467. var uuid = object.uuid;
  11468. var map = properties[ uuid ];
  11469. if ( map === undefined ) {
  11470. map = {};
  11471. properties[ uuid ] = map;
  11472. }
  11473. return map;
  11474. }
  11475. function remove( object ) {
  11476. delete properties[ object.uuid ];
  11477. }
  11478. function clear() {
  11479. properties = {};
  11480. }
  11481. return {
  11482. get: get,
  11483. remove: remove,
  11484. clear: clear
  11485. };
  11486. }
  11487. /**
  11488. * @author mrdoob / http://mrdoob.com/
  11489. */
  11490. function WebGLState( gl, extensions, utils ) {
  11491. function ColorBuffer() {
  11492. var locked = false;
  11493. var color = new Vector4();
  11494. var currentColorMask = null;
  11495. var currentColorClear = new Vector4( 0, 0, 0, 0 );
  11496. return {
  11497. setMask: function ( colorMask ) {
  11498. if ( currentColorMask !== colorMask && ! locked ) {
  11499. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  11500. currentColorMask = colorMask;
  11501. }
  11502. },
  11503. setLocked: function ( lock ) {
  11504. locked = lock;
  11505. },
  11506. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  11507. if ( premultipliedAlpha === true ) {
  11508. r *= a; g *= a; b *= a;
  11509. }
  11510. color.set( r, g, b, a );
  11511. if ( currentColorClear.equals( color ) === false ) {
  11512. gl.clearColor( r, g, b, a );
  11513. currentColorClear.copy( color );
  11514. }
  11515. },
  11516. reset: function () {
  11517. locked = false;
  11518. currentColorMask = null;
  11519. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  11520. }
  11521. };
  11522. }
  11523. function DepthBuffer() {
  11524. var locked = false;
  11525. var currentDepthMask = null;
  11526. var currentDepthFunc = null;
  11527. var currentDepthClear = null;
  11528. return {
  11529. setTest: function ( depthTest ) {
  11530. if ( depthTest ) {
  11531. enable( gl.DEPTH_TEST );
  11532. } else {
  11533. disable( gl.DEPTH_TEST );
  11534. }
  11535. },
  11536. setMask: function ( depthMask ) {
  11537. if ( currentDepthMask !== depthMask && ! locked ) {
  11538. gl.depthMask( depthMask );
  11539. currentDepthMask = depthMask;
  11540. }
  11541. },
  11542. setFunc: function ( depthFunc ) {
  11543. if ( currentDepthFunc !== depthFunc ) {
  11544. if ( depthFunc ) {
  11545. switch ( depthFunc ) {
  11546. case NeverDepth:
  11547. gl.depthFunc( gl.NEVER );
  11548. break;
  11549. case AlwaysDepth:
  11550. gl.depthFunc( gl.ALWAYS );
  11551. break;
  11552. case LessDepth:
  11553. gl.depthFunc( gl.LESS );
  11554. break;
  11555. case LessEqualDepth:
  11556. gl.depthFunc( gl.LEQUAL );
  11557. break;
  11558. case EqualDepth:
  11559. gl.depthFunc( gl.EQUAL );
  11560. break;
  11561. case GreaterEqualDepth:
  11562. gl.depthFunc( gl.GEQUAL );
  11563. break;
  11564. case GreaterDepth:
  11565. gl.depthFunc( gl.GREATER );
  11566. break;
  11567. case NotEqualDepth:
  11568. gl.depthFunc( gl.NOTEQUAL );
  11569. break;
  11570. default:
  11571. gl.depthFunc( gl.LEQUAL );
  11572. }
  11573. } else {
  11574. gl.depthFunc( gl.LEQUAL );
  11575. }
  11576. currentDepthFunc = depthFunc;
  11577. }
  11578. },
  11579. setLocked: function ( lock ) {
  11580. locked = lock;
  11581. },
  11582. setClear: function ( depth ) {
  11583. if ( currentDepthClear !== depth ) {
  11584. gl.clearDepth( depth );
  11585. currentDepthClear = depth;
  11586. }
  11587. },
  11588. reset: function () {
  11589. locked = false;
  11590. currentDepthMask = null;
  11591. currentDepthFunc = null;
  11592. currentDepthClear = null;
  11593. }
  11594. };
  11595. }
  11596. function StencilBuffer() {
  11597. var locked = false;
  11598. var currentStencilMask = null;
  11599. var currentStencilFunc = null;
  11600. var currentStencilRef = null;
  11601. var currentStencilFuncMask = null;
  11602. var currentStencilFail = null;
  11603. var currentStencilZFail = null;
  11604. var currentStencilZPass = null;
  11605. var currentStencilClear = null;
  11606. return {
  11607. setTest: function ( stencilTest ) {
  11608. if ( stencilTest ) {
  11609. enable( gl.STENCIL_TEST );
  11610. } else {
  11611. disable( gl.STENCIL_TEST );
  11612. }
  11613. },
  11614. setMask: function ( stencilMask ) {
  11615. if ( currentStencilMask !== stencilMask && ! locked ) {
  11616. gl.stencilMask( stencilMask );
  11617. currentStencilMask = stencilMask;
  11618. }
  11619. },
  11620. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  11621. if ( currentStencilFunc !== stencilFunc ||
  11622. currentStencilRef !== stencilRef ||
  11623. currentStencilFuncMask !== stencilMask ) {
  11624. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  11625. currentStencilFunc = stencilFunc;
  11626. currentStencilRef = stencilRef;
  11627. currentStencilFuncMask = stencilMask;
  11628. }
  11629. },
  11630. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  11631. if ( currentStencilFail !== stencilFail ||
  11632. currentStencilZFail !== stencilZFail ||
  11633. currentStencilZPass !== stencilZPass ) {
  11634. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  11635. currentStencilFail = stencilFail;
  11636. currentStencilZFail = stencilZFail;
  11637. currentStencilZPass = stencilZPass;
  11638. }
  11639. },
  11640. setLocked: function ( lock ) {
  11641. locked = lock;
  11642. },
  11643. setClear: function ( stencil ) {
  11644. if ( currentStencilClear !== stencil ) {
  11645. gl.clearStencil( stencil );
  11646. currentStencilClear = stencil;
  11647. }
  11648. },
  11649. reset: function () {
  11650. locked = false;
  11651. currentStencilMask = null;
  11652. currentStencilFunc = null;
  11653. currentStencilRef = null;
  11654. currentStencilFuncMask = null;
  11655. currentStencilFail = null;
  11656. currentStencilZFail = null;
  11657. currentStencilZPass = null;
  11658. currentStencilClear = null;
  11659. }
  11660. };
  11661. }
  11662. //
  11663. var colorBuffer = new ColorBuffer();
  11664. var depthBuffer = new DepthBuffer();
  11665. var stencilBuffer = new StencilBuffer();
  11666. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11667. var newAttributes = new Uint8Array( maxVertexAttributes );
  11668. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  11669. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  11670. var capabilities = {};
  11671. var compressedTextureFormats = null;
  11672. var currentProgram = null;
  11673. var currentBlending = null;
  11674. var currentBlendEquation = null;
  11675. var currentBlendSrc = null;
  11676. var currentBlendDst = null;
  11677. var currentBlendEquationAlpha = null;
  11678. var currentBlendSrcAlpha = null;
  11679. var currentBlendDstAlpha = null;
  11680. var currentPremultipledAlpha = false;
  11681. var currentFlipSided = null;
  11682. var currentCullFace = null;
  11683. var currentLineWidth = null;
  11684. var currentPolygonOffsetFactor = null;
  11685. var currentPolygonOffsetUnits = null;
  11686. var maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  11687. var version = parseFloat( /^WebGL\ ([0-9])/.exec( gl.getParameter( gl.VERSION ) )[ 1 ] );
  11688. var lineWidthAvailable = parseFloat( version ) >= 1.0;
  11689. var currentTextureSlot = null;
  11690. var currentBoundTextures = {};
  11691. var currentScissor = new Vector4();
  11692. var currentViewport = new Vector4();
  11693. function createTexture( type, target, count ) {
  11694. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  11695. var texture = gl.createTexture();
  11696. gl.bindTexture( type, texture );
  11697. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  11698. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  11699. for ( var i = 0; i < count; i ++ ) {
  11700. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  11701. }
  11702. return texture;
  11703. }
  11704. var emptyTextures = {};
  11705. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  11706. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  11707. // init
  11708. colorBuffer.setClear( 0, 0, 0, 1 );
  11709. depthBuffer.setClear( 1 );
  11710. stencilBuffer.setClear( 0 );
  11711. enable( gl.DEPTH_TEST );
  11712. depthBuffer.setFunc( LessEqualDepth );
  11713. setFlipSided( false );
  11714. setCullFace( CullFaceBack );
  11715. enable( gl.CULL_FACE );
  11716. enable( gl.BLEND );
  11717. setBlending( NormalBlending );
  11718. //
  11719. function initAttributes() {
  11720. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  11721. newAttributes[ i ] = 0;
  11722. }
  11723. }
  11724. function enableAttribute( attribute ) {
  11725. newAttributes[ attribute ] = 1;
  11726. if ( enabledAttributes[ attribute ] === 0 ) {
  11727. gl.enableVertexAttribArray( attribute );
  11728. enabledAttributes[ attribute ] = 1;
  11729. }
  11730. if ( attributeDivisors[ attribute ] !== 0 ) {
  11731. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11732. extension.vertexAttribDivisorANGLE( attribute, 0 );
  11733. attributeDivisors[ attribute ] = 0;
  11734. }
  11735. }
  11736. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  11737. newAttributes[ attribute ] = 1;
  11738. if ( enabledAttributes[ attribute ] === 0 ) {
  11739. gl.enableVertexAttribArray( attribute );
  11740. enabledAttributes[ attribute ] = 1;
  11741. }
  11742. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  11743. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11744. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  11745. attributeDivisors[ attribute ] = meshPerAttribute;
  11746. }
  11747. }
  11748. function disableUnusedAttributes() {
  11749. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  11750. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  11751. gl.disableVertexAttribArray( i );
  11752. enabledAttributes[ i ] = 0;
  11753. }
  11754. }
  11755. }
  11756. function enable( id ) {
  11757. if ( capabilities[ id ] !== true ) {
  11758. gl.enable( id );
  11759. capabilities[ id ] = true;
  11760. }
  11761. }
  11762. function disable( id ) {
  11763. if ( capabilities[ id ] !== false ) {
  11764. gl.disable( id );
  11765. capabilities[ id ] = false;
  11766. }
  11767. }
  11768. function getCompressedTextureFormats() {
  11769. if ( compressedTextureFormats === null ) {
  11770. compressedTextureFormats = [];
  11771. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  11772. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  11773. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  11774. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  11775. for ( var i = 0; i < formats.length; i ++ ) {
  11776. compressedTextureFormats.push( formats[ i ] );
  11777. }
  11778. }
  11779. }
  11780. return compressedTextureFormats;
  11781. }
  11782. function useProgram( program ) {
  11783. if ( currentProgram !== program ) {
  11784. gl.useProgram( program );
  11785. currentProgram = program;
  11786. return true;
  11787. }
  11788. return false;
  11789. }
  11790. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11791. if ( blending !== NoBlending ) {
  11792. enable( gl.BLEND );
  11793. } else {
  11794. disable( gl.BLEND );
  11795. }
  11796. if ( blending !== CustomBlending ) {
  11797. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  11798. switch ( blending ) {
  11799. case AdditiveBlending:
  11800. if ( premultipliedAlpha ) {
  11801. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11802. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  11803. } else {
  11804. gl.blendEquation( gl.FUNC_ADD );
  11805. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  11806. }
  11807. break;
  11808. case SubtractiveBlending:
  11809. if ( premultipliedAlpha ) {
  11810. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11811. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  11812. } else {
  11813. gl.blendEquation( gl.FUNC_ADD );
  11814. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  11815. }
  11816. break;
  11817. case MultiplyBlending:
  11818. if ( premultipliedAlpha ) {
  11819. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11820. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  11821. } else {
  11822. gl.blendEquation( gl.FUNC_ADD );
  11823. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  11824. }
  11825. break;
  11826. default:
  11827. if ( premultipliedAlpha ) {
  11828. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11829. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11830. } else {
  11831. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11832. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11833. }
  11834. }
  11835. }
  11836. currentBlendEquation = null;
  11837. currentBlendSrc = null;
  11838. currentBlendDst = null;
  11839. currentBlendEquationAlpha = null;
  11840. currentBlendSrcAlpha = null;
  11841. currentBlendDstAlpha = null;
  11842. } else {
  11843. blendEquationAlpha = blendEquationAlpha || blendEquation;
  11844. blendSrcAlpha = blendSrcAlpha || blendSrc;
  11845. blendDstAlpha = blendDstAlpha || blendDst;
  11846. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  11847. gl.blendEquationSeparate( utils.convert( blendEquation ), utils.convert( blendEquationAlpha ) );
  11848. currentBlendEquation = blendEquation;
  11849. currentBlendEquationAlpha = blendEquationAlpha;
  11850. }
  11851. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  11852. gl.blendFuncSeparate( utils.convert( blendSrc ), utils.convert( blendDst ), utils.convert( blendSrcAlpha ), utils.convert( blendDstAlpha ) );
  11853. currentBlendSrc = blendSrc;
  11854. currentBlendDst = blendDst;
  11855. currentBlendSrcAlpha = blendSrcAlpha;
  11856. currentBlendDstAlpha = blendDstAlpha;
  11857. }
  11858. }
  11859. currentBlending = blending;
  11860. currentPremultipledAlpha = premultipliedAlpha;
  11861. }
  11862. function setMaterial( material ) {
  11863. material.side === DoubleSide
  11864. ? disable( gl.CULL_FACE )
  11865. : enable( gl.CULL_FACE );
  11866. setFlipSided( material.side === BackSide );
  11867. material.transparent === true
  11868. ? setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  11869. : setBlending( NoBlending );
  11870. depthBuffer.setFunc( material.depthFunc );
  11871. depthBuffer.setTest( material.depthTest );
  11872. depthBuffer.setMask( material.depthWrite );
  11873. colorBuffer.setMask( material.colorWrite );
  11874. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11875. }
  11876. //
  11877. function setFlipSided( flipSided ) {
  11878. if ( currentFlipSided !== flipSided ) {
  11879. if ( flipSided ) {
  11880. gl.frontFace( gl.CW );
  11881. } else {
  11882. gl.frontFace( gl.CCW );
  11883. }
  11884. currentFlipSided = flipSided;
  11885. }
  11886. }
  11887. function setCullFace( cullFace ) {
  11888. if ( cullFace !== CullFaceNone ) {
  11889. enable( gl.CULL_FACE );
  11890. if ( cullFace !== currentCullFace ) {
  11891. if ( cullFace === CullFaceBack ) {
  11892. gl.cullFace( gl.BACK );
  11893. } else if ( cullFace === CullFaceFront ) {
  11894. gl.cullFace( gl.FRONT );
  11895. } else {
  11896. gl.cullFace( gl.FRONT_AND_BACK );
  11897. }
  11898. }
  11899. } else {
  11900. disable( gl.CULL_FACE );
  11901. }
  11902. currentCullFace = cullFace;
  11903. }
  11904. function setLineWidth( width ) {
  11905. if ( width !== currentLineWidth ) {
  11906. if ( lineWidthAvailable ) gl.lineWidth( width );
  11907. currentLineWidth = width;
  11908. }
  11909. }
  11910. function setPolygonOffset( polygonOffset, factor, units ) {
  11911. if ( polygonOffset ) {
  11912. enable( gl.POLYGON_OFFSET_FILL );
  11913. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  11914. gl.polygonOffset( factor, units );
  11915. currentPolygonOffsetFactor = factor;
  11916. currentPolygonOffsetUnits = units;
  11917. }
  11918. } else {
  11919. disable( gl.POLYGON_OFFSET_FILL );
  11920. }
  11921. }
  11922. function setScissorTest( scissorTest ) {
  11923. if ( scissorTest ) {
  11924. enable( gl.SCISSOR_TEST );
  11925. } else {
  11926. disable( gl.SCISSOR_TEST );
  11927. }
  11928. }
  11929. // texture
  11930. function activeTexture( webglSlot ) {
  11931. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  11932. if ( currentTextureSlot !== webglSlot ) {
  11933. gl.activeTexture( webglSlot );
  11934. currentTextureSlot = webglSlot;
  11935. }
  11936. }
  11937. function bindTexture( webglType, webglTexture ) {
  11938. if ( currentTextureSlot === null ) {
  11939. activeTexture();
  11940. }
  11941. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  11942. if ( boundTexture === undefined ) {
  11943. boundTexture = { type: undefined, texture: undefined };
  11944. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  11945. }
  11946. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  11947. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  11948. boundTexture.type = webglType;
  11949. boundTexture.texture = webglTexture;
  11950. }
  11951. }
  11952. function compressedTexImage2D() {
  11953. try {
  11954. gl.compressedTexImage2D.apply( gl, arguments );
  11955. } catch ( error ) {
  11956. console.error( 'THREE.WebGLState:', error );
  11957. }
  11958. }
  11959. function texImage2D() {
  11960. try {
  11961. gl.texImage2D.apply( gl, arguments );
  11962. } catch ( error ) {
  11963. console.error( 'THREE.WebGLState:', error );
  11964. }
  11965. }
  11966. //
  11967. function scissor( scissor ) {
  11968. if ( currentScissor.equals( scissor ) === false ) {
  11969. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  11970. currentScissor.copy( scissor );
  11971. }
  11972. }
  11973. function viewport( viewport ) {
  11974. if ( currentViewport.equals( viewport ) === false ) {
  11975. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  11976. currentViewport.copy( viewport );
  11977. }
  11978. }
  11979. //
  11980. function reset() {
  11981. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  11982. if ( enabledAttributes[ i ] === 1 ) {
  11983. gl.disableVertexAttribArray( i );
  11984. enabledAttributes[ i ] = 0;
  11985. }
  11986. }
  11987. capabilities = {};
  11988. compressedTextureFormats = null;
  11989. currentTextureSlot = null;
  11990. currentBoundTextures = {};
  11991. currentProgram = null;
  11992. currentBlending = null;
  11993. currentFlipSided = null;
  11994. currentCullFace = null;
  11995. colorBuffer.reset();
  11996. depthBuffer.reset();
  11997. stencilBuffer.reset();
  11998. }
  11999. return {
  12000. buffers: {
  12001. color: colorBuffer,
  12002. depth: depthBuffer,
  12003. stencil: stencilBuffer
  12004. },
  12005. initAttributes: initAttributes,
  12006. enableAttribute: enableAttribute,
  12007. enableAttributeAndDivisor: enableAttributeAndDivisor,
  12008. disableUnusedAttributes: disableUnusedAttributes,
  12009. enable: enable,
  12010. disable: disable,
  12011. getCompressedTextureFormats: getCompressedTextureFormats,
  12012. useProgram: useProgram,
  12013. setBlending: setBlending,
  12014. setMaterial: setMaterial,
  12015. setFlipSided: setFlipSided,
  12016. setCullFace: setCullFace,
  12017. setLineWidth: setLineWidth,
  12018. setPolygonOffset: setPolygonOffset,
  12019. setScissorTest: setScissorTest,
  12020. activeTexture: activeTexture,
  12021. bindTexture: bindTexture,
  12022. compressedTexImage2D: compressedTexImage2D,
  12023. texImage2D: texImage2D,
  12024. scissor: scissor,
  12025. viewport: viewport,
  12026. reset: reset
  12027. };
  12028. }
  12029. /**
  12030. * @author mrdoob / http://mrdoob.com/
  12031. */
  12032. function WebGLCapabilities( gl, extensions, parameters ) {
  12033. var maxAnisotropy;
  12034. function getMaxAnisotropy() {
  12035. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  12036. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  12037. if ( extension !== null ) {
  12038. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  12039. } else {
  12040. maxAnisotropy = 0;
  12041. }
  12042. return maxAnisotropy;
  12043. }
  12044. function getMaxPrecision( precision ) {
  12045. if ( precision === 'highp' ) {
  12046. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  12047. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  12048. return 'highp';
  12049. }
  12050. precision = 'mediump';
  12051. }
  12052. if ( precision === 'mediump' ) {
  12053. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  12054. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  12055. return 'mediump';
  12056. }
  12057. }
  12058. return 'lowp';
  12059. }
  12060. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  12061. var maxPrecision = getMaxPrecision( precision );
  12062. if ( maxPrecision !== precision ) {
  12063. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  12064. precision = maxPrecision;
  12065. }
  12066. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  12067. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  12068. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  12069. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  12070. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  12071. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  12072. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  12073. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  12074. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  12075. var vertexTextures = maxVertexTextures > 0;
  12076. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  12077. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  12078. return {
  12079. getMaxAnisotropy: getMaxAnisotropy,
  12080. getMaxPrecision: getMaxPrecision,
  12081. precision: precision,
  12082. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12083. maxTextures: maxTextures,
  12084. maxVertexTextures: maxVertexTextures,
  12085. maxTextureSize: maxTextureSize,
  12086. maxCubemapSize: maxCubemapSize,
  12087. maxAttributes: maxAttributes,
  12088. maxVertexUniforms: maxVertexUniforms,
  12089. maxVaryings: maxVaryings,
  12090. maxFragmentUniforms: maxFragmentUniforms,
  12091. vertexTextures: vertexTextures,
  12092. floatFragmentTextures: floatFragmentTextures,
  12093. floatVertexTextures: floatVertexTextures
  12094. };
  12095. }
  12096. /**
  12097. * @author mrdoob / http://mrdoob.com/
  12098. */
  12099. function ArrayCamera( array ) {
  12100. PerspectiveCamera.call( this );
  12101. this.cameras = array || [];
  12102. }
  12103. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  12104. constructor: ArrayCamera,
  12105. isArrayCamera: true
  12106. } );
  12107. /**
  12108. * @author mrdoob / http://mrdoob.com/
  12109. */
  12110. function WebVRManager( renderer ) {
  12111. var scope = this;
  12112. var device = null;
  12113. var frameData = null;
  12114. if ( 'VRFrameData' in window ) {
  12115. frameData = new window.VRFrameData();
  12116. }
  12117. var matrixWorldInverse = new Matrix4();
  12118. var standingMatrix = new Matrix4();
  12119. var standingMatrixInverse = new Matrix4();
  12120. var cameraL = new PerspectiveCamera();
  12121. cameraL.bounds = new Vector4( 0.0, 0.0, 0.5, 1.0 );
  12122. cameraL.layers.enable( 1 );
  12123. var cameraR = new PerspectiveCamera();
  12124. cameraR.bounds = new Vector4( 0.5, 0.0, 0.5, 1.0 );
  12125. cameraR.layers.enable( 2 );
  12126. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  12127. cameraVR.layers.enable( 1 );
  12128. cameraVR.layers.enable( 2 );
  12129. //
  12130. var currentSize, currentPixelRatio;
  12131. function onVRDisplayPresentChange() {
  12132. if ( device !== null && device.isPresenting ) {
  12133. var eyeParameters = device.getEyeParameters( 'left' );
  12134. var renderWidth = eyeParameters.renderWidth;
  12135. var renderHeight = eyeParameters.renderHeight;
  12136. currentPixelRatio = renderer.getPixelRatio();
  12137. currentSize = renderer.getSize();
  12138. renderer.setDrawingBufferSize( renderWidth * 2, renderHeight, 1 );
  12139. } else if ( scope.enabled ) {
  12140. renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio );
  12141. }
  12142. }
  12143. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  12144. //
  12145. this.enabled = false;
  12146. this.standing = false;
  12147. this.getDevice = function () {
  12148. return device;
  12149. };
  12150. this.setDevice = function ( value ) {
  12151. if ( value !== undefined ) device = value;
  12152. };
  12153. this.getCamera = function ( camera ) {
  12154. if ( device === null ) return camera;
  12155. device.depthNear = camera.near;
  12156. device.depthFar = camera.far;
  12157. device.getFrameData( frameData );
  12158. //
  12159. var pose = frameData.pose;
  12160. if ( pose.position !== null ) {
  12161. camera.position.fromArray( pose.position );
  12162. } else {
  12163. camera.position.set( 0, 0, 0 );
  12164. }
  12165. if ( pose.orientation !== null ) {
  12166. camera.quaternion.fromArray( pose.orientation );
  12167. }
  12168. camera.updateMatrixWorld();
  12169. var stageParameters = device.stageParameters;
  12170. if ( this.standing && stageParameters ) {
  12171. standingMatrix.fromArray( stageParameters.sittingToStandingTransform );
  12172. standingMatrixInverse.getInverse( standingMatrix );
  12173. camera.matrixWorld.multiply( standingMatrix );
  12174. camera.matrixWorldInverse.multiply( standingMatrixInverse );
  12175. }
  12176. if ( device.isPresenting === false ) return camera;
  12177. //
  12178. cameraL.near = camera.near;
  12179. cameraR.near = camera.near;
  12180. cameraL.far = camera.far;
  12181. cameraR.far = camera.far;
  12182. cameraVR.matrixWorld.copy( camera.matrixWorld );
  12183. cameraVR.matrixWorldInverse.copy( camera.matrixWorldInverse );
  12184. cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix );
  12185. cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix );
  12186. if ( this.standing && stageParameters ) {
  12187. cameraL.matrixWorldInverse.multiply( standingMatrixInverse );
  12188. cameraR.matrixWorldInverse.multiply( standingMatrixInverse );
  12189. }
  12190. var parent = camera.parent;
  12191. if ( parent !== null ) {
  12192. matrixWorldInverse.getInverse( parent.matrixWorld );
  12193. cameraL.matrixWorldInverse.multiply( matrixWorldInverse );
  12194. cameraR.matrixWorldInverse.multiply( matrixWorldInverse );
  12195. }
  12196. // envMap and Mirror needs camera.matrixWorld
  12197. cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse );
  12198. cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse );
  12199. cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix );
  12200. cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix );
  12201. // HACK @mrdoob
  12202. // https://github.com/w3c/webvr/issues/203
  12203. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  12204. //
  12205. var layers = device.getLayers();
  12206. if ( layers.length ) {
  12207. var layer = layers[ 0 ];
  12208. if ( layer.leftBounds !== null && layer.leftBounds.length === 4 ) {
  12209. cameraL.bounds.fromArray( layer.leftBounds );
  12210. }
  12211. if ( layer.rightBounds !== null && layer.rightBounds.length === 4 ) {
  12212. cameraR.bounds.fromArray( layer.rightBounds );
  12213. }
  12214. }
  12215. return cameraVR;
  12216. };
  12217. this.getStandingMatrix = function () {
  12218. return standingMatrix;
  12219. };
  12220. this.submitFrame = function () {
  12221. if ( device && device.isPresenting ) device.submitFrame();
  12222. };
  12223. this.dispose = function() {
  12224. window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange );
  12225. };
  12226. }
  12227. /**
  12228. * @author mrdoob / http://mrdoob.com/
  12229. */
  12230. function WebGLExtensions( gl ) {
  12231. var extensions = {};
  12232. return {
  12233. get: function ( name ) {
  12234. if ( extensions[ name ] !== undefined ) {
  12235. return extensions[ name ];
  12236. }
  12237. var extension;
  12238. switch ( name ) {
  12239. case 'WEBGL_depth_texture':
  12240. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  12241. break;
  12242. case 'EXT_texture_filter_anisotropic':
  12243. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  12244. break;
  12245. case 'WEBGL_compressed_texture_s3tc':
  12246. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  12247. break;
  12248. case 'WEBGL_compressed_texture_pvrtc':
  12249. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  12250. break;
  12251. case 'WEBGL_compressed_texture_etc1':
  12252. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  12253. break;
  12254. default:
  12255. extension = gl.getExtension( name );
  12256. }
  12257. if ( extension === null ) {
  12258. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  12259. }
  12260. extensions[ name ] = extension;
  12261. return extension;
  12262. }
  12263. };
  12264. }
  12265. /**
  12266. * @author tschw
  12267. */
  12268. function WebGLClipping() {
  12269. var scope = this,
  12270. globalState = null,
  12271. numGlobalPlanes = 0,
  12272. localClippingEnabled = false,
  12273. renderingShadows = false,
  12274. plane = new Plane(),
  12275. viewNormalMatrix = new Matrix3(),
  12276. uniform = { value: null, needsUpdate: false };
  12277. this.uniform = uniform;
  12278. this.numPlanes = 0;
  12279. this.numIntersection = 0;
  12280. this.init = function( planes, enableLocalClipping, camera ) {
  12281. var enabled =
  12282. planes.length !== 0 ||
  12283. enableLocalClipping ||
  12284. // enable state of previous frame - the clipping code has to
  12285. // run another frame in order to reset the state:
  12286. numGlobalPlanes !== 0 ||
  12287. localClippingEnabled;
  12288. localClippingEnabled = enableLocalClipping;
  12289. globalState = projectPlanes( planes, camera, 0 );
  12290. numGlobalPlanes = planes.length;
  12291. return enabled;
  12292. };
  12293. this.beginShadows = function() {
  12294. renderingShadows = true;
  12295. projectPlanes( null );
  12296. };
  12297. this.endShadows = function() {
  12298. renderingShadows = false;
  12299. resetGlobalState();
  12300. };
  12301. this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  12302. if ( ! localClippingEnabled ||
  12303. planes === null || planes.length === 0 ||
  12304. renderingShadows && ! clipShadows ) {
  12305. // there's no local clipping
  12306. if ( renderingShadows ) {
  12307. // there's no global clipping
  12308. projectPlanes( null );
  12309. } else {
  12310. resetGlobalState();
  12311. }
  12312. } else {
  12313. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  12314. lGlobal = nGlobal * 4,
  12315. dstArray = cache.clippingState || null;
  12316. uniform.value = dstArray; // ensure unique state
  12317. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  12318. for ( var i = 0; i !== lGlobal; ++ i ) {
  12319. dstArray[ i ] = globalState[ i ];
  12320. }
  12321. cache.clippingState = dstArray;
  12322. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  12323. this.numPlanes += nGlobal;
  12324. }
  12325. };
  12326. function resetGlobalState() {
  12327. if ( uniform.value !== globalState ) {
  12328. uniform.value = globalState;
  12329. uniform.needsUpdate = numGlobalPlanes > 0;
  12330. }
  12331. scope.numPlanes = numGlobalPlanes;
  12332. scope.numIntersection = 0;
  12333. }
  12334. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  12335. var nPlanes = planes !== null ? planes.length : 0,
  12336. dstArray = null;
  12337. if ( nPlanes !== 0 ) {
  12338. dstArray = uniform.value;
  12339. if ( skipTransform !== true || dstArray === null ) {
  12340. var flatSize = dstOffset + nPlanes * 4,
  12341. viewMatrix = camera.matrixWorldInverse;
  12342. viewNormalMatrix.getNormalMatrix( viewMatrix );
  12343. if ( dstArray === null || dstArray.length < flatSize ) {
  12344. dstArray = new Float32Array( flatSize );
  12345. }
  12346. for ( var i = 0, i4 = dstOffset;
  12347. i !== nPlanes; ++ i, i4 += 4 ) {
  12348. plane.copy( planes[ i ] ).
  12349. applyMatrix4( viewMatrix, viewNormalMatrix );
  12350. plane.normal.toArray( dstArray, i4 );
  12351. dstArray[ i4 + 3 ] = plane.constant;
  12352. }
  12353. }
  12354. uniform.value = dstArray;
  12355. uniform.needsUpdate = true;
  12356. }
  12357. scope.numPlanes = nPlanes;
  12358. return dstArray;
  12359. }
  12360. }
  12361. /**
  12362. * @author thespite / http://www.twitter.com/thespite
  12363. */
  12364. function WebGLUtils ( gl, extensions ) {
  12365. function convert ( p ) {
  12366. var extension;
  12367. if ( p === RepeatWrapping ) return gl.REPEAT;
  12368. if ( p === ClampToEdgeWrapping ) return gl.CLAMP_TO_EDGE;
  12369. if ( p === MirroredRepeatWrapping ) return gl.MIRRORED_REPEAT;
  12370. if ( p === NearestFilter ) return gl.NEAREST;
  12371. if ( p === NearestMipMapNearestFilter ) return gl.NEAREST_MIPMAP_NEAREST;
  12372. if ( p === NearestMipMapLinearFilter ) return gl.NEAREST_MIPMAP_LINEAR;
  12373. if ( p === LinearFilter ) return gl.LINEAR;
  12374. if ( p === LinearMipMapNearestFilter ) return gl.LINEAR_MIPMAP_NEAREST;
  12375. if ( p === LinearMipMapLinearFilter ) return gl.LINEAR_MIPMAP_LINEAR;
  12376. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  12377. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  12378. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  12379. if ( p === UnsignedShort565Type ) return gl.UNSIGNED_SHORT_5_6_5;
  12380. if ( p === ByteType ) return gl.BYTE;
  12381. if ( p === ShortType ) return gl.SHORT;
  12382. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  12383. if ( p === IntType ) return gl.INT;
  12384. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  12385. if ( p === FloatType ) return gl.FLOAT;
  12386. if ( p === HalfFloatType ) {
  12387. extension = extensions.get( 'OES_texture_half_float' );
  12388. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  12389. }
  12390. if ( p === AlphaFormat ) return gl.ALPHA;
  12391. if ( p === RGBFormat ) return gl.RGB;
  12392. if ( p === RGBAFormat ) return gl.RGBA;
  12393. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  12394. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  12395. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  12396. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  12397. if ( p === AddEquation ) return gl.FUNC_ADD;
  12398. if ( p === SubtractEquation ) return gl.FUNC_SUBTRACT;
  12399. if ( p === ReverseSubtractEquation ) return gl.FUNC_REVERSE_SUBTRACT;
  12400. if ( p === ZeroFactor ) return gl.ZERO;
  12401. if ( p === OneFactor ) return gl.ONE;
  12402. if ( p === SrcColorFactor ) return gl.SRC_COLOR;
  12403. if ( p === OneMinusSrcColorFactor ) return gl.ONE_MINUS_SRC_COLOR;
  12404. if ( p === SrcAlphaFactor ) return gl.SRC_ALPHA;
  12405. if ( p === OneMinusSrcAlphaFactor ) return gl.ONE_MINUS_SRC_ALPHA;
  12406. if ( p === DstAlphaFactor ) return gl.DST_ALPHA;
  12407. if ( p === OneMinusDstAlphaFactor ) return gl.ONE_MINUS_DST_ALPHA;
  12408. if ( p === DstColorFactor ) return gl.DST_COLOR;
  12409. if ( p === OneMinusDstColorFactor ) return gl.ONE_MINUS_DST_COLOR;
  12410. if ( p === SrcAlphaSaturateFactor ) return gl.SRC_ALPHA_SATURATE;
  12411. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  12412. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  12413. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  12414. if ( extension !== null ) {
  12415. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  12416. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  12417. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  12418. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  12419. }
  12420. }
  12421. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  12422. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  12423. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  12424. if ( extension !== null ) {
  12425. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  12426. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  12427. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  12428. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  12429. }
  12430. }
  12431. if ( p === RGB_ETC1_Format ) {
  12432. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  12433. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  12434. }
  12435. if ( p === MinEquation || p === MaxEquation ) {
  12436. extension = extensions.get( 'EXT_blend_minmax' );
  12437. if ( extension !== null ) {
  12438. if ( p === MinEquation ) return extension.MIN_EXT;
  12439. if ( p === MaxEquation ) return extension.MAX_EXT;
  12440. }
  12441. }
  12442. if ( p === UnsignedInt248Type ) {
  12443. extension = extensions.get( 'WEBGL_depth_texture' );
  12444. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  12445. }
  12446. return 0;
  12447. }
  12448. return { convert: convert }
  12449. }
  12450. // import { Sphere } from '../math/Sphere';
  12451. /**
  12452. * @author supereggbert / http://www.paulbrunt.co.uk/
  12453. * @author mrdoob / http://mrdoob.com/
  12454. * @author alteredq / http://alteredqualia.com/
  12455. * @author szimek / https://github.com/szimek/
  12456. * @author tschw
  12457. */
  12458. function WebGLRenderer( parameters ) {
  12459. console.log( 'THREE.WebGLRenderer', REVISION );
  12460. parameters = parameters || {};
  12461. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  12462. _context = parameters.context !== undefined ? parameters.context : null,
  12463. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  12464. _depth = parameters.depth !== undefined ? parameters.depth : true,
  12465. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  12466. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  12467. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  12468. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  12469. var lightsArray = [];
  12470. var shadowsArray = [];
  12471. var currentRenderList = null;
  12472. var spritesArray = [];
  12473. var flaresArray = [];
  12474. // public properties
  12475. this.domElement = _canvas;
  12476. this.context = null;
  12477. // clearing
  12478. this.autoClear = true;
  12479. this.autoClearColor = true;
  12480. this.autoClearDepth = true;
  12481. this.autoClearStencil = true;
  12482. // scene graph
  12483. this.sortObjects = true;
  12484. // user-defined clipping
  12485. this.clippingPlanes = [];
  12486. this.localClippingEnabled = false;
  12487. // physically based shading
  12488. this.gammaFactor = 2.0; // for backwards compatibility
  12489. this.gammaInput = false;
  12490. this.gammaOutput = false;
  12491. // physical lights
  12492. this.physicallyCorrectLights = false;
  12493. // tone mapping
  12494. this.toneMapping = LinearToneMapping;
  12495. this.toneMappingExposure = 1.0;
  12496. this.toneMappingWhitePoint = 1.0;
  12497. // morphs
  12498. this.maxMorphTargets = 8;
  12499. this.maxMorphNormals = 4;
  12500. // internal properties
  12501. var _this = this,
  12502. _isContextLost = false,
  12503. // internal state cache
  12504. _currentRenderTarget = null,
  12505. _currentFramebuffer = null,
  12506. _currentMaterialId = - 1,
  12507. _currentGeometryProgram = '',
  12508. _currentCamera = null,
  12509. _currentArrayCamera = null,
  12510. _currentViewport = new Vector4(),
  12511. _currentScissor = new Vector4(),
  12512. _currentScissorTest = null,
  12513. //
  12514. _usedTextureUnits = 0,
  12515. //
  12516. _width = _canvas.width,
  12517. _height = _canvas.height,
  12518. _pixelRatio = 1,
  12519. _viewport = new Vector4( 0, 0, _width, _height ),
  12520. _scissor = new Vector4( 0, 0, _width, _height ),
  12521. _scissorTest = false,
  12522. // frustum
  12523. _frustum = new Frustum(),
  12524. // clipping
  12525. _clipping = new WebGLClipping(),
  12526. _clippingEnabled = false,
  12527. _localClippingEnabled = false,
  12528. // camera matrices cache
  12529. _projScreenMatrix = new Matrix4(),
  12530. _vector3 = new Vector3(),
  12531. // info
  12532. _infoMemory = {
  12533. geometries: 0,
  12534. textures: 0
  12535. },
  12536. _infoRender = {
  12537. frame: 0,
  12538. calls: 0,
  12539. vertices: 0,
  12540. faces: 0,
  12541. points: 0
  12542. };
  12543. this.info = {
  12544. render: _infoRender,
  12545. memory: _infoMemory,
  12546. programs: null
  12547. };
  12548. function getTargetPixelRatio() {
  12549. return _currentRenderTarget === null ? _pixelRatio : 1;
  12550. }
  12551. // initialize
  12552. var _gl;
  12553. try {
  12554. var contextAttributes = {
  12555. alpha: _alpha,
  12556. depth: _depth,
  12557. stencil: _stencil,
  12558. antialias: _antialias,
  12559. premultipliedAlpha: _premultipliedAlpha,
  12560. preserveDrawingBuffer: _preserveDrawingBuffer
  12561. };
  12562. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  12563. if ( _gl === null ) {
  12564. if ( _canvas.getContext( 'webgl' ) !== null ) {
  12565. throw 'Error creating WebGL context with your selected attributes.';
  12566. } else {
  12567. throw 'Error creating WebGL context.';
  12568. }
  12569. }
  12570. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  12571. if ( _gl.getShaderPrecisionFormat === undefined ) {
  12572. _gl.getShaderPrecisionFormat = function () {
  12573. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  12574. };
  12575. }
  12576. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  12577. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  12578. } catch ( error ) {
  12579. console.error( 'THREE.WebGLRenderer: ' + error );
  12580. }
  12581. var extensions, capabilities, state;
  12582. var properties, textures, attributes, geometries, objects, lights;
  12583. var programCache, renderLists;
  12584. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  12585. var flareRenderer, spriteRenderer;
  12586. var utils;
  12587. function initGLContext() {
  12588. extensions = new WebGLExtensions( _gl );
  12589. extensions.get( 'WEBGL_depth_texture' );
  12590. extensions.get( 'OES_texture_float' );
  12591. extensions.get( 'OES_texture_float_linear' );
  12592. extensions.get( 'OES_texture_half_float' );
  12593. extensions.get( 'OES_texture_half_float_linear' );
  12594. extensions.get( 'OES_standard_derivatives' );
  12595. extensions.get( 'ANGLE_instanced_arrays' );
  12596. if ( extensions.get( 'OES_element_index_uint' ) ) {
  12597. BufferGeometry.MaxIndex = 4294967296;
  12598. }
  12599. utils = new WebGLUtils( _gl, extensions );
  12600. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  12601. state = new WebGLState( _gl, extensions, utils );
  12602. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  12603. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  12604. properties = new WebGLProperties();
  12605. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, _infoMemory );
  12606. attributes = new WebGLAttributes( _gl );
  12607. geometries = new WebGLGeometries( _gl, attributes, _infoMemory );
  12608. objects = new WebGLObjects( geometries, _infoRender );
  12609. morphtargets = new WebGLMorphtargets( _gl );
  12610. programCache = new WebGLPrograms( _this, extensions, capabilities );
  12611. lights = new WebGLLights();
  12612. renderLists = new WebGLRenderLists();
  12613. background = new WebGLBackground( _this, state, geometries, _premultipliedAlpha );
  12614. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  12615. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  12616. flareRenderer = new WebGLFlareRenderer( _this, _gl, state, textures, capabilities );
  12617. spriteRenderer = new WebGLSpriteRenderer( _this, _gl, state, textures, capabilities );
  12618. _this.info.programs = programCache.programs;
  12619. _this.context = _gl;
  12620. _this.capabilities = capabilities;
  12621. _this.extensions = extensions;
  12622. _this.properties = properties;
  12623. _this.renderLists = renderLists;
  12624. _this.state = state;
  12625. }
  12626. initGLContext();
  12627. // vr
  12628. var vr = new WebVRManager( _this );
  12629. this.vr = vr;
  12630. // shadow map
  12631. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  12632. this.shadowMap = shadowMap;
  12633. // API
  12634. this.getContext = function () {
  12635. return _gl;
  12636. };
  12637. this.getContextAttributes = function () {
  12638. return _gl.getContextAttributes();
  12639. };
  12640. this.forceContextLoss = function () {
  12641. var extension = extensions.get( 'WEBGL_lose_context' );
  12642. if ( extension ) extension.loseContext();
  12643. };
  12644. this.forceContextRestore = function () {
  12645. var extension = extensions.get( 'WEBGL_lose_context' );
  12646. if ( extension ) extension.restoreContext();
  12647. };
  12648. this.getPixelRatio = function () {
  12649. return _pixelRatio;
  12650. };
  12651. this.setPixelRatio = function ( value ) {
  12652. if ( value === undefined ) return;
  12653. _pixelRatio = value;
  12654. this.setSize( _width, _height, false );
  12655. };
  12656. this.getSize = function () {
  12657. return {
  12658. width: _width,
  12659. height: _height
  12660. };
  12661. };
  12662. this.setSize = function ( width, height, updateStyle ) {
  12663. var device = vr.getDevice();
  12664. if ( device && device.isPresenting ) {
  12665. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  12666. return;
  12667. }
  12668. _width = width;
  12669. _height = height;
  12670. _canvas.width = width * _pixelRatio;
  12671. _canvas.height = height * _pixelRatio;
  12672. if ( updateStyle !== false ) {
  12673. _canvas.style.width = width + 'px';
  12674. _canvas.style.height = height + 'px';
  12675. }
  12676. this.setViewport( 0, 0, width, height );
  12677. };
  12678. this.getDrawingBufferSize = function () {
  12679. return {
  12680. width: _width * _pixelRatio,
  12681. height: _height * _pixelRatio
  12682. };
  12683. };
  12684. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  12685. _width = width;
  12686. _height = height;
  12687. _pixelRatio = pixelRatio;
  12688. _canvas.width = width * pixelRatio;
  12689. _canvas.height = height * pixelRatio;
  12690. this.setViewport( 0, 0, width, height );
  12691. };
  12692. this.setViewport = function ( x, y, width, height ) {
  12693. _viewport.set( x, _height - y - height, width, height );
  12694. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  12695. };
  12696. this.setScissor = function ( x, y, width, height ) {
  12697. _scissor.set( x, _height - y - height, width, height );
  12698. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  12699. };
  12700. this.setScissorTest = function ( boolean ) {
  12701. state.setScissorTest( _scissorTest = boolean );
  12702. };
  12703. // Clearing
  12704. this.getClearColor = background.getClearColor;
  12705. this.setClearColor = background.setClearColor;
  12706. this.getClearAlpha = background.getClearAlpha;
  12707. this.setClearAlpha = background.setClearAlpha;
  12708. this.clear = function ( color, depth, stencil ) {
  12709. var bits = 0;
  12710. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12711. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12712. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12713. _gl.clear( bits );
  12714. };
  12715. this.clearColor = function () {
  12716. this.clear( true, false, false );
  12717. };
  12718. this.clearDepth = function () {
  12719. this.clear( false, true, false );
  12720. };
  12721. this.clearStencil = function () {
  12722. this.clear( false, false, true );
  12723. };
  12724. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12725. this.setRenderTarget( renderTarget );
  12726. this.clear( color, depth, stencil );
  12727. };
  12728. //
  12729. this.dispose = function () {
  12730. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  12731. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  12732. renderLists.dispose();
  12733. vr.dispose();
  12734. };
  12735. // Events
  12736. function onContextLost( event ) {
  12737. event.preventDefault();
  12738. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  12739. _isContextLost = true;
  12740. }
  12741. function onContextRestore( event ) {
  12742. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  12743. _isContextLost = false;
  12744. initGLContext();
  12745. }
  12746. function onMaterialDispose( event ) {
  12747. var material = event.target;
  12748. material.removeEventListener( 'dispose', onMaterialDispose );
  12749. deallocateMaterial( material );
  12750. }
  12751. // Buffer deallocation
  12752. function deallocateMaterial( material ) {
  12753. releaseMaterialProgramReference( material );
  12754. properties.remove( material );
  12755. }
  12756. function releaseMaterialProgramReference( material ) {
  12757. var programInfo = properties.get( material ).program;
  12758. material.program = undefined;
  12759. if ( programInfo !== undefined ) {
  12760. programCache.releaseProgram( programInfo );
  12761. }
  12762. }
  12763. // Buffer rendering
  12764. function renderObjectImmediate( object, program, material ) {
  12765. object.render( function ( object ) {
  12766. _this.renderBufferImmediate( object, program, material );
  12767. } );
  12768. }
  12769. this.renderBufferImmediate = function ( object, program, material ) {
  12770. state.initAttributes();
  12771. var buffers = properties.get( object );
  12772. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  12773. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  12774. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  12775. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  12776. var programAttributes = program.getAttributes();
  12777. if ( object.hasPositions ) {
  12778. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  12779. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12780. state.enableAttribute( programAttributes.position );
  12781. _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12782. }
  12783. if ( object.hasNormals ) {
  12784. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  12785. if ( ! material.isMeshPhongMaterial &&
  12786. ! material.isMeshStandardMaterial &&
  12787. ! material.isMeshNormalMaterial &&
  12788. material.flatShading === true ) {
  12789. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  12790. var array = object.normalArray;
  12791. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  12792. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  12793. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  12794. array[ i + 0 ] = nx;
  12795. array[ i + 1 ] = ny;
  12796. array[ i + 2 ] = nz;
  12797. array[ i + 3 ] = nx;
  12798. array[ i + 4 ] = ny;
  12799. array[ i + 5 ] = nz;
  12800. array[ i + 6 ] = nx;
  12801. array[ i + 7 ] = ny;
  12802. array[ i + 8 ] = nz;
  12803. }
  12804. }
  12805. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12806. state.enableAttribute( programAttributes.normal );
  12807. _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12808. }
  12809. if ( object.hasUvs && material.map ) {
  12810. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  12811. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12812. state.enableAttribute( programAttributes.uv );
  12813. _gl.vertexAttribPointer( programAttributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12814. }
  12815. if ( object.hasColors && material.vertexColors !== NoColors ) {
  12816. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  12817. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12818. state.enableAttribute( programAttributes.color );
  12819. _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12820. }
  12821. state.disableUnusedAttributes();
  12822. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12823. object.count = 0;
  12824. };
  12825. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  12826. state.setMaterial( material );
  12827. var program = setProgram( camera, fog, material, object );
  12828. var geometryProgram = geometry.id + '_' + program.id + '_' + ( material.wireframe === true );
  12829. var updateBuffers = false;
  12830. if ( geometryProgram !== _currentGeometryProgram ) {
  12831. _currentGeometryProgram = geometryProgram;
  12832. updateBuffers = true;
  12833. }
  12834. if ( object.morphTargetInfluences ) {
  12835. morphtargets.update( object, geometry, material, program );
  12836. updateBuffers = true;
  12837. }
  12838. //
  12839. var index = geometry.index;
  12840. var position = geometry.attributes.position;
  12841. var rangeFactor = 1;
  12842. if ( material.wireframe === true ) {
  12843. index = geometries.getWireframeAttribute( geometry );
  12844. rangeFactor = 2;
  12845. }
  12846. var attribute;
  12847. var renderer = bufferRenderer;
  12848. if ( index !== null ) {
  12849. attribute = attributes.get( index );
  12850. renderer = indexedBufferRenderer;
  12851. renderer.setIndex( attribute );
  12852. }
  12853. if ( updateBuffers ) {
  12854. setupVertexAttributes( material, program, geometry );
  12855. if ( index !== null ) {
  12856. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attribute.buffer );
  12857. }
  12858. }
  12859. //
  12860. var dataCount = 0;
  12861. if ( index !== null ) {
  12862. dataCount = index.count;
  12863. } else if ( position !== undefined ) {
  12864. dataCount = position.count;
  12865. }
  12866. var rangeStart = geometry.drawRange.start * rangeFactor;
  12867. var rangeCount = geometry.drawRange.count * rangeFactor;
  12868. var groupStart = group !== null ? group.start * rangeFactor : 0;
  12869. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  12870. var drawStart = Math.max( rangeStart, groupStart );
  12871. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  12872. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  12873. if ( drawCount === 0 ) return;
  12874. //
  12875. if ( object.isMesh ) {
  12876. if ( material.wireframe === true ) {
  12877. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  12878. renderer.setMode( _gl.LINES );
  12879. } else {
  12880. switch ( object.drawMode ) {
  12881. case TrianglesDrawMode:
  12882. renderer.setMode( _gl.TRIANGLES );
  12883. break;
  12884. case TriangleStripDrawMode:
  12885. renderer.setMode( _gl.TRIANGLE_STRIP );
  12886. break;
  12887. case TriangleFanDrawMode:
  12888. renderer.setMode( _gl.TRIANGLE_FAN );
  12889. break;
  12890. }
  12891. }
  12892. } else if ( object.isLine ) {
  12893. var lineWidth = material.linewidth;
  12894. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  12895. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  12896. if ( object.isLineSegments ) {
  12897. renderer.setMode( _gl.LINES );
  12898. } else if ( object.isLineLoop ) {
  12899. renderer.setMode( _gl.LINE_LOOP );
  12900. } else {
  12901. renderer.setMode( _gl.LINE_STRIP );
  12902. }
  12903. } else if ( object.isPoints ) {
  12904. renderer.setMode( _gl.POINTS );
  12905. }
  12906. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12907. if ( geometry.maxInstancedCount > 0 ) {
  12908. renderer.renderInstances( geometry, drawStart, drawCount );
  12909. }
  12910. } else {
  12911. renderer.render( drawStart, drawCount );
  12912. }
  12913. };
  12914. function setupVertexAttributes( material, program, geometry, startIndex ) {
  12915. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12916. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  12917. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12918. return;
  12919. }
  12920. }
  12921. if ( startIndex === undefined ) startIndex = 0;
  12922. state.initAttributes();
  12923. var geometryAttributes = geometry.attributes;
  12924. var programAttributes = program.getAttributes();
  12925. var materialDefaultAttributeValues = material.defaultAttributeValues;
  12926. for ( var name in programAttributes ) {
  12927. var programAttribute = programAttributes[ name ];
  12928. if ( programAttribute >= 0 ) {
  12929. var geometryAttribute = geometryAttributes[ name ];
  12930. if ( geometryAttribute !== undefined ) {
  12931. var normalized = geometryAttribute.normalized;
  12932. var size = geometryAttribute.itemSize;
  12933. var attribute = attributes.get( geometryAttribute );
  12934. // TODO Attribute may not be available on context restore
  12935. if ( attribute === undefined ) continue;
  12936. var buffer = attribute.buffer;
  12937. var type = attribute.type;
  12938. var bytesPerElement = attribute.bytesPerElement;
  12939. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  12940. var data = geometryAttribute.data;
  12941. var stride = data.stride;
  12942. var offset = geometryAttribute.offset;
  12943. if ( data && data.isInstancedInterleavedBuffer ) {
  12944. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  12945. if ( geometry.maxInstancedCount === undefined ) {
  12946. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  12947. }
  12948. } else {
  12949. state.enableAttribute( programAttribute );
  12950. }
  12951. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12952. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  12953. } else {
  12954. if ( geometryAttribute.isInstancedBufferAttribute ) {
  12955. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  12956. if ( geometry.maxInstancedCount === undefined ) {
  12957. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  12958. }
  12959. } else {
  12960. state.enableAttribute( programAttribute );
  12961. }
  12962. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12963. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  12964. }
  12965. } else if ( materialDefaultAttributeValues !== undefined ) {
  12966. var value = materialDefaultAttributeValues[ name ];
  12967. if ( value !== undefined ) {
  12968. switch ( value.length ) {
  12969. case 2:
  12970. _gl.vertexAttrib2fv( programAttribute, value );
  12971. break;
  12972. case 3:
  12973. _gl.vertexAttrib3fv( programAttribute, value );
  12974. break;
  12975. case 4:
  12976. _gl.vertexAttrib4fv( programAttribute, value );
  12977. break;
  12978. default:
  12979. _gl.vertexAttrib1fv( programAttribute, value );
  12980. }
  12981. }
  12982. }
  12983. }
  12984. }
  12985. state.disableUnusedAttributes();
  12986. }
  12987. // Compile
  12988. this.compile = function ( scene, camera ) {
  12989. lightsArray.length = 0;
  12990. shadowsArray.length = 0;
  12991. scene.traverse( function ( object ) {
  12992. if ( object.isLight ) {
  12993. lightsArray.push( object );
  12994. if ( object.castShadow ) {
  12995. shadowsArray.push( object );
  12996. }
  12997. }
  12998. } );
  12999. lights.setup( lightsArray, shadowsArray, camera );
  13000. scene.traverse( function ( object ) {
  13001. if ( object.material ) {
  13002. if ( Array.isArray( object.material ) ) {
  13003. for ( var i = 0; i < object.material.length; i ++ ) {
  13004. initMaterial( object.material[ i ], scene.fog, object );
  13005. }
  13006. } else {
  13007. initMaterial( object.material, scene.fog, object );
  13008. }
  13009. }
  13010. } );
  13011. };
  13012. // Animation Loop
  13013. var isAnimating = false;
  13014. var onAnimationFrame = null;
  13015. function start() {
  13016. if ( isAnimating ) return;
  13017. ( vr.getDevice() || window ).requestAnimationFrame( loop );
  13018. isAnimating = true;
  13019. }
  13020. function loop( time ) {
  13021. if ( onAnimationFrame !== null ) onAnimationFrame( time );
  13022. ( vr.getDevice() || window ).requestAnimationFrame( loop );
  13023. }
  13024. this.animate = function ( callback ) {
  13025. onAnimationFrame = callback;
  13026. start();
  13027. };
  13028. // Rendering
  13029. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13030. if ( ! ( camera && camera.isCamera ) ) {
  13031. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13032. return;
  13033. }
  13034. if ( _isContextLost ) return;
  13035. // reset caching for this frame
  13036. _currentGeometryProgram = '';
  13037. _currentMaterialId = - 1;
  13038. _currentCamera = null;
  13039. // update scene graph
  13040. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13041. // update camera matrices and frustum
  13042. if ( camera.parent === null ) camera.updateMatrixWorld();
  13043. if ( vr.enabled ) {
  13044. camera = vr.getCamera( camera );
  13045. }
  13046. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13047. _frustum.setFromMatrix( _projScreenMatrix );
  13048. lightsArray.length = 0;
  13049. shadowsArray.length = 0;
  13050. spritesArray.length = 0;
  13051. flaresArray.length = 0;
  13052. _localClippingEnabled = this.localClippingEnabled;
  13053. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  13054. currentRenderList = renderLists.get( scene, camera );
  13055. currentRenderList.init();
  13056. projectObject( scene, camera, _this.sortObjects );
  13057. if ( _this.sortObjects === true ) {
  13058. currentRenderList.sort();
  13059. }
  13060. //
  13061. if ( _clippingEnabled ) _clipping.beginShadows();
  13062. shadowMap.render( shadowsArray, scene, camera );
  13063. lights.setup( lightsArray, shadowsArray, camera );
  13064. if ( _clippingEnabled ) _clipping.endShadows();
  13065. //
  13066. _infoRender.frame ++;
  13067. _infoRender.calls = 0;
  13068. _infoRender.vertices = 0;
  13069. _infoRender.faces = 0;
  13070. _infoRender.points = 0;
  13071. if ( renderTarget === undefined ) {
  13072. renderTarget = null;
  13073. }
  13074. this.setRenderTarget( renderTarget );
  13075. //
  13076. background.render( currentRenderList, scene, camera, forceClear );
  13077. // render scene
  13078. var opaqueObjects = currentRenderList.opaque;
  13079. var transparentObjects = currentRenderList.transparent;
  13080. if ( scene.overrideMaterial ) {
  13081. var overrideMaterial = scene.overrideMaterial;
  13082. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  13083. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  13084. } else {
  13085. // opaque pass (front-to-back order)
  13086. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  13087. // transparent pass (back-to-front order)
  13088. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  13089. }
  13090. // custom renderers
  13091. spriteRenderer.render( spritesArray, scene, camera );
  13092. flareRenderer.render( flaresArray, scene, camera, _currentViewport );
  13093. // Generate mipmap if we're using any kind of mipmap filtering
  13094. if ( renderTarget ) {
  13095. textures.updateRenderTargetMipmap( renderTarget );
  13096. }
  13097. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13098. state.buffers.depth.setTest( true );
  13099. state.buffers.depth.setMask( true );
  13100. state.buffers.color.setMask( true );
  13101. state.setPolygonOffset( false );
  13102. if ( vr.enabled ) {
  13103. vr.submitFrame();
  13104. }
  13105. // _gl.finish();
  13106. };
  13107. /*
  13108. // TODO Duplicated code (Frustum)
  13109. var _sphere = new Sphere();
  13110. function isObjectViewable( object ) {
  13111. var geometry = object.geometry;
  13112. if ( geometry.boundingSphere === null )
  13113. geometry.computeBoundingSphere();
  13114. _sphere.copy( geometry.boundingSphere ).
  13115. applyMatrix4( object.matrixWorld );
  13116. return isSphereViewable( _sphere );
  13117. }
  13118. function isSpriteViewable( sprite ) {
  13119. _sphere.center.set( 0, 0, 0 );
  13120. _sphere.radius = 0.7071067811865476;
  13121. _sphere.applyMatrix4( sprite.matrixWorld );
  13122. return isSphereViewable( _sphere );
  13123. }
  13124. function isSphereViewable( sphere ) {
  13125. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  13126. var numPlanes = _clipping.numPlanes;
  13127. if ( numPlanes === 0 ) return true;
  13128. var planes = _this.clippingPlanes,
  13129. center = sphere.center,
  13130. negRad = - sphere.radius,
  13131. i = 0;
  13132. do {
  13133. // out when deeper than radius in the negative halfspace
  13134. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  13135. } while ( ++ i !== numPlanes );
  13136. return true;
  13137. }
  13138. */
  13139. function projectObject( object, camera, sortObjects ) {
  13140. if ( ! object.visible ) return;
  13141. var visible = object.layers.test( camera.layers );
  13142. if ( visible ) {
  13143. if ( object.isLight ) {
  13144. lightsArray.push( object );
  13145. if ( object.castShadow ) {
  13146. shadowsArray.push( object );
  13147. }
  13148. } else if ( object.isSprite ) {
  13149. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  13150. spritesArray.push( object );
  13151. }
  13152. } else if ( object.isLensFlare ) {
  13153. flaresArray.push( object );
  13154. } else if ( object.isImmediateRenderObject ) {
  13155. if ( sortObjects ) {
  13156. _vector3.setFromMatrixPosition( object.matrixWorld )
  13157. .applyMatrix4( _projScreenMatrix );
  13158. }
  13159. currentRenderList.push( object, null, object.material, _vector3.z, null );
  13160. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  13161. if ( object.isSkinnedMesh ) {
  13162. object.skeleton.update();
  13163. }
  13164. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  13165. if ( sortObjects ) {
  13166. _vector3.setFromMatrixPosition( object.matrixWorld )
  13167. .applyMatrix4( _projScreenMatrix );
  13168. }
  13169. var geometry = objects.update( object );
  13170. var material = object.material;
  13171. if ( Array.isArray( material ) ) {
  13172. var groups = geometry.groups;
  13173. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  13174. var group = groups[ i ];
  13175. var groupMaterial = material[ group.materialIndex ];
  13176. if ( groupMaterial && groupMaterial.visible ) {
  13177. currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group );
  13178. }
  13179. }
  13180. } else if ( material.visible ) {
  13181. currentRenderList.push( object, geometry, material, _vector3.z, null );
  13182. }
  13183. }
  13184. }
  13185. }
  13186. var children = object.children;
  13187. for ( var i = 0, l = children.length; i < l; i ++ ) {
  13188. projectObject( children[ i ], camera, sortObjects );
  13189. }
  13190. }
  13191. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  13192. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  13193. var renderItem = renderList[ i ];
  13194. var object = renderItem.object;
  13195. var geometry = renderItem.geometry;
  13196. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  13197. var group = renderItem.group;
  13198. if ( camera.isArrayCamera ) {
  13199. _currentArrayCamera = camera;
  13200. var cameras = camera.cameras;
  13201. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  13202. var camera2 = cameras[ j ];
  13203. if ( object.layers.test( camera2.layers ) ) {
  13204. var bounds = camera2.bounds;
  13205. var x = bounds.x * _width;
  13206. var y = bounds.y * _height;
  13207. var width = bounds.z * _width;
  13208. var height = bounds.w * _height;
  13209. state.viewport( _currentViewport.set( x, y, width, height ).multiplyScalar( _pixelRatio ) );
  13210. renderObject( object, scene, camera2, geometry, material, group );
  13211. }
  13212. }
  13213. } else {
  13214. _currentArrayCamera = null;
  13215. renderObject( object, scene, camera, geometry, material, group );
  13216. }
  13217. }
  13218. }
  13219. function renderObject( object, scene, camera, geometry, material, group ) {
  13220. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  13221. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  13222. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  13223. if ( object.isImmediateRenderObject ) {
  13224. state.setMaterial( material );
  13225. var program = setProgram( camera, scene.fog, material, object );
  13226. _currentGeometryProgram = '';
  13227. renderObjectImmediate( object, program, material );
  13228. } else {
  13229. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  13230. }
  13231. object.onAfterRender( _this, scene, camera, geometry, material, group );
  13232. }
  13233. function initMaterial( material, fog, object ) {
  13234. var materialProperties = properties.get( material );
  13235. var parameters = programCache.getParameters(
  13236. material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  13237. var code = programCache.getProgramCode( material, parameters );
  13238. var program = materialProperties.program;
  13239. var programChange = true;
  13240. if ( program === undefined ) {
  13241. // new material
  13242. material.addEventListener( 'dispose', onMaterialDispose );
  13243. } else if ( program.code !== code ) {
  13244. // changed glsl or parameters
  13245. releaseMaterialProgramReference( material );
  13246. } else if ( parameters.shaderID !== undefined ) {
  13247. // same glsl and uniform list
  13248. return;
  13249. } else {
  13250. // only rebuild uniform list
  13251. programChange = false;
  13252. }
  13253. if ( programChange ) {
  13254. if ( parameters.shaderID ) {
  13255. var shader = ShaderLib[ parameters.shaderID ];
  13256. materialProperties.shader = {
  13257. name: material.type,
  13258. uniforms: UniformsUtils.clone( shader.uniforms ),
  13259. vertexShader: shader.vertexShader,
  13260. fragmentShader: shader.fragmentShader
  13261. };
  13262. } else {
  13263. materialProperties.shader = {
  13264. name: material.type,
  13265. uniforms: material.uniforms,
  13266. vertexShader: material.vertexShader,
  13267. fragmentShader: material.fragmentShader
  13268. };
  13269. }
  13270. material.onBeforeCompile( materialProperties.shader );
  13271. program = programCache.acquireProgram( material, materialProperties.shader, parameters, code );
  13272. materialProperties.program = program;
  13273. material.program = program;
  13274. }
  13275. var programAttributes = program.getAttributes();
  13276. if ( material.morphTargets ) {
  13277. material.numSupportedMorphTargets = 0;
  13278. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  13279. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  13280. material.numSupportedMorphTargets ++;
  13281. }
  13282. }
  13283. }
  13284. if ( material.morphNormals ) {
  13285. material.numSupportedMorphNormals = 0;
  13286. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  13287. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  13288. material.numSupportedMorphNormals ++;
  13289. }
  13290. }
  13291. }
  13292. var uniforms = materialProperties.shader.uniforms;
  13293. if ( ! material.isShaderMaterial &&
  13294. ! material.isRawShaderMaterial ||
  13295. material.clipping === true ) {
  13296. materialProperties.numClippingPlanes = _clipping.numPlanes;
  13297. materialProperties.numIntersection = _clipping.numIntersection;
  13298. uniforms.clippingPlanes = _clipping.uniform;
  13299. }
  13300. materialProperties.fog = fog;
  13301. // store the light setup it was created for
  13302. materialProperties.lightsHash = lights.state.hash;
  13303. if ( material.lights ) {
  13304. // wire up the material to this renderer's lighting state
  13305. uniforms.ambientLightColor.value = lights.state.ambient;
  13306. uniforms.directionalLights.value = lights.state.directional;
  13307. uniforms.spotLights.value = lights.state.spot;
  13308. uniforms.rectAreaLights.value = lights.state.rectArea;
  13309. uniforms.pointLights.value = lights.state.point;
  13310. uniforms.hemisphereLights.value = lights.state.hemi;
  13311. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  13312. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  13313. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  13314. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  13315. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  13316. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  13317. // TODO (abelnation): add area lights shadow info to uniforms
  13318. }
  13319. var progUniforms = materialProperties.program.getUniforms(),
  13320. uniformsList =
  13321. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  13322. materialProperties.uniformsList = uniformsList;
  13323. }
  13324. function setProgram( camera, fog, material, object ) {
  13325. _usedTextureUnits = 0;
  13326. var materialProperties = properties.get( material );
  13327. if ( _clippingEnabled ) {
  13328. if ( _localClippingEnabled || camera !== _currentCamera ) {
  13329. var useCache =
  13330. camera === _currentCamera &&
  13331. material.id === _currentMaterialId;
  13332. // we might want to call this function with some ClippingGroup
  13333. // object instead of the material, once it becomes feasible
  13334. // (#8465, #8379)
  13335. _clipping.setState(
  13336. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  13337. camera, materialProperties, useCache );
  13338. }
  13339. }
  13340. if ( material.needsUpdate === false ) {
  13341. if ( materialProperties.program === undefined ) {
  13342. material.needsUpdate = true;
  13343. } else if ( material.fog && materialProperties.fog !== fog ) {
  13344. material.needsUpdate = true;
  13345. } else if ( material.lights && materialProperties.lightsHash !== lights.state.hash ) {
  13346. material.needsUpdate = true;
  13347. } else if ( materialProperties.numClippingPlanes !== undefined &&
  13348. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  13349. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  13350. material.needsUpdate = true;
  13351. }
  13352. }
  13353. if ( material.needsUpdate ) {
  13354. initMaterial( material, fog, object );
  13355. material.needsUpdate = false;
  13356. }
  13357. var refreshProgram = false;
  13358. var refreshMaterial = false;
  13359. var refreshLights = false;
  13360. var program = materialProperties.program,
  13361. p_uniforms = program.getUniforms(),
  13362. m_uniforms = materialProperties.shader.uniforms;
  13363. if ( state.useProgram( program.program ) ) {
  13364. refreshProgram = true;
  13365. refreshMaterial = true;
  13366. refreshLights = true;
  13367. }
  13368. if ( material.id !== _currentMaterialId ) {
  13369. _currentMaterialId = material.id;
  13370. refreshMaterial = true;
  13371. }
  13372. if ( refreshProgram || camera !== _currentCamera ) {
  13373. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  13374. if ( capabilities.logarithmicDepthBuffer ) {
  13375. p_uniforms.setValue( _gl, 'logDepthBufFC',
  13376. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  13377. }
  13378. // Avoid unneeded uniform updates per ArrayCamera's sub-camera
  13379. if ( _currentCamera !== ( _currentArrayCamera || camera ) ) {
  13380. _currentCamera = ( _currentArrayCamera || camera );
  13381. // lighting uniforms depend on the camera so enforce an update
  13382. // now, in case this material supports lights - or later, when
  13383. // the next material that does gets activated:
  13384. refreshMaterial = true; // set to true on material change
  13385. refreshLights = true; // remains set until update done
  13386. }
  13387. // load material specific uniforms
  13388. // (shader material also gets them for the sake of genericity)
  13389. if ( material.isShaderMaterial ||
  13390. material.isMeshPhongMaterial ||
  13391. material.isMeshStandardMaterial ||
  13392. material.envMap ) {
  13393. var uCamPos = p_uniforms.map.cameraPosition;
  13394. if ( uCamPos !== undefined ) {
  13395. uCamPos.setValue( _gl,
  13396. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  13397. }
  13398. }
  13399. if ( material.isMeshPhongMaterial ||
  13400. material.isMeshLambertMaterial ||
  13401. material.isMeshBasicMaterial ||
  13402. material.isMeshStandardMaterial ||
  13403. material.isShaderMaterial ||
  13404. material.skinning ) {
  13405. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  13406. }
  13407. }
  13408. // skinning uniforms must be set even if material didn't change
  13409. // auto-setting of texture unit for bone texture must go before other textures
  13410. // not sure why, but otherwise weird things happen
  13411. if ( material.skinning ) {
  13412. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  13413. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  13414. var skeleton = object.skeleton;
  13415. if ( skeleton ) {
  13416. var bones = skeleton.bones;
  13417. if ( capabilities.floatVertexTextures ) {
  13418. if ( skeleton.boneTexture === undefined ) {
  13419. // layout (1 matrix = 4 pixels)
  13420. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13421. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13422. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13423. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13424. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13425. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  13426. size = _Math.nextPowerOfTwo( Math.ceil( size ) );
  13427. size = Math.max( size, 4 );
  13428. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  13429. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  13430. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  13431. skeleton.boneMatrices = boneMatrices;
  13432. skeleton.boneTexture = boneTexture;
  13433. skeleton.boneTextureSize = size;
  13434. }
  13435. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture );
  13436. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  13437. } else {
  13438. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  13439. }
  13440. }
  13441. }
  13442. if ( refreshMaterial ) {
  13443. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  13444. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  13445. if ( material.lights ) {
  13446. // the current material requires lighting info
  13447. // note: all lighting uniforms are always set correctly
  13448. // they simply reference the renderer's state for their
  13449. // values
  13450. //
  13451. // use the current material's .needsUpdate flags to set
  13452. // the GL state when required
  13453. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  13454. }
  13455. // refresh uniforms common to several materials
  13456. if ( fog && material.fog ) {
  13457. refreshUniformsFog( m_uniforms, fog );
  13458. }
  13459. if ( material.isMeshBasicMaterial ) {
  13460. refreshUniformsCommon( m_uniforms, material );
  13461. } else if ( material.isMeshLambertMaterial ) {
  13462. refreshUniformsCommon( m_uniforms, material );
  13463. refreshUniformsLambert( m_uniforms, material );
  13464. } else if ( material.isMeshPhongMaterial ) {
  13465. refreshUniformsCommon( m_uniforms, material );
  13466. if ( material.isMeshToonMaterial ) {
  13467. refreshUniformsToon( m_uniforms, material );
  13468. } else {
  13469. refreshUniformsPhong( m_uniforms, material );
  13470. }
  13471. } else if ( material.isMeshStandardMaterial ) {
  13472. refreshUniformsCommon( m_uniforms, material );
  13473. if ( material.isMeshPhysicalMaterial ) {
  13474. refreshUniformsPhysical( m_uniforms, material );
  13475. } else {
  13476. refreshUniformsStandard( m_uniforms, material );
  13477. }
  13478. } else if ( material.isMeshDepthMaterial ) {
  13479. refreshUniformsCommon( m_uniforms, material );
  13480. refreshUniformsDepth( m_uniforms, material );
  13481. } else if ( material.isMeshDistanceMaterial ) {
  13482. refreshUniformsCommon( m_uniforms, material );
  13483. refreshUniformsDistance( m_uniforms, material );
  13484. } else if ( material.isMeshNormalMaterial ) {
  13485. refreshUniformsCommon( m_uniforms, material );
  13486. refreshUniformsNormal( m_uniforms, material );
  13487. } else if ( material.isLineBasicMaterial ) {
  13488. refreshUniformsLine( m_uniforms, material );
  13489. if ( material.isLineDashedMaterial ) {
  13490. refreshUniformsDash( m_uniforms, material );
  13491. }
  13492. } else if ( material.isPointsMaterial ) {
  13493. refreshUniformsPoints( m_uniforms, material );
  13494. } else if ( material.isShadowMaterial ) {
  13495. m_uniforms.color.value = material.color;
  13496. m_uniforms.opacity.value = material.opacity;
  13497. }
  13498. // RectAreaLight Texture
  13499. // TODO (mrdoob): Find a nicer implementation
  13500. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = UniformsLib.LTC_MAT_TEXTURE;
  13501. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = UniformsLib.LTC_MAG_TEXTURE;
  13502. WebGLUniforms.upload(
  13503. _gl, materialProperties.uniformsList, m_uniforms, _this );
  13504. }
  13505. // common matrices
  13506. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  13507. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  13508. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  13509. return program;
  13510. }
  13511. // Uniforms (refresh uniforms objects)
  13512. function refreshUniformsCommon( uniforms, material ) {
  13513. uniforms.opacity.value = material.opacity;
  13514. if ( material.color ) {
  13515. uniforms.diffuse.value = material.color;
  13516. }
  13517. if ( material.emissive ) {
  13518. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  13519. }
  13520. if ( material.map ) {
  13521. uniforms.map.value = material.map;
  13522. }
  13523. if ( material.alphaMap ) {
  13524. uniforms.alphaMap.value = material.alphaMap;
  13525. }
  13526. if ( material.specularMap ) {
  13527. uniforms.specularMap.value = material.specularMap;
  13528. }
  13529. if ( material.envMap ) {
  13530. uniforms.envMap.value = material.envMap;
  13531. // don't flip CubeTexture envMaps, flip everything else:
  13532. // WebGLRenderTargetCube will be flipped for backwards compatibility
  13533. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  13534. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  13535. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  13536. uniforms.reflectivity.value = material.reflectivity;
  13537. uniforms.refractionRatio.value = material.refractionRatio;
  13538. }
  13539. if ( material.lightMap ) {
  13540. uniforms.lightMap.value = material.lightMap;
  13541. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13542. }
  13543. if ( material.aoMap ) {
  13544. uniforms.aoMap.value = material.aoMap;
  13545. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13546. }
  13547. // uv repeat and offset setting priorities
  13548. // 1. color map
  13549. // 2. specular map
  13550. // 3. normal map
  13551. // 4. bump map
  13552. // 5. alpha map
  13553. // 6. emissive map
  13554. var uvScaleMap;
  13555. if ( material.map ) {
  13556. uvScaleMap = material.map;
  13557. } else if ( material.specularMap ) {
  13558. uvScaleMap = material.specularMap;
  13559. } else if ( material.displacementMap ) {
  13560. uvScaleMap = material.displacementMap;
  13561. } else if ( material.normalMap ) {
  13562. uvScaleMap = material.normalMap;
  13563. } else if ( material.bumpMap ) {
  13564. uvScaleMap = material.bumpMap;
  13565. } else if ( material.roughnessMap ) {
  13566. uvScaleMap = material.roughnessMap;
  13567. } else if ( material.metalnessMap ) {
  13568. uvScaleMap = material.metalnessMap;
  13569. } else if ( material.alphaMap ) {
  13570. uvScaleMap = material.alphaMap;
  13571. } else if ( material.emissiveMap ) {
  13572. uvScaleMap = material.emissiveMap;
  13573. }
  13574. if ( uvScaleMap !== undefined ) {
  13575. // backwards compatibility
  13576. if ( uvScaleMap.isWebGLRenderTarget ) {
  13577. uvScaleMap = uvScaleMap.texture;
  13578. }
  13579. var offset = uvScaleMap.offset;
  13580. var repeat = uvScaleMap.repeat;
  13581. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13582. }
  13583. }
  13584. function refreshUniformsLine( uniforms, material ) {
  13585. uniforms.diffuse.value = material.color;
  13586. uniforms.opacity.value = material.opacity;
  13587. }
  13588. function refreshUniformsDash( uniforms, material ) {
  13589. uniforms.dashSize.value = material.dashSize;
  13590. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13591. uniforms.scale.value = material.scale;
  13592. }
  13593. function refreshUniformsPoints( uniforms, material ) {
  13594. uniforms.diffuse.value = material.color;
  13595. uniforms.opacity.value = material.opacity;
  13596. uniforms.size.value = material.size * _pixelRatio;
  13597. uniforms.scale.value = _height * 0.5;
  13598. uniforms.map.value = material.map;
  13599. if ( material.map !== null ) {
  13600. var offset = material.map.offset;
  13601. var repeat = material.map.repeat;
  13602. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13603. }
  13604. }
  13605. function refreshUniformsFog( uniforms, fog ) {
  13606. uniforms.fogColor.value = fog.color;
  13607. if ( fog.isFog ) {
  13608. uniforms.fogNear.value = fog.near;
  13609. uniforms.fogFar.value = fog.far;
  13610. } else if ( fog.isFogExp2 ) {
  13611. uniforms.fogDensity.value = fog.density;
  13612. }
  13613. }
  13614. function refreshUniformsLambert( uniforms, material ) {
  13615. if ( material.emissiveMap ) {
  13616. uniforms.emissiveMap.value = material.emissiveMap;
  13617. }
  13618. }
  13619. function refreshUniformsPhong( uniforms, material ) {
  13620. uniforms.specular.value = material.specular;
  13621. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13622. if ( material.emissiveMap ) {
  13623. uniforms.emissiveMap.value = material.emissiveMap;
  13624. }
  13625. if ( material.bumpMap ) {
  13626. uniforms.bumpMap.value = material.bumpMap;
  13627. uniforms.bumpScale.value = material.bumpScale;
  13628. }
  13629. if ( material.normalMap ) {
  13630. uniforms.normalMap.value = material.normalMap;
  13631. uniforms.normalScale.value.copy( material.normalScale );
  13632. }
  13633. if ( material.displacementMap ) {
  13634. uniforms.displacementMap.value = material.displacementMap;
  13635. uniforms.displacementScale.value = material.displacementScale;
  13636. uniforms.displacementBias.value = material.displacementBias;
  13637. }
  13638. }
  13639. function refreshUniformsToon( uniforms, material ) {
  13640. refreshUniformsPhong( uniforms, material );
  13641. if ( material.gradientMap ) {
  13642. uniforms.gradientMap.value = material.gradientMap;
  13643. }
  13644. }
  13645. function refreshUniformsStandard( uniforms, material ) {
  13646. uniforms.roughness.value = material.roughness;
  13647. uniforms.metalness.value = material.metalness;
  13648. if ( material.roughnessMap ) {
  13649. uniforms.roughnessMap.value = material.roughnessMap;
  13650. }
  13651. if ( material.metalnessMap ) {
  13652. uniforms.metalnessMap.value = material.metalnessMap;
  13653. }
  13654. if ( material.emissiveMap ) {
  13655. uniforms.emissiveMap.value = material.emissiveMap;
  13656. }
  13657. if ( material.bumpMap ) {
  13658. uniforms.bumpMap.value = material.bumpMap;
  13659. uniforms.bumpScale.value = material.bumpScale;
  13660. }
  13661. if ( material.normalMap ) {
  13662. uniforms.normalMap.value = material.normalMap;
  13663. uniforms.normalScale.value.copy( material.normalScale );
  13664. }
  13665. if ( material.displacementMap ) {
  13666. uniforms.displacementMap.value = material.displacementMap;
  13667. uniforms.displacementScale.value = material.displacementScale;
  13668. uniforms.displacementBias.value = material.displacementBias;
  13669. }
  13670. if ( material.envMap ) {
  13671. //uniforms.envMap.value = material.envMap; // part of uniforms common
  13672. uniforms.envMapIntensity.value = material.envMapIntensity;
  13673. }
  13674. }
  13675. function refreshUniformsPhysical( uniforms, material ) {
  13676. uniforms.clearCoat.value = material.clearCoat;
  13677. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  13678. refreshUniformsStandard( uniforms, material );
  13679. }
  13680. function refreshUniformsDepth( uniforms, material ) {
  13681. if ( material.displacementMap ) {
  13682. uniforms.displacementMap.value = material.displacementMap;
  13683. uniforms.displacementScale.value = material.displacementScale;
  13684. uniforms.displacementBias.value = material.displacementBias;
  13685. }
  13686. }
  13687. function refreshUniformsDistance( uniforms, material ) {
  13688. if ( material.displacementMap ) {
  13689. uniforms.displacementMap.value = material.displacementMap;
  13690. uniforms.displacementScale.value = material.displacementScale;
  13691. uniforms.displacementBias.value = material.displacementBias;
  13692. }
  13693. uniforms.referencePosition.value.copy( material.referencePosition );
  13694. uniforms.nearDistance.value = material.nearDistance;
  13695. uniforms.farDistance.value = material.farDistance;
  13696. }
  13697. function refreshUniformsNormal( uniforms, material ) {
  13698. if ( material.bumpMap ) {
  13699. uniforms.bumpMap.value = material.bumpMap;
  13700. uniforms.bumpScale.value = material.bumpScale;
  13701. }
  13702. if ( material.normalMap ) {
  13703. uniforms.normalMap.value = material.normalMap;
  13704. uniforms.normalScale.value.copy( material.normalScale );
  13705. }
  13706. if ( material.displacementMap ) {
  13707. uniforms.displacementMap.value = material.displacementMap;
  13708. uniforms.displacementScale.value = material.displacementScale;
  13709. uniforms.displacementBias.value = material.displacementBias;
  13710. }
  13711. }
  13712. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  13713. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  13714. uniforms.ambientLightColor.needsUpdate = value;
  13715. uniforms.directionalLights.needsUpdate = value;
  13716. uniforms.pointLights.needsUpdate = value;
  13717. uniforms.spotLights.needsUpdate = value;
  13718. uniforms.rectAreaLights.needsUpdate = value;
  13719. uniforms.hemisphereLights.needsUpdate = value;
  13720. }
  13721. // GL state setting
  13722. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13723. state.setCullFace( cullFace );
  13724. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  13725. };
  13726. // Textures
  13727. function allocTextureUnit() {
  13728. var textureUnit = _usedTextureUnits;
  13729. if ( textureUnit >= capabilities.maxTextures ) {
  13730. console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  13731. }
  13732. _usedTextureUnits += 1;
  13733. return textureUnit;
  13734. }
  13735. this.allocTextureUnit = allocTextureUnit;
  13736. // this.setTexture2D = setTexture2D;
  13737. this.setTexture2D = ( function () {
  13738. var warned = false;
  13739. // backwards compatibility: peel texture.texture
  13740. return function setTexture2D( texture, slot ) {
  13741. if ( texture && texture.isWebGLRenderTarget ) {
  13742. if ( ! warned ) {
  13743. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  13744. warned = true;
  13745. }
  13746. texture = texture.texture;
  13747. }
  13748. textures.setTexture2D( texture, slot );
  13749. };
  13750. }() );
  13751. this.setTexture = ( function () {
  13752. var warned = false;
  13753. return function setTexture( texture, slot ) {
  13754. if ( ! warned ) {
  13755. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  13756. warned = true;
  13757. }
  13758. textures.setTexture2D( texture, slot );
  13759. };
  13760. }() );
  13761. this.setTextureCube = ( function () {
  13762. var warned = false;
  13763. return function setTextureCube( texture, slot ) {
  13764. // backwards compatibility: peel texture.texture
  13765. if ( texture && texture.isWebGLRenderTargetCube ) {
  13766. if ( ! warned ) {
  13767. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  13768. warned = true;
  13769. }
  13770. texture = texture.texture;
  13771. }
  13772. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  13773. // TODO: unify these code paths
  13774. if ( ( texture && texture.isCubeTexture ) ||
  13775. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  13776. // CompressedTexture can have Array in image :/
  13777. // this function alone should take care of cube textures
  13778. textures.setTextureCube( texture, slot );
  13779. } else {
  13780. // assumed: texture property of THREE.WebGLRenderTargetCube
  13781. textures.setTextureCubeDynamic( texture, slot );
  13782. }
  13783. };
  13784. }() );
  13785. this.getRenderTarget = function () {
  13786. return _currentRenderTarget;
  13787. };
  13788. this.setRenderTarget = function ( renderTarget ) {
  13789. _currentRenderTarget = renderTarget;
  13790. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  13791. textures.setupRenderTarget( renderTarget );
  13792. }
  13793. var framebuffer = null;
  13794. var isCube = false;
  13795. if ( renderTarget ) {
  13796. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  13797. if ( renderTarget.isWebGLRenderTargetCube ) {
  13798. framebuffer = __webglFramebuffer[ renderTarget.activeCubeFace ];
  13799. isCube = true;
  13800. } else {
  13801. framebuffer = __webglFramebuffer;
  13802. }
  13803. _currentViewport.copy( renderTarget.viewport );
  13804. _currentScissor.copy( renderTarget.scissor );
  13805. _currentScissorTest = renderTarget.scissorTest;
  13806. } else {
  13807. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  13808. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  13809. _currentScissorTest = _scissorTest;
  13810. }
  13811. if ( _currentFramebuffer !== framebuffer ) {
  13812. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13813. _currentFramebuffer = framebuffer;
  13814. }
  13815. state.viewport( _currentViewport );
  13816. state.scissor( _currentScissor );
  13817. state.setScissorTest( _currentScissorTest );
  13818. if ( isCube ) {
  13819. var textureProperties = properties.get( renderTarget.texture );
  13820. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  13821. }
  13822. };
  13823. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  13824. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  13825. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  13826. return;
  13827. }
  13828. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  13829. if ( framebuffer ) {
  13830. var restore = false;
  13831. if ( framebuffer !== _currentFramebuffer ) {
  13832. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13833. restore = true;
  13834. }
  13835. try {
  13836. var texture = renderTarget.texture;
  13837. var textureFormat = texture.format;
  13838. var textureType = texture.type;
  13839. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  13840. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  13841. return;
  13842. }
  13843. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  13844. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  13845. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  13846. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  13847. return;
  13848. }
  13849. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13850. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  13851. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  13852. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  13853. }
  13854. } else {
  13855. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13856. }
  13857. } finally {
  13858. if ( restore ) {
  13859. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13860. }
  13861. }
  13862. }
  13863. };
  13864. }
  13865. /**
  13866. * @author mrdoob / http://mrdoob.com/
  13867. * @author alteredq / http://alteredqualia.com/
  13868. */
  13869. function FogExp2 ( color, density ) {
  13870. this.name = '';
  13871. this.color = new Color( color );
  13872. this.density = ( density !== undefined ) ? density : 0.00025;
  13873. }
  13874. FogExp2.prototype.isFogExp2 = true;
  13875. FogExp2.prototype.clone = function () {
  13876. return new FogExp2( this.color.getHex(), this.density );
  13877. };
  13878. FogExp2.prototype.toJSON = function ( meta ) {
  13879. return {
  13880. type: 'FogExp2',
  13881. color: this.color.getHex(),
  13882. density: this.density
  13883. };
  13884. };
  13885. /**
  13886. * @author mrdoob / http://mrdoob.com/
  13887. * @author alteredq / http://alteredqualia.com/
  13888. */
  13889. function Fog ( color, near, far ) {
  13890. this.name = '';
  13891. this.color = new Color( color );
  13892. this.near = ( near !== undefined ) ? near : 1;
  13893. this.far = ( far !== undefined ) ? far : 1000;
  13894. }
  13895. Fog.prototype.isFog = true;
  13896. Fog.prototype.clone = function () {
  13897. return new Fog( this.color.getHex(), this.near, this.far );
  13898. };
  13899. Fog.prototype.toJSON = function ( meta ) {
  13900. return {
  13901. type: 'Fog',
  13902. color: this.color.getHex(),
  13903. near: this.near,
  13904. far: this.far
  13905. };
  13906. };
  13907. /**
  13908. * @author mrdoob / http://mrdoob.com/
  13909. */
  13910. function Scene () {
  13911. Object3D.call( this );
  13912. this.type = 'Scene';
  13913. this.background = null;
  13914. this.fog = null;
  13915. this.overrideMaterial = null;
  13916. this.autoUpdate = true; // checked by the renderer
  13917. }
  13918. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13919. constructor: Scene,
  13920. copy: function ( source, recursive ) {
  13921. Object3D.prototype.copy.call( this, source, recursive );
  13922. if ( source.background !== null ) this.background = source.background.clone();
  13923. if ( source.fog !== null ) this.fog = source.fog.clone();
  13924. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13925. this.autoUpdate = source.autoUpdate;
  13926. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13927. return this;
  13928. },
  13929. toJSON: function ( meta ) {
  13930. var data = Object3D.prototype.toJSON.call( this, meta );
  13931. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  13932. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13933. return data;
  13934. }
  13935. } );
  13936. /**
  13937. * @author mikael emtinger / http://gomo.se/
  13938. * @author alteredq / http://alteredqualia.com/
  13939. */
  13940. function LensFlare( texture, size, distance, blending, color ) {
  13941. Object3D.call( this );
  13942. this.lensFlares = [];
  13943. this.positionScreen = new Vector3();
  13944. this.customUpdateCallback = undefined;
  13945. if ( texture !== undefined ) {
  13946. this.add( texture, size, distance, blending, color );
  13947. }
  13948. }
  13949. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13950. constructor: LensFlare,
  13951. isLensFlare: true,
  13952. copy: function ( source ) {
  13953. Object3D.prototype.copy.call( this, source );
  13954. this.positionScreen.copy( source.positionScreen );
  13955. this.customUpdateCallback = source.customUpdateCallback;
  13956. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13957. this.lensFlares.push( source.lensFlares[ i ] );
  13958. }
  13959. return this;
  13960. },
  13961. add: function ( texture, size, distance, blending, color, opacity ) {
  13962. if ( size === undefined ) size = - 1;
  13963. if ( distance === undefined ) distance = 0;
  13964. if ( opacity === undefined ) opacity = 1;
  13965. if ( color === undefined ) color = new Color( 0xffffff );
  13966. if ( blending === undefined ) blending = NormalBlending;
  13967. distance = Math.min( distance, Math.max( 0, distance ) );
  13968. this.lensFlares.push( {
  13969. texture: texture, // THREE.Texture
  13970. size: size, // size in pixels (-1 = use texture.width)
  13971. distance: distance, // distance (0-1) from light source (0=at light source)
  13972. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13973. scale: 1, // scale
  13974. rotation: 0, // rotation
  13975. opacity: opacity, // opacity
  13976. color: color, // color
  13977. blending: blending // blending
  13978. } );
  13979. },
  13980. /*
  13981. * Update lens flares update positions on all flares based on the screen position
  13982. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13983. */
  13984. updateLensFlares: function () {
  13985. var f, fl = this.lensFlares.length;
  13986. var flare;
  13987. var vecX = - this.positionScreen.x * 2;
  13988. var vecY = - this.positionScreen.y * 2;
  13989. for ( f = 0; f < fl; f ++ ) {
  13990. flare = this.lensFlares[ f ];
  13991. flare.x = this.positionScreen.x + vecX * flare.distance;
  13992. flare.y = this.positionScreen.y + vecY * flare.distance;
  13993. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13994. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13995. }
  13996. }
  13997. } );
  13998. /**
  13999. * @author alteredq / http://alteredqualia.com/
  14000. *
  14001. * parameters = {
  14002. * color: <hex>,
  14003. * opacity: <float>,
  14004. * map: new THREE.Texture( <Image> ),
  14005. *
  14006. * uvOffset: new THREE.Vector2(),
  14007. * uvScale: new THREE.Vector2()
  14008. * }
  14009. */
  14010. function SpriteMaterial( parameters ) {
  14011. Material.call( this );
  14012. this.type = 'SpriteMaterial';
  14013. this.color = new Color( 0xffffff );
  14014. this.map = null;
  14015. this.rotation = 0;
  14016. this.fog = false;
  14017. this.lights = false;
  14018. this.setValues( parameters );
  14019. }
  14020. SpriteMaterial.prototype = Object.create( Material.prototype );
  14021. SpriteMaterial.prototype.constructor = SpriteMaterial;
  14022. SpriteMaterial.prototype.isSpriteMaterial = true;
  14023. SpriteMaterial.prototype.copy = function ( source ) {
  14024. Material.prototype.copy.call( this, source );
  14025. this.color.copy( source.color );
  14026. this.map = source.map;
  14027. this.rotation = source.rotation;
  14028. return this;
  14029. };
  14030. /**
  14031. * @author mikael emtinger / http://gomo.se/
  14032. * @author alteredq / http://alteredqualia.com/
  14033. */
  14034. function Sprite( material ) {
  14035. Object3D.call( this );
  14036. this.type = 'Sprite';
  14037. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  14038. }
  14039. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14040. constructor: Sprite,
  14041. isSprite: true,
  14042. raycast: ( function () {
  14043. var intersectPoint = new Vector3();
  14044. var worldPosition = new Vector3();
  14045. var worldScale = new Vector3();
  14046. return function raycast( raycaster, intersects ) {
  14047. worldPosition.setFromMatrixPosition( this.matrixWorld );
  14048. raycaster.ray.closestPointToPoint( worldPosition, intersectPoint );
  14049. worldScale.setFromMatrixScale( this.matrixWorld );
  14050. var guessSizeSq = worldScale.x * worldScale.y / 4;
  14051. if ( worldPosition.distanceToSquared( intersectPoint ) > guessSizeSq ) return;
  14052. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  14053. if ( distance < raycaster.near || distance > raycaster.far ) return;
  14054. intersects.push( {
  14055. distance: distance,
  14056. point: intersectPoint.clone(),
  14057. face: null,
  14058. object: this
  14059. } );
  14060. };
  14061. }() ),
  14062. clone: function () {
  14063. return new this.constructor( this.material ).copy( this );
  14064. }
  14065. } );
  14066. /**
  14067. * @author mikael emtinger / http://gomo.se/
  14068. * @author alteredq / http://alteredqualia.com/
  14069. * @author mrdoob / http://mrdoob.com/
  14070. */
  14071. function LOD() {
  14072. Object3D.call( this );
  14073. this.type = 'LOD';
  14074. Object.defineProperties( this, {
  14075. levels: {
  14076. enumerable: true,
  14077. value: []
  14078. }
  14079. } );
  14080. }
  14081. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14082. constructor: LOD,
  14083. copy: function ( source ) {
  14084. Object3D.prototype.copy.call( this, source, false );
  14085. var levels = source.levels;
  14086. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  14087. var level = levels[ i ];
  14088. this.addLevel( level.object.clone(), level.distance );
  14089. }
  14090. return this;
  14091. },
  14092. addLevel: function ( object, distance ) {
  14093. if ( distance === undefined ) distance = 0;
  14094. distance = Math.abs( distance );
  14095. var levels = this.levels;
  14096. for ( var l = 0; l < levels.length; l ++ ) {
  14097. if ( distance < levels[ l ].distance ) {
  14098. break;
  14099. }
  14100. }
  14101. levels.splice( l, 0, { distance: distance, object: object } );
  14102. this.add( object );
  14103. },
  14104. getObjectForDistance: function ( distance ) {
  14105. var levels = this.levels;
  14106. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  14107. if ( distance < levels[ i ].distance ) {
  14108. break;
  14109. }
  14110. }
  14111. return levels[ i - 1 ].object;
  14112. },
  14113. raycast: ( function () {
  14114. var matrixPosition = new Vector3();
  14115. return function raycast( raycaster, intersects ) {
  14116. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  14117. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  14118. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  14119. };
  14120. }() ),
  14121. update: function () {
  14122. var v1 = new Vector3();
  14123. var v2 = new Vector3();
  14124. return function update( camera ) {
  14125. var levels = this.levels;
  14126. if ( levels.length > 1 ) {
  14127. v1.setFromMatrixPosition( camera.matrixWorld );
  14128. v2.setFromMatrixPosition( this.matrixWorld );
  14129. var distance = v1.distanceTo( v2 );
  14130. levels[ 0 ].object.visible = true;
  14131. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  14132. if ( distance >= levels[ i ].distance ) {
  14133. levels[ i - 1 ].object.visible = false;
  14134. levels[ i ].object.visible = true;
  14135. } else {
  14136. break;
  14137. }
  14138. }
  14139. for ( ; i < l; i ++ ) {
  14140. levels[ i ].object.visible = false;
  14141. }
  14142. }
  14143. };
  14144. }(),
  14145. toJSON: function ( meta ) {
  14146. var data = Object3D.prototype.toJSON.call( this, meta );
  14147. data.object.levels = [];
  14148. var levels = this.levels;
  14149. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  14150. var level = levels[ i ];
  14151. data.object.levels.push( {
  14152. object: level.object.uuid,
  14153. distance: level.distance
  14154. } );
  14155. }
  14156. return data;
  14157. }
  14158. } );
  14159. /**
  14160. * @author mikael emtinger / http://gomo.se/
  14161. * @author alteredq / http://alteredqualia.com/
  14162. * @author michael guerrero / http://realitymeltdown.com
  14163. * @author ikerr / http://verold.com
  14164. */
  14165. function Skeleton( bones, boneInverses ) {
  14166. // copy the bone array
  14167. bones = bones || [];
  14168. this.bones = bones.slice( 0 );
  14169. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  14170. // use the supplied bone inverses or calculate the inverses
  14171. if ( boneInverses === undefined ) {
  14172. this.calculateInverses();
  14173. } else {
  14174. if ( this.bones.length === boneInverses.length ) {
  14175. this.boneInverses = boneInverses.slice( 0 );
  14176. } else {
  14177. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  14178. this.boneInverses = [];
  14179. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  14180. this.boneInverses.push( new Matrix4() );
  14181. }
  14182. }
  14183. }
  14184. }
  14185. Object.assign( Skeleton.prototype, {
  14186. calculateInverses: function () {
  14187. this.boneInverses = [];
  14188. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  14189. var inverse = new Matrix4();
  14190. if ( this.bones[ i ] ) {
  14191. inverse.getInverse( this.bones[ i ].matrixWorld );
  14192. }
  14193. this.boneInverses.push( inverse );
  14194. }
  14195. },
  14196. pose: function () {
  14197. var bone, i, il;
  14198. // recover the bind-time world matrices
  14199. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  14200. bone = this.bones[ i ];
  14201. if ( bone ) {
  14202. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  14203. }
  14204. }
  14205. // compute the local matrices, positions, rotations and scales
  14206. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  14207. bone = this.bones[ i ];
  14208. if ( bone ) {
  14209. if ( bone.parent && bone.parent.isBone ) {
  14210. bone.matrix.getInverse( bone.parent.matrixWorld );
  14211. bone.matrix.multiply( bone.matrixWorld );
  14212. } else {
  14213. bone.matrix.copy( bone.matrixWorld );
  14214. }
  14215. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  14216. }
  14217. }
  14218. },
  14219. update: ( function () {
  14220. var offsetMatrix = new Matrix4();
  14221. var identityMatrix = new Matrix4();
  14222. return function update() {
  14223. var bones = this.bones;
  14224. var boneInverses = this.boneInverses;
  14225. var boneMatrices = this.boneMatrices;
  14226. var boneTexture = this.boneTexture;
  14227. // flatten bone matrices to array
  14228. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  14229. // compute the offset between the current and the original transform
  14230. var matrix = bones[ i ] ? bones[ i ].matrixWorld : identityMatrix;
  14231. offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  14232. offsetMatrix.toArray( boneMatrices, i * 16 );
  14233. }
  14234. if ( boneTexture !== undefined ) {
  14235. boneTexture.needsUpdate = true;
  14236. }
  14237. };
  14238. } )(),
  14239. clone: function () {
  14240. return new Skeleton( this.bones, this.boneInverses );
  14241. }
  14242. } );
  14243. /**
  14244. * @author mikael emtinger / http://gomo.se/
  14245. * @author alteredq / http://alteredqualia.com/
  14246. * @author ikerr / http://verold.com
  14247. */
  14248. function Bone() {
  14249. Object3D.call( this );
  14250. this.type = 'Bone';
  14251. }
  14252. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14253. constructor: Bone,
  14254. isBone: true
  14255. } );
  14256. /**
  14257. * @author mikael emtinger / http://gomo.se/
  14258. * @author alteredq / http://alteredqualia.com/
  14259. * @author ikerr / http://verold.com
  14260. */
  14261. function SkinnedMesh( geometry, material ) {
  14262. Mesh.call( this, geometry, material );
  14263. this.type = 'SkinnedMesh';
  14264. this.bindMode = 'attached';
  14265. this.bindMatrix = new Matrix4();
  14266. this.bindMatrixInverse = new Matrix4();
  14267. var bones = this.initBones();
  14268. var skeleton = new Skeleton( bones );
  14269. this.bind( skeleton, this.matrixWorld );
  14270. this.normalizeSkinWeights();
  14271. }
  14272. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  14273. constructor: SkinnedMesh,
  14274. isSkinnedMesh: true,
  14275. initBones: function () {
  14276. var bones = [], bone, gbone;
  14277. var i, il;
  14278. if ( this.geometry && this.geometry.bones !== undefined ) {
  14279. // first, create array of 'Bone' objects from geometry data
  14280. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  14281. gbone = this.geometry.bones[ i ];
  14282. // create new 'Bone' object
  14283. bone = new Bone();
  14284. bones.push( bone );
  14285. // apply values
  14286. bone.name = gbone.name;
  14287. bone.position.fromArray( gbone.pos );
  14288. bone.quaternion.fromArray( gbone.rotq );
  14289. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  14290. }
  14291. // second, create bone hierarchy
  14292. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  14293. gbone = this.geometry.bones[ i ];
  14294. if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) {
  14295. // subsequent bones in the hierarchy
  14296. bones[ gbone.parent ].add( bones[ i ] );
  14297. } else {
  14298. // topmost bone, immediate child of the skinned mesh
  14299. this.add( bones[ i ] );
  14300. }
  14301. }
  14302. }
  14303. // now the bones are part of the scene graph and children of the skinned mesh.
  14304. // let's update the corresponding matrices
  14305. this.updateMatrixWorld( true );
  14306. return bones;
  14307. },
  14308. bind: function ( skeleton, bindMatrix ) {
  14309. this.skeleton = skeleton;
  14310. if ( bindMatrix === undefined ) {
  14311. this.updateMatrixWorld( true );
  14312. this.skeleton.calculateInverses();
  14313. bindMatrix = this.matrixWorld;
  14314. }
  14315. this.bindMatrix.copy( bindMatrix );
  14316. this.bindMatrixInverse.getInverse( bindMatrix );
  14317. },
  14318. pose: function () {
  14319. this.skeleton.pose();
  14320. },
  14321. normalizeSkinWeights: function () {
  14322. var scale, i;
  14323. if ( this.geometry && this.geometry.isGeometry ) {
  14324. for ( i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  14325. var sw = this.geometry.skinWeights[ i ];
  14326. scale = 1.0 / sw.lengthManhattan();
  14327. if ( scale !== Infinity ) {
  14328. sw.multiplyScalar( scale );
  14329. } else {
  14330. sw.set( 1, 0, 0, 0 ); // do something reasonable
  14331. }
  14332. }
  14333. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  14334. var vec = new Vector4();
  14335. var skinWeight = this.geometry.attributes.skinWeight;
  14336. for ( i = 0; i < skinWeight.count; i ++ ) {
  14337. vec.x = skinWeight.getX( i );
  14338. vec.y = skinWeight.getY( i );
  14339. vec.z = skinWeight.getZ( i );
  14340. vec.w = skinWeight.getW( i );
  14341. scale = 1.0 / vec.lengthManhattan();
  14342. if ( scale !== Infinity ) {
  14343. vec.multiplyScalar( scale );
  14344. } else {
  14345. vec.set( 1, 0, 0, 0 ); // do something reasonable
  14346. }
  14347. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  14348. }
  14349. }
  14350. },
  14351. updateMatrixWorld: function ( force ) {
  14352. Mesh.prototype.updateMatrixWorld.call( this, force );
  14353. if ( this.bindMode === 'attached' ) {
  14354. this.bindMatrixInverse.getInverse( this.matrixWorld );
  14355. } else if ( this.bindMode === 'detached' ) {
  14356. this.bindMatrixInverse.getInverse( this.bindMatrix );
  14357. } else {
  14358. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  14359. }
  14360. },
  14361. clone: function () {
  14362. return new this.constructor( this.geometry, this.material ).copy( this );
  14363. }
  14364. } );
  14365. /**
  14366. * @author mrdoob / http://mrdoob.com/
  14367. * @author alteredq / http://alteredqualia.com/
  14368. *
  14369. * parameters = {
  14370. * color: <hex>,
  14371. * opacity: <float>,
  14372. *
  14373. * linewidth: <float>,
  14374. * linecap: "round",
  14375. * linejoin: "round"
  14376. * }
  14377. */
  14378. function LineBasicMaterial( parameters ) {
  14379. Material.call( this );
  14380. this.type = 'LineBasicMaterial';
  14381. this.color = new Color( 0xffffff );
  14382. this.linewidth = 1;
  14383. this.linecap = 'round';
  14384. this.linejoin = 'round';
  14385. this.lights = false;
  14386. this.setValues( parameters );
  14387. }
  14388. LineBasicMaterial.prototype = Object.create( Material.prototype );
  14389. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  14390. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  14391. LineBasicMaterial.prototype.copy = function ( source ) {
  14392. Material.prototype.copy.call( this, source );
  14393. this.color.copy( source.color );
  14394. this.linewidth = source.linewidth;
  14395. this.linecap = source.linecap;
  14396. this.linejoin = source.linejoin;
  14397. return this;
  14398. };
  14399. /**
  14400. * @author mrdoob / http://mrdoob.com/
  14401. */
  14402. function Line( geometry, material, mode ) {
  14403. if ( mode === 1 ) {
  14404. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  14405. return new LineSegments( geometry, material );
  14406. }
  14407. Object3D.call( this );
  14408. this.type = 'Line';
  14409. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14410. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  14411. }
  14412. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14413. constructor: Line,
  14414. isLine: true,
  14415. raycast: ( function () {
  14416. var inverseMatrix = new Matrix4();
  14417. var ray = new Ray();
  14418. var sphere = new Sphere();
  14419. return function raycast( raycaster, intersects ) {
  14420. var precision = raycaster.linePrecision;
  14421. var precisionSq = precision * precision;
  14422. var geometry = this.geometry;
  14423. var matrixWorld = this.matrixWorld;
  14424. // Checking boundingSphere distance to ray
  14425. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14426. sphere.copy( geometry.boundingSphere );
  14427. sphere.applyMatrix4( matrixWorld );
  14428. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14429. //
  14430. inverseMatrix.getInverse( matrixWorld );
  14431. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14432. var vStart = new Vector3();
  14433. var vEnd = new Vector3();
  14434. var interSegment = new Vector3();
  14435. var interRay = new Vector3();
  14436. var step = (this && this.isLineSegments) ? 2 : 1;
  14437. if ( geometry.isBufferGeometry ) {
  14438. var index = geometry.index;
  14439. var attributes = geometry.attributes;
  14440. var positions = attributes.position.array;
  14441. if ( index !== null ) {
  14442. var indices = index.array;
  14443. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  14444. var a = indices[ i ];
  14445. var b = indices[ i + 1 ];
  14446. vStart.fromArray( positions, a * 3 );
  14447. vEnd.fromArray( positions, b * 3 );
  14448. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  14449. if ( distSq > precisionSq ) continue;
  14450. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14451. var distance = raycaster.ray.origin.distanceTo( interRay );
  14452. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14453. intersects.push( {
  14454. distance: distance,
  14455. // What do we want? intersection point on the ray or on the segment??
  14456. // point: raycaster.ray.at( distance ),
  14457. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14458. index: i,
  14459. face: null,
  14460. faceIndex: null,
  14461. object: this
  14462. } );
  14463. }
  14464. } else {
  14465. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  14466. vStart.fromArray( positions, 3 * i );
  14467. vEnd.fromArray( positions, 3 * i + 3 );
  14468. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  14469. if ( distSq > precisionSq ) continue;
  14470. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14471. var distance = raycaster.ray.origin.distanceTo( interRay );
  14472. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14473. intersects.push( {
  14474. distance: distance,
  14475. // What do we want? intersection point on the ray or on the segment??
  14476. // point: raycaster.ray.at( distance ),
  14477. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14478. index: i,
  14479. face: null,
  14480. faceIndex: null,
  14481. object: this
  14482. } );
  14483. }
  14484. }
  14485. } else if ( geometry.isGeometry ) {
  14486. var vertices = geometry.vertices;
  14487. var nbVertices = vertices.length;
  14488. for ( var i = 0; i < nbVertices - 1; i += step ) {
  14489. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  14490. if ( distSq > precisionSq ) continue;
  14491. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14492. var distance = raycaster.ray.origin.distanceTo( interRay );
  14493. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14494. intersects.push( {
  14495. distance: distance,
  14496. // What do we want? intersection point on the ray or on the segment??
  14497. // point: raycaster.ray.at( distance ),
  14498. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14499. index: i,
  14500. face: null,
  14501. faceIndex: null,
  14502. object: this
  14503. } );
  14504. }
  14505. }
  14506. };
  14507. }() ),
  14508. clone: function () {
  14509. return new this.constructor( this.geometry, this.material ).copy( this );
  14510. }
  14511. } );
  14512. /**
  14513. * @author mrdoob / http://mrdoob.com/
  14514. */
  14515. function LineSegments( geometry, material ) {
  14516. Line.call( this, geometry, material );
  14517. this.type = 'LineSegments';
  14518. }
  14519. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  14520. constructor: LineSegments,
  14521. isLineSegments: true
  14522. } );
  14523. /**
  14524. * @author mgreter / http://github.com/mgreter
  14525. */
  14526. function LineLoop( geometry, material ) {
  14527. Line.call( this, geometry, material );
  14528. this.type = 'LineLoop';
  14529. }
  14530. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  14531. constructor: LineLoop,
  14532. isLineLoop: true,
  14533. } );
  14534. /**
  14535. * @author mrdoob / http://mrdoob.com/
  14536. * @author alteredq / http://alteredqualia.com/
  14537. *
  14538. * parameters = {
  14539. * color: <hex>,
  14540. * opacity: <float>,
  14541. * map: new THREE.Texture( <Image> ),
  14542. *
  14543. * size: <float>,
  14544. * sizeAttenuation: <bool>
  14545. * }
  14546. */
  14547. function PointsMaterial( parameters ) {
  14548. Material.call( this );
  14549. this.type = 'PointsMaterial';
  14550. this.color = new Color( 0xffffff );
  14551. this.map = null;
  14552. this.size = 1;
  14553. this.sizeAttenuation = true;
  14554. this.lights = false;
  14555. this.setValues( parameters );
  14556. }
  14557. PointsMaterial.prototype = Object.create( Material.prototype );
  14558. PointsMaterial.prototype.constructor = PointsMaterial;
  14559. PointsMaterial.prototype.isPointsMaterial = true;
  14560. PointsMaterial.prototype.copy = function ( source ) {
  14561. Material.prototype.copy.call( this, source );
  14562. this.color.copy( source.color );
  14563. this.map = source.map;
  14564. this.size = source.size;
  14565. this.sizeAttenuation = source.sizeAttenuation;
  14566. return this;
  14567. };
  14568. /**
  14569. * @author alteredq / http://alteredqualia.com/
  14570. */
  14571. function Points( geometry, material ) {
  14572. Object3D.call( this );
  14573. this.type = 'Points';
  14574. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14575. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  14576. }
  14577. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14578. constructor: Points,
  14579. isPoints: true,
  14580. raycast: ( function () {
  14581. var inverseMatrix = new Matrix4();
  14582. var ray = new Ray();
  14583. var sphere = new Sphere();
  14584. return function raycast( raycaster, intersects ) {
  14585. var object = this;
  14586. var geometry = this.geometry;
  14587. var matrixWorld = this.matrixWorld;
  14588. var threshold = raycaster.params.Points.threshold;
  14589. // Checking boundingSphere distance to ray
  14590. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14591. sphere.copy( geometry.boundingSphere );
  14592. sphere.applyMatrix4( matrixWorld );
  14593. sphere.radius += threshold;
  14594. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14595. //
  14596. inverseMatrix.getInverse( matrixWorld );
  14597. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14598. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  14599. var localThresholdSq = localThreshold * localThreshold;
  14600. var position = new Vector3();
  14601. function testPoint( point, index ) {
  14602. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  14603. if ( rayPointDistanceSq < localThresholdSq ) {
  14604. var intersectPoint = ray.closestPointToPoint( point );
  14605. intersectPoint.applyMatrix4( matrixWorld );
  14606. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  14607. if ( distance < raycaster.near || distance > raycaster.far ) return;
  14608. intersects.push( {
  14609. distance: distance,
  14610. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  14611. point: intersectPoint.clone(),
  14612. index: index,
  14613. face: null,
  14614. object: object
  14615. } );
  14616. }
  14617. }
  14618. if ( geometry.isBufferGeometry ) {
  14619. var index = geometry.index;
  14620. var attributes = geometry.attributes;
  14621. var positions = attributes.position.array;
  14622. if ( index !== null ) {
  14623. var indices = index.array;
  14624. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  14625. var a = indices[ i ];
  14626. position.fromArray( positions, a * 3 );
  14627. testPoint( position, a );
  14628. }
  14629. } else {
  14630. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  14631. position.fromArray( positions, i * 3 );
  14632. testPoint( position, i );
  14633. }
  14634. }
  14635. } else {
  14636. var vertices = geometry.vertices;
  14637. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  14638. testPoint( vertices[ i ], i );
  14639. }
  14640. }
  14641. };
  14642. }() ),
  14643. clone: function () {
  14644. return new this.constructor( this.geometry, this.material ).copy( this );
  14645. }
  14646. } );
  14647. /**
  14648. * @author mrdoob / http://mrdoob.com/
  14649. */
  14650. function Group() {
  14651. Object3D.call( this );
  14652. this.type = 'Group';
  14653. }
  14654. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14655. constructor: Group
  14656. } );
  14657. /**
  14658. * @author mrdoob / http://mrdoob.com/
  14659. */
  14660. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14661. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14662. this.generateMipmaps = false;
  14663. var scope = this;
  14664. function update() {
  14665. requestAnimationFrame( update );
  14666. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  14667. scope.needsUpdate = true;
  14668. }
  14669. }
  14670. update();
  14671. }
  14672. VideoTexture.prototype = Object.create( Texture.prototype );
  14673. VideoTexture.prototype.constructor = VideoTexture;
  14674. /**
  14675. * @author alteredq / http://alteredqualia.com/
  14676. */
  14677. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  14678. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  14679. this.image = { width: width, height: height };
  14680. this.mipmaps = mipmaps;
  14681. // no flipping for cube textures
  14682. // (also flipping doesn't work for compressed textures )
  14683. this.flipY = false;
  14684. // can't generate mipmaps for compressed textures
  14685. // mips must be embedded in DDS files
  14686. this.generateMipmaps = false;
  14687. }
  14688. CompressedTexture.prototype = Object.create( Texture.prototype );
  14689. CompressedTexture.prototype.constructor = CompressedTexture;
  14690. CompressedTexture.prototype.isCompressedTexture = true;
  14691. /**
  14692. * @author Matt DesLauriers / @mattdesl
  14693. * @author atix / arthursilber.de
  14694. */
  14695. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  14696. format = format !== undefined ? format : DepthFormat;
  14697. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  14698. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  14699. }
  14700. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  14701. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  14702. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14703. this.image = { width: width, height: height };
  14704. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14705. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14706. this.flipY = false;
  14707. this.generateMipmaps = false;
  14708. }
  14709. DepthTexture.prototype = Object.create( Texture.prototype );
  14710. DepthTexture.prototype.constructor = DepthTexture;
  14711. DepthTexture.prototype.isDepthTexture = true;
  14712. /**
  14713. * @author mrdoob / http://mrdoob.com/
  14714. * @author Mugen87 / https://github.com/Mugen87
  14715. */
  14716. function WireframeGeometry( geometry ) {
  14717. BufferGeometry.call( this );
  14718. this.type = 'WireframeGeometry';
  14719. // buffer
  14720. var vertices = [];
  14721. // helper variables
  14722. var i, j, l, o, ol;
  14723. var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
  14724. var key, keys = [ 'a', 'b', 'c' ];
  14725. var vertex;
  14726. // different logic for Geometry and BufferGeometry
  14727. if ( geometry && geometry.isGeometry ) {
  14728. // create a data structure that contains all edges without duplicates
  14729. var faces = geometry.faces;
  14730. for ( i = 0, l = faces.length; i < l; i ++ ) {
  14731. var face = faces[ i ];
  14732. for ( j = 0; j < 3; j ++ ) {
  14733. edge1 = face[ keys[ j ] ];
  14734. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  14735. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  14736. edge[ 1 ] = Math.max( edge1, edge2 );
  14737. key = edge[ 0 ] + ',' + edge[ 1 ];
  14738. if ( edges[ key ] === undefined ) {
  14739. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  14740. }
  14741. }
  14742. }
  14743. // generate vertices
  14744. for ( key in edges ) {
  14745. e = edges[ key ];
  14746. vertex = geometry.vertices[ e.index1 ];
  14747. vertices.push( vertex.x, vertex.y, vertex.z );
  14748. vertex = geometry.vertices[ e.index2 ];
  14749. vertices.push( vertex.x, vertex.y, vertex.z );
  14750. }
  14751. } else if ( geometry && geometry.isBufferGeometry ) {
  14752. var position, indices, groups;
  14753. var group, start, count;
  14754. var index1, index2;
  14755. vertex = new Vector3();
  14756. if ( geometry.index !== null ) {
  14757. // indexed BufferGeometry
  14758. position = geometry.attributes.position;
  14759. indices = geometry.index;
  14760. groups = geometry.groups;
  14761. if ( groups.length === 0 ) {
  14762. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  14763. }
  14764. // create a data structure that contains all eges without duplicates
  14765. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  14766. group = groups[ o ];
  14767. start = group.start;
  14768. count = group.count;
  14769. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  14770. for ( j = 0; j < 3; j ++ ) {
  14771. edge1 = indices.getX( i + j );
  14772. edge2 = indices.getX( i + ( j + 1 ) % 3 );
  14773. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  14774. edge[ 1 ] = Math.max( edge1, edge2 );
  14775. key = edge[ 0 ] + ',' + edge[ 1 ];
  14776. if ( edges[ key ] === undefined ) {
  14777. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  14778. }
  14779. }
  14780. }
  14781. }
  14782. // generate vertices
  14783. for ( key in edges ) {
  14784. e = edges[ key ];
  14785. vertex.fromBufferAttribute( position, e.index1 );
  14786. vertices.push( vertex.x, vertex.y, vertex.z );
  14787. vertex.fromBufferAttribute( position, e.index2 );
  14788. vertices.push( vertex.x, vertex.y, vertex.z );
  14789. }
  14790. } else {
  14791. // non-indexed BufferGeometry
  14792. position = geometry.attributes.position;
  14793. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  14794. for ( j = 0; j < 3; j ++ ) {
  14795. // three edges per triangle, an edge is represented as (index1, index2)
  14796. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  14797. index1 = 3 * i + j;
  14798. vertex.fromBufferAttribute( position, index1 );
  14799. vertices.push( vertex.x, vertex.y, vertex.z );
  14800. index2 = 3 * i + ( ( j + 1 ) % 3 );
  14801. vertex.fromBufferAttribute( position, index2 );
  14802. vertices.push( vertex.x, vertex.y, vertex.z );
  14803. }
  14804. }
  14805. }
  14806. }
  14807. // build geometry
  14808. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14809. }
  14810. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  14811. WireframeGeometry.prototype.constructor = WireframeGeometry;
  14812. /**
  14813. * @author zz85 / https://github.com/zz85
  14814. * @author Mugen87 / https://github.com/Mugen87
  14815. *
  14816. * Parametric Surfaces Geometry
  14817. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  14818. */
  14819. // ParametricGeometry
  14820. function ParametricGeometry( func, slices, stacks ) {
  14821. Geometry.call( this );
  14822. this.type = 'ParametricGeometry';
  14823. this.parameters = {
  14824. func: func,
  14825. slices: slices,
  14826. stacks: stacks
  14827. };
  14828. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  14829. this.mergeVertices();
  14830. }
  14831. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  14832. ParametricGeometry.prototype.constructor = ParametricGeometry;
  14833. // ParametricBufferGeometry
  14834. function ParametricBufferGeometry( func, slices, stacks ) {
  14835. BufferGeometry.call( this );
  14836. this.type = 'ParametricBufferGeometry';
  14837. this.parameters = {
  14838. func: func,
  14839. slices: slices,
  14840. stacks: stacks
  14841. };
  14842. // buffers
  14843. var indices = [];
  14844. var vertices = [];
  14845. var normals = [];
  14846. var uvs = [];
  14847. var EPS = 0.00001;
  14848. var normal = new Vector3();
  14849. var p0 = new Vector3(), p1 = new Vector3();
  14850. var pu = new Vector3(), pv = new Vector3();
  14851. var i, j;
  14852. // generate vertices, normals and uvs
  14853. var sliceCount = slices + 1;
  14854. for ( i = 0; i <= stacks; i ++ ) {
  14855. var v = i / stacks;
  14856. for ( j = 0; j <= slices; j ++ ) {
  14857. var u = j / slices;
  14858. // vertex
  14859. p0 = func( u, v, p0 );
  14860. vertices.push( p0.x, p0.y, p0.z );
  14861. // normal
  14862. // approximate tangent vectors via finite differences
  14863. if ( u - EPS >= 0 ) {
  14864. p1 = func( u - EPS, v, p1 );
  14865. pu.subVectors( p0, p1 );
  14866. } else {
  14867. p1 = func( u + EPS, v, p1 );
  14868. pu.subVectors( p1, p0 );
  14869. }
  14870. if ( v - EPS >= 0 ) {
  14871. p1 = func( u, v - EPS, p1 );
  14872. pv.subVectors( p0, p1 );
  14873. } else {
  14874. p1 = func( u, v + EPS, p1 );
  14875. pv.subVectors( p1, p0 );
  14876. }
  14877. // cross product of tangent vectors returns surface normal
  14878. normal.crossVectors( pu, pv ).normalize();
  14879. normals.push( normal.x, normal.y, normal.z );
  14880. // uv
  14881. uvs.push( u, v );
  14882. }
  14883. }
  14884. // generate indices
  14885. for ( i = 0; i < stacks; i ++ ) {
  14886. for ( j = 0; j < slices; j ++ ) {
  14887. var a = i * sliceCount + j;
  14888. var b = i * sliceCount + j + 1;
  14889. var c = ( i + 1 ) * sliceCount + j + 1;
  14890. var d = ( i + 1 ) * sliceCount + j;
  14891. // faces one and two
  14892. indices.push( a, b, d );
  14893. indices.push( b, c, d );
  14894. }
  14895. }
  14896. // build geometry
  14897. this.setIndex( indices );
  14898. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14899. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  14900. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14901. }
  14902. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14903. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  14904. /**
  14905. * @author clockworkgeek / https://github.com/clockworkgeek
  14906. * @author timothypratley / https://github.com/timothypratley
  14907. * @author WestLangley / http://github.com/WestLangley
  14908. * @author Mugen87 / https://github.com/Mugen87
  14909. */
  14910. // PolyhedronGeometry
  14911. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  14912. Geometry.call( this );
  14913. this.type = 'PolyhedronGeometry';
  14914. this.parameters = {
  14915. vertices: vertices,
  14916. indices: indices,
  14917. radius: radius,
  14918. detail: detail
  14919. };
  14920. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  14921. this.mergeVertices();
  14922. }
  14923. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  14924. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  14925. // PolyhedronBufferGeometry
  14926. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  14927. BufferGeometry.call( this );
  14928. this.type = 'PolyhedronBufferGeometry';
  14929. this.parameters = {
  14930. vertices: vertices,
  14931. indices: indices,
  14932. radius: radius,
  14933. detail: detail
  14934. };
  14935. radius = radius || 1;
  14936. detail = detail || 0;
  14937. // default buffer data
  14938. var vertexBuffer = [];
  14939. var uvBuffer = [];
  14940. // the subdivision creates the vertex buffer data
  14941. subdivide( detail );
  14942. // all vertices should lie on a conceptual sphere with a given radius
  14943. appplyRadius( radius );
  14944. // finally, create the uv data
  14945. generateUVs();
  14946. // build non-indexed geometry
  14947. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  14948. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  14949. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  14950. if ( detail === 0 ) {
  14951. this.computeVertexNormals(); // flat normals
  14952. } else {
  14953. this.normalizeNormals(); // smooth normals
  14954. }
  14955. // helper functions
  14956. function subdivide( detail ) {
  14957. var a = new Vector3();
  14958. var b = new Vector3();
  14959. var c = new Vector3();
  14960. // iterate over all faces and apply a subdivison with the given detail value
  14961. for ( var i = 0; i < indices.length; i += 3 ) {
  14962. // get the vertices of the face
  14963. getVertexByIndex( indices[ i + 0 ], a );
  14964. getVertexByIndex( indices[ i + 1 ], b );
  14965. getVertexByIndex( indices[ i + 2 ], c );
  14966. // perform subdivision
  14967. subdivideFace( a, b, c, detail );
  14968. }
  14969. }
  14970. function subdivideFace( a, b, c, detail ) {
  14971. var cols = Math.pow( 2, detail );
  14972. // we use this multidimensional array as a data structure for creating the subdivision
  14973. var v = [];
  14974. var i, j;
  14975. // construct all of the vertices for this subdivision
  14976. for ( i = 0; i <= cols; i ++ ) {
  14977. v[ i ] = [];
  14978. var aj = a.clone().lerp( c, i / cols );
  14979. var bj = b.clone().lerp( c, i / cols );
  14980. var rows = cols - i;
  14981. for ( j = 0; j <= rows; j ++ ) {
  14982. if ( j === 0 && i === cols ) {
  14983. v[ i ][ j ] = aj;
  14984. } else {
  14985. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  14986. }
  14987. }
  14988. }
  14989. // construct all of the faces
  14990. for ( i = 0; i < cols; i ++ ) {
  14991. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  14992. var k = Math.floor( j / 2 );
  14993. if ( j % 2 === 0 ) {
  14994. pushVertex( v[ i ][ k + 1 ] );
  14995. pushVertex( v[ i + 1 ][ k ] );
  14996. pushVertex( v[ i ][ k ] );
  14997. } else {
  14998. pushVertex( v[ i ][ k + 1 ] );
  14999. pushVertex( v[ i + 1 ][ k + 1 ] );
  15000. pushVertex( v[ i + 1 ][ k ] );
  15001. }
  15002. }
  15003. }
  15004. }
  15005. function appplyRadius( radius ) {
  15006. var vertex = new Vector3();
  15007. // iterate over the entire buffer and apply the radius to each vertex
  15008. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  15009. vertex.x = vertexBuffer[ i + 0 ];
  15010. vertex.y = vertexBuffer[ i + 1 ];
  15011. vertex.z = vertexBuffer[ i + 2 ];
  15012. vertex.normalize().multiplyScalar( radius );
  15013. vertexBuffer[ i + 0 ] = vertex.x;
  15014. vertexBuffer[ i + 1 ] = vertex.y;
  15015. vertexBuffer[ i + 2 ] = vertex.z;
  15016. }
  15017. }
  15018. function generateUVs() {
  15019. var vertex = new Vector3();
  15020. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  15021. vertex.x = vertexBuffer[ i + 0 ];
  15022. vertex.y = vertexBuffer[ i + 1 ];
  15023. vertex.z = vertexBuffer[ i + 2 ];
  15024. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  15025. var v = inclination( vertex ) / Math.PI + 0.5;
  15026. uvBuffer.push( u, 1 - v );
  15027. }
  15028. correctUVs();
  15029. correctSeam();
  15030. }
  15031. function correctSeam() {
  15032. // handle case when face straddles the seam, see #3269
  15033. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  15034. // uv data of a single face
  15035. var x0 = uvBuffer[ i + 0 ];
  15036. var x1 = uvBuffer[ i + 2 ];
  15037. var x2 = uvBuffer[ i + 4 ];
  15038. var max = Math.max( x0, x1, x2 );
  15039. var min = Math.min( x0, x1, x2 );
  15040. // 0.9 is somewhat arbitrary
  15041. if ( max > 0.9 && min < 0.1 ) {
  15042. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  15043. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  15044. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  15045. }
  15046. }
  15047. }
  15048. function pushVertex( vertex ) {
  15049. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  15050. }
  15051. function getVertexByIndex( index, vertex ) {
  15052. var stride = index * 3;
  15053. vertex.x = vertices[ stride + 0 ];
  15054. vertex.y = vertices[ stride + 1 ];
  15055. vertex.z = vertices[ stride + 2 ];
  15056. }
  15057. function correctUVs() {
  15058. var a = new Vector3();
  15059. var b = new Vector3();
  15060. var c = new Vector3();
  15061. var centroid = new Vector3();
  15062. var uvA = new Vector2();
  15063. var uvB = new Vector2();
  15064. var uvC = new Vector2();
  15065. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  15066. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  15067. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  15068. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  15069. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  15070. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  15071. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  15072. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  15073. var azi = azimuth( centroid );
  15074. correctUV( uvA, j + 0, a, azi );
  15075. correctUV( uvB, j + 2, b, azi );
  15076. correctUV( uvC, j + 4, c, azi );
  15077. }
  15078. }
  15079. function correctUV( uv, stride, vector, azimuth ) {
  15080. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  15081. uvBuffer[ stride ] = uv.x - 1;
  15082. }
  15083. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  15084. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  15085. }
  15086. }
  15087. // Angle around the Y axis, counter-clockwise when looking from above.
  15088. function azimuth( vector ) {
  15089. return Math.atan2( vector.z, - vector.x );
  15090. }
  15091. // Angle above the XZ plane.
  15092. function inclination( vector ) {
  15093. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  15094. }
  15095. }
  15096. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15097. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  15098. /**
  15099. * @author timothypratley / https://github.com/timothypratley
  15100. * @author Mugen87 / https://github.com/Mugen87
  15101. */
  15102. // TetrahedronGeometry
  15103. function TetrahedronGeometry( radius, detail ) {
  15104. Geometry.call( this );
  15105. this.type = 'TetrahedronGeometry';
  15106. this.parameters = {
  15107. radius: radius,
  15108. detail: detail
  15109. };
  15110. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  15111. this.mergeVertices();
  15112. }
  15113. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  15114. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  15115. // TetrahedronBufferGeometry
  15116. function TetrahedronBufferGeometry( radius, detail ) {
  15117. var vertices = [
  15118. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  15119. ];
  15120. var indices = [
  15121. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  15122. ];
  15123. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15124. this.type = 'TetrahedronBufferGeometry';
  15125. this.parameters = {
  15126. radius: radius,
  15127. detail: detail
  15128. };
  15129. }
  15130. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15131. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  15132. /**
  15133. * @author timothypratley / https://github.com/timothypratley
  15134. * @author Mugen87 / https://github.com/Mugen87
  15135. */
  15136. // OctahedronGeometry
  15137. function OctahedronGeometry( radius, detail ) {
  15138. Geometry.call( this );
  15139. this.type = 'OctahedronGeometry';
  15140. this.parameters = {
  15141. radius: radius,
  15142. detail: detail
  15143. };
  15144. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  15145. this.mergeVertices();
  15146. }
  15147. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  15148. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  15149. // OctahedronBufferGeometry
  15150. function OctahedronBufferGeometry( radius, detail ) {
  15151. var vertices = [
  15152. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  15153. ];
  15154. var indices = [
  15155. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  15156. ];
  15157. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15158. this.type = 'OctahedronBufferGeometry';
  15159. this.parameters = {
  15160. radius: radius,
  15161. detail: detail
  15162. };
  15163. }
  15164. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15165. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  15166. /**
  15167. * @author timothypratley / https://github.com/timothypratley
  15168. * @author Mugen87 / https://github.com/Mugen87
  15169. */
  15170. // IcosahedronGeometry
  15171. function IcosahedronGeometry( radius, detail ) {
  15172. Geometry.call( this );
  15173. this.type = 'IcosahedronGeometry';
  15174. this.parameters = {
  15175. radius: radius,
  15176. detail: detail
  15177. };
  15178. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  15179. this.mergeVertices();
  15180. }
  15181. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  15182. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  15183. // IcosahedronBufferGeometry
  15184. function IcosahedronBufferGeometry( radius, detail ) {
  15185. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  15186. var vertices = [
  15187. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  15188. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  15189. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  15190. ];
  15191. var indices = [
  15192. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  15193. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  15194. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  15195. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  15196. ];
  15197. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15198. this.type = 'IcosahedronBufferGeometry';
  15199. this.parameters = {
  15200. radius: radius,
  15201. detail: detail
  15202. };
  15203. }
  15204. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15205. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  15206. /**
  15207. * @author Abe Pazos / https://hamoid.com
  15208. * @author Mugen87 / https://github.com/Mugen87
  15209. */
  15210. // DodecahedronGeometry
  15211. function DodecahedronGeometry( radius, detail ) {
  15212. Geometry.call( this );
  15213. this.type = 'DodecahedronGeometry';
  15214. this.parameters = {
  15215. radius: radius,
  15216. detail: detail
  15217. };
  15218. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  15219. this.mergeVertices();
  15220. }
  15221. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  15222. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  15223. // DodecahedronBufferGeometry
  15224. function DodecahedronBufferGeometry( radius, detail ) {
  15225. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  15226. var r = 1 / t;
  15227. var vertices = [
  15228. // (±1, ±1, ±1)
  15229. - 1, - 1, - 1, - 1, - 1, 1,
  15230. - 1, 1, - 1, - 1, 1, 1,
  15231. 1, - 1, - 1, 1, - 1, 1,
  15232. 1, 1, - 1, 1, 1, 1,
  15233. // (0, ±1/φ, ±φ)
  15234. 0, - r, - t, 0, - r, t,
  15235. 0, r, - t, 0, r, t,
  15236. // (±1/φ, ±φ, 0)
  15237. - r, - t, 0, - r, t, 0,
  15238. r, - t, 0, r, t, 0,
  15239. // (±φ, 0, ±1/φ)
  15240. - t, 0, - r, t, 0, - r,
  15241. - t, 0, r, t, 0, r
  15242. ];
  15243. var indices = [
  15244. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  15245. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  15246. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  15247. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  15248. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  15249. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  15250. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  15251. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  15252. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  15253. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  15254. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  15255. 1, 12, 14, 1, 14, 5, 1, 5, 9
  15256. ];
  15257. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15258. this.type = 'DodecahedronBufferGeometry';
  15259. this.parameters = {
  15260. radius: radius,
  15261. detail: detail
  15262. };
  15263. }
  15264. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15265. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  15266. /**
  15267. * @author oosmoxiecode / https://github.com/oosmoxiecode
  15268. * @author WestLangley / https://github.com/WestLangley
  15269. * @author zz85 / https://github.com/zz85
  15270. * @author miningold / https://github.com/miningold
  15271. * @author jonobr1 / https://github.com/jonobr1
  15272. * @author Mugen87 / https://github.com/Mugen87
  15273. *
  15274. */
  15275. // TubeGeometry
  15276. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  15277. Geometry.call( this );
  15278. this.type = 'TubeGeometry';
  15279. this.parameters = {
  15280. path: path,
  15281. tubularSegments: tubularSegments,
  15282. radius: radius,
  15283. radialSegments: radialSegments,
  15284. closed: closed
  15285. };
  15286. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  15287. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  15288. // expose internals
  15289. this.tangents = bufferGeometry.tangents;
  15290. this.normals = bufferGeometry.normals;
  15291. this.binormals = bufferGeometry.binormals;
  15292. // create geometry
  15293. this.fromBufferGeometry( bufferGeometry );
  15294. this.mergeVertices();
  15295. }
  15296. TubeGeometry.prototype = Object.create( Geometry.prototype );
  15297. TubeGeometry.prototype.constructor = TubeGeometry;
  15298. // TubeBufferGeometry
  15299. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  15300. BufferGeometry.call( this );
  15301. this.type = 'TubeBufferGeometry';
  15302. this.parameters = {
  15303. path: path,
  15304. tubularSegments: tubularSegments,
  15305. radius: radius,
  15306. radialSegments: radialSegments,
  15307. closed: closed
  15308. };
  15309. tubularSegments = tubularSegments || 64;
  15310. radius = radius || 1;
  15311. radialSegments = radialSegments || 8;
  15312. closed = closed || false;
  15313. var frames = path.computeFrenetFrames( tubularSegments, closed );
  15314. // expose internals
  15315. this.tangents = frames.tangents;
  15316. this.normals = frames.normals;
  15317. this.binormals = frames.binormals;
  15318. // helper variables
  15319. var vertex = new Vector3();
  15320. var normal = new Vector3();
  15321. var uv = new Vector2();
  15322. var i, j;
  15323. // buffer
  15324. var vertices = [];
  15325. var normals = [];
  15326. var uvs = [];
  15327. var indices = [];
  15328. // create buffer data
  15329. generateBufferData();
  15330. // build geometry
  15331. this.setIndex( indices );
  15332. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15333. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15334. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15335. // functions
  15336. function generateBufferData() {
  15337. for ( i = 0; i < tubularSegments; i ++ ) {
  15338. generateSegment( i );
  15339. }
  15340. // if the geometry is not closed, generate the last row of vertices and normals
  15341. // at the regular position on the given path
  15342. //
  15343. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  15344. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  15345. // uvs are generated in a separate function.
  15346. // this makes it easy compute correct values for closed geometries
  15347. generateUVs();
  15348. // finally create faces
  15349. generateIndices();
  15350. }
  15351. function generateSegment( i ) {
  15352. // we use getPointAt to sample evenly distributed points from the given path
  15353. var P = path.getPointAt( i / tubularSegments );
  15354. // retrieve corresponding normal and binormal
  15355. var N = frames.normals[ i ];
  15356. var B = frames.binormals[ i ];
  15357. // generate normals and vertices for the current segment
  15358. for ( j = 0; j <= radialSegments; j ++ ) {
  15359. var v = j / radialSegments * Math.PI * 2;
  15360. var sin = Math.sin( v );
  15361. var cos = - Math.cos( v );
  15362. // normal
  15363. normal.x = ( cos * N.x + sin * B.x );
  15364. normal.y = ( cos * N.y + sin * B.y );
  15365. normal.z = ( cos * N.z + sin * B.z );
  15366. normal.normalize();
  15367. normals.push( normal.x, normal.y, normal.z );
  15368. // vertex
  15369. vertex.x = P.x + radius * normal.x;
  15370. vertex.y = P.y + radius * normal.y;
  15371. vertex.z = P.z + radius * normal.z;
  15372. vertices.push( vertex.x, vertex.y, vertex.z );
  15373. }
  15374. }
  15375. function generateIndices() {
  15376. for ( j = 1; j <= tubularSegments; j ++ ) {
  15377. for ( i = 1; i <= radialSegments; i ++ ) {
  15378. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15379. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  15380. var c = ( radialSegments + 1 ) * j + i;
  15381. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15382. // faces
  15383. indices.push( a, b, d );
  15384. indices.push( b, c, d );
  15385. }
  15386. }
  15387. }
  15388. function generateUVs() {
  15389. for ( i = 0; i <= tubularSegments; i ++ ) {
  15390. for ( j = 0; j <= radialSegments; j ++ ) {
  15391. uv.x = i / tubularSegments;
  15392. uv.y = j / radialSegments;
  15393. uvs.push( uv.x, uv.y );
  15394. }
  15395. }
  15396. }
  15397. }
  15398. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15399. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  15400. /**
  15401. * @author oosmoxiecode
  15402. * @author Mugen87 / https://github.com/Mugen87
  15403. *
  15404. * based on http://www.blackpawn.com/texts/pqtorus/
  15405. */
  15406. // TorusKnotGeometry
  15407. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  15408. Geometry.call( this );
  15409. this.type = 'TorusKnotGeometry';
  15410. this.parameters = {
  15411. radius: radius,
  15412. tube: tube,
  15413. tubularSegments: tubularSegments,
  15414. radialSegments: radialSegments,
  15415. p: p,
  15416. q: q
  15417. };
  15418. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  15419. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  15420. this.mergeVertices();
  15421. }
  15422. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  15423. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  15424. // TorusKnotBufferGeometry
  15425. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  15426. BufferGeometry.call( this );
  15427. this.type = 'TorusKnotBufferGeometry';
  15428. this.parameters = {
  15429. radius: radius,
  15430. tube: tube,
  15431. tubularSegments: tubularSegments,
  15432. radialSegments: radialSegments,
  15433. p: p,
  15434. q: q
  15435. };
  15436. radius = radius || 100;
  15437. tube = tube || 40;
  15438. tubularSegments = Math.floor( tubularSegments ) || 64;
  15439. radialSegments = Math.floor( radialSegments ) || 8;
  15440. p = p || 2;
  15441. q = q || 3;
  15442. // buffers
  15443. var indices = [];
  15444. var vertices = [];
  15445. var normals = [];
  15446. var uvs = [];
  15447. // helper variables
  15448. var i, j;
  15449. var vertex = new Vector3();
  15450. var normal = new Vector3();
  15451. var P1 = new Vector3();
  15452. var P2 = new Vector3();
  15453. var B = new Vector3();
  15454. var T = new Vector3();
  15455. var N = new Vector3();
  15456. // generate vertices, normals and uvs
  15457. for ( i = 0; i <= tubularSegments; ++ i ) {
  15458. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  15459. var u = i / tubularSegments * p * Math.PI * 2;
  15460. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  15461. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  15462. calculatePositionOnCurve( u, p, q, radius, P1 );
  15463. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  15464. // calculate orthonormal basis
  15465. T.subVectors( P2, P1 );
  15466. N.addVectors( P2, P1 );
  15467. B.crossVectors( T, N );
  15468. N.crossVectors( B, T );
  15469. // normalize B, N. T can be ignored, we don't use it
  15470. B.normalize();
  15471. N.normalize();
  15472. for ( j = 0; j <= radialSegments; ++ j ) {
  15473. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  15474. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  15475. var v = j / radialSegments * Math.PI * 2;
  15476. var cx = - tube * Math.cos( v );
  15477. var cy = tube * Math.sin( v );
  15478. // now calculate the final vertex position.
  15479. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  15480. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  15481. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  15482. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  15483. vertices.push( vertex.x, vertex.y, vertex.z );
  15484. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  15485. normal.subVectors( vertex, P1 ).normalize();
  15486. normals.push( normal.x, normal.y, normal.z );
  15487. // uv
  15488. uvs.push( i / tubularSegments );
  15489. uvs.push( j / radialSegments );
  15490. }
  15491. }
  15492. // generate indices
  15493. for ( j = 1; j <= tubularSegments; j ++ ) {
  15494. for ( i = 1; i <= radialSegments; i ++ ) {
  15495. // indices
  15496. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15497. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  15498. var c = ( radialSegments + 1 ) * j + i;
  15499. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15500. // faces
  15501. indices.push( a, b, d );
  15502. indices.push( b, c, d );
  15503. }
  15504. }
  15505. // build geometry
  15506. this.setIndex( indices );
  15507. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15508. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15509. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15510. // this function calculates the current position on the torus curve
  15511. function calculatePositionOnCurve( u, p, q, radius, position ) {
  15512. var cu = Math.cos( u );
  15513. var su = Math.sin( u );
  15514. var quOverP = q / p * u;
  15515. var cs = Math.cos( quOverP );
  15516. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  15517. position.y = radius * ( 2 + cs ) * su * 0.5;
  15518. position.z = radius * Math.sin( quOverP ) * 0.5;
  15519. }
  15520. }
  15521. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15522. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  15523. /**
  15524. * @author oosmoxiecode
  15525. * @author mrdoob / http://mrdoob.com/
  15526. * @author Mugen87 / https://github.com/Mugen87
  15527. */
  15528. // TorusGeometry
  15529. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15530. Geometry.call( this );
  15531. this.type = 'TorusGeometry';
  15532. this.parameters = {
  15533. radius: radius,
  15534. tube: tube,
  15535. radialSegments: radialSegments,
  15536. tubularSegments: tubularSegments,
  15537. arc: arc
  15538. };
  15539. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  15540. this.mergeVertices();
  15541. }
  15542. TorusGeometry.prototype = Object.create( Geometry.prototype );
  15543. TorusGeometry.prototype.constructor = TorusGeometry;
  15544. // TorusBufferGeometry
  15545. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15546. BufferGeometry.call( this );
  15547. this.type = 'TorusBufferGeometry';
  15548. this.parameters = {
  15549. radius: radius,
  15550. tube: tube,
  15551. radialSegments: radialSegments,
  15552. tubularSegments: tubularSegments,
  15553. arc: arc
  15554. };
  15555. radius = radius || 100;
  15556. tube = tube || 40;
  15557. radialSegments = Math.floor( radialSegments ) || 8;
  15558. tubularSegments = Math.floor( tubularSegments ) || 6;
  15559. arc = arc || Math.PI * 2;
  15560. // buffers
  15561. var indices = [];
  15562. var vertices = [];
  15563. var normals = [];
  15564. var uvs = [];
  15565. // helper variables
  15566. var center = new Vector3();
  15567. var vertex = new Vector3();
  15568. var normal = new Vector3();
  15569. var j, i;
  15570. // generate vertices, normals and uvs
  15571. for ( j = 0; j <= radialSegments; j ++ ) {
  15572. for ( i = 0; i <= tubularSegments; i ++ ) {
  15573. var u = i / tubularSegments * arc;
  15574. var v = j / radialSegments * Math.PI * 2;
  15575. // vertex
  15576. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  15577. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  15578. vertex.z = tube * Math.sin( v );
  15579. vertices.push( vertex.x, vertex.y, vertex.z );
  15580. // normal
  15581. center.x = radius * Math.cos( u );
  15582. center.y = radius * Math.sin( u );
  15583. normal.subVectors( vertex, center ).normalize();
  15584. normals.push( normal.x, normal.y, normal.z );
  15585. // uv
  15586. uvs.push( i / tubularSegments );
  15587. uvs.push( j / radialSegments );
  15588. }
  15589. }
  15590. // generate indices
  15591. for ( j = 1; j <= radialSegments; j ++ ) {
  15592. for ( i = 1; i <= tubularSegments; i ++ ) {
  15593. // indices
  15594. var a = ( tubularSegments + 1 ) * j + i - 1;
  15595. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  15596. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  15597. var d = ( tubularSegments + 1 ) * j + i;
  15598. // faces
  15599. indices.push( a, b, d );
  15600. indices.push( b, c, d );
  15601. }
  15602. }
  15603. // build geometry
  15604. this.setIndex( indices );
  15605. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15606. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15607. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15608. }
  15609. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15610. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  15611. /**
  15612. * @author zz85 / http://www.lab4games.net/zz85/blog
  15613. */
  15614. var ShapeUtils = {
  15615. // calculate area of the contour polygon
  15616. area: function ( contour ) {
  15617. var n = contour.length;
  15618. var a = 0.0;
  15619. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  15620. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15621. }
  15622. return a * 0.5;
  15623. },
  15624. triangulate: ( function () {
  15625. /**
  15626. * This code is a quick port of code written in C++ which was submitted to
  15627. * flipcode.com by John W. Ratcliff // July 22, 2000
  15628. * See original code and more information here:
  15629. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15630. *
  15631. * ported to actionscript by Zevan Rosser
  15632. * www.actionsnippet.com
  15633. *
  15634. * ported to javascript by Joshua Koo
  15635. * http://www.lab4games.net/zz85/blog
  15636. *
  15637. */
  15638. function snip( contour, u, v, w, n, verts ) {
  15639. var p;
  15640. var ax, ay, bx, by;
  15641. var cx, cy, px, py;
  15642. ax = contour[ verts[ u ] ].x;
  15643. ay = contour[ verts[ u ] ].y;
  15644. bx = contour[ verts[ v ] ].x;
  15645. by = contour[ verts[ v ] ].y;
  15646. cx = contour[ verts[ w ] ].x;
  15647. cy = contour[ verts[ w ] ].y;
  15648. if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false;
  15649. var aX, aY, bX, bY, cX, cY;
  15650. var apx, apy, bpx, bpy, cpx, cpy;
  15651. var cCROSSap, bCROSScp, aCROSSbp;
  15652. aX = cx - bx; aY = cy - by;
  15653. bX = ax - cx; bY = ay - cy;
  15654. cX = bx - ax; cY = by - ay;
  15655. for ( p = 0; p < n; p ++ ) {
  15656. px = contour[ verts[ p ] ].x;
  15657. py = contour[ verts[ p ] ].y;
  15658. if ( ( ( px === ax ) && ( py === ay ) ) ||
  15659. ( ( px === bx ) && ( py === by ) ) ||
  15660. ( ( px === cx ) && ( py === cy ) ) ) continue;
  15661. apx = px - ax; apy = py - ay;
  15662. bpx = px - bx; bpy = py - by;
  15663. cpx = px - cx; cpy = py - cy;
  15664. // see if p is inside triangle abc
  15665. aCROSSbp = aX * bpy - aY * bpx;
  15666. cCROSSap = cX * apy - cY * apx;
  15667. bCROSScp = bX * cpy - bY * cpx;
  15668. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  15669. }
  15670. return true;
  15671. }
  15672. // takes in an contour array and returns
  15673. return function triangulate( contour, indices ) {
  15674. var n = contour.length;
  15675. if ( n < 3 ) return null;
  15676. var result = [],
  15677. verts = [],
  15678. vertIndices = [];
  15679. /* we want a counter-clockwise polygon in verts */
  15680. var u, v, w;
  15681. if ( ShapeUtils.area( contour ) > 0.0 ) {
  15682. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  15683. } else {
  15684. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  15685. }
  15686. var nv = n;
  15687. /* remove nv - 2 vertices, creating 1 triangle every time */
  15688. var count = 2 * nv; /* error detection */
  15689. for ( v = nv - 1; nv > 2; ) {
  15690. /* if we loop, it is probably a non-simple polygon */
  15691. if ( ( count -- ) <= 0 ) {
  15692. //** Triangulate: ERROR - probable bad polygon!
  15693. //throw ( "Warning, unable to triangulate polygon!" );
  15694. //return null;
  15695. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15696. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  15697. if ( indices ) return vertIndices;
  15698. return result;
  15699. }
  15700. /* three consecutive vertices in current polygon, <u,v,w> */
  15701. u = v; if ( nv <= u ) u = 0; /* previous */
  15702. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15703. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15704. if ( snip( contour, u, v, w, nv, verts ) ) {
  15705. var a, b, c, s, t;
  15706. /* true names of the vertices */
  15707. a = verts[ u ];
  15708. b = verts[ v ];
  15709. c = verts[ w ];
  15710. /* output Triangle */
  15711. result.push( [ contour[ a ],
  15712. contour[ b ],
  15713. contour[ c ] ] );
  15714. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15715. /* remove v from the remaining polygon */
  15716. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  15717. verts[ s ] = verts[ t ];
  15718. }
  15719. nv --;
  15720. /* reset error detection counter */
  15721. count = 2 * nv;
  15722. }
  15723. }
  15724. if ( indices ) return vertIndices;
  15725. return result;
  15726. };
  15727. } )(),
  15728. triangulateShape: function ( contour, holes ) {
  15729. function removeDupEndPts(points) {
  15730. var l = points.length;
  15731. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  15732. points.pop();
  15733. }
  15734. }
  15735. removeDupEndPts( contour );
  15736. holes.forEach( removeDupEndPts );
  15737. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  15738. // inOtherPt needs to be collinear to the inSegment
  15739. if ( inSegPt1.x !== inSegPt2.x ) {
  15740. if ( inSegPt1.x < inSegPt2.x ) {
  15741. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  15742. } else {
  15743. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  15744. }
  15745. } else {
  15746. if ( inSegPt1.y < inSegPt2.y ) {
  15747. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  15748. } else {
  15749. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  15750. }
  15751. }
  15752. }
  15753. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  15754. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  15755. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  15756. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  15757. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  15758. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  15759. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  15760. if ( Math.abs( limit ) > Number.EPSILON ) {
  15761. // not parallel
  15762. var perpSeg2;
  15763. if ( limit > 0 ) {
  15764. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  15765. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15766. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  15767. } else {
  15768. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  15769. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15770. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  15771. }
  15772. // i.e. to reduce rounding errors
  15773. // intersection at endpoint of segment#1?
  15774. if ( perpSeg2 === 0 ) {
  15775. if ( ( inExcludeAdjacentSegs ) &&
  15776. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15777. return [ inSeg1Pt1 ];
  15778. }
  15779. if ( perpSeg2 === limit ) {
  15780. if ( ( inExcludeAdjacentSegs ) &&
  15781. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15782. return [ inSeg1Pt2 ];
  15783. }
  15784. // intersection at endpoint of segment#2?
  15785. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  15786. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  15787. // return real intersection point
  15788. var factorSeg1 = perpSeg2 / limit;
  15789. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  15790. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  15791. } else {
  15792. // parallel or collinear
  15793. if ( ( perpSeg1 !== 0 ) ||
  15794. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  15795. // they are collinear or degenerate
  15796. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  15797. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  15798. // both segments are points
  15799. if ( seg1Pt && seg2Pt ) {
  15800. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  15801. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  15802. return [ inSeg1Pt1 ]; // they are the same point
  15803. }
  15804. // segment#1 is a single point
  15805. if ( seg1Pt ) {
  15806. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  15807. return [ inSeg1Pt1 ];
  15808. }
  15809. // segment#2 is a single point
  15810. if ( seg2Pt ) {
  15811. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  15812. return [ inSeg2Pt1 ];
  15813. }
  15814. // they are collinear segments, which might overlap
  15815. var seg1min, seg1max, seg1minVal, seg1maxVal;
  15816. var seg2min, seg2max, seg2minVal, seg2maxVal;
  15817. if ( seg1dx !== 0 ) {
  15818. // the segments are NOT on a vertical line
  15819. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  15820. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  15821. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  15822. } else {
  15823. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  15824. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  15825. }
  15826. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  15827. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  15828. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  15829. } else {
  15830. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  15831. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  15832. }
  15833. } else {
  15834. // the segments are on a vertical line
  15835. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  15836. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  15837. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  15838. } else {
  15839. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  15840. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  15841. }
  15842. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  15843. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  15844. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  15845. } else {
  15846. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  15847. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  15848. }
  15849. }
  15850. if ( seg1minVal <= seg2minVal ) {
  15851. if ( seg1maxVal < seg2minVal ) return [];
  15852. if ( seg1maxVal === seg2minVal ) {
  15853. if ( inExcludeAdjacentSegs ) return [];
  15854. return [ seg2min ];
  15855. }
  15856. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  15857. return [ seg2min, seg2max ];
  15858. } else {
  15859. if ( seg1minVal > seg2maxVal ) return [];
  15860. if ( seg1minVal === seg2maxVal ) {
  15861. if ( inExcludeAdjacentSegs ) return [];
  15862. return [ seg1min ];
  15863. }
  15864. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  15865. return [ seg1min, seg2max ];
  15866. }
  15867. }
  15868. }
  15869. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  15870. // The order of legs is important
  15871. // translation of all points, so that Vertex is at (0,0)
  15872. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  15873. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  15874. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  15875. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  15876. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  15877. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  15878. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  15879. // angle != 180 deg.
  15880. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  15881. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  15882. if ( from2toAngle > 0 ) {
  15883. // main angle < 180 deg.
  15884. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  15885. } else {
  15886. // main angle > 180 deg.
  15887. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  15888. }
  15889. } else {
  15890. // angle == 180 deg.
  15891. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  15892. return ( from2otherAngle > 0 );
  15893. }
  15894. }
  15895. function removeHoles( contour, holes ) {
  15896. var shape = contour.concat(); // work on this shape
  15897. var hole;
  15898. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  15899. // Check if hole point lies within angle around shape point
  15900. var lastShapeIdx = shape.length - 1;
  15901. var prevShapeIdx = inShapeIdx - 1;
  15902. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  15903. var nextShapeIdx = inShapeIdx + 1;
  15904. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  15905. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  15906. if ( ! insideAngle ) {
  15907. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  15908. return false;
  15909. }
  15910. // Check if shape point lies within angle around hole point
  15911. var lastHoleIdx = hole.length - 1;
  15912. var prevHoleIdx = inHoleIdx - 1;
  15913. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  15914. var nextHoleIdx = inHoleIdx + 1;
  15915. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  15916. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  15917. if ( ! insideAngle ) {
  15918. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  15919. return false;
  15920. }
  15921. return true;
  15922. }
  15923. function intersectsShapeEdge( inShapePt, inHolePt ) {
  15924. // checks for intersections with shape edges
  15925. var sIdx, nextIdx, intersection;
  15926. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  15927. nextIdx = sIdx + 1; nextIdx %= shape.length;
  15928. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  15929. if ( intersection.length > 0 ) return true;
  15930. }
  15931. return false;
  15932. }
  15933. var indepHoles = [];
  15934. function intersectsHoleEdge( inShapePt, inHolePt ) {
  15935. // checks for intersections with hole edges
  15936. var ihIdx, chkHole,
  15937. hIdx, nextIdx, intersection;
  15938. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  15939. chkHole = holes[ indepHoles[ ihIdx ] ];
  15940. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  15941. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  15942. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  15943. if ( intersection.length > 0 ) return true;
  15944. }
  15945. }
  15946. return false;
  15947. }
  15948. var holeIndex, shapeIndex,
  15949. shapePt, holePt,
  15950. holeIdx, cutKey, failedCuts = [],
  15951. tmpShape1, tmpShape2,
  15952. tmpHole1, tmpHole2;
  15953. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15954. indepHoles.push( h );
  15955. }
  15956. var minShapeIndex = 0;
  15957. var counter = indepHoles.length * 2;
  15958. while ( indepHoles.length > 0 ) {
  15959. counter --;
  15960. if ( counter < 0 ) {
  15961. console.log( 'THREE.ShapeUtils: Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!' );
  15962. break;
  15963. }
  15964. // search for shape-vertex and hole-vertex,
  15965. // which can be connected without intersections
  15966. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  15967. shapePt = shape[ shapeIndex ];
  15968. holeIndex = - 1;
  15969. // search for hole which can be reached without intersections
  15970. for ( var h = 0; h < indepHoles.length; h ++ ) {
  15971. holeIdx = indepHoles[ h ];
  15972. // prevent multiple checks
  15973. cutKey = shapePt.x + ':' + shapePt.y + ':' + holeIdx;
  15974. if ( failedCuts[ cutKey ] !== undefined ) continue;
  15975. hole = holes[ holeIdx ];
  15976. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  15977. holePt = hole[ h2 ];
  15978. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  15979. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  15980. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  15981. holeIndex = h2;
  15982. indepHoles.splice( h, 1 );
  15983. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  15984. tmpShape2 = shape.slice( shapeIndex );
  15985. tmpHole1 = hole.slice( holeIndex );
  15986. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  15987. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  15988. minShapeIndex = shapeIndex;
  15989. // Debug only, to show the selected cuts
  15990. // glob_CutLines.push( [ shapePt, holePt ] );
  15991. break;
  15992. }
  15993. if ( holeIndex >= 0 ) break; // hole-vertex found
  15994. failedCuts[ cutKey ] = true; // remember failure
  15995. }
  15996. if ( holeIndex >= 0 ) break; // hole-vertex found
  15997. }
  15998. }
  15999. return shape; /* shape with no holes */
  16000. }
  16001. var i, il, f, face,
  16002. key, index,
  16003. allPointsMap = {};
  16004. // 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.
  16005. var allpoints = contour.concat();
  16006. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  16007. Array.prototype.push.apply( allpoints, holes[ h ] );
  16008. }
  16009. //console.log( "allpoints",allpoints, allpoints.length );
  16010. // prepare all points map
  16011. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  16012. key = allpoints[ i ].x + ':' + allpoints[ i ].y;
  16013. if ( allPointsMap[ key ] !== undefined ) {
  16014. console.warn( 'THREE.ShapeUtils: Duplicate point', key, i );
  16015. }
  16016. allPointsMap[ key ] = i;
  16017. }
  16018. // remove holes by cutting paths to holes and adding them to the shape
  16019. var shapeWithoutHoles = removeHoles( contour, holes );
  16020. var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  16021. //console.log( "triangles",triangles, triangles.length );
  16022. // check all face vertices against all points map
  16023. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  16024. face = triangles[ i ];
  16025. for ( f = 0; f < 3; f ++ ) {
  16026. key = face[ f ].x + ':' + face[ f ].y;
  16027. index = allPointsMap[ key ];
  16028. if ( index !== undefined ) {
  16029. face[ f ] = index;
  16030. }
  16031. }
  16032. }
  16033. return triangles.concat();
  16034. },
  16035. isClockWise: function ( pts ) {
  16036. return ShapeUtils.area( pts ) < 0;
  16037. }
  16038. };
  16039. /**
  16040. * @author zz85 / http://www.lab4games.net/zz85/blog
  16041. *
  16042. * Creates extruded geometry from a path shape.
  16043. *
  16044. * parameters = {
  16045. *
  16046. * curveSegments: <int>, // number of points on the curves
  16047. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  16048. * amount: <int>, // Depth to extrude the shape
  16049. *
  16050. * bevelEnabled: <bool>, // turn on bevel
  16051. * bevelThickness: <float>, // how deep into the original shape bevel goes
  16052. * bevelSize: <float>, // how far from shape outline is bevel
  16053. * bevelSegments: <int>, // number of bevel layers
  16054. *
  16055. * extrudePath: <THREE.Curve> // curve to extrude shape along
  16056. * frames: <Object> // containing arrays of tangents, normals, binormals
  16057. *
  16058. * UVGenerator: <Object> // object that provides UV generator functions
  16059. *
  16060. * }
  16061. */
  16062. // ExtrudeGeometry
  16063. function ExtrudeGeometry( shapes, options ) {
  16064. Geometry.call( this );
  16065. this.type = 'ExtrudeGeometry';
  16066. this.parameters = {
  16067. shapes: shapes,
  16068. options: options
  16069. };
  16070. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  16071. this.mergeVertices();
  16072. }
  16073. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  16074. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  16075. // ExtrudeBufferGeometry
  16076. function ExtrudeBufferGeometry( shapes, options ) {
  16077. if ( typeof ( shapes ) === "undefined" ) {
  16078. return;
  16079. }
  16080. BufferGeometry.call( this );
  16081. this.type = 'ExtrudeBufferGeometry';
  16082. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  16083. this.addShapeList( shapes, options );
  16084. this.computeVertexNormals();
  16085. // can't really use automatic vertex normals
  16086. // as then front and back sides get smoothed too
  16087. // should do separate smoothing just for sides
  16088. //this.computeVertexNormals();
  16089. //console.log( "took", ( Date.now() - startTime ) );
  16090. }
  16091. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16092. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  16093. ExtrudeBufferGeometry.prototype.getArrays = function () {
  16094. var positionAttribute = this.getAttribute( "position" );
  16095. var verticesArray = positionAttribute ? Array.prototype.slice.call( positionAttribute.array ) : [];
  16096. var uvAttribute = this.getAttribute( "uv" );
  16097. var uvArray = uvAttribute ? Array.prototype.slice.call( uvAttribute.array ) : [];
  16098. var IndexAttribute = this.index;
  16099. var indicesArray = IndexAttribute ? Array.prototype.slice.call( IndexAttribute.array ) : [];
  16100. return {
  16101. position: verticesArray,
  16102. uv: uvArray,
  16103. index: indicesArray
  16104. };
  16105. };
  16106. ExtrudeBufferGeometry.prototype.addShapeList = function ( shapes, options ) {
  16107. var sl = shapes.length;
  16108. options.arrays = this.getArrays();
  16109. for ( var s = 0; s < sl; s ++ ) {
  16110. var shape = shapes[ s ];
  16111. this.addShape( shape, options );
  16112. }
  16113. this.setIndex( options.arrays.index );
  16114. this.addAttribute( 'position', new Float32BufferAttribute( options.arrays.position, 3 ) );
  16115. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  16116. };
  16117. ExtrudeBufferGeometry.prototype.addShape = function ( shape, options ) {
  16118. var arrays = options.arrays ? options.arrays : this.getArrays();
  16119. var verticesArray = arrays.position;
  16120. var indicesArray = arrays.index;
  16121. var uvArray = arrays.uv;
  16122. var placeholder = [];
  16123. var amount = options.amount !== undefined ? options.amount : 100;
  16124. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  16125. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  16126. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  16127. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  16128. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  16129. var steps = options.steps !== undefined ? options.steps : 1;
  16130. var extrudePath = options.extrudePath;
  16131. var extrudePts, extrudeByPath = false;
  16132. // Use default WorldUVGenerator if no UV generators are specified.
  16133. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  16134. var splineTube, binormal, normal, position2;
  16135. if ( extrudePath ) {
  16136. extrudePts = extrudePath.getSpacedPoints( steps );
  16137. extrudeByPath = true;
  16138. bevelEnabled = false; // bevels not supported for path extrusion
  16139. // SETUP TNB variables
  16140. // TODO1 - have a .isClosed in spline?
  16141. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  16142. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  16143. binormal = new Vector3();
  16144. normal = new Vector3();
  16145. position2 = new Vector3();
  16146. }
  16147. // Safeguards if bevels are not enabled
  16148. if ( ! bevelEnabled ) {
  16149. bevelSegments = 0;
  16150. bevelThickness = 0;
  16151. bevelSize = 0;
  16152. }
  16153. // Variables initialization
  16154. var ahole, h, hl; // looping of holes
  16155. var scope = this;
  16156. var shapePoints = shape.extractPoints( curveSegments );
  16157. var vertices = shapePoints.shape;
  16158. var holes = shapePoints.holes;
  16159. var reverse = ! ShapeUtils.isClockWise( vertices );
  16160. if ( reverse ) {
  16161. vertices = vertices.reverse();
  16162. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  16163. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16164. ahole = holes[ h ];
  16165. if ( ShapeUtils.isClockWise( ahole ) ) {
  16166. holes[ h ] = ahole.reverse();
  16167. }
  16168. }
  16169. }
  16170. var faces = ShapeUtils.triangulateShape( vertices, holes );
  16171. /* Vertices */
  16172. var contour = vertices; // vertices has all points but contour has only points of circumference
  16173. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16174. ahole = holes[ h ];
  16175. vertices = vertices.concat( ahole );
  16176. }
  16177. function scalePt2( pt, vec, size ) {
  16178. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  16179. return vec.clone().multiplyScalar( size ).add( pt );
  16180. }
  16181. var b, bs, t, z,
  16182. vert, vlen = vertices.length,
  16183. face, flen = faces.length;
  16184. // Find directions for point movement
  16185. function getBevelVec( inPt, inPrev, inNext ) {
  16186. // computes for inPt the corresponding point inPt' on a new contour
  16187. // shifted by 1 unit (length of normalized vector) to the left
  16188. // if we walk along contour clockwise, this new contour is outside the old one
  16189. //
  16190. // inPt' is the intersection of the two lines parallel to the two
  16191. // adjacent edges of inPt at a distance of 1 unit on the left side.
  16192. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  16193. // good reading for geometry algorithms (here: line-line intersection)
  16194. // http://geomalgorithms.com/a05-_intersect-1.html
  16195. var v_prev_x = inPt.x - inPrev.x,
  16196. v_prev_y = inPt.y - inPrev.y;
  16197. var v_next_x = inNext.x - inPt.x,
  16198. v_next_y = inNext.y - inPt.y;
  16199. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  16200. // check for collinear edges
  16201. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  16202. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  16203. // not collinear
  16204. // length of vectors for normalizing
  16205. var v_prev_len = Math.sqrt( v_prev_lensq );
  16206. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  16207. // shift adjacent points by unit vectors to the left
  16208. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  16209. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  16210. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  16211. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  16212. // scaling factor for v_prev to intersection point
  16213. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  16214. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  16215. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  16216. // vector from inPt to intersection point
  16217. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  16218. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  16219. // Don't normalize!, otherwise sharp corners become ugly
  16220. // but prevent crazy spikes
  16221. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  16222. if ( v_trans_lensq <= 2 ) {
  16223. return new Vector2( v_trans_x, v_trans_y );
  16224. } else {
  16225. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  16226. }
  16227. } else {
  16228. // handle special case of collinear edges
  16229. var direction_eq = false; // assumes: opposite
  16230. if ( v_prev_x > Number.EPSILON ) {
  16231. if ( v_next_x > Number.EPSILON ) {
  16232. direction_eq = true;
  16233. }
  16234. } else {
  16235. if ( v_prev_x < - Number.EPSILON ) {
  16236. if ( v_next_x < - Number.EPSILON ) {
  16237. direction_eq = true;
  16238. }
  16239. } else {
  16240. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  16241. direction_eq = true;
  16242. }
  16243. }
  16244. }
  16245. if ( direction_eq ) {
  16246. // console.log("Warning: lines are a straight sequence");
  16247. v_trans_x = - v_prev_y;
  16248. v_trans_y = v_prev_x;
  16249. shrink_by = Math.sqrt( v_prev_lensq );
  16250. } else {
  16251. // console.log("Warning: lines are a straight spike");
  16252. v_trans_x = v_prev_x;
  16253. v_trans_y = v_prev_y;
  16254. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  16255. }
  16256. }
  16257. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  16258. }
  16259. var contourMovements = [];
  16260. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  16261. if ( j === il ) j = 0;
  16262. if ( k === il ) k = 0;
  16263. // (j)---(i)---(k)
  16264. // console.log('i,j,k', i, j , k)
  16265. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  16266. }
  16267. var holesMovements = [],
  16268. oneHoleMovements, verticesMovements = contourMovements.concat();
  16269. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16270. ahole = holes[ h ];
  16271. oneHoleMovements = [];
  16272. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  16273. if ( j === il ) j = 0;
  16274. if ( k === il ) k = 0;
  16275. // (j)---(i)---(k)
  16276. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  16277. }
  16278. holesMovements.push( oneHoleMovements );
  16279. verticesMovements = verticesMovements.concat( oneHoleMovements );
  16280. }
  16281. // Loop bevelSegments, 1 for the front, 1 for the back
  16282. for ( b = 0; b < bevelSegments; b ++ ) {
  16283. //for ( b = bevelSegments; b > 0; b -- ) {
  16284. t = b / bevelSegments;
  16285. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  16286. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  16287. // contract shape
  16288. for ( i = 0, il = contour.length; i < il; i ++ ) {
  16289. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  16290. v( vert.x, vert.y, - z );
  16291. }
  16292. // expand holes
  16293. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16294. ahole = holes[ h ];
  16295. oneHoleMovements = holesMovements[ h ];
  16296. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  16297. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  16298. v( vert.x, vert.y, - z );
  16299. }
  16300. }
  16301. }
  16302. bs = bevelSize;
  16303. // Back facing vertices
  16304. for ( i = 0; i < vlen; i ++ ) {
  16305. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  16306. if ( ! extrudeByPath ) {
  16307. v( vert.x, vert.y, 0 );
  16308. } else {
  16309. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  16310. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  16311. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  16312. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  16313. v( position2.x, position2.y, position2.z );
  16314. }
  16315. }
  16316. // Add stepped vertices...
  16317. // Including front facing vertices
  16318. var s;
  16319. for ( s = 1; s <= steps; s ++ ) {
  16320. for ( i = 0; i < vlen; i ++ ) {
  16321. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  16322. if ( ! extrudeByPath ) {
  16323. v( vert.x, vert.y, amount / steps * s );
  16324. } else {
  16325. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  16326. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  16327. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  16328. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  16329. v( position2.x, position2.y, position2.z );
  16330. }
  16331. }
  16332. }
  16333. // Add bevel segments planes
  16334. //for ( b = 1; b <= bevelSegments; b ++ ) {
  16335. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  16336. t = b / bevelSegments;
  16337. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  16338. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  16339. // contract shape
  16340. for ( i = 0, il = contour.length; i < il; i ++ ) {
  16341. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  16342. v( vert.x, vert.y, amount + z );
  16343. }
  16344. // expand holes
  16345. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16346. ahole = holes[ h ];
  16347. oneHoleMovements = holesMovements[ h ];
  16348. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  16349. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  16350. if ( ! extrudeByPath ) {
  16351. v( vert.x, vert.y, amount + z );
  16352. } else {
  16353. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  16354. }
  16355. }
  16356. }
  16357. }
  16358. /* Faces */
  16359. // Top and bottom faces
  16360. buildLidFaces();
  16361. // Sides faces
  16362. buildSideFaces();
  16363. ///// Internal functions
  16364. function buildLidFaces() {
  16365. var start = verticesArray.length/3;
  16366. if ( bevelEnabled ) {
  16367. var layer = 0; // steps + 1
  16368. var offset = vlen * layer;
  16369. // Bottom faces
  16370. for ( i = 0; i < flen; i ++ ) {
  16371. face = faces[ i ];
  16372. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  16373. }
  16374. layer = steps + bevelSegments * 2;
  16375. offset = vlen * layer;
  16376. // Top faces
  16377. for ( i = 0; i < flen; i ++ ) {
  16378. face = faces[ i ];
  16379. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  16380. }
  16381. } else {
  16382. // Bottom faces
  16383. for ( i = 0; i < flen; i ++ ) {
  16384. face = faces[ i ];
  16385. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  16386. }
  16387. // Top faces
  16388. for ( i = 0; i < flen; i ++ ) {
  16389. face = faces[ i ];
  16390. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  16391. }
  16392. }
  16393. scope.addGroup( start, verticesArray.length/3 -start, options.material !== undefined ? options.material : 0);
  16394. }
  16395. // Create faces for the z-sides of the shape
  16396. function buildSideFaces() {
  16397. var start = verticesArray.length/3;
  16398. var layeroffset = 0;
  16399. sidewalls( contour, layeroffset );
  16400. layeroffset += contour.length;
  16401. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16402. ahole = holes[ h ];
  16403. sidewalls( ahole, layeroffset );
  16404. //, true
  16405. layeroffset += ahole.length;
  16406. }
  16407. scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);
  16408. }
  16409. function sidewalls( contour, layeroffset ) {
  16410. var j, k;
  16411. i = contour.length;
  16412. while ( -- i >= 0 ) {
  16413. j = i;
  16414. k = i - 1;
  16415. if ( k < 0 ) k = contour.length - 1;
  16416. //console.log('b', i,j, i-1, k,vertices.length);
  16417. var s = 0,
  16418. sl = steps + bevelSegments * 2;
  16419. for ( s = 0; s < sl; s ++ ) {
  16420. var slen1 = vlen * s;
  16421. var slen2 = vlen * ( s + 1 );
  16422. var a = layeroffset + j + slen1,
  16423. b = layeroffset + k + slen1,
  16424. c = layeroffset + k + slen2,
  16425. d = layeroffset + j + slen2;
  16426. f4( a, b, c, d, contour, s, sl, j, k );
  16427. }
  16428. }
  16429. }
  16430. function v( x, y, z ) {
  16431. placeholder.push( x );
  16432. placeholder.push( y );
  16433. placeholder.push( z );
  16434. }
  16435. function f3( a, b, c ) {
  16436. addVertex( a );
  16437. addVertex( b );
  16438. addVertex( c );
  16439. var nextIndex = verticesArray.length / 3;
  16440. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  16441. addUV( uvs[ 0 ] );
  16442. addUV( uvs[ 1 ] );
  16443. addUV( uvs[ 2 ] );
  16444. }
  16445. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  16446. addVertex( a );
  16447. addVertex( b );
  16448. addVertex( d );
  16449. addVertex( b );
  16450. addVertex( c );
  16451. addVertex( d );
  16452. var nextIndex = verticesArray.length / 3;
  16453. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  16454. addUV( uvs[ 0 ] );
  16455. addUV( uvs[ 1 ] );
  16456. addUV( uvs[ 3 ] );
  16457. addUV( uvs[ 1 ] );
  16458. addUV( uvs[ 2 ] );
  16459. addUV( uvs[ 3 ] );
  16460. }
  16461. function addVertex( index ) {
  16462. indicesArray.push( verticesArray.length / 3 );
  16463. verticesArray.push( placeholder[ index * 3 + 0 ] );
  16464. verticesArray.push( placeholder[ index * 3 + 1 ] );
  16465. verticesArray.push( placeholder[ index * 3 + 2 ] );
  16466. }
  16467. function addUV( vector2 ) {
  16468. uvArray.push( vector2.x );
  16469. uvArray.push( vector2.y );
  16470. }
  16471. if ( ! options.arrays ) {
  16472. this.setIndex( indicesArray );
  16473. this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  16474. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  16475. }
  16476. };
  16477. ExtrudeGeometry.WorldUVGenerator = {
  16478. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  16479. var a_x = vertices[ indexA * 3 ];
  16480. var a_y = vertices[ indexA * 3 + 1 ];
  16481. var b_x = vertices[ indexB * 3 ];
  16482. var b_y = vertices[ indexB * 3 + 1 ];
  16483. var c_x = vertices[ indexC * 3 ];
  16484. var c_y = vertices[ indexC * 3 + 1 ];
  16485. return [
  16486. new Vector2( a_x, a_y ),
  16487. new Vector2( b_x, b_y ),
  16488. new Vector2( c_x, c_y )
  16489. ];
  16490. },
  16491. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  16492. var a_x = vertices[ indexA * 3 ];
  16493. var a_y = vertices[ indexA * 3 + 1 ];
  16494. var a_z = vertices[ indexA * 3 + 2 ];
  16495. var b_x = vertices[ indexB * 3 ];
  16496. var b_y = vertices[ indexB * 3 + 1 ];
  16497. var b_z = vertices[ indexB * 3 + 2 ];
  16498. var c_x = vertices[ indexC * 3 ];
  16499. var c_y = vertices[ indexC * 3 + 1 ];
  16500. var c_z = vertices[ indexC * 3 + 2 ];
  16501. var d_x = vertices[ indexD * 3 ];
  16502. var d_y = vertices[ indexD * 3 + 1 ];
  16503. var d_z = vertices[ indexD * 3 + 2 ];
  16504. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  16505. return [
  16506. new Vector2( a_x, 1 - a_z ),
  16507. new Vector2( b_x, 1 - b_z ),
  16508. new Vector2( c_x, 1 - c_z ),
  16509. new Vector2( d_x, 1 - d_z )
  16510. ];
  16511. } else {
  16512. return [
  16513. new Vector2( a_y, 1 - a_z ),
  16514. new Vector2( b_y, 1 - b_z ),
  16515. new Vector2( c_y, 1 - c_z ),
  16516. new Vector2( d_y, 1 - d_z )
  16517. ];
  16518. }
  16519. }
  16520. };
  16521. /**
  16522. * @author zz85 / http://www.lab4games.net/zz85/blog
  16523. * @author alteredq / http://alteredqualia.com/
  16524. *
  16525. * Text = 3D Text
  16526. *
  16527. * parameters = {
  16528. * font: <THREE.Font>, // font
  16529. *
  16530. * size: <float>, // size of the text
  16531. * height: <float>, // thickness to extrude text
  16532. * curveSegments: <int>, // number of points on the curves
  16533. *
  16534. * bevelEnabled: <bool>, // turn on bevel
  16535. * bevelThickness: <float>, // how deep into text bevel goes
  16536. * bevelSize: <float> // how far from text outline is bevel
  16537. * }
  16538. */
  16539. // TextGeometry
  16540. function TextGeometry( text, parameters ) {
  16541. Geometry.call( this );
  16542. this.type = 'TextGeometry';
  16543. this.parameters = {
  16544. text: text,
  16545. parameters: parameters
  16546. };
  16547. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  16548. this.mergeVertices();
  16549. }
  16550. TextGeometry.prototype = Object.create( Geometry.prototype );
  16551. TextGeometry.prototype.constructor = TextGeometry;
  16552. // TextBufferGeometry
  16553. function TextBufferGeometry( text, parameters ) {
  16554. parameters = parameters || {};
  16555. var font = parameters.font;
  16556. if ( ! ( font && font.isFont ) ) {
  16557. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  16558. return new Geometry();
  16559. }
  16560. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  16561. // translate parameters to ExtrudeGeometry API
  16562. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  16563. // defaults
  16564. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  16565. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  16566. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  16567. ExtrudeBufferGeometry.call( this, shapes, parameters );
  16568. this.type = 'TextBufferGeometry';
  16569. }
  16570. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  16571. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  16572. /**
  16573. * @author mrdoob / http://mrdoob.com/
  16574. * @author benaadams / https://twitter.com/ben_a_adams
  16575. * @author Mugen87 / https://github.com/Mugen87
  16576. */
  16577. // SphereGeometry
  16578. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16579. Geometry.call( this );
  16580. this.type = 'SphereGeometry';
  16581. this.parameters = {
  16582. radius: radius,
  16583. widthSegments: widthSegments,
  16584. heightSegments: heightSegments,
  16585. phiStart: phiStart,
  16586. phiLength: phiLength,
  16587. thetaStart: thetaStart,
  16588. thetaLength: thetaLength
  16589. };
  16590. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  16591. this.mergeVertices();
  16592. }
  16593. SphereGeometry.prototype = Object.create( Geometry.prototype );
  16594. SphereGeometry.prototype.constructor = SphereGeometry;
  16595. // SphereBufferGeometry
  16596. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16597. BufferGeometry.call( this );
  16598. this.type = 'SphereBufferGeometry';
  16599. this.parameters = {
  16600. radius: radius,
  16601. widthSegments: widthSegments,
  16602. heightSegments: heightSegments,
  16603. phiStart: phiStart,
  16604. phiLength: phiLength,
  16605. thetaStart: thetaStart,
  16606. thetaLength: thetaLength
  16607. };
  16608. radius = radius || 50;
  16609. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  16610. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  16611. phiStart = phiStart !== undefined ? phiStart : 0;
  16612. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  16613. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16614. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  16615. var thetaEnd = thetaStart + thetaLength;
  16616. var ix, iy;
  16617. var index = 0;
  16618. var grid = [];
  16619. var vertex = new Vector3();
  16620. var normal = new Vector3();
  16621. // buffers
  16622. var indices = [];
  16623. var vertices = [];
  16624. var normals = [];
  16625. var uvs = [];
  16626. // generate vertices, normals and uvs
  16627. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  16628. var verticesRow = [];
  16629. var v = iy / heightSegments;
  16630. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  16631. var u = ix / widthSegments;
  16632. // vertex
  16633. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16634. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  16635. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16636. vertices.push( vertex.x, vertex.y, vertex.z );
  16637. // normal
  16638. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  16639. normals.push( normal.x, normal.y, normal.z );
  16640. // uv
  16641. uvs.push( u, 1 - v );
  16642. verticesRow.push( index ++ );
  16643. }
  16644. grid.push( verticesRow );
  16645. }
  16646. // indices
  16647. for ( iy = 0; iy < heightSegments; iy ++ ) {
  16648. for ( ix = 0; ix < widthSegments; ix ++ ) {
  16649. var a = grid[ iy ][ ix + 1 ];
  16650. var b = grid[ iy ][ ix ];
  16651. var c = grid[ iy + 1 ][ ix ];
  16652. var d = grid[ iy + 1 ][ ix + 1 ];
  16653. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  16654. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  16655. }
  16656. }
  16657. // build geometry
  16658. this.setIndex( indices );
  16659. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16660. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16661. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16662. }
  16663. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16664. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  16665. /**
  16666. * @author Kaleb Murphy
  16667. * @author Mugen87 / https://github.com/Mugen87
  16668. */
  16669. // RingGeometry
  16670. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16671. Geometry.call( this );
  16672. this.type = 'RingGeometry';
  16673. this.parameters = {
  16674. innerRadius: innerRadius,
  16675. outerRadius: outerRadius,
  16676. thetaSegments: thetaSegments,
  16677. phiSegments: phiSegments,
  16678. thetaStart: thetaStart,
  16679. thetaLength: thetaLength
  16680. };
  16681. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  16682. this.mergeVertices();
  16683. }
  16684. RingGeometry.prototype = Object.create( Geometry.prototype );
  16685. RingGeometry.prototype.constructor = RingGeometry;
  16686. // RingBufferGeometry
  16687. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16688. BufferGeometry.call( this );
  16689. this.type = 'RingBufferGeometry';
  16690. this.parameters = {
  16691. innerRadius: innerRadius,
  16692. outerRadius: outerRadius,
  16693. thetaSegments: thetaSegments,
  16694. phiSegments: phiSegments,
  16695. thetaStart: thetaStart,
  16696. thetaLength: thetaLength
  16697. };
  16698. innerRadius = innerRadius || 20;
  16699. outerRadius = outerRadius || 50;
  16700. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16701. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16702. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  16703. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  16704. // buffers
  16705. var indices = [];
  16706. var vertices = [];
  16707. var normals = [];
  16708. var uvs = [];
  16709. // some helper variables
  16710. var segment;
  16711. var radius = innerRadius;
  16712. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  16713. var vertex = new Vector3();
  16714. var uv = new Vector2();
  16715. var j, i;
  16716. // generate vertices, normals and uvs
  16717. for ( j = 0; j <= phiSegments; j ++ ) {
  16718. for ( i = 0; i <= thetaSegments; i ++ ) {
  16719. // values are generate from the inside of the ring to the outside
  16720. segment = thetaStart + i / thetaSegments * thetaLength;
  16721. // vertex
  16722. vertex.x = radius * Math.cos( segment );
  16723. vertex.y = radius * Math.sin( segment );
  16724. vertices.push( vertex.x, vertex.y, vertex.z );
  16725. // normal
  16726. normals.push( 0, 0, 1 );
  16727. // uv
  16728. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  16729. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  16730. uvs.push( uv.x, uv.y );
  16731. }
  16732. // increase the radius for next row of vertices
  16733. radius += radiusStep;
  16734. }
  16735. // indices
  16736. for ( j = 0; j < phiSegments; j ++ ) {
  16737. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  16738. for ( i = 0; i < thetaSegments; i ++ ) {
  16739. segment = i + thetaSegmentLevel;
  16740. var a = segment;
  16741. var b = segment + thetaSegments + 1;
  16742. var c = segment + thetaSegments + 2;
  16743. var d = segment + 1;
  16744. // faces
  16745. indices.push( a, b, d );
  16746. indices.push( b, c, d );
  16747. }
  16748. }
  16749. // build geometry
  16750. this.setIndex( indices );
  16751. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16752. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16753. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16754. }
  16755. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16756. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  16757. /**
  16758. * @author astrodud / http://astrodud.isgreat.org/
  16759. * @author zz85 / https://github.com/zz85
  16760. * @author bhouston / http://clara.io
  16761. * @author Mugen87 / https://github.com/Mugen87
  16762. */
  16763. // LatheGeometry
  16764. function LatheGeometry( points, segments, phiStart, phiLength ) {
  16765. Geometry.call( this );
  16766. this.type = 'LatheGeometry';
  16767. this.parameters = {
  16768. points: points,
  16769. segments: segments,
  16770. phiStart: phiStart,
  16771. phiLength: phiLength
  16772. };
  16773. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  16774. this.mergeVertices();
  16775. }
  16776. LatheGeometry.prototype = Object.create( Geometry.prototype );
  16777. LatheGeometry.prototype.constructor = LatheGeometry;
  16778. // LatheBufferGeometry
  16779. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  16780. BufferGeometry.call( this );
  16781. this.type = 'LatheBufferGeometry';
  16782. this.parameters = {
  16783. points: points,
  16784. segments: segments,
  16785. phiStart: phiStart,
  16786. phiLength: phiLength
  16787. };
  16788. segments = Math.floor( segments ) || 12;
  16789. phiStart = phiStart || 0;
  16790. phiLength = phiLength || Math.PI * 2;
  16791. // clamp phiLength so it's in range of [ 0, 2PI ]
  16792. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  16793. // buffers
  16794. var indices = [];
  16795. var vertices = [];
  16796. var uvs = [];
  16797. // helper variables
  16798. var base;
  16799. var inverseSegments = 1.0 / segments;
  16800. var vertex = new Vector3();
  16801. var uv = new Vector2();
  16802. var i, j;
  16803. // generate vertices and uvs
  16804. for ( i = 0; i <= segments; i ++ ) {
  16805. var phi = phiStart + i * inverseSegments * phiLength;
  16806. var sin = Math.sin( phi );
  16807. var cos = Math.cos( phi );
  16808. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  16809. // vertex
  16810. vertex.x = points[ j ].x * sin;
  16811. vertex.y = points[ j ].y;
  16812. vertex.z = points[ j ].x * cos;
  16813. vertices.push( vertex.x, vertex.y, vertex.z );
  16814. // uv
  16815. uv.x = i / segments;
  16816. uv.y = j / ( points.length - 1 );
  16817. uvs.push( uv.x, uv.y );
  16818. }
  16819. }
  16820. // indices
  16821. for ( i = 0; i < segments; i ++ ) {
  16822. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  16823. base = j + i * points.length;
  16824. var a = base;
  16825. var b = base + points.length;
  16826. var c = base + points.length + 1;
  16827. var d = base + 1;
  16828. // faces
  16829. indices.push( a, b, d );
  16830. indices.push( b, c, d );
  16831. }
  16832. }
  16833. // build geometry
  16834. this.setIndex( indices );
  16835. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16836. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16837. // generate normals
  16838. this.computeVertexNormals();
  16839. // if the geometry is closed, we need to average the normals along the seam.
  16840. // because the corresponding vertices are identical (but still have different UVs).
  16841. if ( phiLength === Math.PI * 2 ) {
  16842. var normals = this.attributes.normal.array;
  16843. var n1 = new Vector3();
  16844. var n2 = new Vector3();
  16845. var n = new Vector3();
  16846. // this is the buffer offset for the last line of vertices
  16847. base = segments * points.length * 3;
  16848. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  16849. // select the normal of the vertex in the first line
  16850. n1.x = normals[ j + 0 ];
  16851. n1.y = normals[ j + 1 ];
  16852. n1.z = normals[ j + 2 ];
  16853. // select the normal of the vertex in the last line
  16854. n2.x = normals[ base + j + 0 ];
  16855. n2.y = normals[ base + j + 1 ];
  16856. n2.z = normals[ base + j + 2 ];
  16857. // average normals
  16858. n.addVectors( n1, n2 ).normalize();
  16859. // assign the new values to both normals
  16860. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  16861. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  16862. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  16863. }
  16864. }
  16865. }
  16866. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16867. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  16868. /**
  16869. * @author jonobr1 / http://jonobr1.com
  16870. * @author Mugen87 / https://github.com/Mugen87
  16871. */
  16872. // ShapeGeometry
  16873. function ShapeGeometry( shapes, curveSegments ) {
  16874. Geometry.call( this );
  16875. this.type = 'ShapeGeometry';
  16876. if ( typeof curveSegments === 'object' ) {
  16877. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  16878. curveSegments = curveSegments.curveSegments;
  16879. }
  16880. this.parameters = {
  16881. shapes: shapes,
  16882. curveSegments: curveSegments
  16883. };
  16884. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  16885. this.mergeVertices();
  16886. }
  16887. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  16888. ShapeGeometry.prototype.constructor = ShapeGeometry;
  16889. // ShapeBufferGeometry
  16890. function ShapeBufferGeometry( shapes, curveSegments ) {
  16891. BufferGeometry.call( this );
  16892. this.type = 'ShapeBufferGeometry';
  16893. this.parameters = {
  16894. shapes: shapes,
  16895. curveSegments: curveSegments
  16896. };
  16897. curveSegments = curveSegments || 12;
  16898. // buffers
  16899. var indices = [];
  16900. var vertices = [];
  16901. var normals = [];
  16902. var uvs = [];
  16903. // helper variables
  16904. var groupStart = 0;
  16905. var groupCount = 0;
  16906. // allow single and array values for "shapes" parameter
  16907. if ( Array.isArray( shapes ) === false ) {
  16908. addShape( shapes );
  16909. } else {
  16910. for ( var i = 0; i < shapes.length; i ++ ) {
  16911. addShape( shapes[ i ] );
  16912. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  16913. groupStart += groupCount;
  16914. groupCount = 0;
  16915. }
  16916. }
  16917. // build geometry
  16918. this.setIndex( indices );
  16919. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16920. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16921. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16922. // helper functions
  16923. function addShape( shape ) {
  16924. var i, l, shapeHole;
  16925. var indexOffset = vertices.length / 3;
  16926. var points = shape.extractPoints( curveSegments );
  16927. var shapeVertices = points.shape;
  16928. var shapeHoles = points.holes;
  16929. // check direction of vertices
  16930. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  16931. shapeVertices = shapeVertices.reverse();
  16932. // also check if holes are in the opposite direction
  16933. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16934. shapeHole = shapeHoles[ i ];
  16935. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  16936. shapeHoles[ i ] = shapeHole.reverse();
  16937. }
  16938. }
  16939. }
  16940. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  16941. // join vertices of inner and outer paths to a single array
  16942. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16943. shapeHole = shapeHoles[ i ];
  16944. shapeVertices = shapeVertices.concat( shapeHole );
  16945. }
  16946. // vertices, normals, uvs
  16947. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  16948. var vertex = shapeVertices[ i ];
  16949. vertices.push( vertex.x, vertex.y, 0 );
  16950. normals.push( 0, 0, 1 );
  16951. uvs.push( vertex.x, vertex.y ); // world uvs
  16952. }
  16953. // incides
  16954. for ( i = 0, l = faces.length; i < l; i ++ ) {
  16955. var face = faces[ i ];
  16956. var a = face[ 0 ] + indexOffset;
  16957. var b = face[ 1 ] + indexOffset;
  16958. var c = face[ 2 ] + indexOffset;
  16959. indices.push( a, b, c );
  16960. groupCount += 3;
  16961. }
  16962. }
  16963. }
  16964. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16965. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  16966. /**
  16967. * @author WestLangley / http://github.com/WestLangley
  16968. * @author Mugen87 / https://github.com/Mugen87
  16969. */
  16970. function EdgesGeometry( geometry, thresholdAngle ) {
  16971. BufferGeometry.call( this );
  16972. this.type = 'EdgesGeometry';
  16973. this.parameters = {
  16974. thresholdAngle: thresholdAngle
  16975. };
  16976. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  16977. // buffer
  16978. var vertices = [];
  16979. // helper variables
  16980. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  16981. var edge = [ 0, 0 ], edges = {}, edge1, edge2;
  16982. var key, keys = [ 'a', 'b', 'c' ];
  16983. // prepare source geometry
  16984. var geometry2;
  16985. if ( geometry.isBufferGeometry ) {
  16986. geometry2 = new Geometry();
  16987. geometry2.fromBufferGeometry( geometry );
  16988. } else {
  16989. geometry2 = geometry.clone();
  16990. }
  16991. geometry2.mergeVertices();
  16992. geometry2.computeFaceNormals();
  16993. var sourceVertices = geometry2.vertices;
  16994. var faces = geometry2.faces;
  16995. // now create a data structure where each entry represents an edge with its adjoining faces
  16996. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  16997. var face = faces[ i ];
  16998. for ( var j = 0; j < 3; j ++ ) {
  16999. edge1 = face[ keys[ j ] ];
  17000. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  17001. edge[ 0 ] = Math.min( edge1, edge2 );
  17002. edge[ 1 ] = Math.max( edge1, edge2 );
  17003. key = edge[ 0 ] + ',' + edge[ 1 ];
  17004. if ( edges[ key ] === undefined ) {
  17005. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  17006. } else {
  17007. edges[ key ].face2 = i;
  17008. }
  17009. }
  17010. }
  17011. // generate vertices
  17012. for ( key in edges ) {
  17013. var e = edges[ key ];
  17014. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  17015. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  17016. var vertex = sourceVertices[ e.index1 ];
  17017. vertices.push( vertex.x, vertex.y, vertex.z );
  17018. vertex = sourceVertices[ e.index2 ];
  17019. vertices.push( vertex.x, vertex.y, vertex.z );
  17020. }
  17021. }
  17022. // build geometry
  17023. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17024. }
  17025. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  17026. EdgesGeometry.prototype.constructor = EdgesGeometry;
  17027. /**
  17028. * @author mrdoob / http://mrdoob.com/
  17029. * @author Mugen87 / https://github.com/Mugen87
  17030. */
  17031. // CylinderGeometry
  17032. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  17033. Geometry.call( this );
  17034. this.type = 'CylinderGeometry';
  17035. this.parameters = {
  17036. radiusTop: radiusTop,
  17037. radiusBottom: radiusBottom,
  17038. height: height,
  17039. radialSegments: radialSegments,
  17040. heightSegments: heightSegments,
  17041. openEnded: openEnded,
  17042. thetaStart: thetaStart,
  17043. thetaLength: thetaLength
  17044. };
  17045. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  17046. this.mergeVertices();
  17047. }
  17048. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  17049. CylinderGeometry.prototype.constructor = CylinderGeometry;
  17050. // CylinderBufferGeometry
  17051. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  17052. BufferGeometry.call( this );
  17053. this.type = 'CylinderBufferGeometry';
  17054. this.parameters = {
  17055. radiusTop: radiusTop,
  17056. radiusBottom: radiusBottom,
  17057. height: height,
  17058. radialSegments: radialSegments,
  17059. heightSegments: heightSegments,
  17060. openEnded: openEnded,
  17061. thetaStart: thetaStart,
  17062. thetaLength: thetaLength
  17063. };
  17064. var scope = this;
  17065. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  17066. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  17067. height = height !== undefined ? height : 100;
  17068. radialSegments = Math.floor( radialSegments ) || 8;
  17069. heightSegments = Math.floor( heightSegments ) || 1;
  17070. openEnded = openEnded !== undefined ? openEnded : false;
  17071. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  17072. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  17073. // buffers
  17074. var indices = [];
  17075. var vertices = [];
  17076. var normals = [];
  17077. var uvs = [];
  17078. // helper variables
  17079. var index = 0;
  17080. var indexArray = [];
  17081. var halfHeight = height / 2;
  17082. var groupStart = 0;
  17083. // generate geometry
  17084. generateTorso();
  17085. if ( openEnded === false ) {
  17086. if ( radiusTop > 0 ) generateCap( true );
  17087. if ( radiusBottom > 0 ) generateCap( false );
  17088. }
  17089. // build geometry
  17090. this.setIndex( indices );
  17091. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17092. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17093. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17094. function generateTorso() {
  17095. var x, y;
  17096. var normal = new Vector3();
  17097. var vertex = new Vector3();
  17098. var groupCount = 0;
  17099. // this will be used to calculate the normal
  17100. var slope = ( radiusBottom - radiusTop ) / height;
  17101. // generate vertices, normals and uvs
  17102. for ( y = 0; y <= heightSegments; y ++ ) {
  17103. var indexRow = [];
  17104. var v = y / heightSegments;
  17105. // calculate the radius of the current row
  17106. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17107. for ( x = 0; x <= radialSegments; x ++ ) {
  17108. var u = x / radialSegments;
  17109. var theta = u * thetaLength + thetaStart;
  17110. var sinTheta = Math.sin( theta );
  17111. var cosTheta = Math.cos( theta );
  17112. // vertex
  17113. vertex.x = radius * sinTheta;
  17114. vertex.y = - v * height + halfHeight;
  17115. vertex.z = radius * cosTheta;
  17116. vertices.push( vertex.x, vertex.y, vertex.z );
  17117. // normal
  17118. normal.set( sinTheta, slope, cosTheta ).normalize();
  17119. normals.push( normal.x, normal.y, normal.z );
  17120. // uv
  17121. uvs.push( u, 1 - v );
  17122. // save index of vertex in respective row
  17123. indexRow.push( index ++ );
  17124. }
  17125. // now save vertices of the row in our index array
  17126. indexArray.push( indexRow );
  17127. }
  17128. // generate indices
  17129. for ( x = 0; x < radialSegments; x ++ ) {
  17130. for ( y = 0; y < heightSegments; y ++ ) {
  17131. // we use the index array to access the correct indices
  17132. var a = indexArray[ y ][ x ];
  17133. var b = indexArray[ y + 1 ][ x ];
  17134. var c = indexArray[ y + 1 ][ x + 1 ];
  17135. var d = indexArray[ y ][ x + 1 ];
  17136. // faces
  17137. indices.push( a, b, d );
  17138. indices.push( b, c, d );
  17139. // update group counter
  17140. groupCount += 6;
  17141. }
  17142. }
  17143. // add a group to the geometry. this will ensure multi material support
  17144. scope.addGroup( groupStart, groupCount, 0 );
  17145. // calculate new start value for groups
  17146. groupStart += groupCount;
  17147. }
  17148. function generateCap( top ) {
  17149. var x, centerIndexStart, centerIndexEnd;
  17150. var uv = new Vector2();
  17151. var vertex = new Vector3();
  17152. var groupCount = 0;
  17153. var radius = ( top === true ) ? radiusTop : radiusBottom;
  17154. var sign = ( top === true ) ? 1 : - 1;
  17155. // save the index of the first center vertex
  17156. centerIndexStart = index;
  17157. // first we generate the center vertex data of the cap.
  17158. // because the geometry needs one set of uvs per face,
  17159. // we must generate a center vertex per face/segment
  17160. for ( x = 1; x <= radialSegments; x ++ ) {
  17161. // vertex
  17162. vertices.push( 0, halfHeight * sign, 0 );
  17163. // normal
  17164. normals.push( 0, sign, 0 );
  17165. // uv
  17166. uvs.push( 0.5, 0.5 );
  17167. // increase index
  17168. index ++;
  17169. }
  17170. // save the index of the last center vertex
  17171. centerIndexEnd = index;
  17172. // now we generate the surrounding vertices, normals and uvs
  17173. for ( x = 0; x <= radialSegments; x ++ ) {
  17174. var u = x / radialSegments;
  17175. var theta = u * thetaLength + thetaStart;
  17176. var cosTheta = Math.cos( theta );
  17177. var sinTheta = Math.sin( theta );
  17178. // vertex
  17179. vertex.x = radius * sinTheta;
  17180. vertex.y = halfHeight * sign;
  17181. vertex.z = radius * cosTheta;
  17182. vertices.push( vertex.x, vertex.y, vertex.z );
  17183. // normal
  17184. normals.push( 0, sign, 0 );
  17185. // uv
  17186. uv.x = ( cosTheta * 0.5 ) + 0.5;
  17187. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  17188. uvs.push( uv.x, uv.y );
  17189. // increase index
  17190. index ++;
  17191. }
  17192. // generate indices
  17193. for ( x = 0; x < radialSegments; x ++ ) {
  17194. var c = centerIndexStart + x;
  17195. var i = centerIndexEnd + x;
  17196. if ( top === true ) {
  17197. // face top
  17198. indices.push( i, i + 1, c );
  17199. } else {
  17200. // face bottom
  17201. indices.push( i + 1, i, c );
  17202. }
  17203. groupCount += 3;
  17204. }
  17205. // add a group to the geometry. this will ensure multi material support
  17206. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  17207. // calculate new start value for groups
  17208. groupStart += groupCount;
  17209. }
  17210. }
  17211. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  17212. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  17213. /**
  17214. * @author abelnation / http://github.com/abelnation
  17215. */
  17216. // ConeGeometry
  17217. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  17218. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  17219. this.type = 'ConeGeometry';
  17220. this.parameters = {
  17221. radius: radius,
  17222. height: height,
  17223. radialSegments: radialSegments,
  17224. heightSegments: heightSegments,
  17225. openEnded: openEnded,
  17226. thetaStart: thetaStart,
  17227. thetaLength: thetaLength
  17228. };
  17229. }
  17230. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  17231. ConeGeometry.prototype.constructor = ConeGeometry;
  17232. // ConeBufferGeometry
  17233. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  17234. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  17235. this.type = 'ConeBufferGeometry';
  17236. this.parameters = {
  17237. radius: radius,
  17238. height: height,
  17239. radialSegments: radialSegments,
  17240. heightSegments: heightSegments,
  17241. openEnded: openEnded,
  17242. thetaStart: thetaStart,
  17243. thetaLength: thetaLength
  17244. };
  17245. }
  17246. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  17247. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  17248. /**
  17249. * @author benaadams / https://twitter.com/ben_a_adams
  17250. * @author Mugen87 / https://github.com/Mugen87
  17251. * @author hughes
  17252. */
  17253. // CircleGeometry
  17254. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  17255. Geometry.call( this );
  17256. this.type = 'CircleGeometry';
  17257. this.parameters = {
  17258. radius: radius,
  17259. segments: segments,
  17260. thetaStart: thetaStart,
  17261. thetaLength: thetaLength
  17262. };
  17263. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  17264. this.mergeVertices();
  17265. }
  17266. CircleGeometry.prototype = Object.create( Geometry.prototype );
  17267. CircleGeometry.prototype.constructor = CircleGeometry;
  17268. // CircleBufferGeometry
  17269. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  17270. BufferGeometry.call( this );
  17271. this.type = 'CircleBufferGeometry';
  17272. this.parameters = {
  17273. radius: radius,
  17274. segments: segments,
  17275. thetaStart: thetaStart,
  17276. thetaLength: thetaLength
  17277. };
  17278. radius = radius || 50;
  17279. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  17280. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  17281. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  17282. // buffers
  17283. var indices = [];
  17284. var vertices = [];
  17285. var normals = [];
  17286. var uvs = [];
  17287. // helper variables
  17288. var i, s;
  17289. var vertex = new Vector3();
  17290. var uv = new Vector2();
  17291. // center point
  17292. vertices.push( 0, 0, 0 );
  17293. normals.push( 0, 0, 1 );
  17294. uvs.push( 0.5, 0.5 );
  17295. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  17296. var segment = thetaStart + s / segments * thetaLength;
  17297. // vertex
  17298. vertex.x = radius * Math.cos( segment );
  17299. vertex.y = radius * Math.sin( segment );
  17300. vertices.push( vertex.x, vertex.y, vertex.z );
  17301. // normal
  17302. normals.push( 0, 0, 1 );
  17303. // uvs
  17304. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  17305. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  17306. uvs.push( uv.x, uv.y );
  17307. }
  17308. // indices
  17309. for ( i = 1; i <= segments; i ++ ) {
  17310. indices.push( i, i + 1, 0 );
  17311. }
  17312. // build geometry
  17313. this.setIndex( indices );
  17314. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17315. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17316. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17317. }
  17318. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  17319. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  17320. var Geometries = Object.freeze({
  17321. WireframeGeometry: WireframeGeometry,
  17322. ParametricGeometry: ParametricGeometry,
  17323. ParametricBufferGeometry: ParametricBufferGeometry,
  17324. TetrahedronGeometry: TetrahedronGeometry,
  17325. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  17326. OctahedronGeometry: OctahedronGeometry,
  17327. OctahedronBufferGeometry: OctahedronBufferGeometry,
  17328. IcosahedronGeometry: IcosahedronGeometry,
  17329. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  17330. DodecahedronGeometry: DodecahedronGeometry,
  17331. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  17332. PolyhedronGeometry: PolyhedronGeometry,
  17333. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  17334. TubeGeometry: TubeGeometry,
  17335. TubeBufferGeometry: TubeBufferGeometry,
  17336. TorusKnotGeometry: TorusKnotGeometry,
  17337. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  17338. TorusGeometry: TorusGeometry,
  17339. TorusBufferGeometry: TorusBufferGeometry,
  17340. TextGeometry: TextGeometry,
  17341. TextBufferGeometry: TextBufferGeometry,
  17342. SphereGeometry: SphereGeometry,
  17343. SphereBufferGeometry: SphereBufferGeometry,
  17344. RingGeometry: RingGeometry,
  17345. RingBufferGeometry: RingBufferGeometry,
  17346. PlaneGeometry: PlaneGeometry,
  17347. PlaneBufferGeometry: PlaneBufferGeometry,
  17348. LatheGeometry: LatheGeometry,
  17349. LatheBufferGeometry: LatheBufferGeometry,
  17350. ShapeGeometry: ShapeGeometry,
  17351. ShapeBufferGeometry: ShapeBufferGeometry,
  17352. ExtrudeGeometry: ExtrudeGeometry,
  17353. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  17354. EdgesGeometry: EdgesGeometry,
  17355. ConeGeometry: ConeGeometry,
  17356. ConeBufferGeometry: ConeBufferGeometry,
  17357. CylinderGeometry: CylinderGeometry,
  17358. CylinderBufferGeometry: CylinderBufferGeometry,
  17359. CircleGeometry: CircleGeometry,
  17360. CircleBufferGeometry: CircleBufferGeometry,
  17361. BoxGeometry: BoxGeometry,
  17362. BoxBufferGeometry: BoxBufferGeometry
  17363. });
  17364. /**
  17365. * @author mrdoob / http://mrdoob.com/
  17366. *
  17367. * parameters = {
  17368. * color: <THREE.Color>,
  17369. * opacity: <float>
  17370. * }
  17371. */
  17372. function ShadowMaterial( parameters ) {
  17373. Material.call( this );
  17374. this.type = 'ShadowMaterial';
  17375. this.color = new Color( 0x000000 );
  17376. this.opacity = 1.0;
  17377. this.lights = true;
  17378. this.transparent = true;
  17379. this.setValues( parameters );
  17380. }
  17381. ShadowMaterial.prototype = Object.create( Material.prototype );
  17382. ShadowMaterial.prototype.constructor = ShadowMaterial;
  17383. ShadowMaterial.prototype.isShadowMaterial = true;
  17384. /**
  17385. * @author mrdoob / http://mrdoob.com/
  17386. */
  17387. function RawShaderMaterial( parameters ) {
  17388. ShaderMaterial.call( this, parameters );
  17389. this.type = 'RawShaderMaterial';
  17390. }
  17391. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  17392. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  17393. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  17394. /**
  17395. * @author WestLangley / http://github.com/WestLangley
  17396. *
  17397. * parameters = {
  17398. * color: <hex>,
  17399. * roughness: <float>,
  17400. * metalness: <float>,
  17401. * opacity: <float>,
  17402. *
  17403. * map: new THREE.Texture( <Image> ),
  17404. *
  17405. * lightMap: new THREE.Texture( <Image> ),
  17406. * lightMapIntensity: <float>
  17407. *
  17408. * aoMap: new THREE.Texture( <Image> ),
  17409. * aoMapIntensity: <float>
  17410. *
  17411. * emissive: <hex>,
  17412. * emissiveIntensity: <float>
  17413. * emissiveMap: new THREE.Texture( <Image> ),
  17414. *
  17415. * bumpMap: new THREE.Texture( <Image> ),
  17416. * bumpScale: <float>,
  17417. *
  17418. * normalMap: new THREE.Texture( <Image> ),
  17419. * normalScale: <Vector2>,
  17420. *
  17421. * displacementMap: new THREE.Texture( <Image> ),
  17422. * displacementScale: <float>,
  17423. * displacementBias: <float>,
  17424. *
  17425. * roughnessMap: new THREE.Texture( <Image> ),
  17426. *
  17427. * metalnessMap: new THREE.Texture( <Image> ),
  17428. *
  17429. * alphaMap: new THREE.Texture( <Image> ),
  17430. *
  17431. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  17432. * envMapIntensity: <float>
  17433. *
  17434. * refractionRatio: <float>,
  17435. *
  17436. * wireframe: <boolean>,
  17437. * wireframeLinewidth: <float>,
  17438. *
  17439. * skinning: <bool>,
  17440. * morphTargets: <bool>,
  17441. * morphNormals: <bool>
  17442. * }
  17443. */
  17444. function MeshStandardMaterial( parameters ) {
  17445. Material.call( this );
  17446. this.defines = { 'STANDARD': '' };
  17447. this.type = 'MeshStandardMaterial';
  17448. this.color = new Color( 0xffffff ); // diffuse
  17449. this.roughness = 0.5;
  17450. this.metalness = 0.5;
  17451. this.map = null;
  17452. this.lightMap = null;
  17453. this.lightMapIntensity = 1.0;
  17454. this.aoMap = null;
  17455. this.aoMapIntensity = 1.0;
  17456. this.emissive = new Color( 0x000000 );
  17457. this.emissiveIntensity = 1.0;
  17458. this.emissiveMap = null;
  17459. this.bumpMap = null;
  17460. this.bumpScale = 1;
  17461. this.normalMap = null;
  17462. this.normalScale = new Vector2( 1, 1 );
  17463. this.displacementMap = null;
  17464. this.displacementScale = 1;
  17465. this.displacementBias = 0;
  17466. this.roughnessMap = null;
  17467. this.metalnessMap = null;
  17468. this.alphaMap = null;
  17469. this.envMap = null;
  17470. this.envMapIntensity = 1.0;
  17471. this.refractionRatio = 0.98;
  17472. this.wireframe = false;
  17473. this.wireframeLinewidth = 1;
  17474. this.wireframeLinecap = 'round';
  17475. this.wireframeLinejoin = 'round';
  17476. this.skinning = false;
  17477. this.morphTargets = false;
  17478. this.morphNormals = false;
  17479. this.setValues( parameters );
  17480. }
  17481. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  17482. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  17483. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  17484. MeshStandardMaterial.prototype.copy = function ( source ) {
  17485. Material.prototype.copy.call( this, source );
  17486. this.defines = { 'STANDARD': '' };
  17487. this.color.copy( source.color );
  17488. this.roughness = source.roughness;
  17489. this.metalness = source.metalness;
  17490. this.map = source.map;
  17491. this.lightMap = source.lightMap;
  17492. this.lightMapIntensity = source.lightMapIntensity;
  17493. this.aoMap = source.aoMap;
  17494. this.aoMapIntensity = source.aoMapIntensity;
  17495. this.emissive.copy( source.emissive );
  17496. this.emissiveMap = source.emissiveMap;
  17497. this.emissiveIntensity = source.emissiveIntensity;
  17498. this.bumpMap = source.bumpMap;
  17499. this.bumpScale = source.bumpScale;
  17500. this.normalMap = source.normalMap;
  17501. this.normalScale.copy( source.normalScale );
  17502. this.displacementMap = source.displacementMap;
  17503. this.displacementScale = source.displacementScale;
  17504. this.displacementBias = source.displacementBias;
  17505. this.roughnessMap = source.roughnessMap;
  17506. this.metalnessMap = source.metalnessMap;
  17507. this.alphaMap = source.alphaMap;
  17508. this.envMap = source.envMap;
  17509. this.envMapIntensity = source.envMapIntensity;
  17510. this.refractionRatio = source.refractionRatio;
  17511. this.wireframe = source.wireframe;
  17512. this.wireframeLinewidth = source.wireframeLinewidth;
  17513. this.wireframeLinecap = source.wireframeLinecap;
  17514. this.wireframeLinejoin = source.wireframeLinejoin;
  17515. this.skinning = source.skinning;
  17516. this.morphTargets = source.morphTargets;
  17517. this.morphNormals = source.morphNormals;
  17518. return this;
  17519. };
  17520. /**
  17521. * @author WestLangley / http://github.com/WestLangley
  17522. *
  17523. * parameters = {
  17524. * reflectivity: <float>
  17525. * }
  17526. */
  17527. function MeshPhysicalMaterial( parameters ) {
  17528. MeshStandardMaterial.call( this );
  17529. this.defines = { 'PHYSICAL': '' };
  17530. this.type = 'MeshPhysicalMaterial';
  17531. this.reflectivity = 0.5; // maps to F0 = 0.04
  17532. this.clearCoat = 0.0;
  17533. this.clearCoatRoughness = 0.0;
  17534. this.setValues( parameters );
  17535. }
  17536. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  17537. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  17538. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  17539. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  17540. MeshStandardMaterial.prototype.copy.call( this, source );
  17541. this.defines = { 'PHYSICAL': '' };
  17542. this.reflectivity = source.reflectivity;
  17543. this.clearCoat = source.clearCoat;
  17544. this.clearCoatRoughness = source.clearCoatRoughness;
  17545. return this;
  17546. };
  17547. /**
  17548. * @author mrdoob / http://mrdoob.com/
  17549. * @author alteredq / http://alteredqualia.com/
  17550. *
  17551. * parameters = {
  17552. * color: <hex>,
  17553. * specular: <hex>,
  17554. * shininess: <float>,
  17555. * opacity: <float>,
  17556. *
  17557. * map: new THREE.Texture( <Image> ),
  17558. *
  17559. * lightMap: new THREE.Texture( <Image> ),
  17560. * lightMapIntensity: <float>
  17561. *
  17562. * aoMap: new THREE.Texture( <Image> ),
  17563. * aoMapIntensity: <float>
  17564. *
  17565. * emissive: <hex>,
  17566. * emissiveIntensity: <float>
  17567. * emissiveMap: new THREE.Texture( <Image> ),
  17568. *
  17569. * bumpMap: new THREE.Texture( <Image> ),
  17570. * bumpScale: <float>,
  17571. *
  17572. * normalMap: new THREE.Texture( <Image> ),
  17573. * normalScale: <Vector2>,
  17574. *
  17575. * displacementMap: new THREE.Texture( <Image> ),
  17576. * displacementScale: <float>,
  17577. * displacementBias: <float>,
  17578. *
  17579. * specularMap: new THREE.Texture( <Image> ),
  17580. *
  17581. * alphaMap: new THREE.Texture( <Image> ),
  17582. *
  17583. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17584. * combine: THREE.Multiply,
  17585. * reflectivity: <float>,
  17586. * refractionRatio: <float>,
  17587. *
  17588. * wireframe: <boolean>,
  17589. * wireframeLinewidth: <float>,
  17590. *
  17591. * skinning: <bool>,
  17592. * morphTargets: <bool>,
  17593. * morphNormals: <bool>
  17594. * }
  17595. */
  17596. function MeshPhongMaterial( parameters ) {
  17597. Material.call( this );
  17598. this.type = 'MeshPhongMaterial';
  17599. this.color = new Color( 0xffffff ); // diffuse
  17600. this.specular = new Color( 0x111111 );
  17601. this.shininess = 30;
  17602. this.map = null;
  17603. this.lightMap = null;
  17604. this.lightMapIntensity = 1.0;
  17605. this.aoMap = null;
  17606. this.aoMapIntensity = 1.0;
  17607. this.emissive = new Color( 0x000000 );
  17608. this.emissiveIntensity = 1.0;
  17609. this.emissiveMap = null;
  17610. this.bumpMap = null;
  17611. this.bumpScale = 1;
  17612. this.normalMap = null;
  17613. this.normalScale = new Vector2( 1, 1 );
  17614. this.displacementMap = null;
  17615. this.displacementScale = 1;
  17616. this.displacementBias = 0;
  17617. this.specularMap = null;
  17618. this.alphaMap = null;
  17619. this.envMap = null;
  17620. this.combine = MultiplyOperation;
  17621. this.reflectivity = 1;
  17622. this.refractionRatio = 0.98;
  17623. this.wireframe = false;
  17624. this.wireframeLinewidth = 1;
  17625. this.wireframeLinecap = 'round';
  17626. this.wireframeLinejoin = 'round';
  17627. this.skinning = false;
  17628. this.morphTargets = false;
  17629. this.morphNormals = false;
  17630. this.setValues( parameters );
  17631. }
  17632. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  17633. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  17634. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  17635. MeshPhongMaterial.prototype.copy = function ( source ) {
  17636. Material.prototype.copy.call( this, source );
  17637. this.color.copy( source.color );
  17638. this.specular.copy( source.specular );
  17639. this.shininess = source.shininess;
  17640. this.map = source.map;
  17641. this.lightMap = source.lightMap;
  17642. this.lightMapIntensity = source.lightMapIntensity;
  17643. this.aoMap = source.aoMap;
  17644. this.aoMapIntensity = source.aoMapIntensity;
  17645. this.emissive.copy( source.emissive );
  17646. this.emissiveMap = source.emissiveMap;
  17647. this.emissiveIntensity = source.emissiveIntensity;
  17648. this.bumpMap = source.bumpMap;
  17649. this.bumpScale = source.bumpScale;
  17650. this.normalMap = source.normalMap;
  17651. this.normalScale.copy( source.normalScale );
  17652. this.displacementMap = source.displacementMap;
  17653. this.displacementScale = source.displacementScale;
  17654. this.displacementBias = source.displacementBias;
  17655. this.specularMap = source.specularMap;
  17656. this.alphaMap = source.alphaMap;
  17657. this.envMap = source.envMap;
  17658. this.combine = source.combine;
  17659. this.reflectivity = source.reflectivity;
  17660. this.refractionRatio = source.refractionRatio;
  17661. this.wireframe = source.wireframe;
  17662. this.wireframeLinewidth = source.wireframeLinewidth;
  17663. this.wireframeLinecap = source.wireframeLinecap;
  17664. this.wireframeLinejoin = source.wireframeLinejoin;
  17665. this.skinning = source.skinning;
  17666. this.morphTargets = source.morphTargets;
  17667. this.morphNormals = source.morphNormals;
  17668. return this;
  17669. };
  17670. /**
  17671. * @author takahirox / http://github.com/takahirox
  17672. *
  17673. * parameters = {
  17674. * gradientMap: new THREE.Texture( <Image> )
  17675. * }
  17676. */
  17677. function MeshToonMaterial( parameters ) {
  17678. MeshPhongMaterial.call( this );
  17679. this.defines = { 'TOON': '' };
  17680. this.type = 'MeshToonMaterial';
  17681. this.gradientMap = null;
  17682. this.setValues( parameters );
  17683. }
  17684. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  17685. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  17686. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  17687. MeshToonMaterial.prototype.copy = function ( source ) {
  17688. MeshPhongMaterial.prototype.copy.call( this, source );
  17689. this.gradientMap = source.gradientMap;
  17690. return this;
  17691. };
  17692. /**
  17693. * @author mrdoob / http://mrdoob.com/
  17694. * @author WestLangley / http://github.com/WestLangley
  17695. *
  17696. * parameters = {
  17697. * opacity: <float>,
  17698. *
  17699. * bumpMap: new THREE.Texture( <Image> ),
  17700. * bumpScale: <float>,
  17701. *
  17702. * normalMap: new THREE.Texture( <Image> ),
  17703. * normalScale: <Vector2>,
  17704. *
  17705. * displacementMap: new THREE.Texture( <Image> ),
  17706. * displacementScale: <float>,
  17707. * displacementBias: <float>,
  17708. *
  17709. * wireframe: <boolean>,
  17710. * wireframeLinewidth: <float>
  17711. *
  17712. * skinning: <bool>,
  17713. * morphTargets: <bool>,
  17714. * morphNormals: <bool>
  17715. * }
  17716. */
  17717. function MeshNormalMaterial( parameters ) {
  17718. Material.call( this );
  17719. this.type = 'MeshNormalMaterial';
  17720. this.bumpMap = null;
  17721. this.bumpScale = 1;
  17722. this.normalMap = null;
  17723. this.normalScale = new Vector2( 1, 1 );
  17724. this.displacementMap = null;
  17725. this.displacementScale = 1;
  17726. this.displacementBias = 0;
  17727. this.wireframe = false;
  17728. this.wireframeLinewidth = 1;
  17729. this.fog = false;
  17730. this.lights = false;
  17731. this.skinning = false;
  17732. this.morphTargets = false;
  17733. this.morphNormals = false;
  17734. this.setValues( parameters );
  17735. }
  17736. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  17737. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  17738. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  17739. MeshNormalMaterial.prototype.copy = function ( source ) {
  17740. Material.prototype.copy.call( this, source );
  17741. this.bumpMap = source.bumpMap;
  17742. this.bumpScale = source.bumpScale;
  17743. this.normalMap = source.normalMap;
  17744. this.normalScale.copy( source.normalScale );
  17745. this.displacementMap = source.displacementMap;
  17746. this.displacementScale = source.displacementScale;
  17747. this.displacementBias = source.displacementBias;
  17748. this.wireframe = source.wireframe;
  17749. this.wireframeLinewidth = source.wireframeLinewidth;
  17750. this.skinning = source.skinning;
  17751. this.morphTargets = source.morphTargets;
  17752. this.morphNormals = source.morphNormals;
  17753. return this;
  17754. };
  17755. /**
  17756. * @author mrdoob / http://mrdoob.com/
  17757. * @author alteredq / http://alteredqualia.com/
  17758. *
  17759. * parameters = {
  17760. * color: <hex>,
  17761. * opacity: <float>,
  17762. *
  17763. * map: new THREE.Texture( <Image> ),
  17764. *
  17765. * lightMap: new THREE.Texture( <Image> ),
  17766. * lightMapIntensity: <float>
  17767. *
  17768. * aoMap: new THREE.Texture( <Image> ),
  17769. * aoMapIntensity: <float>
  17770. *
  17771. * emissive: <hex>,
  17772. * emissiveIntensity: <float>
  17773. * emissiveMap: new THREE.Texture( <Image> ),
  17774. *
  17775. * specularMap: new THREE.Texture( <Image> ),
  17776. *
  17777. * alphaMap: new THREE.Texture( <Image> ),
  17778. *
  17779. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17780. * combine: THREE.Multiply,
  17781. * reflectivity: <float>,
  17782. * refractionRatio: <float>,
  17783. *
  17784. * wireframe: <boolean>,
  17785. * wireframeLinewidth: <float>,
  17786. *
  17787. * skinning: <bool>,
  17788. * morphTargets: <bool>,
  17789. * morphNormals: <bool>
  17790. * }
  17791. */
  17792. function MeshLambertMaterial( parameters ) {
  17793. Material.call( this );
  17794. this.type = 'MeshLambertMaterial';
  17795. this.color = new Color( 0xffffff ); // diffuse
  17796. this.map = null;
  17797. this.lightMap = null;
  17798. this.lightMapIntensity = 1.0;
  17799. this.aoMap = null;
  17800. this.aoMapIntensity = 1.0;
  17801. this.emissive = new Color( 0x000000 );
  17802. this.emissiveIntensity = 1.0;
  17803. this.emissiveMap = null;
  17804. this.specularMap = null;
  17805. this.alphaMap = null;
  17806. this.envMap = null;
  17807. this.combine = MultiplyOperation;
  17808. this.reflectivity = 1;
  17809. this.refractionRatio = 0.98;
  17810. this.wireframe = false;
  17811. this.wireframeLinewidth = 1;
  17812. this.wireframeLinecap = 'round';
  17813. this.wireframeLinejoin = 'round';
  17814. this.skinning = false;
  17815. this.morphTargets = false;
  17816. this.morphNormals = false;
  17817. this.setValues( parameters );
  17818. }
  17819. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  17820. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  17821. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  17822. MeshLambertMaterial.prototype.copy = function ( source ) {
  17823. Material.prototype.copy.call( this, source );
  17824. this.color.copy( source.color );
  17825. this.map = source.map;
  17826. this.lightMap = source.lightMap;
  17827. this.lightMapIntensity = source.lightMapIntensity;
  17828. this.aoMap = source.aoMap;
  17829. this.aoMapIntensity = source.aoMapIntensity;
  17830. this.emissive.copy( source.emissive );
  17831. this.emissiveMap = source.emissiveMap;
  17832. this.emissiveIntensity = source.emissiveIntensity;
  17833. this.specularMap = source.specularMap;
  17834. this.alphaMap = source.alphaMap;
  17835. this.envMap = source.envMap;
  17836. this.combine = source.combine;
  17837. this.reflectivity = source.reflectivity;
  17838. this.refractionRatio = source.refractionRatio;
  17839. this.wireframe = source.wireframe;
  17840. this.wireframeLinewidth = source.wireframeLinewidth;
  17841. this.wireframeLinecap = source.wireframeLinecap;
  17842. this.wireframeLinejoin = source.wireframeLinejoin;
  17843. this.skinning = source.skinning;
  17844. this.morphTargets = source.morphTargets;
  17845. this.morphNormals = source.morphNormals;
  17846. return this;
  17847. };
  17848. /**
  17849. * @author alteredq / http://alteredqualia.com/
  17850. *
  17851. * parameters = {
  17852. * color: <hex>,
  17853. * opacity: <float>,
  17854. *
  17855. * linewidth: <float>,
  17856. *
  17857. * scale: <float>,
  17858. * dashSize: <float>,
  17859. * gapSize: <float>
  17860. * }
  17861. */
  17862. function LineDashedMaterial( parameters ) {
  17863. LineBasicMaterial.call( this );
  17864. this.type = 'LineDashedMaterial';
  17865. this.scale = 1;
  17866. this.dashSize = 3;
  17867. this.gapSize = 1;
  17868. this.setValues( parameters );
  17869. }
  17870. LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
  17871. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  17872. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  17873. LineDashedMaterial.prototype.copy = function ( source ) {
  17874. LineBasicMaterial.prototype.copy.call( this, source );
  17875. this.scale = source.scale;
  17876. this.dashSize = source.dashSize;
  17877. this.gapSize = source.gapSize;
  17878. return this;
  17879. };
  17880. var Materials = Object.freeze({
  17881. ShadowMaterial: ShadowMaterial,
  17882. SpriteMaterial: SpriteMaterial,
  17883. RawShaderMaterial: RawShaderMaterial,
  17884. ShaderMaterial: ShaderMaterial,
  17885. PointsMaterial: PointsMaterial,
  17886. MeshPhysicalMaterial: MeshPhysicalMaterial,
  17887. MeshStandardMaterial: MeshStandardMaterial,
  17888. MeshPhongMaterial: MeshPhongMaterial,
  17889. MeshToonMaterial: MeshToonMaterial,
  17890. MeshNormalMaterial: MeshNormalMaterial,
  17891. MeshLambertMaterial: MeshLambertMaterial,
  17892. MeshDepthMaterial: MeshDepthMaterial,
  17893. MeshDistanceMaterial: MeshDistanceMaterial,
  17894. MeshBasicMaterial: MeshBasicMaterial,
  17895. LineDashedMaterial: LineDashedMaterial,
  17896. LineBasicMaterial: LineBasicMaterial,
  17897. Material: Material
  17898. });
  17899. /**
  17900. * @author mrdoob / http://mrdoob.com/
  17901. */
  17902. var Cache = {
  17903. enabled: false,
  17904. files: {},
  17905. add: function ( key, file ) {
  17906. if ( this.enabled === false ) return;
  17907. // console.log( 'THREE.Cache', 'Adding key:', key );
  17908. this.files[ key ] = file;
  17909. },
  17910. get: function ( key ) {
  17911. if ( this.enabled === false ) return;
  17912. // console.log( 'THREE.Cache', 'Checking key:', key );
  17913. return this.files[ key ];
  17914. },
  17915. remove: function ( key ) {
  17916. delete this.files[ key ];
  17917. },
  17918. clear: function () {
  17919. this.files = {};
  17920. }
  17921. };
  17922. /**
  17923. * @author mrdoob / http://mrdoob.com/
  17924. */
  17925. function LoadingManager( onLoad, onProgress, onError ) {
  17926. var scope = this;
  17927. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  17928. this.onStart = undefined;
  17929. this.onLoad = onLoad;
  17930. this.onProgress = onProgress;
  17931. this.onError = onError;
  17932. this.itemStart = function ( url ) {
  17933. itemsTotal ++;
  17934. if ( isLoading === false ) {
  17935. if ( scope.onStart !== undefined ) {
  17936. scope.onStart( url, itemsLoaded, itemsTotal );
  17937. }
  17938. }
  17939. isLoading = true;
  17940. };
  17941. this.itemEnd = function ( url ) {
  17942. itemsLoaded ++;
  17943. if ( scope.onProgress !== undefined ) {
  17944. scope.onProgress( url, itemsLoaded, itemsTotal );
  17945. }
  17946. if ( itemsLoaded === itemsTotal ) {
  17947. isLoading = false;
  17948. if ( scope.onLoad !== undefined ) {
  17949. scope.onLoad();
  17950. }
  17951. }
  17952. };
  17953. this.itemError = function ( url ) {
  17954. if ( scope.onError !== undefined ) {
  17955. scope.onError( url );
  17956. }
  17957. };
  17958. }
  17959. var DefaultLoadingManager = new LoadingManager();
  17960. /**
  17961. * @author mrdoob / http://mrdoob.com/
  17962. */
  17963. function FileLoader( manager ) {
  17964. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17965. }
  17966. Object.assign( FileLoader.prototype, {
  17967. load: function ( url, onLoad, onProgress, onError ) {
  17968. if ( url === undefined ) url = '';
  17969. if ( this.path !== undefined ) url = this.path + url;
  17970. var scope = this;
  17971. var cached = Cache.get( url );
  17972. if ( cached !== undefined ) {
  17973. scope.manager.itemStart( url );
  17974. setTimeout( function () {
  17975. if ( onLoad ) onLoad( cached );
  17976. scope.manager.itemEnd( url );
  17977. }, 0 );
  17978. return cached;
  17979. }
  17980. // Check for data: URI
  17981. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  17982. var dataUriRegexResult = url.match( dataUriRegex );
  17983. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  17984. if ( dataUriRegexResult ) {
  17985. var mimeType = dataUriRegexResult[ 1 ];
  17986. var isBase64 = !! dataUriRegexResult[ 2 ];
  17987. var data = dataUriRegexResult[ 3 ];
  17988. data = window.decodeURIComponent( data );
  17989. if ( isBase64 ) data = window.atob( data );
  17990. try {
  17991. var response;
  17992. var responseType = ( this.responseType || '' ).toLowerCase();
  17993. switch ( responseType ) {
  17994. case 'arraybuffer':
  17995. case 'blob':
  17996. response = new ArrayBuffer( data.length );
  17997. var view = new Uint8Array( response );
  17998. for ( var i = 0; i < data.length; i ++ ) {
  17999. view[ i ] = data.charCodeAt( i );
  18000. }
  18001. if ( responseType === 'blob' ) {
  18002. response = new Blob( [ response ], { type: mimeType } );
  18003. }
  18004. break;
  18005. case 'document':
  18006. var parser = new DOMParser();
  18007. response = parser.parseFromString( data, mimeType );
  18008. break;
  18009. case 'json':
  18010. response = JSON.parse( data );
  18011. break;
  18012. default: // 'text' or other
  18013. response = data;
  18014. break;
  18015. }
  18016. // Wait for next browser tick
  18017. window.setTimeout( function () {
  18018. if ( onLoad ) onLoad( response );
  18019. scope.manager.itemEnd( url );
  18020. }, 0 );
  18021. } catch ( error ) {
  18022. // Wait for next browser tick
  18023. window.setTimeout( function () {
  18024. if ( onError ) onError( error );
  18025. scope.manager.itemEnd( url );
  18026. scope.manager.itemError( url );
  18027. }, 0 );
  18028. }
  18029. } else {
  18030. var request = new XMLHttpRequest();
  18031. request.open( 'GET', url, true );
  18032. request.addEventListener( 'load', function ( event ) {
  18033. var response = event.target.response;
  18034. Cache.add( url, response );
  18035. if ( this.status === 200 ) {
  18036. if ( onLoad ) onLoad( response );
  18037. scope.manager.itemEnd( url );
  18038. } else if ( this.status === 0 ) {
  18039. // Some browsers return HTTP Status 0 when using non-http protocol
  18040. // e.g. 'file://' or 'data://'. Handle as success.
  18041. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  18042. if ( onLoad ) onLoad( response );
  18043. scope.manager.itemEnd( url );
  18044. } else {
  18045. if ( onError ) onError( event );
  18046. scope.manager.itemEnd( url );
  18047. scope.manager.itemError( url );
  18048. }
  18049. }, false );
  18050. if ( onProgress !== undefined ) {
  18051. request.addEventListener( 'progress', function ( event ) {
  18052. onProgress( event );
  18053. }, false );
  18054. }
  18055. request.addEventListener( 'error', function ( event ) {
  18056. if ( onError ) onError( event );
  18057. scope.manager.itemEnd( url );
  18058. scope.manager.itemError( url );
  18059. }, false );
  18060. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  18061. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  18062. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  18063. for ( var header in this.requestHeader ) {
  18064. request.setRequestHeader( header, this.requestHeader[ header ] );
  18065. }
  18066. request.send( null );
  18067. }
  18068. scope.manager.itemStart( url );
  18069. return request;
  18070. },
  18071. setPath: function ( value ) {
  18072. this.path = value;
  18073. return this;
  18074. },
  18075. setResponseType: function ( value ) {
  18076. this.responseType = value;
  18077. return this;
  18078. },
  18079. setWithCredentials: function ( value ) {
  18080. this.withCredentials = value;
  18081. return this;
  18082. },
  18083. setMimeType: function ( value ) {
  18084. this.mimeType = value;
  18085. return this;
  18086. },
  18087. setRequestHeader: function ( value ) {
  18088. this.requestHeader = value;
  18089. return this;
  18090. }
  18091. } );
  18092. /**
  18093. * @author mrdoob / http://mrdoob.com/
  18094. *
  18095. * Abstract Base class to block based textures loader (dds, pvr, ...)
  18096. */
  18097. function CompressedTextureLoader( manager ) {
  18098. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18099. // override in sub classes
  18100. this._parser = null;
  18101. }
  18102. Object.assign( CompressedTextureLoader.prototype, {
  18103. load: function ( url, onLoad, onProgress, onError ) {
  18104. var scope = this;
  18105. var images = [];
  18106. var texture = new CompressedTexture();
  18107. texture.image = images;
  18108. var loader = new FileLoader( this.manager );
  18109. loader.setPath( this.path );
  18110. loader.setResponseType( 'arraybuffer' );
  18111. function loadTexture( i ) {
  18112. loader.load( url[ i ], function ( buffer ) {
  18113. var texDatas = scope._parser( buffer, true );
  18114. images[ i ] = {
  18115. width: texDatas.width,
  18116. height: texDatas.height,
  18117. format: texDatas.format,
  18118. mipmaps: texDatas.mipmaps
  18119. };
  18120. loaded += 1;
  18121. if ( loaded === 6 ) {
  18122. if ( texDatas.mipmapCount === 1 )
  18123. texture.minFilter = LinearFilter;
  18124. texture.format = texDatas.format;
  18125. texture.needsUpdate = true;
  18126. if ( onLoad ) onLoad( texture );
  18127. }
  18128. }, onProgress, onError );
  18129. }
  18130. if ( Array.isArray( url ) ) {
  18131. var loaded = 0;
  18132. for ( var i = 0, il = url.length; i < il; ++ i ) {
  18133. loadTexture( i );
  18134. }
  18135. } else {
  18136. // compressed cubemap texture stored in a single DDS file
  18137. loader.load( url, function ( buffer ) {
  18138. var texDatas = scope._parser( buffer, true );
  18139. if ( texDatas.isCubemap ) {
  18140. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  18141. for ( var f = 0; f < faces; f ++ ) {
  18142. images[ f ] = { mipmaps : [] };
  18143. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  18144. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  18145. images[ f ].format = texDatas.format;
  18146. images[ f ].width = texDatas.width;
  18147. images[ f ].height = texDatas.height;
  18148. }
  18149. }
  18150. } else {
  18151. texture.image.width = texDatas.width;
  18152. texture.image.height = texDatas.height;
  18153. texture.mipmaps = texDatas.mipmaps;
  18154. }
  18155. if ( texDatas.mipmapCount === 1 ) {
  18156. texture.minFilter = LinearFilter;
  18157. }
  18158. texture.format = texDatas.format;
  18159. texture.needsUpdate = true;
  18160. if ( onLoad ) onLoad( texture );
  18161. }, onProgress, onError );
  18162. }
  18163. return texture;
  18164. },
  18165. setPath: function ( value ) {
  18166. this.path = value;
  18167. return this;
  18168. }
  18169. } );
  18170. /**
  18171. * @author Nikos M. / https://github.com/foo123/
  18172. *
  18173. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  18174. */
  18175. function DataTextureLoader( manager ) {
  18176. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18177. // override in sub classes
  18178. this._parser = null;
  18179. }
  18180. Object.assign( DataTextureLoader.prototype, {
  18181. load: function ( url, onLoad, onProgress, onError ) {
  18182. var scope = this;
  18183. var texture = new DataTexture();
  18184. var loader = new FileLoader( this.manager );
  18185. loader.setResponseType( 'arraybuffer' );
  18186. loader.load( url, function ( buffer ) {
  18187. var texData = scope._parser( buffer );
  18188. if ( ! texData ) return;
  18189. if ( undefined !== texData.image ) {
  18190. texture.image = texData.image;
  18191. } else if ( undefined !== texData.data ) {
  18192. texture.image.width = texData.width;
  18193. texture.image.height = texData.height;
  18194. texture.image.data = texData.data;
  18195. }
  18196. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  18197. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  18198. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  18199. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  18200. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  18201. if ( undefined !== texData.format ) {
  18202. texture.format = texData.format;
  18203. }
  18204. if ( undefined !== texData.type ) {
  18205. texture.type = texData.type;
  18206. }
  18207. if ( undefined !== texData.mipmaps ) {
  18208. texture.mipmaps = texData.mipmaps;
  18209. }
  18210. if ( 1 === texData.mipmapCount ) {
  18211. texture.minFilter = LinearFilter;
  18212. }
  18213. texture.needsUpdate = true;
  18214. if ( onLoad ) onLoad( texture, texData );
  18215. }, onProgress, onError );
  18216. return texture;
  18217. }
  18218. } );
  18219. /**
  18220. * @author mrdoob / http://mrdoob.com/
  18221. */
  18222. function ImageLoader( manager ) {
  18223. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18224. }
  18225. Object.assign( ImageLoader.prototype, {
  18226. crossOrigin: 'Anonymous',
  18227. load: function ( url, onLoad, onProgress, onError ) {
  18228. if ( url === undefined ) url = '';
  18229. if ( this.path !== undefined ) url = this.path + url;
  18230. var scope = this;
  18231. var cached = Cache.get( url );
  18232. if ( cached !== undefined ) {
  18233. scope.manager.itemStart( url );
  18234. setTimeout( function () {
  18235. if ( onLoad ) onLoad( cached );
  18236. scope.manager.itemEnd( url );
  18237. }, 0 );
  18238. return cached;
  18239. }
  18240. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  18241. image.addEventListener( 'load', function () {
  18242. Cache.add( url, this );
  18243. if ( onLoad ) onLoad( this );
  18244. scope.manager.itemEnd( url );
  18245. }, false );
  18246. /*
  18247. image.addEventListener( 'progress', function ( event ) {
  18248. if ( onProgress ) onProgress( event );
  18249. }, false );
  18250. */
  18251. image.addEventListener( 'error', function ( event ) {
  18252. if ( onError ) onError( event );
  18253. scope.manager.itemEnd( url );
  18254. scope.manager.itemError( url );
  18255. }, false );
  18256. if ( url.substr( 0, 5 ) !== 'data:' ) {
  18257. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  18258. }
  18259. scope.manager.itemStart( url );
  18260. image.src = url;
  18261. return image;
  18262. },
  18263. setCrossOrigin: function ( value ) {
  18264. this.crossOrigin = value;
  18265. return this;
  18266. },
  18267. setPath: function ( value ) {
  18268. this.path = value;
  18269. return this;
  18270. }
  18271. } );
  18272. /**
  18273. * @author mrdoob / http://mrdoob.com/
  18274. */
  18275. function CubeTextureLoader( manager ) {
  18276. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18277. }
  18278. Object.assign( CubeTextureLoader.prototype, {
  18279. crossOrigin: 'Anonymous',
  18280. load: function ( urls, onLoad, onProgress, onError ) {
  18281. var texture = new CubeTexture();
  18282. var loader = new ImageLoader( this.manager );
  18283. loader.setCrossOrigin( this.crossOrigin );
  18284. loader.setPath( this.path );
  18285. var loaded = 0;
  18286. function loadTexture( i ) {
  18287. loader.load( urls[ i ], function ( image ) {
  18288. texture.images[ i ] = image;
  18289. loaded ++;
  18290. if ( loaded === 6 ) {
  18291. texture.needsUpdate = true;
  18292. if ( onLoad ) onLoad( texture );
  18293. }
  18294. }, undefined, onError );
  18295. }
  18296. for ( var i = 0; i < urls.length; ++ i ) {
  18297. loadTexture( i );
  18298. }
  18299. return texture;
  18300. },
  18301. setCrossOrigin: function ( value ) {
  18302. this.crossOrigin = value;
  18303. return this;
  18304. },
  18305. setPath: function ( value ) {
  18306. this.path = value;
  18307. return this;
  18308. }
  18309. } );
  18310. /**
  18311. * @author mrdoob / http://mrdoob.com/
  18312. */
  18313. function TextureLoader( manager ) {
  18314. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18315. }
  18316. Object.assign( TextureLoader.prototype, {
  18317. crossOrigin: 'Anonymous',
  18318. load: function ( url, onLoad, onProgress, onError ) {
  18319. var loader = new ImageLoader( this.manager );
  18320. loader.setCrossOrigin( this.crossOrigin );
  18321. loader.setPath( this.path );
  18322. var texture = new Texture();
  18323. texture.image = loader.load( url, function () {
  18324. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  18325. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  18326. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  18327. texture.needsUpdate = true;
  18328. if ( onLoad !== undefined ) {
  18329. onLoad( texture );
  18330. }
  18331. }, onProgress, onError );
  18332. return texture;
  18333. },
  18334. setCrossOrigin: function ( value ) {
  18335. this.crossOrigin = value;
  18336. return this;
  18337. },
  18338. setPath: function ( value ) {
  18339. this.path = value;
  18340. return this;
  18341. }
  18342. } );
  18343. /**
  18344. * @author mrdoob / http://mrdoob.com/
  18345. * @author alteredq / http://alteredqualia.com/
  18346. */
  18347. function Light( color, intensity ) {
  18348. Object3D.call( this );
  18349. this.type = 'Light';
  18350. this.color = new Color( color );
  18351. this.intensity = intensity !== undefined ? intensity : 1;
  18352. this.receiveShadow = undefined;
  18353. }
  18354. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18355. constructor: Light,
  18356. isLight: true,
  18357. copy: function ( source ) {
  18358. Object3D.prototype.copy.call( this, source );
  18359. this.color.copy( source.color );
  18360. this.intensity = source.intensity;
  18361. return this;
  18362. },
  18363. toJSON: function ( meta ) {
  18364. var data = Object3D.prototype.toJSON.call( this, meta );
  18365. data.object.color = this.color.getHex();
  18366. data.object.intensity = this.intensity;
  18367. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  18368. if ( this.distance !== undefined ) data.object.distance = this.distance;
  18369. if ( this.angle !== undefined ) data.object.angle = this.angle;
  18370. if ( this.decay !== undefined ) data.object.decay = this.decay;
  18371. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  18372. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  18373. return data;
  18374. }
  18375. } );
  18376. /**
  18377. * @author alteredq / http://alteredqualia.com/
  18378. */
  18379. function HemisphereLight( skyColor, groundColor, intensity ) {
  18380. Light.call( this, skyColor, intensity );
  18381. this.type = 'HemisphereLight';
  18382. this.castShadow = undefined;
  18383. this.position.copy( Object3D.DefaultUp );
  18384. this.updateMatrix();
  18385. this.groundColor = new Color( groundColor );
  18386. }
  18387. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18388. constructor: HemisphereLight,
  18389. isHemisphereLight: true,
  18390. copy: function ( source ) {
  18391. Light.prototype.copy.call( this, source );
  18392. this.groundColor.copy( source.groundColor );
  18393. return this;
  18394. }
  18395. } );
  18396. /**
  18397. * @author mrdoob / http://mrdoob.com/
  18398. */
  18399. function LightShadow( camera ) {
  18400. this.camera = camera;
  18401. this.bias = 0;
  18402. this.radius = 1;
  18403. this.mapSize = new Vector2( 512, 512 );
  18404. this.map = null;
  18405. this.matrix = new Matrix4();
  18406. }
  18407. Object.assign( LightShadow.prototype, {
  18408. copy: function ( source ) {
  18409. this.camera = source.camera.clone();
  18410. this.bias = source.bias;
  18411. this.radius = source.radius;
  18412. this.mapSize.copy( source.mapSize );
  18413. return this;
  18414. },
  18415. clone: function () {
  18416. return new this.constructor().copy( this );
  18417. },
  18418. toJSON: function () {
  18419. var object = {};
  18420. if ( this.bias !== 0 ) object.bias = this.bias;
  18421. if ( this.radius !== 1 ) object.radius = this.radius;
  18422. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  18423. object.camera = this.camera.toJSON( false ).object;
  18424. delete object.camera.matrix;
  18425. return object;
  18426. }
  18427. } );
  18428. /**
  18429. * @author mrdoob / http://mrdoob.com/
  18430. */
  18431. function SpotLightShadow() {
  18432. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  18433. }
  18434. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18435. constructor: SpotLightShadow,
  18436. isSpotLightShadow: true,
  18437. update: function ( light ) {
  18438. var camera = this.camera;
  18439. var fov = _Math.RAD2DEG * 2 * light.angle;
  18440. var aspect = this.mapSize.width / this.mapSize.height;
  18441. var far = light.distance || camera.far;
  18442. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  18443. camera.fov = fov;
  18444. camera.aspect = aspect;
  18445. camera.far = far;
  18446. camera.updateProjectionMatrix();
  18447. }
  18448. }
  18449. } );
  18450. /**
  18451. * @author alteredq / http://alteredqualia.com/
  18452. */
  18453. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  18454. Light.call( this, color, intensity );
  18455. this.type = 'SpotLight';
  18456. this.position.copy( Object3D.DefaultUp );
  18457. this.updateMatrix();
  18458. this.target = new Object3D();
  18459. Object.defineProperty( this, 'power', {
  18460. get: function () {
  18461. // intensity = power per solid angle.
  18462. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18463. return this.intensity * Math.PI;
  18464. },
  18465. set: function ( power ) {
  18466. // intensity = power per solid angle.
  18467. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18468. this.intensity = power / Math.PI;
  18469. }
  18470. } );
  18471. this.distance = ( distance !== undefined ) ? distance : 0;
  18472. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  18473. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  18474. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18475. this.shadow = new SpotLightShadow();
  18476. }
  18477. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18478. constructor: SpotLight,
  18479. isSpotLight: true,
  18480. copy: function ( source ) {
  18481. Light.prototype.copy.call( this, source );
  18482. this.distance = source.distance;
  18483. this.angle = source.angle;
  18484. this.penumbra = source.penumbra;
  18485. this.decay = source.decay;
  18486. this.target = source.target.clone();
  18487. this.shadow = source.shadow.clone();
  18488. return this;
  18489. }
  18490. } );
  18491. /**
  18492. * @author mrdoob / http://mrdoob.com/
  18493. */
  18494. function PointLight( color, intensity, distance, decay ) {
  18495. Light.call( this, color, intensity );
  18496. this.type = 'PointLight';
  18497. Object.defineProperty( this, 'power', {
  18498. get: function () {
  18499. // intensity = power per solid angle.
  18500. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18501. return this.intensity * 4 * Math.PI;
  18502. },
  18503. set: function ( power ) {
  18504. // intensity = power per solid angle.
  18505. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18506. this.intensity = power / ( 4 * Math.PI );
  18507. }
  18508. } );
  18509. this.distance = ( distance !== undefined ) ? distance : 0;
  18510. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18511. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  18512. }
  18513. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18514. constructor: PointLight,
  18515. isPointLight: true,
  18516. copy: function ( source ) {
  18517. Light.prototype.copy.call( this, source );
  18518. this.distance = source.distance;
  18519. this.decay = source.decay;
  18520. this.shadow = source.shadow.clone();
  18521. return this;
  18522. }
  18523. } );
  18524. /**
  18525. * @author mrdoob / http://mrdoob.com/
  18526. */
  18527. function DirectionalLightShadow( ) {
  18528. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  18529. }
  18530. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18531. constructor: DirectionalLightShadow
  18532. } );
  18533. /**
  18534. * @author mrdoob / http://mrdoob.com/
  18535. * @author alteredq / http://alteredqualia.com/
  18536. */
  18537. function DirectionalLight( color, intensity ) {
  18538. Light.call( this, color, intensity );
  18539. this.type = 'DirectionalLight';
  18540. this.position.copy( Object3D.DefaultUp );
  18541. this.updateMatrix();
  18542. this.target = new Object3D();
  18543. this.shadow = new DirectionalLightShadow();
  18544. }
  18545. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18546. constructor: DirectionalLight,
  18547. isDirectionalLight: true,
  18548. copy: function ( source ) {
  18549. Light.prototype.copy.call( this, source );
  18550. this.target = source.target.clone();
  18551. this.shadow = source.shadow.clone();
  18552. return this;
  18553. }
  18554. } );
  18555. /**
  18556. * @author mrdoob / http://mrdoob.com/
  18557. */
  18558. function AmbientLight( color, intensity ) {
  18559. Light.call( this, color, intensity );
  18560. this.type = 'AmbientLight';
  18561. this.castShadow = undefined;
  18562. }
  18563. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18564. constructor: AmbientLight,
  18565. isAmbientLight: true
  18566. } );
  18567. /**
  18568. * @author abelnation / http://github.com/abelnation
  18569. */
  18570. function RectAreaLight( color, intensity, width, height ) {
  18571. Light.call( this, color, intensity );
  18572. this.type = 'RectAreaLight';
  18573. this.position.set( 0, 1, 0 );
  18574. this.updateMatrix();
  18575. this.width = ( width !== undefined ) ? width : 10;
  18576. this.height = ( height !== undefined ) ? height : 10;
  18577. // TODO (abelnation): distance/decay
  18578. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  18579. // TODO (abelnation): shadows
  18580. }
  18581. // TODO (abelnation): RectAreaLight update when light shape is changed
  18582. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18583. constructor: RectAreaLight,
  18584. isRectAreaLight: true,
  18585. copy: function ( source ) {
  18586. Light.prototype.copy.call( this, source );
  18587. this.width = source.width;
  18588. this.height = source.height;
  18589. return this;
  18590. },
  18591. toJSON: function ( meta ) {
  18592. var data = Light.prototype.toJSON.call( this, meta );
  18593. data.object.width = this.width;
  18594. data.object.height = this.height;
  18595. return data;
  18596. }
  18597. } );
  18598. /**
  18599. * @author tschw
  18600. * @author Ben Houston / http://clara.io/
  18601. * @author David Sarno / http://lighthaus.us/
  18602. */
  18603. var AnimationUtils = {
  18604. // same as Array.prototype.slice, but also works on typed arrays
  18605. arraySlice: function ( array, from, to ) {
  18606. if ( AnimationUtils.isTypedArray( array ) ) {
  18607. // in ios9 array.subarray(from, undefined) will return empty array
  18608. // but array.subarray(from) or array.subarray(from, len) is correct
  18609. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  18610. }
  18611. return array.slice( from, to );
  18612. },
  18613. // converts an array to a specific type
  18614. convertArray: function ( array, type, forceClone ) {
  18615. if ( ! array || // let 'undefined' and 'null' pass
  18616. ! forceClone && array.constructor === type ) return array;
  18617. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  18618. return new type( array ); // create typed array
  18619. }
  18620. return Array.prototype.slice.call( array ); // create Array
  18621. },
  18622. isTypedArray: function ( object ) {
  18623. return ArrayBuffer.isView( object ) &&
  18624. ! ( object instanceof DataView );
  18625. },
  18626. // returns an array by which times and values can be sorted
  18627. getKeyframeOrder: function ( times ) {
  18628. function compareTime( i, j ) {
  18629. return times[ i ] - times[ j ];
  18630. }
  18631. var n = times.length;
  18632. var result = new Array( n );
  18633. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  18634. result.sort( compareTime );
  18635. return result;
  18636. },
  18637. // uses the array previously returned by 'getKeyframeOrder' to sort data
  18638. sortedArray: function ( values, stride, order ) {
  18639. var nValues = values.length;
  18640. var result = new values.constructor( nValues );
  18641. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  18642. var srcOffset = order[ i ] * stride;
  18643. for ( var j = 0; j !== stride; ++ j ) {
  18644. result[ dstOffset ++ ] = values[ srcOffset + j ];
  18645. }
  18646. }
  18647. return result;
  18648. },
  18649. // function for parsing AOS keyframe formats
  18650. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  18651. var i = 1, key = jsonKeys[ 0 ];
  18652. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  18653. key = jsonKeys[ i ++ ];
  18654. }
  18655. if ( key === undefined ) return; // no data
  18656. var value = key[ valuePropertyName ];
  18657. if ( value === undefined ) return; // no data
  18658. if ( Array.isArray( value ) ) {
  18659. do {
  18660. value = key[ valuePropertyName ];
  18661. if ( value !== undefined ) {
  18662. times.push( key.time );
  18663. values.push.apply( values, value ); // push all elements
  18664. }
  18665. key = jsonKeys[ i ++ ];
  18666. } while ( key !== undefined );
  18667. } else if ( value.toArray !== undefined ) {
  18668. // ...assume THREE.Math-ish
  18669. do {
  18670. value = key[ valuePropertyName ];
  18671. if ( value !== undefined ) {
  18672. times.push( key.time );
  18673. value.toArray( values, values.length );
  18674. }
  18675. key = jsonKeys[ i ++ ];
  18676. } while ( key !== undefined );
  18677. } else {
  18678. // otherwise push as-is
  18679. do {
  18680. value = key[ valuePropertyName ];
  18681. if ( value !== undefined ) {
  18682. times.push( key.time );
  18683. values.push( value );
  18684. }
  18685. key = jsonKeys[ i ++ ];
  18686. } while ( key !== undefined );
  18687. }
  18688. }
  18689. };
  18690. /**
  18691. * Abstract base class of interpolants over parametric samples.
  18692. *
  18693. * The parameter domain is one dimensional, typically the time or a path
  18694. * along a curve defined by the data.
  18695. *
  18696. * The sample values can have any dimensionality and derived classes may
  18697. * apply special interpretations to the data.
  18698. *
  18699. * This class provides the interval seek in a Template Method, deferring
  18700. * the actual interpolation to derived classes.
  18701. *
  18702. * Time complexity is O(1) for linear access crossing at most two points
  18703. * and O(log N) for random access, where N is the number of positions.
  18704. *
  18705. * References:
  18706. *
  18707. * http://www.oodesign.com/template-method-pattern.html
  18708. *
  18709. * @author tschw
  18710. */
  18711. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18712. this.parameterPositions = parameterPositions;
  18713. this._cachedIndex = 0;
  18714. this.resultBuffer = resultBuffer !== undefined ?
  18715. resultBuffer : new sampleValues.constructor( sampleSize );
  18716. this.sampleValues = sampleValues;
  18717. this.valueSize = sampleSize;
  18718. }
  18719. Object.assign( Interpolant.prototype, {
  18720. evaluate: function( t ) {
  18721. var pp = this.parameterPositions,
  18722. i1 = this._cachedIndex,
  18723. t1 = pp[ i1 ],
  18724. t0 = pp[ i1 - 1 ];
  18725. validate_interval: {
  18726. seek: {
  18727. var right;
  18728. linear_scan: {
  18729. //- See http://jsperf.com/comparison-to-undefined/3
  18730. //- slower code:
  18731. //-
  18732. //- if ( t >= t1 || t1 === undefined ) {
  18733. forward_scan: if ( ! ( t < t1 ) ) {
  18734. for ( var giveUpAt = i1 + 2; ;) {
  18735. if ( t1 === undefined ) {
  18736. if ( t < t0 ) break forward_scan;
  18737. // after end
  18738. i1 = pp.length;
  18739. this._cachedIndex = i1;
  18740. return this.afterEnd_( i1 - 1, t, t0 );
  18741. }
  18742. if ( i1 === giveUpAt ) break; // this loop
  18743. t0 = t1;
  18744. t1 = pp[ ++ i1 ];
  18745. if ( t < t1 ) {
  18746. // we have arrived at the sought interval
  18747. break seek;
  18748. }
  18749. }
  18750. // prepare binary search on the right side of the index
  18751. right = pp.length;
  18752. break linear_scan;
  18753. }
  18754. //- slower code:
  18755. //- if ( t < t0 || t0 === undefined ) {
  18756. if ( ! ( t >= t0 ) ) {
  18757. // looping?
  18758. var t1global = pp[ 1 ];
  18759. if ( t < t1global ) {
  18760. i1 = 2; // + 1, using the scan for the details
  18761. t0 = t1global;
  18762. }
  18763. // linear reverse scan
  18764. for ( var giveUpAt = i1 - 2; ;) {
  18765. if ( t0 === undefined ) {
  18766. // before start
  18767. this._cachedIndex = 0;
  18768. return this.beforeStart_( 0, t, t1 );
  18769. }
  18770. if ( i1 === giveUpAt ) break; // this loop
  18771. t1 = t0;
  18772. t0 = pp[ -- i1 - 1 ];
  18773. if ( t >= t0 ) {
  18774. // we have arrived at the sought interval
  18775. break seek;
  18776. }
  18777. }
  18778. // prepare binary search on the left side of the index
  18779. right = i1;
  18780. i1 = 0;
  18781. break linear_scan;
  18782. }
  18783. // the interval is valid
  18784. break validate_interval;
  18785. } // linear scan
  18786. // binary search
  18787. while ( i1 < right ) {
  18788. var mid = ( i1 + right ) >>> 1;
  18789. if ( t < pp[ mid ] ) {
  18790. right = mid;
  18791. } else {
  18792. i1 = mid + 1;
  18793. }
  18794. }
  18795. t1 = pp[ i1 ];
  18796. t0 = pp[ i1 - 1 ];
  18797. // check boundary cases, again
  18798. if ( t0 === undefined ) {
  18799. this._cachedIndex = 0;
  18800. return this.beforeStart_( 0, t, t1 );
  18801. }
  18802. if ( t1 === undefined ) {
  18803. i1 = pp.length;
  18804. this._cachedIndex = i1;
  18805. return this.afterEnd_( i1 - 1, t0, t );
  18806. }
  18807. } // seek
  18808. this._cachedIndex = i1;
  18809. this.intervalChanged_( i1, t0, t1 );
  18810. } // validate_interval
  18811. return this.interpolate_( i1, t0, t, t1 );
  18812. },
  18813. settings: null, // optional, subclass-specific settings structure
  18814. // Note: The indirection allows central control of many interpolants.
  18815. // --- Protected interface
  18816. DefaultSettings_: {},
  18817. getSettings_: function() {
  18818. return this.settings || this.DefaultSettings_;
  18819. },
  18820. copySampleValue_: function( index ) {
  18821. // copies a sample value to the result buffer
  18822. var result = this.resultBuffer,
  18823. values = this.sampleValues,
  18824. stride = this.valueSize,
  18825. offset = index * stride;
  18826. for ( var i = 0; i !== stride; ++ i ) {
  18827. result[ i ] = values[ offset + i ];
  18828. }
  18829. return result;
  18830. },
  18831. // Template methods for derived classes:
  18832. interpolate_: function( i1, t0, t, t1 ) {
  18833. throw new Error( "call to abstract method" );
  18834. // implementations shall return this.resultBuffer
  18835. },
  18836. intervalChanged_: function( i1, t0, t1 ) {
  18837. // empty
  18838. }
  18839. } );
  18840. //!\ DECLARE ALIAS AFTER assign prototype !
  18841. Object.assign( Interpolant.prototype, {
  18842. //( 0, t, t0 ), returns this.resultBuffer
  18843. beforeStart_: Interpolant.prototype.copySampleValue_,
  18844. //( N-1, tN-1, t ), returns this.resultBuffer
  18845. afterEnd_: Interpolant.prototype.copySampleValue_,
  18846. } );
  18847. /**
  18848. * Fast and simple cubic spline interpolant.
  18849. *
  18850. * It was derived from a Hermitian construction setting the first derivative
  18851. * at each sample position to the linear slope between neighboring positions
  18852. * over their parameter interval.
  18853. *
  18854. * @author tschw
  18855. */
  18856. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18857. Interpolant.call(
  18858. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18859. this._weightPrev = -0;
  18860. this._offsetPrev = -0;
  18861. this._weightNext = -0;
  18862. this._offsetNext = -0;
  18863. }
  18864. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18865. constructor: CubicInterpolant,
  18866. DefaultSettings_: {
  18867. endingStart: ZeroCurvatureEnding,
  18868. endingEnd: ZeroCurvatureEnding
  18869. },
  18870. intervalChanged_: function( i1, t0, t1 ) {
  18871. var pp = this.parameterPositions,
  18872. iPrev = i1 - 2,
  18873. iNext = i1 + 1,
  18874. tPrev = pp[ iPrev ],
  18875. tNext = pp[ iNext ];
  18876. if ( tPrev === undefined ) {
  18877. switch ( this.getSettings_().endingStart ) {
  18878. case ZeroSlopeEnding:
  18879. // f'(t0) = 0
  18880. iPrev = i1;
  18881. tPrev = 2 * t0 - t1;
  18882. break;
  18883. case WrapAroundEnding:
  18884. // use the other end of the curve
  18885. iPrev = pp.length - 2;
  18886. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  18887. break;
  18888. default: // ZeroCurvatureEnding
  18889. // f''(t0) = 0 a.k.a. Natural Spline
  18890. iPrev = i1;
  18891. tPrev = t1;
  18892. }
  18893. }
  18894. if ( tNext === undefined ) {
  18895. switch ( this.getSettings_().endingEnd ) {
  18896. case ZeroSlopeEnding:
  18897. // f'(tN) = 0
  18898. iNext = i1;
  18899. tNext = 2 * t1 - t0;
  18900. break;
  18901. case WrapAroundEnding:
  18902. // use the other end of the curve
  18903. iNext = 1;
  18904. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  18905. break;
  18906. default: // ZeroCurvatureEnding
  18907. // f''(tN) = 0, a.k.a. Natural Spline
  18908. iNext = i1 - 1;
  18909. tNext = t0;
  18910. }
  18911. }
  18912. var halfDt = ( t1 - t0 ) * 0.5,
  18913. stride = this.valueSize;
  18914. this._weightPrev = halfDt / ( t0 - tPrev );
  18915. this._weightNext = halfDt / ( tNext - t1 );
  18916. this._offsetPrev = iPrev * stride;
  18917. this._offsetNext = iNext * stride;
  18918. },
  18919. interpolate_: function( i1, t0, t, t1 ) {
  18920. var result = this.resultBuffer,
  18921. values = this.sampleValues,
  18922. stride = this.valueSize,
  18923. o1 = i1 * stride, o0 = o1 - stride,
  18924. oP = this._offsetPrev, oN = this._offsetNext,
  18925. wP = this._weightPrev, wN = this._weightNext,
  18926. p = ( t - t0 ) / ( t1 - t0 ),
  18927. pp = p * p,
  18928. ppp = pp * p;
  18929. // evaluate polynomials
  18930. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  18931. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  18932. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  18933. var sN = wN * ppp - wN * pp;
  18934. // combine data linearly
  18935. for ( var i = 0; i !== stride; ++ i ) {
  18936. result[ i ] =
  18937. sP * values[ oP + i ] +
  18938. s0 * values[ o0 + i ] +
  18939. s1 * values[ o1 + i ] +
  18940. sN * values[ oN + i ];
  18941. }
  18942. return result;
  18943. }
  18944. } );
  18945. /**
  18946. * @author tschw
  18947. */
  18948. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18949. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18950. }
  18951. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18952. constructor: LinearInterpolant,
  18953. interpolate_: function( i1, t0, t, t1 ) {
  18954. var result = this.resultBuffer,
  18955. values = this.sampleValues,
  18956. stride = this.valueSize,
  18957. offset1 = i1 * stride,
  18958. offset0 = offset1 - stride,
  18959. weight1 = ( t - t0 ) / ( t1 - t0 ),
  18960. weight0 = 1 - weight1;
  18961. for ( var i = 0; i !== stride; ++ i ) {
  18962. result[ i ] =
  18963. values[ offset0 + i ] * weight0 +
  18964. values[ offset1 + i ] * weight1;
  18965. }
  18966. return result;
  18967. }
  18968. } );
  18969. /**
  18970. *
  18971. * Interpolant that evaluates to the sample value at the position preceeding
  18972. * the parameter.
  18973. *
  18974. * @author tschw
  18975. */
  18976. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18977. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18978. }
  18979. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18980. constructor: DiscreteInterpolant,
  18981. interpolate_: function( i1, t0, t, t1 ) {
  18982. return this.copySampleValue_( i1 - 1 );
  18983. }
  18984. } );
  18985. var KeyframeTrackPrototype;
  18986. KeyframeTrackPrototype = {
  18987. TimeBufferType: Float32Array,
  18988. ValueBufferType: Float32Array,
  18989. DefaultInterpolation: InterpolateLinear,
  18990. InterpolantFactoryMethodDiscrete: function ( result ) {
  18991. return new DiscreteInterpolant(
  18992. this.times, this.values, this.getValueSize(), result );
  18993. },
  18994. InterpolantFactoryMethodLinear: function ( result ) {
  18995. return new LinearInterpolant(
  18996. this.times, this.values, this.getValueSize(), result );
  18997. },
  18998. InterpolantFactoryMethodSmooth: function ( result ) {
  18999. return new CubicInterpolant(
  19000. this.times, this.values, this.getValueSize(), result );
  19001. },
  19002. setInterpolation: function ( interpolation ) {
  19003. var factoryMethod;
  19004. switch ( interpolation ) {
  19005. case InterpolateDiscrete:
  19006. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  19007. break;
  19008. case InterpolateLinear:
  19009. factoryMethod = this.InterpolantFactoryMethodLinear;
  19010. break;
  19011. case InterpolateSmooth:
  19012. factoryMethod = this.InterpolantFactoryMethodSmooth;
  19013. break;
  19014. }
  19015. if ( factoryMethod === undefined ) {
  19016. var message = "unsupported interpolation for " +
  19017. this.ValueTypeName + " keyframe track named " + this.name;
  19018. if ( this.createInterpolant === undefined ) {
  19019. // fall back to default, unless the default itself is messed up
  19020. if ( interpolation !== this.DefaultInterpolation ) {
  19021. this.setInterpolation( this.DefaultInterpolation );
  19022. } else {
  19023. throw new Error( message ); // fatal, in this case
  19024. }
  19025. }
  19026. console.warn( 'THREE.KeyframeTrackPrototype:', message );
  19027. return;
  19028. }
  19029. this.createInterpolant = factoryMethod;
  19030. },
  19031. getInterpolation: function () {
  19032. switch ( this.createInterpolant ) {
  19033. case this.InterpolantFactoryMethodDiscrete:
  19034. return InterpolateDiscrete;
  19035. case this.InterpolantFactoryMethodLinear:
  19036. return InterpolateLinear;
  19037. case this.InterpolantFactoryMethodSmooth:
  19038. return InterpolateSmooth;
  19039. }
  19040. },
  19041. getValueSize: function () {
  19042. return this.values.length / this.times.length;
  19043. },
  19044. // move all keyframes either forwards or backwards in time
  19045. shift: function ( timeOffset ) {
  19046. if ( timeOffset !== 0.0 ) {
  19047. var times = this.times;
  19048. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  19049. times[ i ] += timeOffset;
  19050. }
  19051. }
  19052. return this;
  19053. },
  19054. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  19055. scale: function ( timeScale ) {
  19056. if ( timeScale !== 1.0 ) {
  19057. var times = this.times;
  19058. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  19059. times[ i ] *= timeScale;
  19060. }
  19061. }
  19062. return this;
  19063. },
  19064. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  19065. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  19066. trim: function ( startTime, endTime ) {
  19067. var times = this.times,
  19068. nKeys = times.length,
  19069. from = 0,
  19070. to = nKeys - 1;
  19071. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  19072. while ( to !== - 1 && times[ to ] > endTime ) -- to;
  19073. ++ to; // inclusive -> exclusive bound
  19074. if ( from !== 0 || to !== nKeys ) {
  19075. // empty tracks are forbidden, so keep at least one keyframe
  19076. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  19077. var stride = this.getValueSize();
  19078. this.times = AnimationUtils.arraySlice( times, from, to );
  19079. this.values = AnimationUtils.
  19080. arraySlice( this.values, from * stride, to * stride );
  19081. }
  19082. return this;
  19083. },
  19084. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  19085. validate: function () {
  19086. var valid = true;
  19087. var valueSize = this.getValueSize();
  19088. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  19089. console.error( 'THREE.KeyframeTrackPrototype: Invalid value size in track.', this );
  19090. valid = false;
  19091. }
  19092. var times = this.times,
  19093. values = this.values,
  19094. nKeys = times.length;
  19095. if ( nKeys === 0 ) {
  19096. console.error( 'THREE.KeyframeTrackPrototype: Track is empty.', this );
  19097. valid = false;
  19098. }
  19099. var prevTime = null;
  19100. for ( var i = 0; i !== nKeys; i ++ ) {
  19101. var currTime = times[ i ];
  19102. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  19103. console.error( 'THREE.KeyframeTrackPrototype: Time is not a valid number.', this, i, currTime );
  19104. valid = false;
  19105. break;
  19106. }
  19107. if ( prevTime !== null && prevTime > currTime ) {
  19108. console.error( 'THREE.KeyframeTrackPrototype: Out of order keys.', this, i, currTime, prevTime );
  19109. valid = false;
  19110. break;
  19111. }
  19112. prevTime = currTime;
  19113. }
  19114. if ( values !== undefined ) {
  19115. if ( AnimationUtils.isTypedArray( values ) ) {
  19116. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  19117. var value = values[ i ];
  19118. if ( isNaN( value ) ) {
  19119. console.error( 'THREE.KeyframeTrackPrototype: Value is not a valid number.', this, i, value );
  19120. valid = false;
  19121. break;
  19122. }
  19123. }
  19124. }
  19125. }
  19126. return valid;
  19127. },
  19128. // removes equivalent sequential keys as common in morph target sequences
  19129. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  19130. optimize: function () {
  19131. var times = this.times,
  19132. values = this.values,
  19133. stride = this.getValueSize(),
  19134. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  19135. writeIndex = 1,
  19136. lastIndex = times.length - 1;
  19137. for ( var i = 1; i < lastIndex; ++ i ) {
  19138. var keep = false;
  19139. var time = times[ i ];
  19140. var timeNext = times[ i + 1 ];
  19141. // remove adjacent keyframes scheduled at the same time
  19142. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  19143. if ( ! smoothInterpolation ) {
  19144. // remove unnecessary keyframes same as their neighbors
  19145. var offset = i * stride,
  19146. offsetP = offset - stride,
  19147. offsetN = offset + stride;
  19148. for ( var j = 0; j !== stride; ++ j ) {
  19149. var value = values[ offset + j ];
  19150. if ( value !== values[ offsetP + j ] ||
  19151. value !== values[ offsetN + j ] ) {
  19152. keep = true;
  19153. break;
  19154. }
  19155. }
  19156. } else keep = true;
  19157. }
  19158. // in-place compaction
  19159. if ( keep ) {
  19160. if ( i !== writeIndex ) {
  19161. times[ writeIndex ] = times[ i ];
  19162. var readOffset = i * stride,
  19163. writeOffset = writeIndex * stride;
  19164. for ( var j = 0; j !== stride; ++ j )
  19165. values[ writeOffset + j ] = values[ readOffset + j ];
  19166. }
  19167. ++ writeIndex;
  19168. }
  19169. }
  19170. // flush last keyframe (compaction looks ahead)
  19171. if ( lastIndex > 0 ) {
  19172. times[ writeIndex ] = times[ lastIndex ];
  19173. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j )
  19174. values[ writeOffset + j ] = values[ readOffset + j ];
  19175. ++ writeIndex;
  19176. }
  19177. if ( writeIndex !== times.length ) {
  19178. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  19179. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  19180. }
  19181. return this;
  19182. }
  19183. };
  19184. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  19185. if ( name === undefined ) throw new Error( "track name is undefined" );
  19186. if ( times === undefined || times.length === 0 ) {
  19187. throw new Error( "no keyframes in track named " + name );
  19188. }
  19189. this.name = name;
  19190. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  19191. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  19192. this.setInterpolation( interpolation || this.DefaultInterpolation );
  19193. this.validate();
  19194. this.optimize();
  19195. }
  19196. /**
  19197. *
  19198. * A Track of vectored keyframe values.
  19199. *
  19200. *
  19201. * @author Ben Houston / http://clara.io/
  19202. * @author David Sarno / http://lighthaus.us/
  19203. * @author tschw
  19204. */
  19205. function VectorKeyframeTrack( name, times, values, interpolation ) {
  19206. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19207. }
  19208. VectorKeyframeTrack.prototype =
  19209. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19210. constructor: VectorKeyframeTrack,
  19211. ValueTypeName: 'vector'
  19212. // ValueBufferType is inherited
  19213. // DefaultInterpolation is inherited
  19214. } );
  19215. /**
  19216. * Spherical linear unit quaternion interpolant.
  19217. *
  19218. * @author tschw
  19219. */
  19220. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19221. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  19222. }
  19223. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  19224. constructor: QuaternionLinearInterpolant,
  19225. interpolate_: function( i1, t0, t, t1 ) {
  19226. var result = this.resultBuffer,
  19227. values = this.sampleValues,
  19228. stride = this.valueSize,
  19229. offset = i1 * stride,
  19230. alpha = ( t - t0 ) / ( t1 - t0 );
  19231. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  19232. Quaternion.slerpFlat( result, 0,
  19233. values, offset - stride, values, offset, alpha );
  19234. }
  19235. return result;
  19236. }
  19237. } );
  19238. /**
  19239. *
  19240. * A Track of quaternion keyframe values.
  19241. *
  19242. * @author Ben Houston / http://clara.io/
  19243. * @author David Sarno / http://lighthaus.us/
  19244. * @author tschw
  19245. */
  19246. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  19247. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19248. }
  19249. QuaternionKeyframeTrack.prototype =
  19250. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19251. constructor: QuaternionKeyframeTrack,
  19252. ValueTypeName: 'quaternion',
  19253. // ValueBufferType is inherited
  19254. DefaultInterpolation: InterpolateLinear,
  19255. InterpolantFactoryMethodLinear: function( result ) {
  19256. return new QuaternionLinearInterpolant(
  19257. this.times, this.values, this.getValueSize(), result );
  19258. },
  19259. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  19260. } );
  19261. /**
  19262. *
  19263. * A Track of numeric keyframe values.
  19264. *
  19265. * @author Ben Houston / http://clara.io/
  19266. * @author David Sarno / http://lighthaus.us/
  19267. * @author tschw
  19268. */
  19269. function NumberKeyframeTrack( name, times, values, interpolation ) {
  19270. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19271. }
  19272. NumberKeyframeTrack.prototype =
  19273. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19274. constructor: NumberKeyframeTrack,
  19275. ValueTypeName: 'number'
  19276. // ValueBufferType is inherited
  19277. // DefaultInterpolation is inherited
  19278. } );
  19279. /**
  19280. *
  19281. * A Track that interpolates Strings
  19282. *
  19283. *
  19284. * @author Ben Houston / http://clara.io/
  19285. * @author David Sarno / http://lighthaus.us/
  19286. * @author tschw
  19287. */
  19288. function StringKeyframeTrack( name, times, values, interpolation ) {
  19289. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19290. }
  19291. StringKeyframeTrack.prototype =
  19292. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19293. constructor: StringKeyframeTrack,
  19294. ValueTypeName: 'string',
  19295. ValueBufferType: Array,
  19296. DefaultInterpolation: InterpolateDiscrete,
  19297. InterpolantFactoryMethodLinear: undefined,
  19298. InterpolantFactoryMethodSmooth: undefined
  19299. } );
  19300. /**
  19301. *
  19302. * A Track of Boolean keyframe values.
  19303. *
  19304. *
  19305. * @author Ben Houston / http://clara.io/
  19306. * @author David Sarno / http://lighthaus.us/
  19307. * @author tschw
  19308. */
  19309. function BooleanKeyframeTrack( name, times, values ) {
  19310. KeyframeTrackConstructor.call( this, name, times, values );
  19311. }
  19312. BooleanKeyframeTrack.prototype =
  19313. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19314. constructor: BooleanKeyframeTrack,
  19315. ValueTypeName: 'bool',
  19316. ValueBufferType: Array,
  19317. DefaultInterpolation: InterpolateDiscrete,
  19318. InterpolantFactoryMethodLinear: undefined,
  19319. InterpolantFactoryMethodSmooth: undefined
  19320. // Note: Actually this track could have a optimized / compressed
  19321. // representation of a single value and a custom interpolant that
  19322. // computes "firstValue ^ isOdd( index )".
  19323. } );
  19324. /**
  19325. *
  19326. * A Track of keyframe values that represent color.
  19327. *
  19328. *
  19329. * @author Ben Houston / http://clara.io/
  19330. * @author David Sarno / http://lighthaus.us/
  19331. * @author tschw
  19332. */
  19333. function ColorKeyframeTrack( name, times, values, interpolation ) {
  19334. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19335. }
  19336. ColorKeyframeTrack.prototype =
  19337. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19338. constructor: ColorKeyframeTrack,
  19339. ValueTypeName: 'color'
  19340. // ValueBufferType is inherited
  19341. // DefaultInterpolation is inherited
  19342. // Note: Very basic implementation and nothing special yet.
  19343. // However, this is the place for color space parameterization.
  19344. } );
  19345. /**
  19346. *
  19347. * A timed sequence of keyframes for a specific property.
  19348. *
  19349. *
  19350. * @author Ben Houston / http://clara.io/
  19351. * @author David Sarno / http://lighthaus.us/
  19352. * @author tschw
  19353. */
  19354. function KeyframeTrack( name, times, values, interpolation ) {
  19355. KeyframeTrackConstructor.apply( this, arguments );
  19356. }
  19357. KeyframeTrack.prototype = KeyframeTrackPrototype;
  19358. KeyframeTrackPrototype.constructor = KeyframeTrack;
  19359. // Static methods:
  19360. Object.assign( KeyframeTrack, {
  19361. // Serialization (in static context, because of constructor invocation
  19362. // and automatic invocation of .toJSON):
  19363. parse: function( json ) {
  19364. if( json.type === undefined ) {
  19365. throw new Error( "track type undefined, can not parse" );
  19366. }
  19367. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  19368. if ( json.times === undefined ) {
  19369. var times = [], values = [];
  19370. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  19371. json.times = times;
  19372. json.values = values;
  19373. }
  19374. // derived classes can define a static parse method
  19375. if ( trackType.parse !== undefined ) {
  19376. return trackType.parse( json );
  19377. } else {
  19378. // by default, we assume a constructor compatible with the base
  19379. return new trackType(
  19380. json.name, json.times, json.values, json.interpolation );
  19381. }
  19382. },
  19383. toJSON: function( track ) {
  19384. var trackType = track.constructor;
  19385. var json;
  19386. // derived classes can define a static toJSON method
  19387. if ( trackType.toJSON !== undefined ) {
  19388. json = trackType.toJSON( track );
  19389. } else {
  19390. // by default, we assume the data can be serialized as-is
  19391. json = {
  19392. 'name': track.name,
  19393. 'times': AnimationUtils.convertArray( track.times, Array ),
  19394. 'values': AnimationUtils.convertArray( track.values, Array )
  19395. };
  19396. var interpolation = track.getInterpolation();
  19397. if ( interpolation !== track.DefaultInterpolation ) {
  19398. json.interpolation = interpolation;
  19399. }
  19400. }
  19401. json.type = track.ValueTypeName; // mandatory
  19402. return json;
  19403. },
  19404. _getTrackTypeForValueTypeName: function( typeName ) {
  19405. switch( typeName.toLowerCase() ) {
  19406. case "scalar":
  19407. case "double":
  19408. case "float":
  19409. case "number":
  19410. case "integer":
  19411. return NumberKeyframeTrack;
  19412. case "vector":
  19413. case "vector2":
  19414. case "vector3":
  19415. case "vector4":
  19416. return VectorKeyframeTrack;
  19417. case "color":
  19418. return ColorKeyframeTrack;
  19419. case "quaternion":
  19420. return QuaternionKeyframeTrack;
  19421. case "bool":
  19422. case "boolean":
  19423. return BooleanKeyframeTrack;
  19424. case "string":
  19425. return StringKeyframeTrack;
  19426. }
  19427. throw new Error( "Unsupported typeName: " + typeName );
  19428. }
  19429. } );
  19430. /**
  19431. *
  19432. * Reusable set of Tracks that represent an animation.
  19433. *
  19434. * @author Ben Houston / http://clara.io/
  19435. * @author David Sarno / http://lighthaus.us/
  19436. */
  19437. function AnimationClip( name, duration, tracks ) {
  19438. this.name = name;
  19439. this.tracks = tracks;
  19440. this.duration = ( duration !== undefined ) ? duration : - 1;
  19441. this.uuid = _Math.generateUUID();
  19442. // this means it should figure out its duration by scanning the tracks
  19443. if ( this.duration < 0 ) {
  19444. this.resetDuration();
  19445. }
  19446. this.optimize();
  19447. }
  19448. Object.assign( AnimationClip, {
  19449. parse: function ( json ) {
  19450. var tracks = [],
  19451. jsonTracks = json.tracks,
  19452. frameTime = 1.0 / ( json.fps || 1.0 );
  19453. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  19454. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  19455. }
  19456. return new AnimationClip( json.name, json.duration, tracks );
  19457. },
  19458. toJSON: function ( clip ) {
  19459. var tracks = [],
  19460. clipTracks = clip.tracks;
  19461. var json = {
  19462. 'name': clip.name,
  19463. 'duration': clip.duration,
  19464. 'tracks': tracks
  19465. };
  19466. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  19467. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  19468. }
  19469. return json;
  19470. },
  19471. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  19472. var numMorphTargets = morphTargetSequence.length;
  19473. var tracks = [];
  19474. for ( var i = 0; i < numMorphTargets; i ++ ) {
  19475. var times = [];
  19476. var values = [];
  19477. times.push(
  19478. ( i + numMorphTargets - 1 ) % numMorphTargets,
  19479. i,
  19480. ( i + 1 ) % numMorphTargets );
  19481. values.push( 0, 1, 0 );
  19482. var order = AnimationUtils.getKeyframeOrder( times );
  19483. times = AnimationUtils.sortedArray( times, 1, order );
  19484. values = AnimationUtils.sortedArray( values, 1, order );
  19485. // if there is a key at the first frame, duplicate it as the
  19486. // last frame as well for perfect loop.
  19487. if ( ! noLoop && times[ 0 ] === 0 ) {
  19488. times.push( numMorphTargets );
  19489. values.push( values[ 0 ] );
  19490. }
  19491. tracks.push(
  19492. new NumberKeyframeTrack(
  19493. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  19494. times, values
  19495. ).scale( 1.0 / fps ) );
  19496. }
  19497. return new AnimationClip( name, - 1, tracks );
  19498. },
  19499. findByName: function ( objectOrClipArray, name ) {
  19500. var clipArray = objectOrClipArray;
  19501. if ( ! Array.isArray( objectOrClipArray ) ) {
  19502. var o = objectOrClipArray;
  19503. clipArray = o.geometry && o.geometry.animations || o.animations;
  19504. }
  19505. for ( var i = 0; i < clipArray.length; i ++ ) {
  19506. if ( clipArray[ i ].name === name ) {
  19507. return clipArray[ i ];
  19508. }
  19509. }
  19510. return null;
  19511. },
  19512. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  19513. var animationToMorphTargets = {};
  19514. // tested with https://regex101.com/ on trick sequences
  19515. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  19516. var pattern = /^([\w-]*?)([\d]+)$/;
  19517. // sort morph target names into animation groups based
  19518. // patterns like Walk_001, Walk_002, Run_001, Run_002
  19519. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  19520. var morphTarget = morphTargets[ i ];
  19521. var parts = morphTarget.name.match( pattern );
  19522. if ( parts && parts.length > 1 ) {
  19523. var name = parts[ 1 ];
  19524. var animationMorphTargets = animationToMorphTargets[ name ];
  19525. if ( ! animationMorphTargets ) {
  19526. animationToMorphTargets[ name ] = animationMorphTargets = [];
  19527. }
  19528. animationMorphTargets.push( morphTarget );
  19529. }
  19530. }
  19531. var clips = [];
  19532. for ( var name in animationToMorphTargets ) {
  19533. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  19534. }
  19535. return clips;
  19536. },
  19537. // parse the animation.hierarchy format
  19538. parseAnimation: function ( animation, bones ) {
  19539. if ( ! animation ) {
  19540. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  19541. return null;
  19542. }
  19543. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  19544. // only return track if there are actually keys.
  19545. if ( animationKeys.length !== 0 ) {
  19546. var times = [];
  19547. var values = [];
  19548. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  19549. // empty keys are filtered out, so check again
  19550. if ( times.length !== 0 ) {
  19551. destTracks.push( new trackType( trackName, times, values ) );
  19552. }
  19553. }
  19554. };
  19555. var tracks = [];
  19556. var clipName = animation.name || 'default';
  19557. // automatic length determination in AnimationClip.
  19558. var duration = animation.length || - 1;
  19559. var fps = animation.fps || 30;
  19560. var hierarchyTracks = animation.hierarchy || [];
  19561. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  19562. var animationKeys = hierarchyTracks[ h ].keys;
  19563. // skip empty tracks
  19564. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  19565. // process morph targets
  19566. if ( animationKeys[ 0 ].morphTargets ) {
  19567. // figure out all morph targets used in this track
  19568. var morphTargetNames = {};
  19569. for ( var k = 0; k < animationKeys.length; k ++ ) {
  19570. if ( animationKeys[ k ].morphTargets ) {
  19571. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  19572. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  19573. }
  19574. }
  19575. }
  19576. // create a track for each morph target with all zero
  19577. // morphTargetInfluences except for the keys in which
  19578. // the morphTarget is named.
  19579. for ( var morphTargetName in morphTargetNames ) {
  19580. var times = [];
  19581. var values = [];
  19582. for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  19583. var animationKey = animationKeys[ k ];
  19584. times.push( animationKey.time );
  19585. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  19586. }
  19587. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  19588. }
  19589. duration = morphTargetNames.length * ( fps || 1.0 );
  19590. } else {
  19591. // ...assume skeletal animation
  19592. var boneName = '.bones[' + bones[ h ].name + ']';
  19593. addNonemptyTrack(
  19594. VectorKeyframeTrack, boneName + '.position',
  19595. animationKeys, 'pos', tracks );
  19596. addNonemptyTrack(
  19597. QuaternionKeyframeTrack, boneName + '.quaternion',
  19598. animationKeys, 'rot', tracks );
  19599. addNonemptyTrack(
  19600. VectorKeyframeTrack, boneName + '.scale',
  19601. animationKeys, 'scl', tracks );
  19602. }
  19603. }
  19604. if ( tracks.length === 0 ) {
  19605. return null;
  19606. }
  19607. var clip = new AnimationClip( clipName, duration, tracks );
  19608. return clip;
  19609. }
  19610. } );
  19611. Object.assign( AnimationClip.prototype, {
  19612. resetDuration: function () {
  19613. var tracks = this.tracks, duration = 0;
  19614. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  19615. var track = this.tracks[ i ];
  19616. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  19617. }
  19618. this.duration = duration;
  19619. },
  19620. trim: function () {
  19621. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19622. this.tracks[ i ].trim( 0, this.duration );
  19623. }
  19624. return this;
  19625. },
  19626. optimize: function () {
  19627. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19628. this.tracks[ i ].optimize();
  19629. }
  19630. return this;
  19631. }
  19632. } );
  19633. /**
  19634. * @author mrdoob / http://mrdoob.com/
  19635. */
  19636. function MaterialLoader( manager ) {
  19637. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19638. this.textures = {};
  19639. }
  19640. Object.assign( MaterialLoader.prototype, {
  19641. load: function ( url, onLoad, onProgress, onError ) {
  19642. var scope = this;
  19643. var loader = new FileLoader( scope.manager );
  19644. loader.load( url, function ( text ) {
  19645. onLoad( scope.parse( JSON.parse( text ) ) );
  19646. }, onProgress, onError );
  19647. },
  19648. setTextures: function ( value ) {
  19649. this.textures = value;
  19650. },
  19651. parse: function ( json ) {
  19652. var textures = this.textures;
  19653. function getTexture( name ) {
  19654. if ( textures[ name ] === undefined ) {
  19655. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  19656. }
  19657. return textures[ name ];
  19658. }
  19659. var material = new Materials[ json.type ]();
  19660. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  19661. if ( json.name !== undefined ) material.name = json.name;
  19662. if ( json.color !== undefined ) material.color.setHex( json.color );
  19663. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  19664. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  19665. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  19666. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  19667. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  19668. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  19669. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  19670. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  19671. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  19672. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  19673. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  19674. if ( json.fog !== undefined ) material.fog = json.fog;
  19675. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  19676. if ( json.blending !== undefined ) material.blending = json.blending;
  19677. if ( json.side !== undefined ) material.side = json.side;
  19678. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  19679. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  19680. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  19681. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  19682. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  19683. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  19684. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  19685. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  19686. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  19687. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  19688. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  19689. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  19690. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  19691. if ( json.visible !== undefined ) material.visible = json.visible;
  19692. if ( json.userData !== undefined ) material.userData = json.userData;
  19693. // Deprecated
  19694. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  19695. // for PointsMaterial
  19696. if ( json.size !== undefined ) material.size = json.size;
  19697. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  19698. // maps
  19699. if ( json.map !== undefined ) material.map = getTexture( json.map );
  19700. if ( json.alphaMap !== undefined ) {
  19701. material.alphaMap = getTexture( json.alphaMap );
  19702. material.transparent = true;
  19703. }
  19704. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  19705. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  19706. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  19707. if ( json.normalScale !== undefined ) {
  19708. var normalScale = json.normalScale;
  19709. if ( Array.isArray( normalScale ) === false ) {
  19710. // Blender exporter used to export a scalar. See #7459
  19711. normalScale = [ normalScale, normalScale ];
  19712. }
  19713. material.normalScale = new Vector2().fromArray( normalScale );
  19714. }
  19715. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  19716. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  19717. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  19718. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  19719. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  19720. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  19721. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  19722. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  19723. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  19724. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  19725. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  19726. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  19727. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  19728. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  19729. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  19730. return material;
  19731. }
  19732. } );
  19733. /**
  19734. * @author mrdoob / http://mrdoob.com/
  19735. */
  19736. function BufferGeometryLoader( manager ) {
  19737. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19738. }
  19739. Object.assign( BufferGeometryLoader.prototype, {
  19740. load: function ( url, onLoad, onProgress, onError ) {
  19741. var scope = this;
  19742. var loader = new FileLoader( scope.manager );
  19743. loader.load( url, function ( text ) {
  19744. onLoad( scope.parse( JSON.parse( text ) ) );
  19745. }, onProgress, onError );
  19746. },
  19747. parse: function ( json ) {
  19748. var geometry = new BufferGeometry();
  19749. var index = json.data.index;
  19750. if ( index !== undefined ) {
  19751. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  19752. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  19753. }
  19754. var attributes = json.data.attributes;
  19755. for ( var key in attributes ) {
  19756. var attribute = attributes[ key ];
  19757. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  19758. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  19759. }
  19760. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  19761. if ( groups !== undefined ) {
  19762. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  19763. var group = groups[ i ];
  19764. geometry.addGroup( group.start, group.count, group.materialIndex );
  19765. }
  19766. }
  19767. var boundingSphere = json.data.boundingSphere;
  19768. if ( boundingSphere !== undefined ) {
  19769. var center = new Vector3();
  19770. if ( boundingSphere.center !== undefined ) {
  19771. center.fromArray( boundingSphere.center );
  19772. }
  19773. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  19774. }
  19775. return geometry;
  19776. }
  19777. } );
  19778. var TYPED_ARRAYS = {
  19779. Int8Array: Int8Array,
  19780. Uint8Array: Uint8Array,
  19781. // Workaround for IE11 pre KB2929437. See #11440
  19782. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  19783. Int16Array: Int16Array,
  19784. Uint16Array: Uint16Array,
  19785. Int32Array: Int32Array,
  19786. Uint32Array: Uint32Array,
  19787. Float32Array: Float32Array,
  19788. Float64Array: Float64Array
  19789. };
  19790. /**
  19791. * @author alteredq / http://alteredqualia.com/
  19792. */
  19793. function Loader() {
  19794. this.onLoadStart = function () {};
  19795. this.onLoadProgress = function () {};
  19796. this.onLoadComplete = function () {};
  19797. }
  19798. Loader.Handlers = {
  19799. handlers: [],
  19800. add: function ( regex, loader ) {
  19801. this.handlers.push( regex, loader );
  19802. },
  19803. get: function ( file ) {
  19804. var handlers = this.handlers;
  19805. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  19806. var regex = handlers[ i ];
  19807. var loader = handlers[ i + 1 ];
  19808. if ( regex.test( file ) ) {
  19809. return loader;
  19810. }
  19811. }
  19812. return null;
  19813. }
  19814. };
  19815. Object.assign( Loader.prototype, {
  19816. crossOrigin: undefined,
  19817. extractUrlBase: function ( url ) {
  19818. var parts = url.split( '/' );
  19819. if ( parts.length === 1 ) return './';
  19820. parts.pop();
  19821. return parts.join( '/' ) + '/';
  19822. },
  19823. initMaterials: function ( materials, texturePath, crossOrigin ) {
  19824. var array = [];
  19825. for ( var i = 0; i < materials.length; ++ i ) {
  19826. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  19827. }
  19828. return array;
  19829. },
  19830. createMaterial: ( function () {
  19831. var BlendingMode = {
  19832. NoBlending: NoBlending,
  19833. NormalBlending: NormalBlending,
  19834. AdditiveBlending: AdditiveBlending,
  19835. SubtractiveBlending: SubtractiveBlending,
  19836. MultiplyBlending: MultiplyBlending,
  19837. CustomBlending: CustomBlending
  19838. };
  19839. var color = new Color();
  19840. var textureLoader = new TextureLoader();
  19841. var materialLoader = new MaterialLoader();
  19842. return function createMaterial( m, texturePath, crossOrigin ) {
  19843. // convert from old material format
  19844. var textures = {};
  19845. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  19846. var fullPath = texturePath + path;
  19847. var loader = Loader.Handlers.get( fullPath );
  19848. var texture;
  19849. if ( loader !== null ) {
  19850. texture = loader.load( fullPath );
  19851. } else {
  19852. textureLoader.setCrossOrigin( crossOrigin );
  19853. texture = textureLoader.load( fullPath );
  19854. }
  19855. if ( repeat !== undefined ) {
  19856. texture.repeat.fromArray( repeat );
  19857. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  19858. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  19859. }
  19860. if ( offset !== undefined ) {
  19861. texture.offset.fromArray( offset );
  19862. }
  19863. if ( wrap !== undefined ) {
  19864. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  19865. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  19866. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  19867. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  19868. }
  19869. if ( anisotropy !== undefined ) {
  19870. texture.anisotropy = anisotropy;
  19871. }
  19872. var uuid = _Math.generateUUID();
  19873. textures[ uuid ] = texture;
  19874. return uuid;
  19875. }
  19876. //
  19877. var json = {
  19878. uuid: _Math.generateUUID(),
  19879. type: 'MeshLambertMaterial'
  19880. };
  19881. for ( var name in m ) {
  19882. var value = m[ name ];
  19883. switch ( name ) {
  19884. case 'DbgColor':
  19885. case 'DbgIndex':
  19886. case 'opticalDensity':
  19887. case 'illumination':
  19888. break;
  19889. case 'DbgName':
  19890. json.name = value;
  19891. break;
  19892. case 'blending':
  19893. json.blending = BlendingMode[ value ];
  19894. break;
  19895. case 'colorAmbient':
  19896. case 'mapAmbient':
  19897. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  19898. break;
  19899. case 'colorDiffuse':
  19900. json.color = color.fromArray( value ).getHex();
  19901. break;
  19902. case 'colorSpecular':
  19903. json.specular = color.fromArray( value ).getHex();
  19904. break;
  19905. case 'colorEmissive':
  19906. json.emissive = color.fromArray( value ).getHex();
  19907. break;
  19908. case 'specularCoef':
  19909. json.shininess = value;
  19910. break;
  19911. case 'shading':
  19912. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  19913. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  19914. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  19915. break;
  19916. case 'mapDiffuse':
  19917. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  19918. break;
  19919. case 'mapDiffuseRepeat':
  19920. case 'mapDiffuseOffset':
  19921. case 'mapDiffuseWrap':
  19922. case 'mapDiffuseAnisotropy':
  19923. break;
  19924. case 'mapEmissive':
  19925. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  19926. break;
  19927. case 'mapEmissiveRepeat':
  19928. case 'mapEmissiveOffset':
  19929. case 'mapEmissiveWrap':
  19930. case 'mapEmissiveAnisotropy':
  19931. break;
  19932. case 'mapLight':
  19933. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  19934. break;
  19935. case 'mapLightRepeat':
  19936. case 'mapLightOffset':
  19937. case 'mapLightWrap':
  19938. case 'mapLightAnisotropy':
  19939. break;
  19940. case 'mapAO':
  19941. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  19942. break;
  19943. case 'mapAORepeat':
  19944. case 'mapAOOffset':
  19945. case 'mapAOWrap':
  19946. case 'mapAOAnisotropy':
  19947. break;
  19948. case 'mapBump':
  19949. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  19950. break;
  19951. case 'mapBumpScale':
  19952. json.bumpScale = value;
  19953. break;
  19954. case 'mapBumpRepeat':
  19955. case 'mapBumpOffset':
  19956. case 'mapBumpWrap':
  19957. case 'mapBumpAnisotropy':
  19958. break;
  19959. case 'mapNormal':
  19960. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  19961. break;
  19962. case 'mapNormalFactor':
  19963. json.normalScale = [ value, value ];
  19964. break;
  19965. case 'mapNormalRepeat':
  19966. case 'mapNormalOffset':
  19967. case 'mapNormalWrap':
  19968. case 'mapNormalAnisotropy':
  19969. break;
  19970. case 'mapSpecular':
  19971. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  19972. break;
  19973. case 'mapSpecularRepeat':
  19974. case 'mapSpecularOffset':
  19975. case 'mapSpecularWrap':
  19976. case 'mapSpecularAnisotropy':
  19977. break;
  19978. case 'mapMetalness':
  19979. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  19980. break;
  19981. case 'mapMetalnessRepeat':
  19982. case 'mapMetalnessOffset':
  19983. case 'mapMetalnessWrap':
  19984. case 'mapMetalnessAnisotropy':
  19985. break;
  19986. case 'mapRoughness':
  19987. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  19988. break;
  19989. case 'mapRoughnessRepeat':
  19990. case 'mapRoughnessOffset':
  19991. case 'mapRoughnessWrap':
  19992. case 'mapRoughnessAnisotropy':
  19993. break;
  19994. case 'mapAlpha':
  19995. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  19996. break;
  19997. case 'mapAlphaRepeat':
  19998. case 'mapAlphaOffset':
  19999. case 'mapAlphaWrap':
  20000. case 'mapAlphaAnisotropy':
  20001. break;
  20002. case 'flipSided':
  20003. json.side = BackSide;
  20004. break;
  20005. case 'doubleSided':
  20006. json.side = DoubleSide;
  20007. break;
  20008. case 'transparency':
  20009. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  20010. json.opacity = value;
  20011. break;
  20012. case 'depthTest':
  20013. case 'depthWrite':
  20014. case 'colorWrite':
  20015. case 'opacity':
  20016. case 'reflectivity':
  20017. case 'transparent':
  20018. case 'visible':
  20019. case 'wireframe':
  20020. json[ name ] = value;
  20021. break;
  20022. case 'vertexColors':
  20023. if ( value === true ) json.vertexColors = VertexColors;
  20024. if ( value === 'face' ) json.vertexColors = FaceColors;
  20025. break;
  20026. default:
  20027. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  20028. break;
  20029. }
  20030. }
  20031. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  20032. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  20033. if ( json.opacity < 1 ) json.transparent = true;
  20034. materialLoader.setTextures( textures );
  20035. return materialLoader.parse( json );
  20036. };
  20037. } )()
  20038. } );
  20039. /**
  20040. * @author mrdoob / http://mrdoob.com/
  20041. * @author alteredq / http://alteredqualia.com/
  20042. */
  20043. function JSONLoader( manager ) {
  20044. if ( typeof manager === 'boolean' ) {
  20045. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  20046. manager = undefined;
  20047. }
  20048. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  20049. this.withCredentials = false;
  20050. }
  20051. Object.assign( JSONLoader.prototype, {
  20052. load: function ( url, onLoad, onProgress, onError ) {
  20053. var scope = this;
  20054. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  20055. var loader = new FileLoader( this.manager );
  20056. loader.setWithCredentials( this.withCredentials );
  20057. loader.load( url, function ( text ) {
  20058. var json = JSON.parse( text );
  20059. var metadata = json.metadata;
  20060. if ( metadata !== undefined ) {
  20061. var type = metadata.type;
  20062. if ( type !== undefined ) {
  20063. if ( type.toLowerCase() === 'object' ) {
  20064. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  20065. return;
  20066. }
  20067. if ( type.toLowerCase() === 'scene' ) {
  20068. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  20069. return;
  20070. }
  20071. }
  20072. }
  20073. var object = scope.parse( json, texturePath );
  20074. onLoad( object.geometry, object.materials );
  20075. }, onProgress, onError );
  20076. },
  20077. setTexturePath: function ( value ) {
  20078. this.texturePath = value;
  20079. },
  20080. parse: ( function () {
  20081. function parseModel( json, geometry ) {
  20082. function isBitSet( value, position ) {
  20083. return value & ( 1 << position );
  20084. }
  20085. var i, j, fi,
  20086. offset, zLength,
  20087. colorIndex, normalIndex, uvIndex, materialIndex,
  20088. type,
  20089. isQuad,
  20090. hasMaterial,
  20091. hasFaceVertexUv,
  20092. hasFaceNormal, hasFaceVertexNormal,
  20093. hasFaceColor, hasFaceVertexColor,
  20094. vertex, face, faceA, faceB, hex, normal,
  20095. uvLayer, uv, u, v,
  20096. faces = json.faces,
  20097. vertices = json.vertices,
  20098. normals = json.normals,
  20099. colors = json.colors,
  20100. scale = json.scale,
  20101. nUvLayers = 0;
  20102. if ( json.uvs !== undefined ) {
  20103. // disregard empty arrays
  20104. for ( i = 0; i < json.uvs.length; i ++ ) {
  20105. if ( json.uvs[ i ].length ) nUvLayers ++;
  20106. }
  20107. for ( i = 0; i < nUvLayers; i ++ ) {
  20108. geometry.faceVertexUvs[ i ] = [];
  20109. }
  20110. }
  20111. offset = 0;
  20112. zLength = vertices.length;
  20113. while ( offset < zLength ) {
  20114. vertex = new Vector3();
  20115. vertex.x = vertices[ offset ++ ] * scale;
  20116. vertex.y = vertices[ offset ++ ] * scale;
  20117. vertex.z = vertices[ offset ++ ] * scale;
  20118. geometry.vertices.push( vertex );
  20119. }
  20120. offset = 0;
  20121. zLength = faces.length;
  20122. while ( offset < zLength ) {
  20123. type = faces[ offset ++ ];
  20124. isQuad = isBitSet( type, 0 );
  20125. hasMaterial = isBitSet( type, 1 );
  20126. hasFaceVertexUv = isBitSet( type, 3 );
  20127. hasFaceNormal = isBitSet( type, 4 );
  20128. hasFaceVertexNormal = isBitSet( type, 5 );
  20129. hasFaceColor = isBitSet( type, 6 );
  20130. hasFaceVertexColor = isBitSet( type, 7 );
  20131. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  20132. if ( isQuad ) {
  20133. faceA = new Face3();
  20134. faceA.a = faces[ offset ];
  20135. faceA.b = faces[ offset + 1 ];
  20136. faceA.c = faces[ offset + 3 ];
  20137. faceB = new Face3();
  20138. faceB.a = faces[ offset + 1 ];
  20139. faceB.b = faces[ offset + 2 ];
  20140. faceB.c = faces[ offset + 3 ];
  20141. offset += 4;
  20142. if ( hasMaterial ) {
  20143. materialIndex = faces[ offset ++ ];
  20144. faceA.materialIndex = materialIndex;
  20145. faceB.materialIndex = materialIndex;
  20146. }
  20147. // to get face <=> uv index correspondence
  20148. fi = geometry.faces.length;
  20149. if ( hasFaceVertexUv ) {
  20150. for ( i = 0; i < nUvLayers; i ++ ) {
  20151. uvLayer = json.uvs[ i ];
  20152. geometry.faceVertexUvs[ i ][ fi ] = [];
  20153. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  20154. for ( j = 0; j < 4; j ++ ) {
  20155. uvIndex = faces[ offset ++ ];
  20156. u = uvLayer[ uvIndex * 2 ];
  20157. v = uvLayer[ uvIndex * 2 + 1 ];
  20158. uv = new Vector2( u, v );
  20159. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  20160. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  20161. }
  20162. }
  20163. }
  20164. if ( hasFaceNormal ) {
  20165. normalIndex = faces[ offset ++ ] * 3;
  20166. faceA.normal.set(
  20167. normals[ normalIndex ++ ],
  20168. normals[ normalIndex ++ ],
  20169. normals[ normalIndex ]
  20170. );
  20171. faceB.normal.copy( faceA.normal );
  20172. }
  20173. if ( hasFaceVertexNormal ) {
  20174. for ( i = 0; i < 4; i ++ ) {
  20175. normalIndex = faces[ offset ++ ] * 3;
  20176. normal = new Vector3(
  20177. normals[ normalIndex ++ ],
  20178. normals[ normalIndex ++ ],
  20179. normals[ normalIndex ]
  20180. );
  20181. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  20182. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  20183. }
  20184. }
  20185. if ( hasFaceColor ) {
  20186. colorIndex = faces[ offset ++ ];
  20187. hex = colors[ colorIndex ];
  20188. faceA.color.setHex( hex );
  20189. faceB.color.setHex( hex );
  20190. }
  20191. if ( hasFaceVertexColor ) {
  20192. for ( i = 0; i < 4; i ++ ) {
  20193. colorIndex = faces[ offset ++ ];
  20194. hex = colors[ colorIndex ];
  20195. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  20196. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  20197. }
  20198. }
  20199. geometry.faces.push( faceA );
  20200. geometry.faces.push( faceB );
  20201. } else {
  20202. face = new Face3();
  20203. face.a = faces[ offset ++ ];
  20204. face.b = faces[ offset ++ ];
  20205. face.c = faces[ offset ++ ];
  20206. if ( hasMaterial ) {
  20207. materialIndex = faces[ offset ++ ];
  20208. face.materialIndex = materialIndex;
  20209. }
  20210. // to get face <=> uv index correspondence
  20211. fi = geometry.faces.length;
  20212. if ( hasFaceVertexUv ) {
  20213. for ( i = 0; i < nUvLayers; i ++ ) {
  20214. uvLayer = json.uvs[ i ];
  20215. geometry.faceVertexUvs[ i ][ fi ] = [];
  20216. for ( j = 0; j < 3; j ++ ) {
  20217. uvIndex = faces[ offset ++ ];
  20218. u = uvLayer[ uvIndex * 2 ];
  20219. v = uvLayer[ uvIndex * 2 + 1 ];
  20220. uv = new Vector2( u, v );
  20221. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  20222. }
  20223. }
  20224. }
  20225. if ( hasFaceNormal ) {
  20226. normalIndex = faces[ offset ++ ] * 3;
  20227. face.normal.set(
  20228. normals[ normalIndex ++ ],
  20229. normals[ normalIndex ++ ],
  20230. normals[ normalIndex ]
  20231. );
  20232. }
  20233. if ( hasFaceVertexNormal ) {
  20234. for ( i = 0; i < 3; i ++ ) {
  20235. normalIndex = faces[ offset ++ ] * 3;
  20236. normal = new Vector3(
  20237. normals[ normalIndex ++ ],
  20238. normals[ normalIndex ++ ],
  20239. normals[ normalIndex ]
  20240. );
  20241. face.vertexNormals.push( normal );
  20242. }
  20243. }
  20244. if ( hasFaceColor ) {
  20245. colorIndex = faces[ offset ++ ];
  20246. face.color.setHex( colors[ colorIndex ] );
  20247. }
  20248. if ( hasFaceVertexColor ) {
  20249. for ( i = 0; i < 3; i ++ ) {
  20250. colorIndex = faces[ offset ++ ];
  20251. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  20252. }
  20253. }
  20254. geometry.faces.push( face );
  20255. }
  20256. }
  20257. }
  20258. function parseSkin( json, geometry ) {
  20259. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  20260. if ( json.skinWeights ) {
  20261. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  20262. var x = json.skinWeights[ i ];
  20263. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  20264. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  20265. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  20266. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  20267. }
  20268. }
  20269. if ( json.skinIndices ) {
  20270. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  20271. var a = json.skinIndices[ i ];
  20272. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  20273. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  20274. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  20275. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  20276. }
  20277. }
  20278. geometry.bones = json.bones;
  20279. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  20280. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  20281. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  20282. }
  20283. }
  20284. function parseMorphing( json, geometry ) {
  20285. var scale = json.scale;
  20286. if ( json.morphTargets !== undefined ) {
  20287. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  20288. geometry.morphTargets[ i ] = {};
  20289. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  20290. geometry.morphTargets[ i ].vertices = [];
  20291. var dstVertices = geometry.morphTargets[ i ].vertices;
  20292. var srcVertices = json.morphTargets[ i ].vertices;
  20293. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  20294. var vertex = new Vector3();
  20295. vertex.x = srcVertices[ v ] * scale;
  20296. vertex.y = srcVertices[ v + 1 ] * scale;
  20297. vertex.z = srcVertices[ v + 2 ] * scale;
  20298. dstVertices.push( vertex );
  20299. }
  20300. }
  20301. }
  20302. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  20303. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  20304. var faces = geometry.faces;
  20305. var morphColors = json.morphColors[ 0 ].colors;
  20306. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20307. faces[ i ].color.fromArray( morphColors, i * 3 );
  20308. }
  20309. }
  20310. }
  20311. function parseAnimations( json, geometry ) {
  20312. var outputAnimations = [];
  20313. // parse old style Bone/Hierarchy animations
  20314. var animations = [];
  20315. if ( json.animation !== undefined ) {
  20316. animations.push( json.animation );
  20317. }
  20318. if ( json.animations !== undefined ) {
  20319. if ( json.animations.length ) {
  20320. animations = animations.concat( json.animations );
  20321. } else {
  20322. animations.push( json.animations );
  20323. }
  20324. }
  20325. for ( var i = 0; i < animations.length; i ++ ) {
  20326. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  20327. if ( clip ) outputAnimations.push( clip );
  20328. }
  20329. // parse implicit morph animations
  20330. if ( geometry.morphTargets ) {
  20331. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  20332. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  20333. outputAnimations = outputAnimations.concat( morphAnimationClips );
  20334. }
  20335. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  20336. }
  20337. return function ( json, texturePath ) {
  20338. if ( json.data !== undefined ) {
  20339. // Geometry 4.0 spec
  20340. json = json.data;
  20341. }
  20342. if ( json.scale !== undefined ) {
  20343. json.scale = 1.0 / json.scale;
  20344. } else {
  20345. json.scale = 1.0;
  20346. }
  20347. var geometry = new Geometry();
  20348. parseModel( json, geometry );
  20349. parseSkin( json, geometry );
  20350. parseMorphing( json, geometry );
  20351. parseAnimations( json, geometry );
  20352. geometry.computeFaceNormals();
  20353. geometry.computeBoundingSphere();
  20354. if ( json.materials === undefined || json.materials.length === 0 ) {
  20355. return { geometry: geometry };
  20356. } else {
  20357. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  20358. return { geometry: geometry, materials: materials };
  20359. }
  20360. };
  20361. } )()
  20362. } );
  20363. /**
  20364. * @author mrdoob / http://mrdoob.com/
  20365. */
  20366. function ObjectLoader( manager ) {
  20367. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  20368. this.texturePath = '';
  20369. }
  20370. Object.assign( ObjectLoader.prototype, {
  20371. load: function ( url, onLoad, onProgress, onError ) {
  20372. if ( this.texturePath === '' ) {
  20373. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  20374. }
  20375. var scope = this;
  20376. var loader = new FileLoader( scope.manager );
  20377. loader.load( url, function ( text ) {
  20378. var json = null;
  20379. try {
  20380. json = JSON.parse( text );
  20381. } catch ( error ) {
  20382. if ( onError !== undefined ) onError( error );
  20383. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  20384. return;
  20385. }
  20386. var metadata = json.metadata;
  20387. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  20388. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  20389. return;
  20390. }
  20391. scope.parse( json, onLoad );
  20392. }, onProgress, onError );
  20393. },
  20394. setTexturePath: function ( value ) {
  20395. this.texturePath = value;
  20396. },
  20397. setCrossOrigin: function ( value ) {
  20398. this.crossOrigin = value;
  20399. },
  20400. parse: function ( json, onLoad ) {
  20401. var geometries = this.parseGeometries( json.geometries );
  20402. var images = this.parseImages( json.images, function () {
  20403. if ( onLoad !== undefined ) onLoad( object );
  20404. } );
  20405. var textures = this.parseTextures( json.textures, images );
  20406. var materials = this.parseMaterials( json.materials, textures );
  20407. var object = this.parseObject( json.object, geometries, materials );
  20408. if ( json.animations ) {
  20409. object.animations = this.parseAnimations( json.animations );
  20410. }
  20411. if ( json.images === undefined || json.images.length === 0 ) {
  20412. if ( onLoad !== undefined ) onLoad( object );
  20413. }
  20414. return object;
  20415. },
  20416. parseGeometries: function ( json ) {
  20417. var geometries = {};
  20418. if ( json !== undefined ) {
  20419. var geometryLoader = new JSONLoader();
  20420. var bufferGeometryLoader = new BufferGeometryLoader();
  20421. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20422. var geometry;
  20423. var data = json[ i ];
  20424. switch ( data.type ) {
  20425. case 'PlaneGeometry':
  20426. case 'PlaneBufferGeometry':
  20427. geometry = new Geometries[ data.type ](
  20428. data.width,
  20429. data.height,
  20430. data.widthSegments,
  20431. data.heightSegments
  20432. );
  20433. break;
  20434. case 'BoxGeometry':
  20435. case 'BoxBufferGeometry':
  20436. case 'CubeGeometry': // backwards compatible
  20437. geometry = new Geometries[ data.type ](
  20438. data.width,
  20439. data.height,
  20440. data.depth,
  20441. data.widthSegments,
  20442. data.heightSegments,
  20443. data.depthSegments
  20444. );
  20445. break;
  20446. case 'CircleGeometry':
  20447. case 'CircleBufferGeometry':
  20448. geometry = new Geometries[ data.type ](
  20449. data.radius,
  20450. data.segments,
  20451. data.thetaStart,
  20452. data.thetaLength
  20453. );
  20454. break;
  20455. case 'CylinderGeometry':
  20456. case 'CylinderBufferGeometry':
  20457. geometry = new Geometries[ data.type ](
  20458. data.radiusTop,
  20459. data.radiusBottom,
  20460. data.height,
  20461. data.radialSegments,
  20462. data.heightSegments,
  20463. data.openEnded,
  20464. data.thetaStart,
  20465. data.thetaLength
  20466. );
  20467. break;
  20468. case 'ConeGeometry':
  20469. case 'ConeBufferGeometry':
  20470. geometry = new Geometries[ data.type ](
  20471. data.radius,
  20472. data.height,
  20473. data.radialSegments,
  20474. data.heightSegments,
  20475. data.openEnded,
  20476. data.thetaStart,
  20477. data.thetaLength
  20478. );
  20479. break;
  20480. case 'SphereGeometry':
  20481. case 'SphereBufferGeometry':
  20482. geometry = new Geometries[ data.type ](
  20483. data.radius,
  20484. data.widthSegments,
  20485. data.heightSegments,
  20486. data.phiStart,
  20487. data.phiLength,
  20488. data.thetaStart,
  20489. data.thetaLength
  20490. );
  20491. break;
  20492. case 'DodecahedronGeometry':
  20493. case 'IcosahedronGeometry':
  20494. case 'OctahedronGeometry':
  20495. case 'TetrahedronGeometry':
  20496. geometry = new Geometries[ data.type ](
  20497. data.radius,
  20498. data.detail
  20499. );
  20500. break;
  20501. case 'RingGeometry':
  20502. case 'RingBufferGeometry':
  20503. geometry = new Geometries[ data.type ](
  20504. data.innerRadius,
  20505. data.outerRadius,
  20506. data.thetaSegments,
  20507. data.phiSegments,
  20508. data.thetaStart,
  20509. data.thetaLength
  20510. );
  20511. break;
  20512. case 'TorusGeometry':
  20513. case 'TorusBufferGeometry':
  20514. geometry = new Geometries[ data.type ](
  20515. data.radius,
  20516. data.tube,
  20517. data.radialSegments,
  20518. data.tubularSegments,
  20519. data.arc
  20520. );
  20521. break;
  20522. case 'TorusKnotGeometry':
  20523. case 'TorusKnotBufferGeometry':
  20524. geometry = new Geometries[ data.type ](
  20525. data.radius,
  20526. data.tube,
  20527. data.tubularSegments,
  20528. data.radialSegments,
  20529. data.p,
  20530. data.q
  20531. );
  20532. break;
  20533. case 'LatheGeometry':
  20534. case 'LatheBufferGeometry':
  20535. geometry = new Geometries[ data.type ](
  20536. data.points,
  20537. data.segments,
  20538. data.phiStart,
  20539. data.phiLength
  20540. );
  20541. break;
  20542. case 'BufferGeometry':
  20543. geometry = bufferGeometryLoader.parse( data );
  20544. break;
  20545. case 'Geometry':
  20546. geometry = geometryLoader.parse( data, this.texturePath ).geometry;
  20547. break;
  20548. default:
  20549. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  20550. continue;
  20551. }
  20552. geometry.uuid = data.uuid;
  20553. if ( data.name !== undefined ) geometry.name = data.name;
  20554. geometries[ data.uuid ] = geometry;
  20555. }
  20556. }
  20557. return geometries;
  20558. },
  20559. parseMaterials: function ( json, textures ) {
  20560. var materials = {};
  20561. if ( json !== undefined ) {
  20562. var loader = new MaterialLoader();
  20563. loader.setTextures( textures );
  20564. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20565. var data = json[ i ];
  20566. if ( data.type === 'MultiMaterial' ) {
  20567. // Deprecated
  20568. var array = [];
  20569. for ( var j = 0; j < data.materials.length; j ++ ) {
  20570. array.push( loader.parse( data.materials[ j ] ) );
  20571. }
  20572. materials[ data.uuid ] = array;
  20573. } else {
  20574. materials[ data.uuid ] = loader.parse( data );
  20575. }
  20576. }
  20577. }
  20578. return materials;
  20579. },
  20580. parseAnimations: function ( json ) {
  20581. var animations = [];
  20582. for ( var i = 0; i < json.length; i ++ ) {
  20583. var clip = AnimationClip.parse( json[ i ] );
  20584. animations.push( clip );
  20585. }
  20586. return animations;
  20587. },
  20588. parseImages: function ( json, onLoad ) {
  20589. var scope = this;
  20590. var images = {};
  20591. function loadImage( url ) {
  20592. scope.manager.itemStart( url );
  20593. return loader.load( url, function () {
  20594. scope.manager.itemEnd( url );
  20595. }, undefined, function () {
  20596. scope.manager.itemEnd( url );
  20597. scope.manager.itemError( url );
  20598. } );
  20599. }
  20600. if ( json !== undefined && json.length > 0 ) {
  20601. var manager = new LoadingManager( onLoad );
  20602. var loader = new ImageLoader( manager );
  20603. loader.setCrossOrigin( this.crossOrigin );
  20604. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20605. var image = json[ i ];
  20606. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  20607. images[ image.uuid ] = loadImage( path );
  20608. }
  20609. }
  20610. return images;
  20611. },
  20612. parseTextures: function ( json, images ) {
  20613. function parseConstant( value, type ) {
  20614. if ( typeof( value ) === 'number' ) return value;
  20615. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  20616. return type[ value ];
  20617. }
  20618. var textures = {};
  20619. if ( json !== undefined ) {
  20620. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20621. var data = json[ i ];
  20622. if ( data.image === undefined ) {
  20623. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  20624. }
  20625. if ( images[ data.image ] === undefined ) {
  20626. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  20627. }
  20628. var texture = new Texture( images[ data.image ] );
  20629. texture.needsUpdate = true;
  20630. texture.uuid = data.uuid;
  20631. if ( data.name !== undefined ) texture.name = data.name;
  20632. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  20633. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  20634. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  20635. if ( data.wrap !== undefined ) {
  20636. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  20637. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  20638. }
  20639. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  20640. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  20641. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  20642. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  20643. textures[ data.uuid ] = texture;
  20644. }
  20645. }
  20646. return textures;
  20647. },
  20648. parseObject: function () {
  20649. var matrix = new Matrix4();
  20650. return function parseObject( data, geometries, materials ) {
  20651. var object;
  20652. function getGeometry( name ) {
  20653. if ( geometries[ name ] === undefined ) {
  20654. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  20655. }
  20656. return geometries[ name ];
  20657. }
  20658. function getMaterial( name ) {
  20659. if ( name === undefined ) return undefined;
  20660. if ( Array.isArray( name ) ) {
  20661. var array = [];
  20662. for ( var i = 0, l = name.length; i < l; i ++ ) {
  20663. var uuid = name[ i ];
  20664. if ( materials[ uuid ] === undefined ) {
  20665. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  20666. }
  20667. array.push( materials[ uuid ] );
  20668. }
  20669. return array;
  20670. }
  20671. if ( materials[ name ] === undefined ) {
  20672. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  20673. }
  20674. return materials[ name ];
  20675. }
  20676. switch ( data.type ) {
  20677. case 'Scene':
  20678. object = new Scene();
  20679. if ( data.background !== undefined ) {
  20680. if ( Number.isInteger( data.background ) ) {
  20681. object.background = new Color( data.background );
  20682. }
  20683. }
  20684. if ( data.fog !== undefined ) {
  20685. if ( data.fog.type === 'Fog' ) {
  20686. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  20687. } else if ( data.fog.type === 'FogExp2' ) {
  20688. object.fog = new FogExp2( data.fog.color, data.fog.density );
  20689. }
  20690. }
  20691. break;
  20692. case 'PerspectiveCamera':
  20693. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  20694. if ( data.focus !== undefined ) object.focus = data.focus;
  20695. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  20696. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  20697. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  20698. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  20699. break;
  20700. case 'OrthographicCamera':
  20701. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  20702. break;
  20703. case 'AmbientLight':
  20704. object = new AmbientLight( data.color, data.intensity );
  20705. break;
  20706. case 'DirectionalLight':
  20707. object = new DirectionalLight( data.color, data.intensity );
  20708. break;
  20709. case 'PointLight':
  20710. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  20711. break;
  20712. case 'RectAreaLight':
  20713. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  20714. break;
  20715. case 'SpotLight':
  20716. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  20717. break;
  20718. case 'HemisphereLight':
  20719. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  20720. break;
  20721. case 'SkinnedMesh':
  20722. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  20723. case 'Mesh':
  20724. var geometry = getGeometry( data.geometry );
  20725. var material = getMaterial( data.material );
  20726. if ( geometry.bones && geometry.bones.length > 0 ) {
  20727. object = new SkinnedMesh( geometry, material );
  20728. } else {
  20729. object = new Mesh( geometry, material );
  20730. }
  20731. break;
  20732. case 'LOD':
  20733. object = new LOD();
  20734. break;
  20735. case 'Line':
  20736. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  20737. break;
  20738. case 'LineLoop':
  20739. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  20740. break;
  20741. case 'LineSegments':
  20742. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  20743. break;
  20744. case 'PointCloud':
  20745. case 'Points':
  20746. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  20747. break;
  20748. case 'Sprite':
  20749. object = new Sprite( getMaterial( data.material ) );
  20750. break;
  20751. case 'Group':
  20752. object = new Group();
  20753. break;
  20754. default:
  20755. object = new Object3D();
  20756. }
  20757. object.uuid = data.uuid;
  20758. if ( data.name !== undefined ) object.name = data.name;
  20759. if ( data.matrix !== undefined ) {
  20760. matrix.fromArray( data.matrix );
  20761. matrix.decompose( object.position, object.quaternion, object.scale );
  20762. } else {
  20763. if ( data.position !== undefined ) object.position.fromArray( data.position );
  20764. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  20765. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  20766. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  20767. }
  20768. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  20769. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  20770. if ( data.shadow ) {
  20771. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  20772. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  20773. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  20774. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  20775. }
  20776. if ( data.visible !== undefined ) object.visible = data.visible;
  20777. if ( data.userData !== undefined ) object.userData = data.userData;
  20778. if ( data.children !== undefined ) {
  20779. var children = data.children;
  20780. for ( var i = 0; i < children.length; i ++ ) {
  20781. object.add( this.parseObject( children[ i ], geometries, materials ) );
  20782. }
  20783. }
  20784. if ( data.type === 'LOD' ) {
  20785. var levels = data.levels;
  20786. for ( var l = 0; l < levels.length; l ++ ) {
  20787. var level = levels[ l ];
  20788. var child = object.getObjectByProperty( 'uuid', level.object );
  20789. if ( child !== undefined ) {
  20790. object.addLevel( child, level.distance );
  20791. }
  20792. }
  20793. }
  20794. return object;
  20795. };
  20796. }()
  20797. } );
  20798. var TEXTURE_MAPPING = {
  20799. UVMapping: UVMapping,
  20800. CubeReflectionMapping: CubeReflectionMapping,
  20801. CubeRefractionMapping: CubeRefractionMapping,
  20802. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  20803. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  20804. SphericalReflectionMapping: SphericalReflectionMapping,
  20805. CubeUVReflectionMapping: CubeUVReflectionMapping,
  20806. CubeUVRefractionMapping: CubeUVRefractionMapping
  20807. };
  20808. var TEXTURE_WRAPPING = {
  20809. RepeatWrapping: RepeatWrapping,
  20810. ClampToEdgeWrapping: ClampToEdgeWrapping,
  20811. MirroredRepeatWrapping: MirroredRepeatWrapping
  20812. };
  20813. var TEXTURE_FILTER = {
  20814. NearestFilter: NearestFilter,
  20815. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  20816. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  20817. LinearFilter: LinearFilter,
  20818. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  20819. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  20820. };
  20821. /**
  20822. * @author zz85 / http://www.lab4games.net/zz85/blog
  20823. *
  20824. * Bezier Curves formulas obtained from
  20825. * http://en.wikipedia.org/wiki/Bézier_curve
  20826. */
  20827. function CatmullRom( t, p0, p1, p2, p3 ) {
  20828. var v0 = ( p2 - p0 ) * 0.5;
  20829. var v1 = ( p3 - p1 ) * 0.5;
  20830. var t2 = t * t;
  20831. var t3 = t * t2;
  20832. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20833. }
  20834. //
  20835. function QuadraticBezierP0( t, p ) {
  20836. var k = 1 - t;
  20837. return k * k * p;
  20838. }
  20839. function QuadraticBezierP1( t, p ) {
  20840. return 2 * ( 1 - t ) * t * p;
  20841. }
  20842. function QuadraticBezierP2( t, p ) {
  20843. return t * t * p;
  20844. }
  20845. function QuadraticBezier( t, p0, p1, p2 ) {
  20846. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  20847. QuadraticBezierP2( t, p2 );
  20848. }
  20849. //
  20850. function CubicBezierP0( t, p ) {
  20851. var k = 1 - t;
  20852. return k * k * k * p;
  20853. }
  20854. function CubicBezierP1( t, p ) {
  20855. var k = 1 - t;
  20856. return 3 * k * k * t * p;
  20857. }
  20858. function CubicBezierP2( t, p ) {
  20859. return 3 * ( 1 - t ) * t * t * p;
  20860. }
  20861. function CubicBezierP3( t, p ) {
  20862. return t * t * t * p;
  20863. }
  20864. function CubicBezier( t, p0, p1, p2, p3 ) {
  20865. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  20866. CubicBezierP3( t, p3 );
  20867. }
  20868. /**
  20869. * @author zz85 / http://www.lab4games.net/zz85/blog
  20870. * Extensible curve object
  20871. *
  20872. * Some common of curve methods:
  20873. * .getPoint(t), getTangent(t)
  20874. * .getPointAt(u), getTangentAt(u)
  20875. * .getPoints(), .getSpacedPoints()
  20876. * .getLength()
  20877. * .updateArcLengths()
  20878. *
  20879. * This following curves inherit from THREE.Curve:
  20880. *
  20881. * -- 2D curves --
  20882. * THREE.ArcCurve
  20883. * THREE.CubicBezierCurve
  20884. * THREE.EllipseCurve
  20885. * THREE.LineCurve
  20886. * THREE.QuadraticBezierCurve
  20887. * THREE.SplineCurve
  20888. *
  20889. * -- 3D curves --
  20890. * THREE.CatmullRomCurve3
  20891. * THREE.CubicBezierCurve3
  20892. * THREE.LineCurve3
  20893. * THREE.QuadraticBezierCurve3
  20894. *
  20895. * A series of curves can be represented as a THREE.CurvePath.
  20896. *
  20897. **/
  20898. /**************************************************************
  20899. * Abstract Curve base class
  20900. **************************************************************/
  20901. function Curve() {
  20902. this.arcLengthDivisions = 200;
  20903. }
  20904. Object.assign( Curve.prototype, {
  20905. // Virtual base class method to overwrite and implement in subclasses
  20906. // - t [0 .. 1]
  20907. getPoint: function () {
  20908. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  20909. return null;
  20910. },
  20911. // Get point at relative position in curve according to arc length
  20912. // - u [0 .. 1]
  20913. getPointAt: function ( u ) {
  20914. var t = this.getUtoTmapping( u );
  20915. return this.getPoint( t );
  20916. },
  20917. // Get sequence of points using getPoint( t )
  20918. getPoints: function ( divisions ) {
  20919. if ( divisions === undefined ) divisions = 5;
  20920. var points = [];
  20921. for ( var d = 0; d <= divisions; d ++ ) {
  20922. points.push( this.getPoint( d / divisions ) );
  20923. }
  20924. return points;
  20925. },
  20926. // Get sequence of points using getPointAt( u )
  20927. getSpacedPoints: function ( divisions ) {
  20928. if ( divisions === undefined ) divisions = 5;
  20929. var points = [];
  20930. for ( var d = 0; d <= divisions; d ++ ) {
  20931. points.push( this.getPointAt( d / divisions ) );
  20932. }
  20933. return points;
  20934. },
  20935. // Get total curve arc length
  20936. getLength: function () {
  20937. var lengths = this.getLengths();
  20938. return lengths[ lengths.length - 1 ];
  20939. },
  20940. // Get list of cumulative segment lengths
  20941. getLengths: function ( divisions ) {
  20942. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  20943. if ( this.cacheArcLengths &&
  20944. ( this.cacheArcLengths.length === divisions + 1 ) &&
  20945. ! this.needsUpdate ) {
  20946. return this.cacheArcLengths;
  20947. }
  20948. this.needsUpdate = false;
  20949. var cache = [];
  20950. var current, last = this.getPoint( 0 );
  20951. var p, sum = 0;
  20952. cache.push( 0 );
  20953. for ( p = 1; p <= divisions; p ++ ) {
  20954. current = this.getPoint( p / divisions );
  20955. sum += current.distanceTo( last );
  20956. cache.push( sum );
  20957. last = current;
  20958. }
  20959. this.cacheArcLengths = cache;
  20960. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  20961. },
  20962. updateArcLengths: function () {
  20963. this.needsUpdate = true;
  20964. this.getLengths();
  20965. },
  20966. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20967. getUtoTmapping: function ( u, distance ) {
  20968. var arcLengths = this.getLengths();
  20969. var i = 0, il = arcLengths.length;
  20970. var targetArcLength; // The targeted u distance value to get
  20971. if ( distance ) {
  20972. targetArcLength = distance;
  20973. } else {
  20974. targetArcLength = u * arcLengths[ il - 1 ];
  20975. }
  20976. // binary search for the index with largest value smaller than target u distance
  20977. var low = 0, high = il - 1, comparison;
  20978. while ( low <= high ) {
  20979. 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
  20980. comparison = arcLengths[ i ] - targetArcLength;
  20981. if ( comparison < 0 ) {
  20982. low = i + 1;
  20983. } else if ( comparison > 0 ) {
  20984. high = i - 1;
  20985. } else {
  20986. high = i;
  20987. break;
  20988. // DONE
  20989. }
  20990. }
  20991. i = high;
  20992. if ( arcLengths[ i ] === targetArcLength ) {
  20993. return i / ( il - 1 );
  20994. }
  20995. // we could get finer grain at lengths, or use simple interpolation between two points
  20996. var lengthBefore = arcLengths[ i ];
  20997. var lengthAfter = arcLengths[ i + 1 ];
  20998. var segmentLength = lengthAfter - lengthBefore;
  20999. // determine where we are between the 'before' and 'after' points
  21000. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  21001. // add that fractional amount to t
  21002. var t = ( i + segmentFraction ) / ( il - 1 );
  21003. return t;
  21004. },
  21005. // Returns a unit vector tangent at t
  21006. // In case any sub curve does not implement its tangent derivation,
  21007. // 2 points a small delta apart will be used to find its gradient
  21008. // which seems to give a reasonable approximation
  21009. getTangent: function ( t ) {
  21010. var delta = 0.0001;
  21011. var t1 = t - delta;
  21012. var t2 = t + delta;
  21013. // Capping in case of danger
  21014. if ( t1 < 0 ) t1 = 0;
  21015. if ( t2 > 1 ) t2 = 1;
  21016. var pt1 = this.getPoint( t1 );
  21017. var pt2 = this.getPoint( t2 );
  21018. var vec = pt2.clone().sub( pt1 );
  21019. return vec.normalize();
  21020. },
  21021. getTangentAt: function ( u ) {
  21022. var t = this.getUtoTmapping( u );
  21023. return this.getTangent( t );
  21024. },
  21025. computeFrenetFrames: function ( segments, closed ) {
  21026. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  21027. var normal = new Vector3();
  21028. var tangents = [];
  21029. var normals = [];
  21030. var binormals = [];
  21031. var vec = new Vector3();
  21032. var mat = new Matrix4();
  21033. var i, u, theta;
  21034. // compute the tangent vectors for each segment on the curve
  21035. for ( i = 0; i <= segments; i ++ ) {
  21036. u = i / segments;
  21037. tangents[ i ] = this.getTangentAt( u );
  21038. tangents[ i ].normalize();
  21039. }
  21040. // select an initial normal vector perpendicular to the first tangent vector,
  21041. // and in the direction of the minimum tangent xyz component
  21042. normals[ 0 ] = new Vector3();
  21043. binormals[ 0 ] = new Vector3();
  21044. var min = Number.MAX_VALUE;
  21045. var tx = Math.abs( tangents[ 0 ].x );
  21046. var ty = Math.abs( tangents[ 0 ].y );
  21047. var tz = Math.abs( tangents[ 0 ].z );
  21048. if ( tx <= min ) {
  21049. min = tx;
  21050. normal.set( 1, 0, 0 );
  21051. }
  21052. if ( ty <= min ) {
  21053. min = ty;
  21054. normal.set( 0, 1, 0 );
  21055. }
  21056. if ( tz <= min ) {
  21057. normal.set( 0, 0, 1 );
  21058. }
  21059. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  21060. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  21061. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  21062. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  21063. for ( i = 1; i <= segments; i ++ ) {
  21064. normals[ i ] = normals[ i - 1 ].clone();
  21065. binormals[ i ] = binormals[ i - 1 ].clone();
  21066. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  21067. if ( vec.length() > Number.EPSILON ) {
  21068. vec.normalize();
  21069. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  21070. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  21071. }
  21072. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21073. }
  21074. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  21075. if ( closed === true ) {
  21076. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  21077. theta /= segments;
  21078. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  21079. theta = - theta;
  21080. }
  21081. for ( i = 1; i <= segments; i ++ ) {
  21082. // twist a little...
  21083. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  21084. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21085. }
  21086. }
  21087. return {
  21088. tangents: tangents,
  21089. normals: normals,
  21090. binormals: binormals
  21091. };
  21092. }
  21093. } );
  21094. function LineCurve( v1, v2 ) {
  21095. Curve.call( this );
  21096. this.v1 = v1;
  21097. this.v2 = v2;
  21098. }
  21099. LineCurve.prototype = Object.create( Curve.prototype );
  21100. LineCurve.prototype.constructor = LineCurve;
  21101. LineCurve.prototype.isLineCurve = true;
  21102. LineCurve.prototype.getPoint = function ( t ) {
  21103. if ( t === 1 ) {
  21104. return this.v2.clone();
  21105. }
  21106. var point = this.v2.clone().sub( this.v1 );
  21107. point.multiplyScalar( t ).add( this.v1 );
  21108. return point;
  21109. };
  21110. // Line curve is linear, so we can overwrite default getPointAt
  21111. LineCurve.prototype.getPointAt = function ( u ) {
  21112. return this.getPoint( u );
  21113. };
  21114. LineCurve.prototype.getTangent = function ( t ) {
  21115. var tangent = this.v2.clone().sub( this.v1 );
  21116. return tangent.normalize();
  21117. };
  21118. /**
  21119. * @author zz85 / http://www.lab4games.net/zz85/blog
  21120. *
  21121. **/
  21122. /**************************************************************
  21123. * Curved Path - a curve path is simply a array of connected
  21124. * curves, but retains the api of a curve
  21125. **************************************************************/
  21126. function CurvePath() {
  21127. Curve.call( this );
  21128. this.curves = [];
  21129. this.autoClose = false; // Automatically closes the path
  21130. }
  21131. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  21132. constructor: CurvePath,
  21133. add: function ( curve ) {
  21134. this.curves.push( curve );
  21135. },
  21136. closePath: function () {
  21137. // Add a line curve if start and end of lines are not connected
  21138. var startPoint = this.curves[ 0 ].getPoint( 0 );
  21139. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  21140. if ( ! startPoint.equals( endPoint ) ) {
  21141. this.curves.push( new LineCurve( endPoint, startPoint ) );
  21142. }
  21143. },
  21144. // To get accurate point with reference to
  21145. // entire path distance at time t,
  21146. // following has to be done:
  21147. // 1. Length of each sub path have to be known
  21148. // 2. Locate and identify type of curve
  21149. // 3. Get t for the curve
  21150. // 4. Return curve.getPointAt(t')
  21151. getPoint: function ( t ) {
  21152. var d = t * this.getLength();
  21153. var curveLengths = this.getCurveLengths();
  21154. var i = 0;
  21155. // To think about boundaries points.
  21156. while ( i < curveLengths.length ) {
  21157. if ( curveLengths[ i ] >= d ) {
  21158. var diff = curveLengths[ i ] - d;
  21159. var curve = this.curves[ i ];
  21160. var segmentLength = curve.getLength();
  21161. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21162. return curve.getPointAt( u );
  21163. }
  21164. i ++;
  21165. }
  21166. return null;
  21167. // loop where sum != 0, sum > d , sum+1 <d
  21168. },
  21169. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21170. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21171. // getPoint() depends on getLength
  21172. getLength: function () {
  21173. var lens = this.getCurveLengths();
  21174. return lens[ lens.length - 1 ];
  21175. },
  21176. // cacheLengths must be recalculated.
  21177. updateArcLengths: function () {
  21178. this.needsUpdate = true;
  21179. this.cacheLengths = null;
  21180. this.getCurveLengths();
  21181. },
  21182. // Compute lengths and cache them
  21183. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21184. getCurveLengths: function () {
  21185. // We use cache values if curves and cache array are same length
  21186. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  21187. return this.cacheLengths;
  21188. }
  21189. // Get length of sub-curve
  21190. // Push sums into cached array
  21191. var lengths = [], sums = 0;
  21192. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  21193. sums += this.curves[ i ].getLength();
  21194. lengths.push( sums );
  21195. }
  21196. this.cacheLengths = lengths;
  21197. return lengths;
  21198. },
  21199. getSpacedPoints: function ( divisions ) {
  21200. if ( divisions === undefined ) divisions = 40;
  21201. var points = [];
  21202. for ( var i = 0; i <= divisions; i ++ ) {
  21203. points.push( this.getPoint( i / divisions ) );
  21204. }
  21205. if ( this.autoClose ) {
  21206. points.push( points[ 0 ] );
  21207. }
  21208. return points;
  21209. },
  21210. getPoints: function ( divisions ) {
  21211. divisions = divisions || 12;
  21212. var points = [], last;
  21213. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  21214. var curve = curves[ i ];
  21215. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  21216. : (curve && curve.isLineCurve) ? 1
  21217. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  21218. : divisions;
  21219. var pts = curve.getPoints( resolution );
  21220. for ( var j = 0; j < pts.length; j++ ) {
  21221. var point = pts[ j ];
  21222. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  21223. points.push( point );
  21224. last = point;
  21225. }
  21226. }
  21227. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  21228. points.push( points[ 0 ] );
  21229. }
  21230. return points;
  21231. },
  21232. /**************************************************************
  21233. * Create Geometries Helpers
  21234. **************************************************************/
  21235. /// Generate geometry from path points (for Line or Points objects)
  21236. createPointsGeometry: function ( divisions ) {
  21237. var pts = this.getPoints( divisions );
  21238. return this.createGeometry( pts );
  21239. },
  21240. // Generate geometry from equidistant sampling along the path
  21241. createSpacedPointsGeometry: function ( divisions ) {
  21242. var pts = this.getSpacedPoints( divisions );
  21243. return this.createGeometry( pts );
  21244. },
  21245. createGeometry: function ( points ) {
  21246. var geometry = new Geometry();
  21247. for ( var i = 0, l = points.length; i < l; i ++ ) {
  21248. var point = points[ i ];
  21249. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  21250. }
  21251. return geometry;
  21252. }
  21253. } );
  21254. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21255. Curve.call( this );
  21256. this.aX = aX;
  21257. this.aY = aY;
  21258. this.xRadius = xRadius;
  21259. this.yRadius = yRadius;
  21260. this.aStartAngle = aStartAngle;
  21261. this.aEndAngle = aEndAngle;
  21262. this.aClockwise = aClockwise;
  21263. this.aRotation = aRotation || 0;
  21264. }
  21265. EllipseCurve.prototype = Object.create( Curve.prototype );
  21266. EllipseCurve.prototype.constructor = EllipseCurve;
  21267. EllipseCurve.prototype.isEllipseCurve = true;
  21268. EllipseCurve.prototype.getPoint = function ( t ) {
  21269. var twoPi = Math.PI * 2;
  21270. var deltaAngle = this.aEndAngle - this.aStartAngle;
  21271. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  21272. // ensures that deltaAngle is 0 .. 2 PI
  21273. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  21274. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  21275. if ( deltaAngle < Number.EPSILON ) {
  21276. if ( samePoints ) {
  21277. deltaAngle = 0;
  21278. } else {
  21279. deltaAngle = twoPi;
  21280. }
  21281. }
  21282. if ( this.aClockwise === true && ! samePoints ) {
  21283. if ( deltaAngle === twoPi ) {
  21284. deltaAngle = - twoPi;
  21285. } else {
  21286. deltaAngle = deltaAngle - twoPi;
  21287. }
  21288. }
  21289. var angle = this.aStartAngle + t * deltaAngle;
  21290. var x = this.aX + this.xRadius * Math.cos( angle );
  21291. var y = this.aY + this.yRadius * Math.sin( angle );
  21292. if ( this.aRotation !== 0 ) {
  21293. var cos = Math.cos( this.aRotation );
  21294. var sin = Math.sin( this.aRotation );
  21295. var tx = x - this.aX;
  21296. var ty = y - this.aY;
  21297. // Rotate the point about the center of the ellipse.
  21298. x = tx * cos - ty * sin + this.aX;
  21299. y = tx * sin + ty * cos + this.aY;
  21300. }
  21301. return new Vector2( x, y );
  21302. };
  21303. function SplineCurve( points /* array of Vector2 */ ) {
  21304. Curve.call( this );
  21305. this.points = ( points === undefined ) ? [] : points;
  21306. }
  21307. SplineCurve.prototype = Object.create( Curve.prototype );
  21308. SplineCurve.prototype.constructor = SplineCurve;
  21309. SplineCurve.prototype.isSplineCurve = true;
  21310. SplineCurve.prototype.getPoint = function ( t ) {
  21311. var points = this.points;
  21312. var point = ( points.length - 1 ) * t;
  21313. var intPoint = Math.floor( point );
  21314. var weight = point - intPoint;
  21315. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  21316. var point1 = points[ intPoint ];
  21317. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21318. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21319. return new Vector2(
  21320. CatmullRom( weight, point0.x, point1.x, point2.x, point3.x ),
  21321. CatmullRom( weight, point0.y, point1.y, point2.y, point3.y )
  21322. );
  21323. };
  21324. function CubicBezierCurve( v0, v1, v2, v3 ) {
  21325. Curve.call( this );
  21326. this.v0 = v0;
  21327. this.v1 = v1;
  21328. this.v2 = v2;
  21329. this.v3 = v3;
  21330. }
  21331. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  21332. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  21333. CubicBezierCurve.prototype.getPoint = function ( t ) {
  21334. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21335. return new Vector2(
  21336. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21337. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  21338. );
  21339. };
  21340. function QuadraticBezierCurve( v0, v1, v2 ) {
  21341. Curve.call( this );
  21342. this.v0 = v0;
  21343. this.v1 = v1;
  21344. this.v2 = v2;
  21345. }
  21346. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  21347. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  21348. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  21349. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21350. return new Vector2(
  21351. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21352. QuadraticBezier( t, v0.y, v1.y, v2.y )
  21353. );
  21354. };
  21355. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  21356. fromPoints: function ( vectors ) {
  21357. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  21358. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  21359. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  21360. }
  21361. },
  21362. moveTo: function ( x, y ) {
  21363. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  21364. },
  21365. lineTo: function ( x, y ) {
  21366. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  21367. this.curves.push( curve );
  21368. this.currentPoint.set( x, y );
  21369. },
  21370. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  21371. var curve = new QuadraticBezierCurve(
  21372. this.currentPoint.clone(),
  21373. new Vector2( aCPx, aCPy ),
  21374. new Vector2( aX, aY )
  21375. );
  21376. this.curves.push( curve );
  21377. this.currentPoint.set( aX, aY );
  21378. },
  21379. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21380. var curve = new CubicBezierCurve(
  21381. this.currentPoint.clone(),
  21382. new Vector2( aCP1x, aCP1y ),
  21383. new Vector2( aCP2x, aCP2y ),
  21384. new Vector2( aX, aY )
  21385. );
  21386. this.curves.push( curve );
  21387. this.currentPoint.set( aX, aY );
  21388. },
  21389. splineThru: function ( pts /*Array of Vector*/ ) {
  21390. var npts = [ this.currentPoint.clone() ].concat( pts );
  21391. var curve = new SplineCurve( npts );
  21392. this.curves.push( curve );
  21393. this.currentPoint.copy( pts[ pts.length - 1 ] );
  21394. },
  21395. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21396. var x0 = this.currentPoint.x;
  21397. var y0 = this.currentPoint.y;
  21398. this.absarc( aX + x0, aY + y0, aRadius,
  21399. aStartAngle, aEndAngle, aClockwise );
  21400. },
  21401. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21402. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21403. },
  21404. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21405. var x0 = this.currentPoint.x;
  21406. var y0 = this.currentPoint.y;
  21407. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21408. },
  21409. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21410. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21411. if ( this.curves.length > 0 ) {
  21412. // if a previous curve is present, attempt to join
  21413. var firstPoint = curve.getPoint( 0 );
  21414. if ( ! firstPoint.equals( this.currentPoint ) ) {
  21415. this.lineTo( firstPoint.x, firstPoint.y );
  21416. }
  21417. }
  21418. this.curves.push( curve );
  21419. var lastPoint = curve.getPoint( 1 );
  21420. this.currentPoint.copy( lastPoint );
  21421. }
  21422. } );
  21423. /**
  21424. * @author zz85 / http://www.lab4games.net/zz85/blog
  21425. * Creates free form 2d path using series of points, lines or curves.
  21426. **/
  21427. function Path( points ) {
  21428. CurvePath.call( this );
  21429. this.currentPoint = new Vector2();
  21430. if ( points ) {
  21431. this.fromPoints( points );
  21432. }
  21433. }
  21434. Path.prototype = PathPrototype;
  21435. PathPrototype.constructor = Path;
  21436. /**
  21437. * @author zz85 / http://www.lab4games.net/zz85/blog
  21438. * Defines a 2d shape plane using paths.
  21439. **/
  21440. // STEP 1 Create a path.
  21441. // STEP 2 Turn path into shape.
  21442. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  21443. // STEP 3a - Extract points from each shape, turn to vertices
  21444. // STEP 3b - Triangulate each shape, add faces.
  21445. function Shape() {
  21446. Path.apply( this, arguments );
  21447. this.holes = [];
  21448. }
  21449. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  21450. constructor: Shape,
  21451. getPointsHoles: function ( divisions ) {
  21452. var holesPts = [];
  21453. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  21454. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  21455. }
  21456. return holesPts;
  21457. },
  21458. // Get points of shape and holes (keypoints based on segments parameter)
  21459. extractAllPoints: function ( divisions ) {
  21460. return {
  21461. shape: this.getPoints( divisions ),
  21462. holes: this.getPointsHoles( divisions )
  21463. };
  21464. },
  21465. extractPoints: function ( divisions ) {
  21466. return this.extractAllPoints( divisions );
  21467. }
  21468. } );
  21469. /**
  21470. * @author zz85 / http://www.lab4games.net/zz85/blog
  21471. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  21472. **/
  21473. function ShapePath() {
  21474. this.subPaths = [];
  21475. this.currentPath = null;
  21476. }
  21477. Object.assign( ShapePath.prototype, {
  21478. moveTo: function ( x, y ) {
  21479. this.currentPath = new Path();
  21480. this.subPaths.push( this.currentPath );
  21481. this.currentPath.moveTo( x, y );
  21482. },
  21483. lineTo: function ( x, y ) {
  21484. this.currentPath.lineTo( x, y );
  21485. },
  21486. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  21487. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21488. },
  21489. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21490. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21491. },
  21492. splineThru: function ( pts ) {
  21493. this.currentPath.splineThru( pts );
  21494. },
  21495. toShapes: function ( isCCW, noHoles ) {
  21496. function toShapesNoHoles( inSubpaths ) {
  21497. var shapes = [];
  21498. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21499. var tmpPath = inSubpaths[ i ];
  21500. var tmpShape = new Shape();
  21501. tmpShape.curves = tmpPath.curves;
  21502. shapes.push( tmpShape );
  21503. }
  21504. return shapes;
  21505. }
  21506. function isPointInsidePolygon( inPt, inPolygon ) {
  21507. var polyLen = inPolygon.length;
  21508. // inPt on polygon contour => immediate success or
  21509. // toggling of inside/outside at every single! intersection point of an edge
  21510. // with the horizontal line through inPt, left of inPt
  21511. // not counting lowerY endpoints of edges and whole edges on that line
  21512. var inside = false;
  21513. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21514. var edgeLowPt = inPolygon[ p ];
  21515. var edgeHighPt = inPolygon[ q ];
  21516. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  21517. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  21518. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21519. // not parallel
  21520. if ( edgeDy < 0 ) {
  21521. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21522. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21523. }
  21524. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21525. if ( inPt.y === edgeLowPt.y ) {
  21526. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21527. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21528. } else {
  21529. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21530. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21531. if ( perpEdge < 0 ) continue;
  21532. inside = ! inside; // true intersection left of inPt
  21533. }
  21534. } else {
  21535. // parallel or collinear
  21536. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21537. // edge lies on the same horizontal line as inPt
  21538. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21539. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21540. // continue;
  21541. }
  21542. }
  21543. return inside;
  21544. }
  21545. var isClockWise = ShapeUtils.isClockWise;
  21546. var subPaths = this.subPaths;
  21547. if ( subPaths.length === 0 ) return [];
  21548. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  21549. var solid, tmpPath, tmpShape, shapes = [];
  21550. if ( subPaths.length === 1 ) {
  21551. tmpPath = subPaths[ 0 ];
  21552. tmpShape = new Shape();
  21553. tmpShape.curves = tmpPath.curves;
  21554. shapes.push( tmpShape );
  21555. return shapes;
  21556. }
  21557. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21558. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21559. // console.log("Holes first", holesFirst);
  21560. var betterShapeHoles = [];
  21561. var newShapes = [];
  21562. var newShapeHoles = [];
  21563. var mainIdx = 0;
  21564. var tmpPoints;
  21565. newShapes[ mainIdx ] = undefined;
  21566. newShapeHoles[ mainIdx ] = [];
  21567. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  21568. tmpPath = subPaths[ i ];
  21569. tmpPoints = tmpPath.getPoints();
  21570. solid = isClockWise( tmpPoints );
  21571. solid = isCCW ? ! solid : solid;
  21572. if ( solid ) {
  21573. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21574. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21575. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21576. if ( holesFirst ) mainIdx ++;
  21577. newShapeHoles[ mainIdx ] = [];
  21578. //console.log('cw', i);
  21579. } else {
  21580. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21581. //console.log('ccw', i);
  21582. }
  21583. }
  21584. // only Holes? -> probably all Shapes with wrong orientation
  21585. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21586. if ( newShapes.length > 1 ) {
  21587. var ambiguous = false;
  21588. var toChange = [];
  21589. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21590. betterShapeHoles[ sIdx ] = [];
  21591. }
  21592. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21593. var sho = newShapeHoles[ sIdx ];
  21594. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21595. var ho = sho[ hIdx ];
  21596. var hole_unassigned = true;
  21597. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21598. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21599. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  21600. if ( hole_unassigned ) {
  21601. hole_unassigned = false;
  21602. betterShapeHoles[ s2Idx ].push( ho );
  21603. } else {
  21604. ambiguous = true;
  21605. }
  21606. }
  21607. }
  21608. if ( hole_unassigned ) {
  21609. betterShapeHoles[ sIdx ].push( ho );
  21610. }
  21611. }
  21612. }
  21613. // console.log("ambiguous: ", ambiguous);
  21614. if ( toChange.length > 0 ) {
  21615. // console.log("to change: ", toChange);
  21616. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  21617. }
  21618. }
  21619. var tmpHoles;
  21620. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  21621. tmpShape = newShapes[ i ].s;
  21622. shapes.push( tmpShape );
  21623. tmpHoles = newShapeHoles[ i ];
  21624. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21625. tmpShape.holes.push( tmpHoles[ j ].h );
  21626. }
  21627. }
  21628. //console.log("shape", shapes);
  21629. return shapes;
  21630. }
  21631. } );
  21632. /**
  21633. * @author zz85 / http://www.lab4games.net/zz85/blog
  21634. * @author mrdoob / http://mrdoob.com/
  21635. */
  21636. function Font( data ) {
  21637. this.data = data;
  21638. }
  21639. Object.assign( Font.prototype, {
  21640. isFont: true,
  21641. generateShapes: function ( text, size, divisions ) {
  21642. function createPaths( text ) {
  21643. var chars = String( text ).split( '' );
  21644. var scale = size / data.resolution;
  21645. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  21646. var offsetX = 0, offsetY = 0;
  21647. var paths = [];
  21648. for ( var i = 0; i < chars.length; i ++ ) {
  21649. var char = chars[ i ];
  21650. if ( char === '\n' ) {
  21651. offsetX = 0;
  21652. offsetY -= line_height;
  21653. } else {
  21654. var ret = createPath( char, scale, offsetX, offsetY );
  21655. offsetX += ret.offsetX;
  21656. paths.push( ret.path );
  21657. }
  21658. }
  21659. return paths;
  21660. }
  21661. function createPath( c, scale, offsetX, offsetY ) {
  21662. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  21663. if ( ! glyph ) return;
  21664. var path = new ShapePath();
  21665. var pts = [];
  21666. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  21667. if ( glyph.o ) {
  21668. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  21669. for ( var i = 0, l = outline.length; i < l; ) {
  21670. var action = outline[ i ++ ];
  21671. switch ( action ) {
  21672. case 'm': // moveTo
  21673. x = outline[ i ++ ] * scale + offsetX;
  21674. y = outline[ i ++ ] * scale + offsetY;
  21675. path.moveTo( x, y );
  21676. break;
  21677. case 'l': // lineTo
  21678. x = outline[ i ++ ] * scale + offsetX;
  21679. y = outline[ i ++ ] * scale + offsetY;
  21680. path.lineTo( x, y );
  21681. break;
  21682. case 'q': // quadraticCurveTo
  21683. cpx = outline[ i ++ ] * scale + offsetX;
  21684. cpy = outline[ i ++ ] * scale + offsetY;
  21685. cpx1 = outline[ i ++ ] * scale + offsetX;
  21686. cpy1 = outline[ i ++ ] * scale + offsetY;
  21687. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  21688. laste = pts[ pts.length - 1 ];
  21689. if ( laste ) {
  21690. cpx0 = laste.x;
  21691. cpy0 = laste.y;
  21692. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21693. var t = i2 / divisions;
  21694. QuadraticBezier( t, cpx0, cpx1, cpx );
  21695. QuadraticBezier( t, cpy0, cpy1, cpy );
  21696. }
  21697. }
  21698. break;
  21699. case 'b': // bezierCurveTo
  21700. cpx = outline[ i ++ ] * scale + offsetX;
  21701. cpy = outline[ i ++ ] * scale + offsetY;
  21702. cpx1 = outline[ i ++ ] * scale + offsetX;
  21703. cpy1 = outline[ i ++ ] * scale + offsetY;
  21704. cpx2 = outline[ i ++ ] * scale + offsetX;
  21705. cpy2 = outline[ i ++ ] * scale + offsetY;
  21706. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  21707. laste = pts[ pts.length - 1 ];
  21708. if ( laste ) {
  21709. cpx0 = laste.x;
  21710. cpy0 = laste.y;
  21711. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21712. var t = i2 / divisions;
  21713. CubicBezier( t, cpx0, cpx1, cpx2, cpx );
  21714. CubicBezier( t, cpy0, cpy1, cpy2, cpy );
  21715. }
  21716. }
  21717. break;
  21718. }
  21719. }
  21720. }
  21721. return { offsetX: glyph.ha * scale, path: path };
  21722. }
  21723. //
  21724. if ( size === undefined ) size = 100;
  21725. if ( divisions === undefined ) divisions = 4;
  21726. var data = this.data;
  21727. var paths = createPaths( text );
  21728. var shapes = [];
  21729. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  21730. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  21731. }
  21732. return shapes;
  21733. }
  21734. } );
  21735. /**
  21736. * @author mrdoob / http://mrdoob.com/
  21737. */
  21738. function FontLoader( manager ) {
  21739. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21740. }
  21741. Object.assign( FontLoader.prototype, {
  21742. load: function ( url, onLoad, onProgress, onError ) {
  21743. var scope = this;
  21744. var loader = new FileLoader( this.manager );
  21745. loader.load( url, function ( text ) {
  21746. var json;
  21747. try {
  21748. json = JSON.parse( text );
  21749. } catch ( e ) {
  21750. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  21751. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  21752. }
  21753. var font = scope.parse( json );
  21754. if ( onLoad ) onLoad( font );
  21755. }, onProgress, onError );
  21756. },
  21757. parse: function ( json ) {
  21758. return new Font( json );
  21759. }
  21760. } );
  21761. var context;
  21762. var AudioContext = {
  21763. getContext: function () {
  21764. if ( context === undefined ) {
  21765. context = new ( window.AudioContext || window.webkitAudioContext )();
  21766. }
  21767. return context;
  21768. },
  21769. setContext: function ( value ) {
  21770. context = value;
  21771. }
  21772. };
  21773. /**
  21774. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21775. */
  21776. function AudioLoader( manager ) {
  21777. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21778. }
  21779. Object.assign( AudioLoader.prototype, {
  21780. load: function ( url, onLoad, onProgress, onError ) {
  21781. var loader = new FileLoader( this.manager );
  21782. loader.setResponseType( 'arraybuffer' );
  21783. loader.load( url, function ( buffer ) {
  21784. var context = AudioContext.getContext();
  21785. context.decodeAudioData( buffer, function ( audioBuffer ) {
  21786. onLoad( audioBuffer );
  21787. } );
  21788. }, onProgress, onError );
  21789. }
  21790. } );
  21791. /**
  21792. * @author mrdoob / http://mrdoob.com/
  21793. */
  21794. function StereoCamera() {
  21795. this.type = 'StereoCamera';
  21796. this.aspect = 1;
  21797. this.eyeSep = 0.064;
  21798. this.cameraL = new PerspectiveCamera();
  21799. this.cameraL.layers.enable( 1 );
  21800. this.cameraL.matrixAutoUpdate = false;
  21801. this.cameraR = new PerspectiveCamera();
  21802. this.cameraR.layers.enable( 2 );
  21803. this.cameraR.matrixAutoUpdate = false;
  21804. }
  21805. Object.assign( StereoCamera.prototype, {
  21806. update: ( function () {
  21807. var instance, focus, fov, aspect, near, far, zoom, eyeSep;
  21808. var eyeRight = new Matrix4();
  21809. var eyeLeft = new Matrix4();
  21810. return function update( camera ) {
  21811. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  21812. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  21813. far !== camera.far || zoom !== camera.zoom || eyeSep !== this.eyeSep;
  21814. if ( needsUpdate ) {
  21815. instance = this;
  21816. focus = camera.focus;
  21817. fov = camera.fov;
  21818. aspect = camera.aspect * this.aspect;
  21819. near = camera.near;
  21820. far = camera.far;
  21821. zoom = camera.zoom;
  21822. // Off-axis stereoscopic effect based on
  21823. // http://paulbourke.net/stereographics/stereorender/
  21824. var projectionMatrix = camera.projectionMatrix.clone();
  21825. eyeSep = this.eyeSep / 2;
  21826. var eyeSepOnProjection = eyeSep * near / focus;
  21827. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  21828. var xmin, xmax;
  21829. // translate xOffset
  21830. eyeLeft.elements[ 12 ] = - eyeSep;
  21831. eyeRight.elements[ 12 ] = eyeSep;
  21832. // for left eye
  21833. xmin = - ymax * aspect + eyeSepOnProjection;
  21834. xmax = ymax * aspect + eyeSepOnProjection;
  21835. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21836. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21837. this.cameraL.projectionMatrix.copy( projectionMatrix );
  21838. // for right eye
  21839. xmin = - ymax * aspect - eyeSepOnProjection;
  21840. xmax = ymax * aspect - eyeSepOnProjection;
  21841. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21842. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21843. this.cameraR.projectionMatrix.copy( projectionMatrix );
  21844. }
  21845. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  21846. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  21847. };
  21848. } )()
  21849. } );
  21850. /**
  21851. * Camera for rendering cube maps
  21852. * - renders scene into axis-aligned cube
  21853. *
  21854. * @author alteredq / http://alteredqualia.com/
  21855. */
  21856. function CubeCamera( near, far, cubeResolution ) {
  21857. Object3D.call( this );
  21858. this.type = 'CubeCamera';
  21859. var fov = 90, aspect = 1;
  21860. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  21861. cameraPX.up.set( 0, - 1, 0 );
  21862. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  21863. this.add( cameraPX );
  21864. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  21865. cameraNX.up.set( 0, - 1, 0 );
  21866. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  21867. this.add( cameraNX );
  21868. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  21869. cameraPY.up.set( 0, 0, 1 );
  21870. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  21871. this.add( cameraPY );
  21872. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  21873. cameraNY.up.set( 0, 0, - 1 );
  21874. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  21875. this.add( cameraNY );
  21876. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  21877. cameraPZ.up.set( 0, - 1, 0 );
  21878. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  21879. this.add( cameraPZ );
  21880. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  21881. cameraNZ.up.set( 0, - 1, 0 );
  21882. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  21883. this.add( cameraNZ );
  21884. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  21885. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  21886. this.renderTarget.texture.name = "CubeCamera";
  21887. this.update = function ( renderer, scene ) {
  21888. if ( this.parent === null ) this.updateMatrixWorld();
  21889. var renderTarget = this.renderTarget;
  21890. var generateMipmaps = renderTarget.texture.generateMipmaps;
  21891. renderTarget.texture.generateMipmaps = false;
  21892. renderTarget.activeCubeFace = 0;
  21893. renderer.render( scene, cameraPX, renderTarget );
  21894. renderTarget.activeCubeFace = 1;
  21895. renderer.render( scene, cameraNX, renderTarget );
  21896. renderTarget.activeCubeFace = 2;
  21897. renderer.render( scene, cameraPY, renderTarget );
  21898. renderTarget.activeCubeFace = 3;
  21899. renderer.render( scene, cameraNY, renderTarget );
  21900. renderTarget.activeCubeFace = 4;
  21901. renderer.render( scene, cameraPZ, renderTarget );
  21902. renderTarget.texture.generateMipmaps = generateMipmaps;
  21903. renderTarget.activeCubeFace = 5;
  21904. renderer.render( scene, cameraNZ, renderTarget );
  21905. renderer.setRenderTarget( null );
  21906. };
  21907. this.clear = function ( renderer, color, depth, stencil ) {
  21908. var renderTarget = this.renderTarget;
  21909. for ( var i = 0; i < 6; i ++ ) {
  21910. renderTarget.activeCubeFace = i;
  21911. renderer.setRenderTarget( renderTarget );
  21912. renderer.clear( color, depth, stencil );
  21913. }
  21914. renderer.setRenderTarget( null );
  21915. };
  21916. }
  21917. CubeCamera.prototype = Object.create( Object3D.prototype );
  21918. CubeCamera.prototype.constructor = CubeCamera;
  21919. /**
  21920. * @author mrdoob / http://mrdoob.com/
  21921. */
  21922. function AudioListener() {
  21923. Object3D.call( this );
  21924. this.type = 'AudioListener';
  21925. this.context = AudioContext.getContext();
  21926. this.gain = this.context.createGain();
  21927. this.gain.connect( this.context.destination );
  21928. this.filter = null;
  21929. }
  21930. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21931. constructor: AudioListener,
  21932. getInput: function () {
  21933. return this.gain;
  21934. },
  21935. removeFilter: function ( ) {
  21936. if ( this.filter !== null ) {
  21937. this.gain.disconnect( this.filter );
  21938. this.filter.disconnect( this.context.destination );
  21939. this.gain.connect( this.context.destination );
  21940. this.filter = null;
  21941. }
  21942. },
  21943. getFilter: function () {
  21944. return this.filter;
  21945. },
  21946. setFilter: function ( value ) {
  21947. if ( this.filter !== null ) {
  21948. this.gain.disconnect( this.filter );
  21949. this.filter.disconnect( this.context.destination );
  21950. } else {
  21951. this.gain.disconnect( this.context.destination );
  21952. }
  21953. this.filter = value;
  21954. this.gain.connect( this.filter );
  21955. this.filter.connect( this.context.destination );
  21956. },
  21957. getMasterVolume: function () {
  21958. return this.gain.gain.value;
  21959. },
  21960. setMasterVolume: function ( value ) {
  21961. this.gain.gain.value = value;
  21962. },
  21963. updateMatrixWorld: ( function () {
  21964. var position = new Vector3();
  21965. var quaternion = new Quaternion();
  21966. var scale = new Vector3();
  21967. var orientation = new Vector3();
  21968. return function updateMatrixWorld( force ) {
  21969. Object3D.prototype.updateMatrixWorld.call( this, force );
  21970. var listener = this.context.listener;
  21971. var up = this.up;
  21972. this.matrixWorld.decompose( position, quaternion, scale );
  21973. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  21974. if ( listener.positionX ) {
  21975. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  21976. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  21977. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  21978. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  21979. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  21980. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  21981. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  21982. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  21983. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  21984. } else {
  21985. listener.setPosition( position.x, position.y, position.z );
  21986. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  21987. }
  21988. };
  21989. } )()
  21990. } );
  21991. /**
  21992. * @author mrdoob / http://mrdoob.com/
  21993. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21994. */
  21995. function Audio( listener ) {
  21996. Object3D.call( this );
  21997. this.type = 'Audio';
  21998. this.context = listener.context;
  21999. this.gain = this.context.createGain();
  22000. this.gain.connect( listener.getInput() );
  22001. this.autoplay = false;
  22002. this.buffer = null;
  22003. this.loop = false;
  22004. this.startTime = 0;
  22005. this.playbackRate = 1;
  22006. this.isPlaying = false;
  22007. this.hasPlaybackControl = true;
  22008. this.sourceType = 'empty';
  22009. this.filters = [];
  22010. }
  22011. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  22012. constructor: Audio,
  22013. getOutput: function () {
  22014. return this.gain;
  22015. },
  22016. setNodeSource: function ( audioNode ) {
  22017. this.hasPlaybackControl = false;
  22018. this.sourceType = 'audioNode';
  22019. this.source = audioNode;
  22020. this.connect();
  22021. return this;
  22022. },
  22023. setBuffer: function ( audioBuffer ) {
  22024. this.buffer = audioBuffer;
  22025. this.sourceType = 'buffer';
  22026. if ( this.autoplay ) this.play();
  22027. return this;
  22028. },
  22029. play: function () {
  22030. if ( this.isPlaying === true ) {
  22031. console.warn( 'THREE.Audio: Audio is already playing.' );
  22032. return;
  22033. }
  22034. if ( this.hasPlaybackControl === false ) {
  22035. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22036. return;
  22037. }
  22038. var source = this.context.createBufferSource();
  22039. source.buffer = this.buffer;
  22040. source.loop = this.loop;
  22041. source.onended = this.onEnded.bind( this );
  22042. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  22043. source.start( 0, this.startTime );
  22044. this.isPlaying = true;
  22045. this.source = source;
  22046. return this.connect();
  22047. },
  22048. pause: function () {
  22049. if ( this.hasPlaybackControl === false ) {
  22050. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22051. return;
  22052. }
  22053. this.source.stop();
  22054. this.startTime = this.context.currentTime;
  22055. this.isPlaying = false;
  22056. return this;
  22057. },
  22058. stop: function () {
  22059. if ( this.hasPlaybackControl === false ) {
  22060. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22061. return;
  22062. }
  22063. this.source.stop();
  22064. this.startTime = 0;
  22065. this.isPlaying = false;
  22066. return this;
  22067. },
  22068. connect: function () {
  22069. if ( this.filters.length > 0 ) {
  22070. this.source.connect( this.filters[ 0 ] );
  22071. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  22072. this.filters[ i - 1 ].connect( this.filters[ i ] );
  22073. }
  22074. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  22075. } else {
  22076. this.source.connect( this.getOutput() );
  22077. }
  22078. return this;
  22079. },
  22080. disconnect: function () {
  22081. if ( this.filters.length > 0 ) {
  22082. this.source.disconnect( this.filters[ 0 ] );
  22083. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  22084. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  22085. }
  22086. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  22087. } else {
  22088. this.source.disconnect( this.getOutput() );
  22089. }
  22090. return this;
  22091. },
  22092. getFilters: function () {
  22093. return this.filters;
  22094. },
  22095. setFilters: function ( value ) {
  22096. if ( ! value ) value = [];
  22097. if ( this.isPlaying === true ) {
  22098. this.disconnect();
  22099. this.filters = value;
  22100. this.connect();
  22101. } else {
  22102. this.filters = value;
  22103. }
  22104. return this;
  22105. },
  22106. getFilter: function () {
  22107. return this.getFilters()[ 0 ];
  22108. },
  22109. setFilter: function ( filter ) {
  22110. return this.setFilters( filter ? [ filter ] : [] );
  22111. },
  22112. setPlaybackRate: function ( value ) {
  22113. if ( this.hasPlaybackControl === false ) {
  22114. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22115. return;
  22116. }
  22117. this.playbackRate = value;
  22118. if ( this.isPlaying === true ) {
  22119. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  22120. }
  22121. return this;
  22122. },
  22123. getPlaybackRate: function () {
  22124. return this.playbackRate;
  22125. },
  22126. onEnded: function () {
  22127. this.isPlaying = false;
  22128. },
  22129. getLoop: function () {
  22130. if ( this.hasPlaybackControl === false ) {
  22131. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22132. return false;
  22133. }
  22134. return this.loop;
  22135. },
  22136. setLoop: function ( value ) {
  22137. if ( this.hasPlaybackControl === false ) {
  22138. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22139. return;
  22140. }
  22141. this.loop = value;
  22142. if ( this.isPlaying === true ) {
  22143. this.source.loop = this.loop;
  22144. }
  22145. return this;
  22146. },
  22147. getVolume: function () {
  22148. return this.gain.gain.value;
  22149. },
  22150. setVolume: function ( value ) {
  22151. this.gain.gain.value = value;
  22152. return this;
  22153. }
  22154. } );
  22155. /**
  22156. * @author mrdoob / http://mrdoob.com/
  22157. */
  22158. function PositionalAudio( listener ) {
  22159. Audio.call( this, listener );
  22160. this.panner = this.context.createPanner();
  22161. this.panner.connect( this.gain );
  22162. }
  22163. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  22164. constructor: PositionalAudio,
  22165. getOutput: function () {
  22166. return this.panner;
  22167. },
  22168. getRefDistance: function () {
  22169. return this.panner.refDistance;
  22170. },
  22171. setRefDistance: function ( value ) {
  22172. this.panner.refDistance = value;
  22173. },
  22174. getRolloffFactor: function () {
  22175. return this.panner.rolloffFactor;
  22176. },
  22177. setRolloffFactor: function ( value ) {
  22178. this.panner.rolloffFactor = value;
  22179. },
  22180. getDistanceModel: function () {
  22181. return this.panner.distanceModel;
  22182. },
  22183. setDistanceModel: function ( value ) {
  22184. this.panner.distanceModel = value;
  22185. },
  22186. getMaxDistance: function () {
  22187. return this.panner.maxDistance;
  22188. },
  22189. setMaxDistance: function ( value ) {
  22190. this.panner.maxDistance = value;
  22191. },
  22192. updateMatrixWorld: ( function () {
  22193. var position = new Vector3();
  22194. return function updateMatrixWorld( force ) {
  22195. Object3D.prototype.updateMatrixWorld.call( this, force );
  22196. position.setFromMatrixPosition( this.matrixWorld );
  22197. this.panner.setPosition( position.x, position.y, position.z );
  22198. };
  22199. } )()
  22200. } );
  22201. /**
  22202. * @author mrdoob / http://mrdoob.com/
  22203. */
  22204. function AudioAnalyser( audio, fftSize ) {
  22205. this.analyser = audio.context.createAnalyser();
  22206. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  22207. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  22208. audio.getOutput().connect( this.analyser );
  22209. }
  22210. Object.assign( AudioAnalyser.prototype, {
  22211. getFrequencyData: function () {
  22212. this.analyser.getByteFrequencyData( this.data );
  22213. return this.data;
  22214. },
  22215. getAverageFrequency: function () {
  22216. var value = 0, data = this.getFrequencyData();
  22217. for ( var i = 0; i < data.length; i ++ ) {
  22218. value += data[ i ];
  22219. }
  22220. return value / data.length;
  22221. }
  22222. } );
  22223. /**
  22224. *
  22225. * Buffered scene graph property that allows weighted accumulation.
  22226. *
  22227. *
  22228. * @author Ben Houston / http://clara.io/
  22229. * @author David Sarno / http://lighthaus.us/
  22230. * @author tschw
  22231. */
  22232. function PropertyMixer( binding, typeName, valueSize ) {
  22233. this.binding = binding;
  22234. this.valueSize = valueSize;
  22235. var bufferType = Float64Array,
  22236. mixFunction;
  22237. switch ( typeName ) {
  22238. case 'quaternion':
  22239. mixFunction = this._slerp;
  22240. break;
  22241. case 'string':
  22242. case 'bool':
  22243. bufferType = Array;
  22244. mixFunction = this._select;
  22245. break;
  22246. default:
  22247. mixFunction = this._lerp;
  22248. }
  22249. this.buffer = new bufferType( valueSize * 4 );
  22250. // layout: [ incoming | accu0 | accu1 | orig ]
  22251. //
  22252. // interpolators can use .buffer as their .result
  22253. // the data then goes to 'incoming'
  22254. //
  22255. // 'accu0' and 'accu1' are used frame-interleaved for
  22256. // the cumulative result and are compared to detect
  22257. // changes
  22258. //
  22259. // 'orig' stores the original state of the property
  22260. this._mixBufferRegion = mixFunction;
  22261. this.cumulativeWeight = 0;
  22262. this.useCount = 0;
  22263. this.referenceCount = 0;
  22264. }
  22265. Object.assign( PropertyMixer.prototype, {
  22266. // accumulate data in the 'incoming' region into 'accu<i>'
  22267. accumulate: function ( accuIndex, weight ) {
  22268. // note: happily accumulating nothing when weight = 0, the caller knows
  22269. // the weight and shouldn't have made the call in the first place
  22270. var buffer = this.buffer,
  22271. stride = this.valueSize,
  22272. offset = accuIndex * stride + stride,
  22273. currentWeight = this.cumulativeWeight;
  22274. if ( currentWeight === 0 ) {
  22275. // accuN := incoming * weight
  22276. for ( var i = 0; i !== stride; ++ i ) {
  22277. buffer[ offset + i ] = buffer[ i ];
  22278. }
  22279. currentWeight = weight;
  22280. } else {
  22281. // accuN := accuN + incoming * weight
  22282. currentWeight += weight;
  22283. var mix = weight / currentWeight;
  22284. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  22285. }
  22286. this.cumulativeWeight = currentWeight;
  22287. },
  22288. // apply the state of 'accu<i>' to the binding when accus differ
  22289. apply: function ( accuIndex ) {
  22290. var stride = this.valueSize,
  22291. buffer = this.buffer,
  22292. offset = accuIndex * stride + stride,
  22293. weight = this.cumulativeWeight,
  22294. binding = this.binding;
  22295. this.cumulativeWeight = 0;
  22296. if ( weight < 1 ) {
  22297. // accuN := accuN + original * ( 1 - cumulativeWeight )
  22298. var originalValueOffset = stride * 3;
  22299. this._mixBufferRegion(
  22300. buffer, offset, originalValueOffset, 1 - weight, stride );
  22301. }
  22302. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  22303. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  22304. // value has changed -> update scene graph
  22305. binding.setValue( buffer, offset );
  22306. break;
  22307. }
  22308. }
  22309. },
  22310. // remember the state of the bound property and copy it to both accus
  22311. saveOriginalState: function () {
  22312. var binding = this.binding;
  22313. var buffer = this.buffer,
  22314. stride = this.valueSize,
  22315. originalValueOffset = stride * 3;
  22316. binding.getValue( buffer, originalValueOffset );
  22317. // accu[0..1] := orig -- initially detect changes against the original
  22318. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  22319. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  22320. }
  22321. this.cumulativeWeight = 0;
  22322. },
  22323. // apply the state previously taken via 'saveOriginalState' to the binding
  22324. restoreOriginalState: function () {
  22325. var originalValueOffset = this.valueSize * 3;
  22326. this.binding.setValue( this.buffer, originalValueOffset );
  22327. },
  22328. // mix functions
  22329. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  22330. if ( t >= 0.5 ) {
  22331. for ( var i = 0; i !== stride; ++ i ) {
  22332. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  22333. }
  22334. }
  22335. },
  22336. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  22337. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  22338. },
  22339. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  22340. var s = 1 - t;
  22341. for ( var i = 0; i !== stride; ++ i ) {
  22342. var j = dstOffset + i;
  22343. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  22344. }
  22345. }
  22346. } );
  22347. /**
  22348. *
  22349. * A reference to a real property in the scene graph.
  22350. *
  22351. *
  22352. * @author Ben Houston / http://clara.io/
  22353. * @author David Sarno / http://lighthaus.us/
  22354. * @author tschw
  22355. */
  22356. function Composite( targetGroup, path, optionalParsedPath ) {
  22357. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  22358. this._targetGroup = targetGroup;
  22359. this._bindings = targetGroup.subscribe_( path, parsedPath );
  22360. }
  22361. Object.assign( Composite.prototype, {
  22362. getValue: function ( array, offset ) {
  22363. this.bind(); // bind all binding
  22364. var firstValidIndex = this._targetGroup.nCachedObjects_,
  22365. binding = this._bindings[ firstValidIndex ];
  22366. // and only call .getValue on the first
  22367. if ( binding !== undefined ) binding.getValue( array, offset );
  22368. },
  22369. setValue: function ( array, offset ) {
  22370. var bindings = this._bindings;
  22371. for ( var i = this._targetGroup.nCachedObjects_,
  22372. n = bindings.length; i !== n; ++ i ) {
  22373. bindings[ i ].setValue( array, offset );
  22374. }
  22375. },
  22376. bind: function () {
  22377. var bindings = this._bindings;
  22378. for ( var i = this._targetGroup.nCachedObjects_,
  22379. n = bindings.length; i !== n; ++ i ) {
  22380. bindings[ i ].bind();
  22381. }
  22382. },
  22383. unbind: function () {
  22384. var bindings = this._bindings;
  22385. for ( var i = this._targetGroup.nCachedObjects_,
  22386. n = bindings.length; i !== n; ++ i ) {
  22387. bindings[ i ].unbind();
  22388. }
  22389. }
  22390. } );
  22391. function PropertyBinding( rootNode, path, parsedPath ) {
  22392. this.path = path;
  22393. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  22394. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  22395. this.rootNode = rootNode;
  22396. }
  22397. Object.assign( PropertyBinding, {
  22398. Composite: Composite,
  22399. create: function ( root, path, parsedPath ) {
  22400. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  22401. return new PropertyBinding( root, path, parsedPath );
  22402. } else {
  22403. return new PropertyBinding.Composite( root, path, parsedPath );
  22404. }
  22405. },
  22406. /**
  22407. * Replaces spaces with underscores and removes unsupported characters from
  22408. * node names, to ensure compatibility with parseTrackName().
  22409. *
  22410. * @param {string} name Node name to be sanitized.
  22411. * @return {string}
  22412. */
  22413. sanitizeNodeName: function ( name ) {
  22414. return name.replace( /\s/g, '_' ).replace( /[^\w-]/g, '' );
  22415. },
  22416. parseTrackName: function () {
  22417. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  22418. // be matched to parse the rest of the track name.
  22419. var directoryRe = /((?:[\w-]+[\/:])*)/;
  22420. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  22421. var nodeRe = /([\w-\.]+)?/;
  22422. // Object on target node, and accessor. Name may contain only word
  22423. // characters. Accessor may contain any character except closing bracket.
  22424. var objectRe = /(?:\.([\w-]+)(?:\[(.+)\])?)?/;
  22425. // Property and accessor. May contain only word characters. Accessor may
  22426. // contain any non-bracket characters.
  22427. var propertyRe = /\.([\w-]+)(?:\[(.+)\])?/;
  22428. var trackRe = new RegExp(''
  22429. + '^'
  22430. + directoryRe.source
  22431. + nodeRe.source
  22432. + objectRe.source
  22433. + propertyRe.source
  22434. + '$'
  22435. );
  22436. var supportedObjectNames = [ 'material', 'materials', 'bones' ];
  22437. return function ( trackName ) {
  22438. var matches = trackRe.exec( trackName );
  22439. if ( ! matches ) {
  22440. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  22441. }
  22442. var results = {
  22443. // directoryName: matches[ 1 ], // (tschw) currently unused
  22444. nodeName: matches[ 2 ],
  22445. objectName: matches[ 3 ],
  22446. objectIndex: matches[ 4 ],
  22447. propertyName: matches[ 5 ], // required
  22448. propertyIndex: matches[ 6 ]
  22449. };
  22450. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  22451. if ( lastDot !== undefined && lastDot !== -1 ) {
  22452. var objectName = results.nodeName.substring( lastDot + 1 );
  22453. // Object names must be checked against a whitelist. Otherwise, there
  22454. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  22455. // 'bar' could be the objectName, or part of a nodeName (which can
  22456. // include '.' characters).
  22457. if ( supportedObjectNames.indexOf( objectName ) !== -1 ) {
  22458. results.nodeName = results.nodeName.substring( 0, lastDot );
  22459. results.objectName = objectName;
  22460. }
  22461. }
  22462. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  22463. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  22464. }
  22465. return results;
  22466. };
  22467. }(),
  22468. findNode: function ( root, nodeName ) {
  22469. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  22470. return root;
  22471. }
  22472. // search into skeleton bones.
  22473. if ( root.skeleton ) {
  22474. var searchSkeleton = function ( skeleton ) {
  22475. for ( var i = 0; i < skeleton.bones.length; i ++ ) {
  22476. var bone = skeleton.bones[ i ];
  22477. if ( bone.name === nodeName ) {
  22478. return bone;
  22479. }
  22480. }
  22481. return null;
  22482. };
  22483. var bone = searchSkeleton( root.skeleton );
  22484. if ( bone ) {
  22485. return bone;
  22486. }
  22487. }
  22488. // search into node subtree.
  22489. if ( root.children ) {
  22490. var searchNodeSubtree = function ( children ) {
  22491. for ( var i = 0; i < children.length; i ++ ) {
  22492. var childNode = children[ i ];
  22493. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  22494. return childNode;
  22495. }
  22496. var result = searchNodeSubtree( childNode.children );
  22497. if ( result ) return result;
  22498. }
  22499. return null;
  22500. };
  22501. var subTreeNode = searchNodeSubtree( root.children );
  22502. if ( subTreeNode ) {
  22503. return subTreeNode;
  22504. }
  22505. }
  22506. return null;
  22507. }
  22508. } );
  22509. Object.assign( PropertyBinding.prototype, { // prototype, continued
  22510. // these are used to "bind" a nonexistent property
  22511. _getValue_unavailable: function () {},
  22512. _setValue_unavailable: function () {},
  22513. BindingType: {
  22514. Direct: 0,
  22515. EntireArray: 1,
  22516. ArrayElement: 2,
  22517. HasFromToArray: 3
  22518. },
  22519. Versioning: {
  22520. None: 0,
  22521. NeedsUpdate: 1,
  22522. MatrixWorldNeedsUpdate: 2
  22523. },
  22524. GetterByBindingType: [
  22525. function getValue_direct( buffer, offset ) {
  22526. buffer[ offset ] = this.node[ this.propertyName ];
  22527. },
  22528. function getValue_array( buffer, offset ) {
  22529. var source = this.resolvedProperty;
  22530. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  22531. buffer[ offset ++ ] = source[ i ];
  22532. }
  22533. },
  22534. function getValue_arrayElement( buffer, offset ) {
  22535. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  22536. },
  22537. function getValue_toArray( buffer, offset ) {
  22538. this.resolvedProperty.toArray( buffer, offset );
  22539. }
  22540. ],
  22541. SetterByBindingTypeAndVersioning: [
  22542. [
  22543. // Direct
  22544. function setValue_direct( buffer, offset ) {
  22545. this.node[ this.propertyName ] = buffer[ offset ];
  22546. },
  22547. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  22548. this.node[ this.propertyName ] = buffer[ offset ];
  22549. this.targetObject.needsUpdate = true;
  22550. },
  22551. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22552. this.node[ this.propertyName ] = buffer[ offset ];
  22553. this.targetObject.matrixWorldNeedsUpdate = true;
  22554. }
  22555. ], [
  22556. // EntireArray
  22557. function setValue_array( buffer, offset ) {
  22558. var dest = this.resolvedProperty;
  22559. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22560. dest[ i ] = buffer[ offset ++ ];
  22561. }
  22562. },
  22563. function setValue_array_setNeedsUpdate( buffer, offset ) {
  22564. var dest = this.resolvedProperty;
  22565. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22566. dest[ i ] = buffer[ offset ++ ];
  22567. }
  22568. this.targetObject.needsUpdate = true;
  22569. },
  22570. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22571. var dest = this.resolvedProperty;
  22572. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22573. dest[ i ] = buffer[ offset ++ ];
  22574. }
  22575. this.targetObject.matrixWorldNeedsUpdate = true;
  22576. }
  22577. ], [
  22578. // ArrayElement
  22579. function setValue_arrayElement( buffer, offset ) {
  22580. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22581. },
  22582. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  22583. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22584. this.targetObject.needsUpdate = true;
  22585. },
  22586. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22587. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22588. this.targetObject.matrixWorldNeedsUpdate = true;
  22589. }
  22590. ], [
  22591. // HasToFromArray
  22592. function setValue_fromArray( buffer, offset ) {
  22593. this.resolvedProperty.fromArray( buffer, offset );
  22594. },
  22595. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  22596. this.resolvedProperty.fromArray( buffer, offset );
  22597. this.targetObject.needsUpdate = true;
  22598. },
  22599. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22600. this.resolvedProperty.fromArray( buffer, offset );
  22601. this.targetObject.matrixWorldNeedsUpdate = true;
  22602. }
  22603. ]
  22604. ],
  22605. getValue: function getValue_unbound( targetArray, offset ) {
  22606. this.bind();
  22607. this.getValue( targetArray, offset );
  22608. // Note: This class uses a State pattern on a per-method basis:
  22609. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  22610. // prototype version of these methods with one that represents
  22611. // the bound state. When the property is not found, the methods
  22612. // become no-ops.
  22613. },
  22614. setValue: function getValue_unbound( sourceArray, offset ) {
  22615. this.bind();
  22616. this.setValue( sourceArray, offset );
  22617. },
  22618. // create getter / setter pair for a property in the scene graph
  22619. bind: function () {
  22620. var targetObject = this.node,
  22621. parsedPath = this.parsedPath,
  22622. objectName = parsedPath.objectName,
  22623. propertyName = parsedPath.propertyName,
  22624. propertyIndex = parsedPath.propertyIndex;
  22625. if ( ! targetObject ) {
  22626. targetObject = PropertyBinding.findNode(
  22627. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  22628. this.node = targetObject;
  22629. }
  22630. // set fail state so we can just 'return' on error
  22631. this.getValue = this._getValue_unavailable;
  22632. this.setValue = this._setValue_unavailable;
  22633. // ensure there is a value node
  22634. if ( ! targetObject ) {
  22635. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  22636. return;
  22637. }
  22638. if ( objectName ) {
  22639. var objectIndex = parsedPath.objectIndex;
  22640. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  22641. switch ( objectName ) {
  22642. case 'materials':
  22643. if ( ! targetObject.material ) {
  22644. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  22645. return;
  22646. }
  22647. if ( ! targetObject.material.materials ) {
  22648. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  22649. return;
  22650. }
  22651. targetObject = targetObject.material.materials;
  22652. break;
  22653. case 'bones':
  22654. if ( ! targetObject.skeleton ) {
  22655. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  22656. return;
  22657. }
  22658. // potential future optimization: skip this if propertyIndex is already an integer
  22659. // and convert the integer string to a true integer.
  22660. targetObject = targetObject.skeleton.bones;
  22661. // support resolving morphTarget names into indices.
  22662. for ( var i = 0; i < targetObject.length; i ++ ) {
  22663. if ( targetObject[ i ].name === objectIndex ) {
  22664. objectIndex = i;
  22665. break;
  22666. }
  22667. }
  22668. break;
  22669. default:
  22670. if ( targetObject[ objectName ] === undefined ) {
  22671. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  22672. return;
  22673. }
  22674. targetObject = targetObject[ objectName ];
  22675. }
  22676. if ( objectIndex !== undefined ) {
  22677. if ( targetObject[ objectIndex ] === undefined ) {
  22678. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  22679. return;
  22680. }
  22681. targetObject = targetObject[ objectIndex ];
  22682. }
  22683. }
  22684. // resolve property
  22685. var nodeProperty = targetObject[ propertyName ];
  22686. if ( nodeProperty === undefined ) {
  22687. var nodeName = parsedPath.nodeName;
  22688. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  22689. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  22690. return;
  22691. }
  22692. // determine versioning scheme
  22693. var versioning = this.Versioning.None;
  22694. if ( targetObject.needsUpdate !== undefined ) { // material
  22695. versioning = this.Versioning.NeedsUpdate;
  22696. this.targetObject = targetObject;
  22697. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  22698. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  22699. this.targetObject = targetObject;
  22700. }
  22701. // determine how the property gets bound
  22702. var bindingType = this.BindingType.Direct;
  22703. if ( propertyIndex !== undefined ) {
  22704. // access a sub element of the property array (only primitives are supported right now)
  22705. if ( propertyName === "morphTargetInfluences" ) {
  22706. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  22707. // support resolving morphTarget names into indices.
  22708. if ( ! targetObject.geometry ) {
  22709. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  22710. return;
  22711. }
  22712. if ( targetObject.geometry.isBufferGeometry ) {
  22713. if ( ! targetObject.geometry.morphAttributes ) {
  22714. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  22715. return;
  22716. }
  22717. for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {
  22718. if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {
  22719. propertyIndex = i;
  22720. break;
  22721. }
  22722. }
  22723. } else {
  22724. if ( ! targetObject.geometry.morphTargets ) {
  22725. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
  22726. return;
  22727. }
  22728. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  22729. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  22730. propertyIndex = i;
  22731. break;
  22732. }
  22733. }
  22734. }
  22735. }
  22736. bindingType = this.BindingType.ArrayElement;
  22737. this.resolvedProperty = nodeProperty;
  22738. this.propertyIndex = propertyIndex;
  22739. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  22740. // must use copy for Object3D.Euler/Quaternion
  22741. bindingType = this.BindingType.HasFromToArray;
  22742. this.resolvedProperty = nodeProperty;
  22743. } else if ( Array.isArray( nodeProperty ) ) {
  22744. bindingType = this.BindingType.EntireArray;
  22745. this.resolvedProperty = nodeProperty;
  22746. } else {
  22747. this.propertyName = propertyName;
  22748. }
  22749. // select getter / setter
  22750. this.getValue = this.GetterByBindingType[ bindingType ];
  22751. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  22752. },
  22753. unbind: function () {
  22754. this.node = null;
  22755. // back to the prototype version of getValue / setValue
  22756. // note: avoiding to mutate the shape of 'this' via 'delete'
  22757. this.getValue = this._getValue_unbound;
  22758. this.setValue = this._setValue_unbound;
  22759. }
  22760. } );
  22761. //!\ DECLARE ALIAS AFTER assign prototype !
  22762. Object.assign( PropertyBinding.prototype, {
  22763. // initial state of these methods that calls 'bind'
  22764. _getValue_unbound: PropertyBinding.prototype.getValue,
  22765. _setValue_unbound: PropertyBinding.prototype.setValue,
  22766. } );
  22767. /**
  22768. *
  22769. * A group of objects that receives a shared animation state.
  22770. *
  22771. * Usage:
  22772. *
  22773. * - Add objects you would otherwise pass as 'root' to the
  22774. * constructor or the .clipAction method of AnimationMixer.
  22775. *
  22776. * - Instead pass this object as 'root'.
  22777. *
  22778. * - You can also add and remove objects later when the mixer
  22779. * is running.
  22780. *
  22781. * Note:
  22782. *
  22783. * Objects of this class appear as one object to the mixer,
  22784. * so cache control of the individual objects must be done
  22785. * on the group.
  22786. *
  22787. * Limitation:
  22788. *
  22789. * - The animated properties must be compatible among the
  22790. * all objects in the group.
  22791. *
  22792. * - A single property can either be controlled through a
  22793. * target group or directly, but not both.
  22794. *
  22795. * @author tschw
  22796. */
  22797. function AnimationObjectGroup( var_args ) {
  22798. this.uuid = _Math.generateUUID();
  22799. // cached objects followed by the active ones
  22800. this._objects = Array.prototype.slice.call( arguments );
  22801. this.nCachedObjects_ = 0; // threshold
  22802. // note: read by PropertyBinding.Composite
  22803. var indices = {};
  22804. this._indicesByUUID = indices; // for bookkeeping
  22805. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22806. indices[ arguments[ i ].uuid ] = i;
  22807. }
  22808. this._paths = []; // inside: string
  22809. this._parsedPaths = []; // inside: { we don't care, here }
  22810. this._bindings = []; // inside: Array< PropertyBinding >
  22811. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  22812. var scope = this;
  22813. this.stats = {
  22814. objects: {
  22815. get total() { return scope._objects.length; },
  22816. get inUse() { return this.total - scope.nCachedObjects_; }
  22817. },
  22818. get bindingsPerObject() { return scope._bindings.length; }
  22819. };
  22820. }
  22821. Object.assign( AnimationObjectGroup.prototype, {
  22822. isAnimationObjectGroup: true,
  22823. add: function( var_args ) {
  22824. var objects = this._objects,
  22825. nObjects = objects.length,
  22826. nCachedObjects = this.nCachedObjects_,
  22827. indicesByUUID = this._indicesByUUID,
  22828. paths = this._paths,
  22829. parsedPaths = this._parsedPaths,
  22830. bindings = this._bindings,
  22831. nBindings = bindings.length;
  22832. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22833. var object = arguments[ i ],
  22834. uuid = object.uuid,
  22835. index = indicesByUUID[ uuid ],
  22836. knownObject = undefined;
  22837. if ( index === undefined ) {
  22838. // unknown object -> add it to the ACTIVE region
  22839. index = nObjects ++;
  22840. indicesByUUID[ uuid ] = index;
  22841. objects.push( object );
  22842. // accounting is done, now do the same for all bindings
  22843. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22844. bindings[ j ].push(
  22845. new PropertyBinding(
  22846. object, paths[ j ], parsedPaths[ j ] ) );
  22847. }
  22848. } else if ( index < nCachedObjects ) {
  22849. knownObject = objects[ index ];
  22850. // move existing object to the ACTIVE region
  22851. var firstActiveIndex = -- nCachedObjects,
  22852. lastCachedObject = objects[ firstActiveIndex ];
  22853. indicesByUUID[ lastCachedObject.uuid ] = index;
  22854. objects[ index ] = lastCachedObject;
  22855. indicesByUUID[ uuid ] = firstActiveIndex;
  22856. objects[ firstActiveIndex ] = object;
  22857. // accounting is done, now do the same for all bindings
  22858. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22859. var bindingsForPath = bindings[ j ],
  22860. lastCached = bindingsForPath[ firstActiveIndex ],
  22861. binding = bindingsForPath[ index ];
  22862. bindingsForPath[ index ] = lastCached;
  22863. if ( binding === undefined ) {
  22864. // since we do not bother to create new bindings
  22865. // for objects that are cached, the binding may
  22866. // or may not exist
  22867. binding = new PropertyBinding(
  22868. object, paths[ j ], parsedPaths[ j ] );
  22869. }
  22870. bindingsForPath[ firstActiveIndex ] = binding;
  22871. }
  22872. } else if ( objects[ index ] !== knownObject ) {
  22873. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  22874. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  22875. } // else the object is already where we want it to be
  22876. } // for arguments
  22877. this.nCachedObjects_ = nCachedObjects;
  22878. },
  22879. remove: function( var_args ) {
  22880. var objects = this._objects,
  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 && index >= nCachedObjects ) {
  22890. // move existing object into the CACHED region
  22891. var lastCachedIndex = nCachedObjects ++,
  22892. firstActiveObject = objects[ lastCachedIndex ];
  22893. indicesByUUID[ firstActiveObject.uuid ] = index;
  22894. objects[ index ] = firstActiveObject;
  22895. indicesByUUID[ uuid ] = lastCachedIndex;
  22896. objects[ lastCachedIndex ] = object;
  22897. // accounting is done, now do the same for all bindings
  22898. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22899. var bindingsForPath = bindings[ j ],
  22900. firstActive = bindingsForPath[ lastCachedIndex ],
  22901. binding = bindingsForPath[ index ];
  22902. bindingsForPath[ index ] = firstActive;
  22903. bindingsForPath[ lastCachedIndex ] = binding;
  22904. }
  22905. }
  22906. } // for arguments
  22907. this.nCachedObjects_ = nCachedObjects;
  22908. },
  22909. // remove & forget
  22910. uncache: function( var_args ) {
  22911. var objects = this._objects,
  22912. nObjects = objects.length,
  22913. nCachedObjects = this.nCachedObjects_,
  22914. indicesByUUID = this._indicesByUUID,
  22915. bindings = this._bindings,
  22916. nBindings = bindings.length;
  22917. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22918. var object = arguments[ i ],
  22919. uuid = object.uuid,
  22920. index = indicesByUUID[ uuid ];
  22921. if ( index !== undefined ) {
  22922. delete indicesByUUID[ uuid ];
  22923. if ( index < nCachedObjects ) {
  22924. // object is cached, shrink the CACHED region
  22925. var firstActiveIndex = -- nCachedObjects,
  22926. lastCachedObject = objects[ firstActiveIndex ],
  22927. lastIndex = -- nObjects,
  22928. lastObject = objects[ lastIndex ];
  22929. // last cached object takes this object's place
  22930. indicesByUUID[ lastCachedObject.uuid ] = index;
  22931. objects[ index ] = lastCachedObject;
  22932. // last object goes to the activated slot and pop
  22933. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  22934. objects[ firstActiveIndex ] = lastObject;
  22935. objects.pop();
  22936. // accounting is done, now do the same for all bindings
  22937. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22938. var bindingsForPath = bindings[ j ],
  22939. lastCached = bindingsForPath[ firstActiveIndex ],
  22940. last = bindingsForPath[ lastIndex ];
  22941. bindingsForPath[ index ] = lastCached;
  22942. bindingsForPath[ firstActiveIndex ] = last;
  22943. bindingsForPath.pop();
  22944. }
  22945. } else {
  22946. // object is active, just swap with the last and pop
  22947. var lastIndex = -- nObjects,
  22948. lastObject = objects[ lastIndex ];
  22949. indicesByUUID[ lastObject.uuid ] = index;
  22950. objects[ index ] = lastObject;
  22951. objects.pop();
  22952. // accounting is done, now do the same for all bindings
  22953. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22954. var bindingsForPath = bindings[ j ];
  22955. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  22956. bindingsForPath.pop();
  22957. }
  22958. } // cached or active
  22959. } // if object is known
  22960. } // for arguments
  22961. this.nCachedObjects_ = nCachedObjects;
  22962. },
  22963. // Internal interface used by befriended PropertyBinding.Composite:
  22964. subscribe_: function ( path, parsedPath ) {
  22965. // returns an array of bindings for the given path that is changed
  22966. // according to the contained objects in the group
  22967. var indicesByPath = this._bindingsIndicesByPath,
  22968. index = indicesByPath[ path ],
  22969. bindings = this._bindings;
  22970. if ( index !== undefined ) return bindings[ index ];
  22971. var paths = this._paths,
  22972. parsedPaths = this._parsedPaths,
  22973. objects = this._objects,
  22974. nObjects = objects.length,
  22975. nCachedObjects = this.nCachedObjects_,
  22976. bindingsForPath = new Array( nObjects );
  22977. index = bindings.length;
  22978. indicesByPath[ path ] = index;
  22979. paths.push( path );
  22980. parsedPaths.push( parsedPath );
  22981. bindings.push( bindingsForPath );
  22982. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  22983. var object = objects[ i ];
  22984. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  22985. }
  22986. return bindingsForPath;
  22987. },
  22988. unsubscribe_: function ( path ) {
  22989. // tells the group to forget about a property path and no longer
  22990. // update the array previously obtained with 'subscribe_'
  22991. var indicesByPath = this._bindingsIndicesByPath,
  22992. index = indicesByPath[ path ];
  22993. if ( index !== undefined ) {
  22994. var paths = this._paths,
  22995. parsedPaths = this._parsedPaths,
  22996. bindings = this._bindings,
  22997. lastBindingsIndex = bindings.length - 1,
  22998. lastBindings = bindings[ lastBindingsIndex ],
  22999. lastBindingsPath = path[ lastBindingsIndex ];
  23000. indicesByPath[ lastBindingsPath ] = index;
  23001. bindings[ index ] = lastBindings;
  23002. bindings.pop();
  23003. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  23004. parsedPaths.pop();
  23005. paths[ index ] = paths[ lastBindingsIndex ];
  23006. paths.pop();
  23007. }
  23008. }
  23009. } );
  23010. /**
  23011. *
  23012. * Action provided by AnimationMixer for scheduling clip playback on specific
  23013. * objects.
  23014. *
  23015. * @author Ben Houston / http://clara.io/
  23016. * @author David Sarno / http://lighthaus.us/
  23017. * @author tschw
  23018. *
  23019. */
  23020. function AnimationAction( mixer, clip, localRoot ) {
  23021. this._mixer = mixer;
  23022. this._clip = clip;
  23023. this._localRoot = localRoot || null;
  23024. var tracks = clip.tracks,
  23025. nTracks = tracks.length,
  23026. interpolants = new Array( nTracks );
  23027. var interpolantSettings = {
  23028. endingStart: ZeroCurvatureEnding,
  23029. endingEnd: ZeroCurvatureEnding
  23030. };
  23031. for ( var i = 0; i !== nTracks; ++ i ) {
  23032. var interpolant = tracks[ i ].createInterpolant( null );
  23033. interpolants[ i ] = interpolant;
  23034. interpolant.settings = interpolantSettings;
  23035. }
  23036. this._interpolantSettings = interpolantSettings;
  23037. this._interpolants = interpolants; // bound by the mixer
  23038. // inside: PropertyMixer (managed by the mixer)
  23039. this._propertyBindings = new Array( nTracks );
  23040. this._cacheIndex = null; // for the memory manager
  23041. this._byClipCacheIndex = null; // for the memory manager
  23042. this._timeScaleInterpolant = null;
  23043. this._weightInterpolant = null;
  23044. this.loop = LoopRepeat;
  23045. this._loopCount = -1;
  23046. // global mixer time when the action is to be started
  23047. // it's set back to 'null' upon start of the action
  23048. this._startTime = null;
  23049. // scaled local time of the action
  23050. // gets clamped or wrapped to 0..clip.duration according to loop
  23051. this.time = 0;
  23052. this.timeScale = 1;
  23053. this._effectiveTimeScale = 1;
  23054. this.weight = 1;
  23055. this._effectiveWeight = 1;
  23056. this.repetitions = Infinity; // no. of repetitions when looping
  23057. this.paused = false; // true -> zero effective time scale
  23058. this.enabled = true; // false -> zero effective weight
  23059. this.clampWhenFinished = false; // keep feeding the last frame?
  23060. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  23061. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  23062. }
  23063. Object.assign( AnimationAction.prototype, {
  23064. // State & Scheduling
  23065. play: function() {
  23066. this._mixer._activateAction( this );
  23067. return this;
  23068. },
  23069. stop: function() {
  23070. this._mixer._deactivateAction( this );
  23071. return this.reset();
  23072. },
  23073. reset: function() {
  23074. this.paused = false;
  23075. this.enabled = true;
  23076. this.time = 0; // restart clip
  23077. this._loopCount = -1; // forget previous loops
  23078. this._startTime = null; // forget scheduling
  23079. return this.stopFading().stopWarping();
  23080. },
  23081. isRunning: function() {
  23082. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  23083. this._startTime === null && this._mixer._isActiveAction( this );
  23084. },
  23085. // return true when play has been called
  23086. isScheduled: function() {
  23087. return this._mixer._isActiveAction( this );
  23088. },
  23089. startAt: function( time ) {
  23090. this._startTime = time;
  23091. return this;
  23092. },
  23093. setLoop: function( mode, repetitions ) {
  23094. this.loop = mode;
  23095. this.repetitions = repetitions;
  23096. return this;
  23097. },
  23098. // Weight
  23099. // set the weight stopping any scheduled fading
  23100. // although .enabled = false yields an effective weight of zero, this
  23101. // method does *not* change .enabled, because it would be confusing
  23102. setEffectiveWeight: function( weight ) {
  23103. this.weight = weight;
  23104. // note: same logic as when updated at runtime
  23105. this._effectiveWeight = this.enabled ? weight : 0;
  23106. return this.stopFading();
  23107. },
  23108. // return the weight considering fading and .enabled
  23109. getEffectiveWeight: function() {
  23110. return this._effectiveWeight;
  23111. },
  23112. fadeIn: function( duration ) {
  23113. return this._scheduleFading( duration, 0, 1 );
  23114. },
  23115. fadeOut: function( duration ) {
  23116. return this._scheduleFading( duration, 1, 0 );
  23117. },
  23118. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  23119. fadeOutAction.fadeOut( duration );
  23120. this.fadeIn( duration );
  23121. if( warp ) {
  23122. var fadeInDuration = this._clip.duration,
  23123. fadeOutDuration = fadeOutAction._clip.duration,
  23124. startEndRatio = fadeOutDuration / fadeInDuration,
  23125. endStartRatio = fadeInDuration / fadeOutDuration;
  23126. fadeOutAction.warp( 1.0, startEndRatio, duration );
  23127. this.warp( endStartRatio, 1.0, duration );
  23128. }
  23129. return this;
  23130. },
  23131. crossFadeTo: function( fadeInAction, duration, warp ) {
  23132. return fadeInAction.crossFadeFrom( this, duration, warp );
  23133. },
  23134. stopFading: function() {
  23135. var weightInterpolant = this._weightInterpolant;
  23136. if ( weightInterpolant !== null ) {
  23137. this._weightInterpolant = null;
  23138. this._mixer._takeBackControlInterpolant( weightInterpolant );
  23139. }
  23140. return this;
  23141. },
  23142. // Time Scale Control
  23143. // set the time scale stopping any scheduled warping
  23144. // although .paused = true yields an effective time scale of zero, this
  23145. // method does *not* change .paused, because it would be confusing
  23146. setEffectiveTimeScale: function( timeScale ) {
  23147. this.timeScale = timeScale;
  23148. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  23149. return this.stopWarping();
  23150. },
  23151. // return the time scale considering warping and .paused
  23152. getEffectiveTimeScale: function() {
  23153. return this._effectiveTimeScale;
  23154. },
  23155. setDuration: function( duration ) {
  23156. this.timeScale = this._clip.duration / duration;
  23157. return this.stopWarping();
  23158. },
  23159. syncWith: function( action ) {
  23160. this.time = action.time;
  23161. this.timeScale = action.timeScale;
  23162. return this.stopWarping();
  23163. },
  23164. halt: function( duration ) {
  23165. return this.warp( this._effectiveTimeScale, 0, duration );
  23166. },
  23167. warp: function( startTimeScale, endTimeScale, duration ) {
  23168. var mixer = this._mixer, now = mixer.time,
  23169. interpolant = this._timeScaleInterpolant,
  23170. timeScale = this.timeScale;
  23171. if ( interpolant === null ) {
  23172. interpolant = mixer._lendControlInterpolant();
  23173. this._timeScaleInterpolant = interpolant;
  23174. }
  23175. var times = interpolant.parameterPositions,
  23176. values = interpolant.sampleValues;
  23177. times[ 0 ] = now;
  23178. times[ 1 ] = now + duration;
  23179. values[ 0 ] = startTimeScale / timeScale;
  23180. values[ 1 ] = endTimeScale / timeScale;
  23181. return this;
  23182. },
  23183. stopWarping: function() {
  23184. var timeScaleInterpolant = this._timeScaleInterpolant;
  23185. if ( timeScaleInterpolant !== null ) {
  23186. this._timeScaleInterpolant = null;
  23187. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  23188. }
  23189. return this;
  23190. },
  23191. // Object Accessors
  23192. getMixer: function() {
  23193. return this._mixer;
  23194. },
  23195. getClip: function() {
  23196. return this._clip;
  23197. },
  23198. getRoot: function() {
  23199. return this._localRoot || this._mixer._root;
  23200. },
  23201. // Interna
  23202. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  23203. // called by the mixer
  23204. if ( ! this.enabled ) {
  23205. // call ._updateWeight() to update ._effectiveWeight
  23206. this._updateWeight( time );
  23207. return;
  23208. }
  23209. var startTime = this._startTime;
  23210. if ( startTime !== null ) {
  23211. // check for scheduled start of action
  23212. var timeRunning = ( time - startTime ) * timeDirection;
  23213. if ( timeRunning < 0 || timeDirection === 0 ) {
  23214. return; // yet to come / don't decide when delta = 0
  23215. }
  23216. // start
  23217. this._startTime = null; // unschedule
  23218. deltaTime = timeDirection * timeRunning;
  23219. }
  23220. // apply time scale and advance time
  23221. deltaTime *= this._updateTimeScale( time );
  23222. var clipTime = this._updateTime( deltaTime );
  23223. // note: _updateTime may disable the action resulting in
  23224. // an effective weight of 0
  23225. var weight = this._updateWeight( time );
  23226. if ( weight > 0 ) {
  23227. var interpolants = this._interpolants;
  23228. var propertyMixers = this._propertyBindings;
  23229. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  23230. interpolants[ j ].evaluate( clipTime );
  23231. propertyMixers[ j ].accumulate( accuIndex, weight );
  23232. }
  23233. }
  23234. },
  23235. _updateWeight: function( time ) {
  23236. var weight = 0;
  23237. if ( this.enabled ) {
  23238. weight = this.weight;
  23239. var interpolant = this._weightInterpolant;
  23240. if ( interpolant !== null ) {
  23241. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  23242. weight *= interpolantValue;
  23243. if ( time > interpolant.parameterPositions[ 1 ] ) {
  23244. this.stopFading();
  23245. if ( interpolantValue === 0 ) {
  23246. // faded out, disable
  23247. this.enabled = false;
  23248. }
  23249. }
  23250. }
  23251. }
  23252. this._effectiveWeight = weight;
  23253. return weight;
  23254. },
  23255. _updateTimeScale: function( time ) {
  23256. var timeScale = 0;
  23257. if ( ! this.paused ) {
  23258. timeScale = this.timeScale;
  23259. var interpolant = this._timeScaleInterpolant;
  23260. if ( interpolant !== null ) {
  23261. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  23262. timeScale *= interpolantValue;
  23263. if ( time > interpolant.parameterPositions[ 1 ] ) {
  23264. this.stopWarping();
  23265. if ( timeScale === 0 ) {
  23266. // motion has halted, pause
  23267. this.paused = true;
  23268. } else {
  23269. // warp done - apply final time scale
  23270. this.timeScale = timeScale;
  23271. }
  23272. }
  23273. }
  23274. }
  23275. this._effectiveTimeScale = timeScale;
  23276. return timeScale;
  23277. },
  23278. _updateTime: function( deltaTime ) {
  23279. var time = this.time + deltaTime;
  23280. if ( deltaTime === 0 ) return time;
  23281. var duration = this._clip.duration,
  23282. loop = this.loop,
  23283. loopCount = this._loopCount;
  23284. if ( loop === LoopOnce ) {
  23285. if ( loopCount === -1 ) {
  23286. // just started
  23287. this._loopCount = 0;
  23288. this._setEndings( true, true, false );
  23289. }
  23290. handle_stop: {
  23291. if ( time >= duration ) {
  23292. time = duration;
  23293. } else if ( time < 0 ) {
  23294. time = 0;
  23295. } else break handle_stop;
  23296. if ( this.clampWhenFinished ) this.paused = true;
  23297. else this.enabled = false;
  23298. this._mixer.dispatchEvent( {
  23299. type: 'finished', action: this,
  23300. direction: deltaTime < 0 ? -1 : 1
  23301. } );
  23302. }
  23303. } else { // repetitive Repeat or PingPong
  23304. var pingPong = ( loop === LoopPingPong );
  23305. if ( loopCount === -1 ) {
  23306. // just started
  23307. if ( deltaTime >= 0 ) {
  23308. loopCount = 0;
  23309. this._setEndings(
  23310. true, this.repetitions === 0, pingPong );
  23311. } else {
  23312. // when looping in reverse direction, the initial
  23313. // transition through zero counts as a repetition,
  23314. // so leave loopCount at -1
  23315. this._setEndings(
  23316. this.repetitions === 0, true, pingPong );
  23317. }
  23318. }
  23319. if ( time >= duration || time < 0 ) {
  23320. // wrap around
  23321. var loopDelta = Math.floor( time / duration ); // signed
  23322. time -= duration * loopDelta;
  23323. loopCount += Math.abs( loopDelta );
  23324. var pending = this.repetitions - loopCount;
  23325. if ( pending < 0 ) {
  23326. // have to stop (switch state, clamp time, fire event)
  23327. if ( this.clampWhenFinished ) this.paused = true;
  23328. else this.enabled = false;
  23329. time = deltaTime > 0 ? duration : 0;
  23330. this._mixer.dispatchEvent( {
  23331. type: 'finished', action: this,
  23332. direction: deltaTime > 0 ? 1 : -1
  23333. } );
  23334. } else {
  23335. // keep running
  23336. if ( pending === 0 ) {
  23337. // entering the last round
  23338. var atStart = deltaTime < 0;
  23339. this._setEndings( atStart, ! atStart, pingPong );
  23340. } else {
  23341. this._setEndings( false, false, pingPong );
  23342. }
  23343. this._loopCount = loopCount;
  23344. this._mixer.dispatchEvent( {
  23345. type: 'loop', action: this, loopDelta: loopDelta
  23346. } );
  23347. }
  23348. }
  23349. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  23350. // invert time for the "pong round"
  23351. this.time = time;
  23352. return duration - time;
  23353. }
  23354. }
  23355. this.time = time;
  23356. return time;
  23357. },
  23358. _setEndings: function( atStart, atEnd, pingPong ) {
  23359. var settings = this._interpolantSettings;
  23360. if ( pingPong ) {
  23361. settings.endingStart = ZeroSlopeEnding;
  23362. settings.endingEnd = ZeroSlopeEnding;
  23363. } else {
  23364. // assuming for LoopOnce atStart == atEnd == true
  23365. if ( atStart ) {
  23366. settings.endingStart = this.zeroSlopeAtStart ?
  23367. ZeroSlopeEnding : ZeroCurvatureEnding;
  23368. } else {
  23369. settings.endingStart = WrapAroundEnding;
  23370. }
  23371. if ( atEnd ) {
  23372. settings.endingEnd = this.zeroSlopeAtEnd ?
  23373. ZeroSlopeEnding : ZeroCurvatureEnding;
  23374. } else {
  23375. settings.endingEnd = WrapAroundEnding;
  23376. }
  23377. }
  23378. },
  23379. _scheduleFading: function( duration, weightNow, weightThen ) {
  23380. var mixer = this._mixer, now = mixer.time,
  23381. interpolant = this._weightInterpolant;
  23382. if ( interpolant === null ) {
  23383. interpolant = mixer._lendControlInterpolant();
  23384. this._weightInterpolant = interpolant;
  23385. }
  23386. var times = interpolant.parameterPositions,
  23387. values = interpolant.sampleValues;
  23388. times[ 0 ] = now; values[ 0 ] = weightNow;
  23389. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  23390. return this;
  23391. }
  23392. } );
  23393. /**
  23394. *
  23395. * Player for AnimationClips.
  23396. *
  23397. *
  23398. * @author Ben Houston / http://clara.io/
  23399. * @author David Sarno / http://lighthaus.us/
  23400. * @author tschw
  23401. */
  23402. function AnimationMixer( root ) {
  23403. this._root = root;
  23404. this._initMemoryManager();
  23405. this._accuIndex = 0;
  23406. this.time = 0;
  23407. this.timeScale = 1.0;
  23408. }
  23409. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, {
  23410. _bindAction: function ( action, prototypeAction ) {
  23411. var root = action._localRoot || this._root,
  23412. tracks = action._clip.tracks,
  23413. nTracks = tracks.length,
  23414. bindings = action._propertyBindings,
  23415. interpolants = action._interpolants,
  23416. rootUuid = root.uuid,
  23417. bindingsByRoot = this._bindingsByRootAndName,
  23418. bindingsByName = bindingsByRoot[ rootUuid ];
  23419. if ( bindingsByName === undefined ) {
  23420. bindingsByName = {};
  23421. bindingsByRoot[ rootUuid ] = bindingsByName;
  23422. }
  23423. for ( var i = 0; i !== nTracks; ++ i ) {
  23424. var track = tracks[ i ],
  23425. trackName = track.name,
  23426. binding = bindingsByName[ trackName ];
  23427. if ( binding !== undefined ) {
  23428. bindings[ i ] = binding;
  23429. } else {
  23430. binding = bindings[ i ];
  23431. if ( binding !== undefined ) {
  23432. // existing binding, make sure the cache knows
  23433. if ( binding._cacheIndex === null ) {
  23434. ++ binding.referenceCount;
  23435. this._addInactiveBinding( binding, rootUuid, trackName );
  23436. }
  23437. continue;
  23438. }
  23439. var path = prototypeAction && prototypeAction.
  23440. _propertyBindings[ i ].binding.parsedPath;
  23441. binding = new PropertyMixer(
  23442. PropertyBinding.create( root, trackName, path ),
  23443. track.ValueTypeName, track.getValueSize() );
  23444. ++ binding.referenceCount;
  23445. this._addInactiveBinding( binding, rootUuid, trackName );
  23446. bindings[ i ] = binding;
  23447. }
  23448. interpolants[ i ].resultBuffer = binding.buffer;
  23449. }
  23450. },
  23451. _activateAction: function ( action ) {
  23452. if ( ! this._isActiveAction( action ) ) {
  23453. if ( action._cacheIndex === null ) {
  23454. // this action has been forgotten by the cache, but the user
  23455. // appears to be still using it -> rebind
  23456. var rootUuid = ( action._localRoot || this._root ).uuid,
  23457. clipUuid = action._clip.uuid,
  23458. actionsForClip = this._actionsByClip[ clipUuid ];
  23459. this._bindAction( action,
  23460. actionsForClip && actionsForClip.knownActions[ 0 ] );
  23461. this._addInactiveAction( action, clipUuid, rootUuid );
  23462. }
  23463. var bindings = action._propertyBindings;
  23464. // increment reference counts / sort out state
  23465. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23466. var binding = bindings[ i ];
  23467. if ( binding.useCount ++ === 0 ) {
  23468. this._lendBinding( binding );
  23469. binding.saveOriginalState();
  23470. }
  23471. }
  23472. this._lendAction( action );
  23473. }
  23474. },
  23475. _deactivateAction: function ( action ) {
  23476. if ( this._isActiveAction( action ) ) {
  23477. var bindings = action._propertyBindings;
  23478. // decrement reference counts / sort out state
  23479. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23480. var binding = bindings[ i ];
  23481. if ( -- binding.useCount === 0 ) {
  23482. binding.restoreOriginalState();
  23483. this._takeBackBinding( binding );
  23484. }
  23485. }
  23486. this._takeBackAction( action );
  23487. }
  23488. },
  23489. // Memory manager
  23490. _initMemoryManager: function () {
  23491. this._actions = []; // 'nActiveActions' followed by inactive ones
  23492. this._nActiveActions = 0;
  23493. this._actionsByClip = {};
  23494. // inside:
  23495. // {
  23496. // knownActions: Array< AnimationAction > - used as prototypes
  23497. // actionByRoot: AnimationAction - lookup
  23498. // }
  23499. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  23500. this._nActiveBindings = 0;
  23501. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  23502. this._controlInterpolants = []; // same game as above
  23503. this._nActiveControlInterpolants = 0;
  23504. var scope = this;
  23505. this.stats = {
  23506. actions: {
  23507. get total() { return scope._actions.length; },
  23508. get inUse() { return scope._nActiveActions; }
  23509. },
  23510. bindings: {
  23511. get total() { return scope._bindings.length; },
  23512. get inUse() { return scope._nActiveBindings; }
  23513. },
  23514. controlInterpolants: {
  23515. get total() { return scope._controlInterpolants.length; },
  23516. get inUse() { return scope._nActiveControlInterpolants; }
  23517. }
  23518. };
  23519. },
  23520. // Memory management for AnimationAction objects
  23521. _isActiveAction: function ( action ) {
  23522. var index = action._cacheIndex;
  23523. return index !== null && index < this._nActiveActions;
  23524. },
  23525. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  23526. var actions = this._actions,
  23527. actionsByClip = this._actionsByClip,
  23528. actionsForClip = actionsByClip[ clipUuid ];
  23529. if ( actionsForClip === undefined ) {
  23530. actionsForClip = {
  23531. knownActions: [ action ],
  23532. actionByRoot: {}
  23533. };
  23534. action._byClipCacheIndex = 0;
  23535. actionsByClip[ clipUuid ] = actionsForClip;
  23536. } else {
  23537. var knownActions = actionsForClip.knownActions;
  23538. action._byClipCacheIndex = knownActions.length;
  23539. knownActions.push( action );
  23540. }
  23541. action._cacheIndex = actions.length;
  23542. actions.push( action );
  23543. actionsForClip.actionByRoot[ rootUuid ] = action;
  23544. },
  23545. _removeInactiveAction: function ( action ) {
  23546. var actions = this._actions,
  23547. lastInactiveAction = actions[ actions.length - 1 ],
  23548. cacheIndex = action._cacheIndex;
  23549. lastInactiveAction._cacheIndex = cacheIndex;
  23550. actions[ cacheIndex ] = lastInactiveAction;
  23551. actions.pop();
  23552. action._cacheIndex = null;
  23553. var clipUuid = action._clip.uuid,
  23554. actionsByClip = this._actionsByClip,
  23555. actionsForClip = actionsByClip[ clipUuid ],
  23556. knownActionsForClip = actionsForClip.knownActions,
  23557. lastKnownAction =
  23558. knownActionsForClip[ knownActionsForClip.length - 1 ],
  23559. byClipCacheIndex = action._byClipCacheIndex;
  23560. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  23561. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  23562. knownActionsForClip.pop();
  23563. action._byClipCacheIndex = null;
  23564. var actionByRoot = actionsForClip.actionByRoot,
  23565. rootUuid = ( action._localRoot || this._root ).uuid;
  23566. delete actionByRoot[ rootUuid ];
  23567. if ( knownActionsForClip.length === 0 ) {
  23568. delete actionsByClip[ clipUuid ];
  23569. }
  23570. this._removeInactiveBindingsForAction( action );
  23571. },
  23572. _removeInactiveBindingsForAction: function ( action ) {
  23573. var bindings = action._propertyBindings;
  23574. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23575. var binding = bindings[ i ];
  23576. if ( -- binding.referenceCount === 0 ) {
  23577. this._removeInactiveBinding( binding );
  23578. }
  23579. }
  23580. },
  23581. _lendAction: function ( action ) {
  23582. // [ active actions | inactive actions ]
  23583. // [ active actions >| inactive actions ]
  23584. // s a
  23585. // <-swap->
  23586. // a s
  23587. var actions = this._actions,
  23588. prevIndex = action._cacheIndex,
  23589. lastActiveIndex = this._nActiveActions ++,
  23590. firstInactiveAction = actions[ lastActiveIndex ];
  23591. action._cacheIndex = lastActiveIndex;
  23592. actions[ lastActiveIndex ] = action;
  23593. firstInactiveAction._cacheIndex = prevIndex;
  23594. actions[ prevIndex ] = firstInactiveAction;
  23595. },
  23596. _takeBackAction: function ( action ) {
  23597. // [ active actions | inactive actions ]
  23598. // [ active actions |< inactive actions ]
  23599. // a s
  23600. // <-swap->
  23601. // s a
  23602. var actions = this._actions,
  23603. prevIndex = action._cacheIndex,
  23604. firstInactiveIndex = -- this._nActiveActions,
  23605. lastActiveAction = actions[ firstInactiveIndex ];
  23606. action._cacheIndex = firstInactiveIndex;
  23607. actions[ firstInactiveIndex ] = action;
  23608. lastActiveAction._cacheIndex = prevIndex;
  23609. actions[ prevIndex ] = lastActiveAction;
  23610. },
  23611. // Memory management for PropertyMixer objects
  23612. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  23613. var bindingsByRoot = this._bindingsByRootAndName,
  23614. bindingByName = bindingsByRoot[ rootUuid ],
  23615. bindings = this._bindings;
  23616. if ( bindingByName === undefined ) {
  23617. bindingByName = {};
  23618. bindingsByRoot[ rootUuid ] = bindingByName;
  23619. }
  23620. bindingByName[ trackName ] = binding;
  23621. binding._cacheIndex = bindings.length;
  23622. bindings.push( binding );
  23623. },
  23624. _removeInactiveBinding: function ( binding ) {
  23625. var bindings = this._bindings,
  23626. propBinding = binding.binding,
  23627. rootUuid = propBinding.rootNode.uuid,
  23628. trackName = propBinding.path,
  23629. bindingsByRoot = this._bindingsByRootAndName,
  23630. bindingByName = bindingsByRoot[ rootUuid ],
  23631. lastInactiveBinding = bindings[ bindings.length - 1 ],
  23632. cacheIndex = binding._cacheIndex;
  23633. lastInactiveBinding._cacheIndex = cacheIndex;
  23634. bindings[ cacheIndex ] = lastInactiveBinding;
  23635. bindings.pop();
  23636. delete bindingByName[ trackName ];
  23637. remove_empty_map: {
  23638. for ( var _ in bindingByName ) break remove_empty_map;
  23639. delete bindingsByRoot[ rootUuid ];
  23640. }
  23641. },
  23642. _lendBinding: function ( binding ) {
  23643. var bindings = this._bindings,
  23644. prevIndex = binding._cacheIndex,
  23645. lastActiveIndex = this._nActiveBindings ++,
  23646. firstInactiveBinding = bindings[ lastActiveIndex ];
  23647. binding._cacheIndex = lastActiveIndex;
  23648. bindings[ lastActiveIndex ] = binding;
  23649. firstInactiveBinding._cacheIndex = prevIndex;
  23650. bindings[ prevIndex ] = firstInactiveBinding;
  23651. },
  23652. _takeBackBinding: function ( binding ) {
  23653. var bindings = this._bindings,
  23654. prevIndex = binding._cacheIndex,
  23655. firstInactiveIndex = -- this._nActiveBindings,
  23656. lastActiveBinding = bindings[ firstInactiveIndex ];
  23657. binding._cacheIndex = firstInactiveIndex;
  23658. bindings[ firstInactiveIndex ] = binding;
  23659. lastActiveBinding._cacheIndex = prevIndex;
  23660. bindings[ prevIndex ] = lastActiveBinding;
  23661. },
  23662. // Memory management of Interpolants for weight and time scale
  23663. _lendControlInterpolant: function () {
  23664. var interpolants = this._controlInterpolants,
  23665. lastActiveIndex = this._nActiveControlInterpolants ++,
  23666. interpolant = interpolants[ lastActiveIndex ];
  23667. if ( interpolant === undefined ) {
  23668. interpolant = new LinearInterpolant(
  23669. new Float32Array( 2 ), new Float32Array( 2 ),
  23670. 1, this._controlInterpolantsResultBuffer );
  23671. interpolant.__cacheIndex = lastActiveIndex;
  23672. interpolants[ lastActiveIndex ] = interpolant;
  23673. }
  23674. return interpolant;
  23675. },
  23676. _takeBackControlInterpolant: function ( interpolant ) {
  23677. var interpolants = this._controlInterpolants,
  23678. prevIndex = interpolant.__cacheIndex,
  23679. firstInactiveIndex = -- this._nActiveControlInterpolants,
  23680. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  23681. interpolant.__cacheIndex = firstInactiveIndex;
  23682. interpolants[ firstInactiveIndex ] = interpolant;
  23683. lastActiveInterpolant.__cacheIndex = prevIndex;
  23684. interpolants[ prevIndex ] = lastActiveInterpolant;
  23685. },
  23686. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  23687. // return an action for a clip optionally using a custom root target
  23688. // object (this method allocates a lot of dynamic memory in case a
  23689. // previously unknown clip/root combination is specified)
  23690. clipAction: function ( clip, optionalRoot ) {
  23691. var root = optionalRoot || this._root,
  23692. rootUuid = root.uuid,
  23693. clipObject = typeof clip === 'string' ?
  23694. AnimationClip.findByName( root, clip ) : clip,
  23695. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  23696. actionsForClip = this._actionsByClip[ clipUuid ],
  23697. prototypeAction = null;
  23698. if ( actionsForClip !== undefined ) {
  23699. var existingAction =
  23700. actionsForClip.actionByRoot[ rootUuid ];
  23701. if ( existingAction !== undefined ) {
  23702. return existingAction;
  23703. }
  23704. // we know the clip, so we don't have to parse all
  23705. // the bindings again but can just copy
  23706. prototypeAction = actionsForClip.knownActions[ 0 ];
  23707. // also, take the clip from the prototype action
  23708. if ( clipObject === null )
  23709. clipObject = prototypeAction._clip;
  23710. }
  23711. // clip must be known when specified via string
  23712. if ( clipObject === null ) return null;
  23713. // allocate all resources required to run it
  23714. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  23715. this._bindAction( newAction, prototypeAction );
  23716. // and make the action known to the memory manager
  23717. this._addInactiveAction( newAction, clipUuid, rootUuid );
  23718. return newAction;
  23719. },
  23720. // get an existing action
  23721. existingAction: function ( clip, optionalRoot ) {
  23722. var root = optionalRoot || this._root,
  23723. rootUuid = root.uuid,
  23724. clipObject = typeof clip === 'string' ?
  23725. AnimationClip.findByName( root, clip ) : clip,
  23726. clipUuid = clipObject ? clipObject.uuid : clip,
  23727. actionsForClip = this._actionsByClip[ clipUuid ];
  23728. if ( actionsForClip !== undefined ) {
  23729. return actionsForClip.actionByRoot[ rootUuid ] || null;
  23730. }
  23731. return null;
  23732. },
  23733. // deactivates all previously scheduled actions
  23734. stopAllAction: function () {
  23735. var actions = this._actions,
  23736. nActions = this._nActiveActions,
  23737. bindings = this._bindings,
  23738. nBindings = this._nActiveBindings;
  23739. this._nActiveActions = 0;
  23740. this._nActiveBindings = 0;
  23741. for ( var i = 0; i !== nActions; ++ i ) {
  23742. actions[ i ].reset();
  23743. }
  23744. for ( var i = 0; i !== nBindings; ++ i ) {
  23745. bindings[ i ].useCount = 0;
  23746. }
  23747. return this;
  23748. },
  23749. // advance the time and update apply the animation
  23750. update: function ( deltaTime ) {
  23751. deltaTime *= this.timeScale;
  23752. var actions = this._actions,
  23753. nActions = this._nActiveActions,
  23754. time = this.time += deltaTime,
  23755. timeDirection = Math.sign( deltaTime ),
  23756. accuIndex = this._accuIndex ^= 1;
  23757. // run active actions
  23758. for ( var i = 0; i !== nActions; ++ i ) {
  23759. var action = actions[ i ];
  23760. action._update( time, deltaTime, timeDirection, accuIndex );
  23761. }
  23762. // update scene graph
  23763. var bindings = this._bindings,
  23764. nBindings = this._nActiveBindings;
  23765. for ( var i = 0; i !== nBindings; ++ i ) {
  23766. bindings[ i ].apply( accuIndex );
  23767. }
  23768. return this;
  23769. },
  23770. // return this mixer's root target object
  23771. getRoot: function () {
  23772. return this._root;
  23773. },
  23774. // free all resources specific to a particular clip
  23775. uncacheClip: function ( clip ) {
  23776. var actions = this._actions,
  23777. clipUuid = clip.uuid,
  23778. actionsByClip = this._actionsByClip,
  23779. actionsForClip = actionsByClip[ clipUuid ];
  23780. if ( actionsForClip !== undefined ) {
  23781. // note: just calling _removeInactiveAction would mess up the
  23782. // iteration state and also require updating the state we can
  23783. // just throw away
  23784. var actionsToRemove = actionsForClip.knownActions;
  23785. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  23786. var action = actionsToRemove[ i ];
  23787. this._deactivateAction( action );
  23788. var cacheIndex = action._cacheIndex,
  23789. lastInactiveAction = actions[ actions.length - 1 ];
  23790. action._cacheIndex = null;
  23791. action._byClipCacheIndex = null;
  23792. lastInactiveAction._cacheIndex = cacheIndex;
  23793. actions[ cacheIndex ] = lastInactiveAction;
  23794. actions.pop();
  23795. this._removeInactiveBindingsForAction( action );
  23796. }
  23797. delete actionsByClip[ clipUuid ];
  23798. }
  23799. },
  23800. // free all resources specific to a particular root target object
  23801. uncacheRoot: function ( root ) {
  23802. var rootUuid = root.uuid,
  23803. actionsByClip = this._actionsByClip;
  23804. for ( var clipUuid in actionsByClip ) {
  23805. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  23806. action = actionByRoot[ rootUuid ];
  23807. if ( action !== undefined ) {
  23808. this._deactivateAction( action );
  23809. this._removeInactiveAction( action );
  23810. }
  23811. }
  23812. var bindingsByRoot = this._bindingsByRootAndName,
  23813. bindingByName = bindingsByRoot[ rootUuid ];
  23814. if ( bindingByName !== undefined ) {
  23815. for ( var trackName in bindingByName ) {
  23816. var binding = bindingByName[ trackName ];
  23817. binding.restoreOriginalState();
  23818. this._removeInactiveBinding( binding );
  23819. }
  23820. }
  23821. },
  23822. // remove a targeted clip from the cache
  23823. uncacheAction: function ( clip, optionalRoot ) {
  23824. var action = this.existingAction( clip, optionalRoot );
  23825. if ( action !== null ) {
  23826. this._deactivateAction( action );
  23827. this._removeInactiveAction( action );
  23828. }
  23829. }
  23830. } );
  23831. /**
  23832. * @author mrdoob / http://mrdoob.com/
  23833. */
  23834. function Uniform( value ) {
  23835. if ( typeof value === 'string' ) {
  23836. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  23837. value = arguments[ 1 ];
  23838. }
  23839. this.value = value;
  23840. }
  23841. Uniform.prototype.clone = function () {
  23842. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  23843. };
  23844. /**
  23845. * @author benaadams / https://twitter.com/ben_a_adams
  23846. */
  23847. function InstancedBufferGeometry() {
  23848. BufferGeometry.call( this );
  23849. this.type = 'InstancedBufferGeometry';
  23850. this.maxInstancedCount = undefined;
  23851. }
  23852. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  23853. constructor: InstancedBufferGeometry,
  23854. isInstancedBufferGeometry: true,
  23855. addGroup: function ( start, count, materialIndex ) {
  23856. this.groups.push( {
  23857. start: start,
  23858. count: count,
  23859. materialIndex: materialIndex
  23860. } );
  23861. },
  23862. copy: function ( source ) {
  23863. var index = source.index;
  23864. if ( index !== null ) {
  23865. this.setIndex( index.clone() );
  23866. }
  23867. var attributes = source.attributes;
  23868. for ( var name in attributes ) {
  23869. var attribute = attributes[ name ];
  23870. this.addAttribute( name, attribute.clone() );
  23871. }
  23872. var groups = source.groups;
  23873. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  23874. var group = groups[ i ];
  23875. this.addGroup( group.start, group.count, group.materialIndex );
  23876. }
  23877. return this;
  23878. }
  23879. } );
  23880. /**
  23881. * @author benaadams / https://twitter.com/ben_a_adams
  23882. */
  23883. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  23884. this.uuid = _Math.generateUUID();
  23885. this.data = interleavedBuffer;
  23886. this.itemSize = itemSize;
  23887. this.offset = offset;
  23888. this.normalized = normalized === true;
  23889. }
  23890. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  23891. count: {
  23892. get: function () {
  23893. return this.data.count;
  23894. }
  23895. },
  23896. array: {
  23897. get: function () {
  23898. return this.data.array;
  23899. }
  23900. }
  23901. } );
  23902. Object.assign( InterleavedBufferAttribute.prototype, {
  23903. isInterleavedBufferAttribute: true,
  23904. setX: function ( index, x ) {
  23905. this.data.array[ index * this.data.stride + this.offset ] = x;
  23906. return this;
  23907. },
  23908. setY: function ( index, y ) {
  23909. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  23910. return this;
  23911. },
  23912. setZ: function ( index, z ) {
  23913. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  23914. return this;
  23915. },
  23916. setW: function ( index, w ) {
  23917. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  23918. return this;
  23919. },
  23920. getX: function ( index ) {
  23921. return this.data.array[ index * this.data.stride + this.offset ];
  23922. },
  23923. getY: function ( index ) {
  23924. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  23925. },
  23926. getZ: function ( index ) {
  23927. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  23928. },
  23929. getW: function ( index ) {
  23930. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  23931. },
  23932. setXY: function ( index, x, y ) {
  23933. index = index * this.data.stride + this.offset;
  23934. this.data.array[ index + 0 ] = x;
  23935. this.data.array[ index + 1 ] = y;
  23936. return this;
  23937. },
  23938. setXYZ: function ( index, x, y, z ) {
  23939. index = index * this.data.stride + this.offset;
  23940. this.data.array[ index + 0 ] = x;
  23941. this.data.array[ index + 1 ] = y;
  23942. this.data.array[ index + 2 ] = z;
  23943. return this;
  23944. },
  23945. setXYZW: function ( index, x, y, z, w ) {
  23946. index = index * this.data.stride + this.offset;
  23947. this.data.array[ index + 0 ] = x;
  23948. this.data.array[ index + 1 ] = y;
  23949. this.data.array[ index + 2 ] = z;
  23950. this.data.array[ index + 3 ] = w;
  23951. return this;
  23952. }
  23953. } );
  23954. /**
  23955. * @author benaadams / https://twitter.com/ben_a_adams
  23956. */
  23957. function InterleavedBuffer( array, stride ) {
  23958. this.uuid = _Math.generateUUID();
  23959. this.array = array;
  23960. this.stride = stride;
  23961. this.count = array !== undefined ? array.length / stride : 0;
  23962. this.dynamic = false;
  23963. this.updateRange = { offset: 0, count: - 1 };
  23964. this.onUploadCallback = function () {};
  23965. this.version = 0;
  23966. }
  23967. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  23968. set: function ( value ) {
  23969. if ( value === true ) this.version ++;
  23970. }
  23971. } );
  23972. Object.assign( InterleavedBuffer.prototype, {
  23973. isInterleavedBuffer: true,
  23974. setArray: function ( array ) {
  23975. if ( Array.isArray( array ) ) {
  23976. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  23977. }
  23978. this.count = array !== undefined ? array.length / this.stride : 0;
  23979. this.array = array;
  23980. },
  23981. setDynamic: function ( value ) {
  23982. this.dynamic = value;
  23983. return this;
  23984. },
  23985. copy: function ( source ) {
  23986. this.array = new source.array.constructor( source.array );
  23987. this.count = source.count;
  23988. this.stride = source.stride;
  23989. this.dynamic = source.dynamic;
  23990. return this;
  23991. },
  23992. copyAt: function ( index1, attribute, index2 ) {
  23993. index1 *= this.stride;
  23994. index2 *= attribute.stride;
  23995. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  23996. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  23997. }
  23998. return this;
  23999. },
  24000. set: function ( value, offset ) {
  24001. if ( offset === undefined ) offset = 0;
  24002. this.array.set( value, offset );
  24003. return this;
  24004. },
  24005. clone: function () {
  24006. return new this.constructor().copy( this );
  24007. },
  24008. onUpload: function ( callback ) {
  24009. this.onUploadCallback = callback;
  24010. return this;
  24011. }
  24012. } );
  24013. /**
  24014. * @author benaadams / https://twitter.com/ben_a_adams
  24015. */
  24016. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  24017. InterleavedBuffer.call( this, array, stride );
  24018. this.meshPerAttribute = meshPerAttribute || 1;
  24019. }
  24020. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  24021. constructor: InstancedInterleavedBuffer,
  24022. isInstancedInterleavedBuffer: true,
  24023. copy: function ( source ) {
  24024. InterleavedBuffer.prototype.copy.call( this, source );
  24025. this.meshPerAttribute = source.meshPerAttribute;
  24026. return this;
  24027. }
  24028. } );
  24029. /**
  24030. * @author benaadams / https://twitter.com/ben_a_adams
  24031. */
  24032. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  24033. BufferAttribute.call( this, array, itemSize );
  24034. this.meshPerAttribute = meshPerAttribute || 1;
  24035. }
  24036. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  24037. constructor: InstancedBufferAttribute,
  24038. isInstancedBufferAttribute: true,
  24039. copy: function ( source ) {
  24040. BufferAttribute.prototype.copy.call( this, source );
  24041. this.meshPerAttribute = source.meshPerAttribute;
  24042. return this;
  24043. }
  24044. } );
  24045. /**
  24046. * @author mrdoob / http://mrdoob.com/
  24047. * @author bhouston / http://clara.io/
  24048. * @author stephomi / http://stephaneginier.com/
  24049. */
  24050. function Raycaster( origin, direction, near, far ) {
  24051. this.ray = new Ray( origin, direction );
  24052. // direction is assumed to be normalized (for accurate distance calculations)
  24053. this.near = near || 0;
  24054. this.far = far || Infinity;
  24055. this.params = {
  24056. Mesh: {},
  24057. Line: {},
  24058. LOD: {},
  24059. Points: { threshold: 1 },
  24060. Sprite: {}
  24061. };
  24062. Object.defineProperties( this.params, {
  24063. PointCloud: {
  24064. get: function () {
  24065. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  24066. return this.Points;
  24067. }
  24068. }
  24069. } );
  24070. }
  24071. function ascSort( a, b ) {
  24072. return a.distance - b.distance;
  24073. }
  24074. function intersectObject( object, raycaster, intersects, recursive ) {
  24075. if ( object.visible === false ) return;
  24076. object.raycast( raycaster, intersects );
  24077. if ( recursive === true ) {
  24078. var children = object.children;
  24079. for ( var i = 0, l = children.length; i < l; i ++ ) {
  24080. intersectObject( children[ i ], raycaster, intersects, true );
  24081. }
  24082. }
  24083. }
  24084. Object.assign( Raycaster.prototype, {
  24085. linePrecision: 1,
  24086. set: function ( origin, direction ) {
  24087. // direction is assumed to be normalized (for accurate distance calculations)
  24088. this.ray.set( origin, direction );
  24089. },
  24090. setFromCamera: function ( coords, camera ) {
  24091. if ( ( camera && camera.isPerspectiveCamera ) ) {
  24092. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  24093. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  24094. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  24095. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  24096. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  24097. } else {
  24098. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  24099. }
  24100. },
  24101. intersectObject: function ( object, recursive ) {
  24102. var intersects = [];
  24103. intersectObject( object, this, intersects, recursive );
  24104. intersects.sort( ascSort );
  24105. return intersects;
  24106. },
  24107. intersectObjects: function ( objects, recursive ) {
  24108. var intersects = [];
  24109. if ( Array.isArray( objects ) === false ) {
  24110. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  24111. return intersects;
  24112. }
  24113. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  24114. intersectObject( objects[ i ], this, intersects, recursive );
  24115. }
  24116. intersects.sort( ascSort );
  24117. return intersects;
  24118. }
  24119. } );
  24120. /**
  24121. * @author alteredq / http://alteredqualia.com/
  24122. */
  24123. function Clock( autoStart ) {
  24124. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  24125. this.startTime = 0;
  24126. this.oldTime = 0;
  24127. this.elapsedTime = 0;
  24128. this.running = false;
  24129. }
  24130. Object.assign( Clock.prototype, {
  24131. start: function () {
  24132. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  24133. this.oldTime = this.startTime;
  24134. this.elapsedTime = 0;
  24135. this.running = true;
  24136. },
  24137. stop: function () {
  24138. this.getElapsedTime();
  24139. this.running = false;
  24140. this.autoStart = false;
  24141. },
  24142. getElapsedTime: function () {
  24143. this.getDelta();
  24144. return this.elapsedTime;
  24145. },
  24146. getDelta: function () {
  24147. var diff = 0;
  24148. if ( this.autoStart && ! this.running ) {
  24149. this.start();
  24150. return 0;
  24151. }
  24152. if ( this.running ) {
  24153. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  24154. diff = ( newTime - this.oldTime ) / 1000;
  24155. this.oldTime = newTime;
  24156. this.elapsedTime += diff;
  24157. }
  24158. return diff;
  24159. }
  24160. } );
  24161. /**
  24162. * @author bhouston / http://clara.io
  24163. * @author WestLangley / http://github.com/WestLangley
  24164. *
  24165. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  24166. *
  24167. * The poles (phi) are at the positive and negative y axis.
  24168. * The equator starts at positive z.
  24169. */
  24170. function Spherical( radius, phi, theta ) {
  24171. this.radius = ( radius !== undefined ) ? radius : 1.0;
  24172. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  24173. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  24174. return this;
  24175. }
  24176. Object.assign( Spherical.prototype, {
  24177. set: function ( radius, phi, theta ) {
  24178. this.radius = radius;
  24179. this.phi = phi;
  24180. this.theta = theta;
  24181. return this;
  24182. },
  24183. clone: function () {
  24184. return new this.constructor().copy( this );
  24185. },
  24186. copy: function ( other ) {
  24187. this.radius = other.radius;
  24188. this.phi = other.phi;
  24189. this.theta = other.theta;
  24190. return this;
  24191. },
  24192. // restrict phi to be betwee EPS and PI-EPS
  24193. makeSafe: function() {
  24194. var EPS = 0.000001;
  24195. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  24196. return this;
  24197. },
  24198. setFromVector3: function( vec3 ) {
  24199. this.radius = vec3.length();
  24200. if ( this.radius === 0 ) {
  24201. this.theta = 0;
  24202. this.phi = 0;
  24203. } else {
  24204. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  24205. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  24206. }
  24207. return this;
  24208. }
  24209. } );
  24210. /**
  24211. * @author Mugen87 / https://github.com/Mugen87
  24212. *
  24213. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  24214. *
  24215. */
  24216. function Cylindrical( radius, theta, y ) {
  24217. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  24218. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  24219. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  24220. return this;
  24221. }
  24222. Object.assign( Cylindrical.prototype, {
  24223. set: function ( radius, theta, y ) {
  24224. this.radius = radius;
  24225. this.theta = theta;
  24226. this.y = y;
  24227. return this;
  24228. },
  24229. clone: function () {
  24230. return new this.constructor().copy( this );
  24231. },
  24232. copy: function ( other ) {
  24233. this.radius = other.radius;
  24234. this.theta = other.theta;
  24235. this.y = other.y;
  24236. return this;
  24237. },
  24238. setFromVector3: function( vec3 ) {
  24239. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  24240. this.theta = Math.atan2( vec3.x, vec3.z );
  24241. this.y = vec3.y;
  24242. return this;
  24243. }
  24244. } );
  24245. /**
  24246. * @author alteredq / http://alteredqualia.com/
  24247. */
  24248. function ImmediateRenderObject( material ) {
  24249. Object3D.call( this );
  24250. this.material = material;
  24251. this.render = function ( renderCallback ) {};
  24252. }
  24253. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  24254. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  24255. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  24256. /**
  24257. * @author mrdoob / http://mrdoob.com/
  24258. * @author WestLangley / http://github.com/WestLangley
  24259. */
  24260. function VertexNormalsHelper( object, size, hex, linewidth ) {
  24261. this.object = object;
  24262. this.size = ( size !== undefined ) ? size : 1;
  24263. var color = ( hex !== undefined ) ? hex : 0xff0000;
  24264. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24265. //
  24266. var nNormals = 0;
  24267. var objGeometry = this.object.geometry;
  24268. if ( objGeometry && objGeometry.isGeometry ) {
  24269. nNormals = objGeometry.faces.length * 3;
  24270. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24271. nNormals = objGeometry.attributes.normal.count;
  24272. }
  24273. //
  24274. var geometry = new BufferGeometry();
  24275. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24276. geometry.addAttribute( 'position', positions );
  24277. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24278. //
  24279. this.matrixAutoUpdate = false;
  24280. this.update();
  24281. }
  24282. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24283. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  24284. VertexNormalsHelper.prototype.update = ( function () {
  24285. var v1 = new Vector3();
  24286. var v2 = new Vector3();
  24287. var normalMatrix = new Matrix3();
  24288. return function update() {
  24289. var keys = [ 'a', 'b', 'c' ];
  24290. this.object.updateMatrixWorld( true );
  24291. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24292. var matrixWorld = this.object.matrixWorld;
  24293. var position = this.geometry.attributes.position;
  24294. //
  24295. var objGeometry = this.object.geometry;
  24296. if ( objGeometry && objGeometry.isGeometry ) {
  24297. var vertices = objGeometry.vertices;
  24298. var faces = objGeometry.faces;
  24299. var idx = 0;
  24300. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24301. var face = faces[ i ];
  24302. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  24303. var vertex = vertices[ face[ keys[ j ] ] ];
  24304. var normal = face.vertexNormals[ j ];
  24305. v1.copy( vertex ).applyMatrix4( matrixWorld );
  24306. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24307. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24308. idx = idx + 1;
  24309. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24310. idx = idx + 1;
  24311. }
  24312. }
  24313. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24314. var objPos = objGeometry.attributes.position;
  24315. var objNorm = objGeometry.attributes.normal;
  24316. var idx = 0;
  24317. // for simplicity, ignore index and drawcalls, and render every normal
  24318. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  24319. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  24320. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  24321. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24322. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24323. idx = idx + 1;
  24324. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24325. idx = idx + 1;
  24326. }
  24327. }
  24328. position.needsUpdate = true;
  24329. };
  24330. }() );
  24331. /**
  24332. * @author alteredq / http://alteredqualia.com/
  24333. * @author mrdoob / http://mrdoob.com/
  24334. * @author WestLangley / http://github.com/WestLangley
  24335. */
  24336. function SpotLightHelper( light, color ) {
  24337. Object3D.call( this );
  24338. this.light = light;
  24339. this.light.updateMatrixWorld();
  24340. this.matrix = light.matrixWorld;
  24341. this.matrixAutoUpdate = false;
  24342. this.color = color;
  24343. var geometry = new BufferGeometry();
  24344. var positions = [
  24345. 0, 0, 0, 0, 0, 1,
  24346. 0, 0, 0, 1, 0, 1,
  24347. 0, 0, 0, - 1, 0, 1,
  24348. 0, 0, 0, 0, 1, 1,
  24349. 0, 0, 0, 0, - 1, 1
  24350. ];
  24351. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  24352. var p1 = ( i / l ) * Math.PI * 2;
  24353. var p2 = ( j / l ) * Math.PI * 2;
  24354. positions.push(
  24355. Math.cos( p1 ), Math.sin( p1 ), 1,
  24356. Math.cos( p2 ), Math.sin( p2 ), 1
  24357. );
  24358. }
  24359. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  24360. var material = new LineBasicMaterial( { fog: false } );
  24361. this.cone = new LineSegments( geometry, material );
  24362. this.add( this.cone );
  24363. this.update();
  24364. }
  24365. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  24366. SpotLightHelper.prototype.constructor = SpotLightHelper;
  24367. SpotLightHelper.prototype.dispose = function () {
  24368. this.cone.geometry.dispose();
  24369. this.cone.material.dispose();
  24370. };
  24371. SpotLightHelper.prototype.update = function () {
  24372. var vector = new Vector3();
  24373. var vector2 = new Vector3();
  24374. return function update() {
  24375. this.light.updateMatrixWorld();
  24376. var coneLength = this.light.distance ? this.light.distance : 1000;
  24377. var coneWidth = coneLength * Math.tan( this.light.angle );
  24378. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  24379. vector.setFromMatrixPosition( this.light.matrixWorld );
  24380. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24381. this.cone.lookAt( vector2.sub( vector ) );
  24382. if ( this.color !== undefined ) {
  24383. this.cone.material.color.set( this.color );
  24384. } else {
  24385. this.cone.material.color.copy( this.light.color );
  24386. }
  24387. };
  24388. }();
  24389. /**
  24390. * @author Sean Griffin / http://twitter.com/sgrif
  24391. * @author Michael Guerrero / http://realitymeltdown.com
  24392. * @author mrdoob / http://mrdoob.com/
  24393. * @author ikerr / http://verold.com
  24394. * @author Mugen87 / https://github.com/Mugen87
  24395. */
  24396. function getBoneList( object ) {
  24397. var boneList = [];
  24398. if ( object && object.isBone ) {
  24399. boneList.push( object );
  24400. }
  24401. for ( var i = 0; i < object.children.length; i ++ ) {
  24402. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  24403. }
  24404. return boneList;
  24405. }
  24406. function SkeletonHelper( object ) {
  24407. var bones = getBoneList( object );
  24408. var geometry = new BufferGeometry();
  24409. var vertices = [];
  24410. var colors = [];
  24411. var color1 = new Color( 0, 0, 1 );
  24412. var color2 = new Color( 0, 1, 0 );
  24413. for ( var i = 0; i < bones.length; i ++ ) {
  24414. var bone = bones[ i ];
  24415. if ( bone.parent && bone.parent.isBone ) {
  24416. vertices.push( 0, 0, 0 );
  24417. vertices.push( 0, 0, 0 );
  24418. colors.push( color1.r, color1.g, color1.b );
  24419. colors.push( color2.r, color2.g, color2.b );
  24420. }
  24421. }
  24422. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24423. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24424. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  24425. LineSegments.call( this, geometry, material );
  24426. this.root = object;
  24427. this.bones = bones;
  24428. this.matrix = object.matrixWorld;
  24429. this.matrixAutoUpdate = false;
  24430. this.onBeforeRender();
  24431. }
  24432. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  24433. SkeletonHelper.prototype.constructor = SkeletonHelper;
  24434. SkeletonHelper.prototype.onBeforeRender = function () {
  24435. var vector = new Vector3();
  24436. var boneMatrix = new Matrix4();
  24437. var matrixWorldInv = new Matrix4();
  24438. return function onBeforeRender() {
  24439. var bones = this.bones;
  24440. var geometry = this.geometry;
  24441. var position = geometry.getAttribute( 'position' );
  24442. matrixWorldInv.getInverse( this.root.matrixWorld );
  24443. for ( var i = 0, j = 0; i < bones.length; i ++ ) {
  24444. var bone = bones[ i ];
  24445. if ( bone.parent && bone.parent.isBone ) {
  24446. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  24447. vector.setFromMatrixPosition( boneMatrix );
  24448. position.setXYZ( j, vector.x, vector.y, vector.z );
  24449. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  24450. vector.setFromMatrixPosition( boneMatrix );
  24451. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  24452. j += 2;
  24453. }
  24454. }
  24455. geometry.getAttribute( 'position' ).needsUpdate = true;
  24456. };
  24457. }();
  24458. /**
  24459. * @author alteredq / http://alteredqualia.com/
  24460. * @author mrdoob / http://mrdoob.com/
  24461. */
  24462. function PointLightHelper( light, sphereSize, color ) {
  24463. this.light = light;
  24464. this.light.updateMatrixWorld();
  24465. this.color = color;
  24466. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  24467. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  24468. Mesh.call( this, geometry, material );
  24469. this.matrix = this.light.matrixWorld;
  24470. this.matrixAutoUpdate = false;
  24471. this.update();
  24472. /*
  24473. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  24474. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  24475. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  24476. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  24477. var d = light.distance;
  24478. if ( d === 0.0 ) {
  24479. this.lightDistance.visible = false;
  24480. } else {
  24481. this.lightDistance.scale.set( d, d, d );
  24482. }
  24483. this.add( this.lightDistance );
  24484. */
  24485. }
  24486. PointLightHelper.prototype = Object.create( Mesh.prototype );
  24487. PointLightHelper.prototype.constructor = PointLightHelper;
  24488. PointLightHelper.prototype.dispose = function () {
  24489. this.geometry.dispose();
  24490. this.material.dispose();
  24491. };
  24492. PointLightHelper.prototype.update = function () {
  24493. if ( this.color !== undefined ) {
  24494. this.material.color.set( this.color );
  24495. } else {
  24496. this.material.color.copy( this.light.color );
  24497. }
  24498. /*
  24499. var d = this.light.distance;
  24500. if ( d === 0.0 ) {
  24501. this.lightDistance.visible = false;
  24502. } else {
  24503. this.lightDistance.visible = true;
  24504. this.lightDistance.scale.set( d, d, d );
  24505. }
  24506. */
  24507. };
  24508. /**
  24509. * @author abelnation / http://github.com/abelnation
  24510. * @author Mugen87 / http://github.com/Mugen87
  24511. * @author WestLangley / http://github.com/WestLangley
  24512. */
  24513. function RectAreaLightHelper( light, color ) {
  24514. Object3D.call( this );
  24515. this.light = light;
  24516. this.light.updateMatrixWorld();
  24517. this.matrix = light.matrixWorld;
  24518. this.matrixAutoUpdate = false;
  24519. this.color = color;
  24520. var material = new LineBasicMaterial( { fog: false } );
  24521. var geometry = new BufferGeometry();
  24522. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 5 * 3 ), 3 ) );
  24523. this.line = new Line( geometry, material );
  24524. this.add( this.line );
  24525. this.update();
  24526. }
  24527. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  24528. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  24529. RectAreaLightHelper.prototype.dispose = function () {
  24530. this.children[ 0 ].geometry.dispose();
  24531. this.children[ 0 ].material.dispose();
  24532. };
  24533. RectAreaLightHelper.prototype.update = function () {
  24534. // calculate new dimensions of the helper
  24535. var hx = this.light.width * 0.5;
  24536. var hy = this.light.height * 0.5;
  24537. var position = this.line.geometry.attributes.position;
  24538. var array = position.array;
  24539. // update vertices
  24540. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  24541. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  24542. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  24543. array[ 9 ] = - hx; array[ 10 ] = - hy; array[ 11 ] = 0;
  24544. array[ 12 ] = hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  24545. position.needsUpdate = true;
  24546. if ( this.color !== undefined ) {
  24547. this.line.material.color.set( this.color );
  24548. } else {
  24549. this.line.material.color.copy( this.light.color );
  24550. }
  24551. };
  24552. /**
  24553. * @author alteredq / http://alteredqualia.com/
  24554. * @author mrdoob / http://mrdoob.com/
  24555. * @author Mugen87 / https://github.com/Mugen87
  24556. */
  24557. function HemisphereLightHelper( light, size, color ) {
  24558. Object3D.call( this );
  24559. this.light = light;
  24560. this.light.updateMatrixWorld();
  24561. this.matrix = light.matrixWorld;
  24562. this.matrixAutoUpdate = false;
  24563. this.color = color;
  24564. var geometry = new OctahedronBufferGeometry( size );
  24565. geometry.rotateY( Math.PI * 0.5 );
  24566. this.material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  24567. if ( this.color === undefined ) this.material.vertexColors = VertexColors;
  24568. var position = geometry.getAttribute( 'position' );
  24569. var colors = new Float32Array( position.count * 3 );
  24570. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  24571. this.add( new Mesh( geometry, this.material ) );
  24572. this.update();
  24573. }
  24574. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  24575. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  24576. HemisphereLightHelper.prototype.dispose = function () {
  24577. this.children[ 0 ].geometry.dispose();
  24578. this.children[ 0 ].material.dispose();
  24579. };
  24580. HemisphereLightHelper.prototype.update = function () {
  24581. var vector = new Vector3();
  24582. var color1 = new Color();
  24583. var color2 = new Color();
  24584. return function update() {
  24585. var mesh = this.children[ 0 ];
  24586. if ( this.color !== undefined ) {
  24587. this.material.color.set( this.color );
  24588. } else {
  24589. var colors = mesh.geometry.getAttribute( 'color' );
  24590. color1.copy( this.light.color );
  24591. color2.copy( this.light.groundColor );
  24592. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  24593. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  24594. colors.setXYZ( i, color.r, color.g, color.b );
  24595. }
  24596. colors.needsUpdate = true;
  24597. }
  24598. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  24599. };
  24600. }();
  24601. /**
  24602. * @author mrdoob / http://mrdoob.com/
  24603. */
  24604. function GridHelper( size, divisions, color1, color2 ) {
  24605. size = size || 10;
  24606. divisions = divisions || 10;
  24607. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24608. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24609. var center = divisions / 2;
  24610. var step = size / divisions;
  24611. var halfSize = size / 2;
  24612. var vertices = [], colors = [];
  24613. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  24614. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  24615. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  24616. var color = i === center ? color1 : color2;
  24617. color.toArray( colors, j ); j += 3;
  24618. color.toArray( colors, j ); j += 3;
  24619. color.toArray( colors, j ); j += 3;
  24620. color.toArray( colors, j ); j += 3;
  24621. }
  24622. var geometry = new BufferGeometry();
  24623. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24624. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24625. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24626. LineSegments.call( this, geometry, material );
  24627. }
  24628. GridHelper.prototype = Object.create( LineSegments.prototype );
  24629. GridHelper.prototype.constructor = GridHelper;
  24630. /**
  24631. * @author mrdoob / http://mrdoob.com/
  24632. * @author Mugen87 / http://github.com/Mugen87
  24633. * @author Hectate / http://www.github.com/Hectate
  24634. */
  24635. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  24636. radius = radius || 10;
  24637. radials = radials || 16;
  24638. circles = circles || 8;
  24639. divisions = divisions || 64;
  24640. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24641. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24642. var vertices = [];
  24643. var colors = [];
  24644. var x, z;
  24645. var v, i, j, r, color;
  24646. // create the radials
  24647. for ( i = 0; i <= radials; i ++ ) {
  24648. v = ( i / radials ) * ( Math.PI * 2 );
  24649. x = Math.sin( v ) * radius;
  24650. z = Math.cos( v ) * radius;
  24651. vertices.push( 0, 0, 0 );
  24652. vertices.push( x, 0, z );
  24653. color = ( i & 1 ) ? color1 : color2;
  24654. colors.push( color.r, color.g, color.b );
  24655. colors.push( color.r, color.g, color.b );
  24656. }
  24657. // create the circles
  24658. for ( i = 0; i <= circles; i ++ ) {
  24659. color = ( i & 1 ) ? color1 : color2;
  24660. r = radius - ( radius / circles * i );
  24661. for ( j = 0; j < divisions; j ++ ) {
  24662. // first vertex
  24663. v = ( j / divisions ) * ( Math.PI * 2 );
  24664. x = Math.sin( v ) * r;
  24665. z = Math.cos( v ) * r;
  24666. vertices.push( x, 0, z );
  24667. colors.push( color.r, color.g, color.b );
  24668. // second vertex
  24669. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  24670. x = Math.sin( v ) * r;
  24671. z = Math.cos( v ) * r;
  24672. vertices.push( x, 0, z );
  24673. colors.push( color.r, color.g, color.b );
  24674. }
  24675. }
  24676. var geometry = new BufferGeometry();
  24677. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24678. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24679. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24680. LineSegments.call( this, geometry, material );
  24681. }
  24682. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  24683. PolarGridHelper.prototype.constructor = PolarGridHelper;
  24684. /**
  24685. * @author mrdoob / http://mrdoob.com/
  24686. * @author WestLangley / http://github.com/WestLangley
  24687. */
  24688. function FaceNormalsHelper( object, size, hex, linewidth ) {
  24689. // FaceNormalsHelper only supports THREE.Geometry
  24690. this.object = object;
  24691. this.size = ( size !== undefined ) ? size : 1;
  24692. var color = ( hex !== undefined ) ? hex : 0xffff00;
  24693. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24694. //
  24695. var nNormals = 0;
  24696. var objGeometry = this.object.geometry;
  24697. if ( objGeometry && objGeometry.isGeometry ) {
  24698. nNormals = objGeometry.faces.length;
  24699. } else {
  24700. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  24701. }
  24702. //
  24703. var geometry = new BufferGeometry();
  24704. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24705. geometry.addAttribute( 'position', positions );
  24706. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24707. //
  24708. this.matrixAutoUpdate = false;
  24709. this.update();
  24710. }
  24711. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24712. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  24713. FaceNormalsHelper.prototype.update = ( function () {
  24714. var v1 = new Vector3();
  24715. var v2 = new Vector3();
  24716. var normalMatrix = new Matrix3();
  24717. return function update() {
  24718. this.object.updateMatrixWorld( true );
  24719. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24720. var matrixWorld = this.object.matrixWorld;
  24721. var position = this.geometry.attributes.position;
  24722. //
  24723. var objGeometry = this.object.geometry;
  24724. var vertices = objGeometry.vertices;
  24725. var faces = objGeometry.faces;
  24726. var idx = 0;
  24727. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24728. var face = faces[ i ];
  24729. var normal = face.normal;
  24730. v1.copy( vertices[ face.a ] )
  24731. .add( vertices[ face.b ] )
  24732. .add( vertices[ face.c ] )
  24733. .divideScalar( 3 )
  24734. .applyMatrix4( matrixWorld );
  24735. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24736. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24737. idx = idx + 1;
  24738. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24739. idx = idx + 1;
  24740. }
  24741. position.needsUpdate = true;
  24742. };
  24743. }() );
  24744. /**
  24745. * @author alteredq / http://alteredqualia.com/
  24746. * @author mrdoob / http://mrdoob.com/
  24747. * @author WestLangley / http://github.com/WestLangley
  24748. */
  24749. function DirectionalLightHelper( light, size, color ) {
  24750. Object3D.call( this );
  24751. this.light = light;
  24752. this.light.updateMatrixWorld();
  24753. this.matrix = light.matrixWorld;
  24754. this.matrixAutoUpdate = false;
  24755. this.color = color;
  24756. if ( size === undefined ) size = 1;
  24757. var geometry = new BufferGeometry();
  24758. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  24759. - size, size, 0,
  24760. size, size, 0,
  24761. size, - size, 0,
  24762. - size, - size, 0,
  24763. - size, size, 0
  24764. ], 3 ) );
  24765. var material = new LineBasicMaterial( { fog: false } );
  24766. this.lightPlane = new Line( geometry, material );
  24767. this.add( this.lightPlane );
  24768. geometry = new BufferGeometry();
  24769. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  24770. this.targetLine = new Line( geometry, material );
  24771. this.add( this.targetLine );
  24772. this.update();
  24773. }
  24774. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  24775. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  24776. DirectionalLightHelper.prototype.dispose = function () {
  24777. this.lightPlane.geometry.dispose();
  24778. this.lightPlane.material.dispose();
  24779. this.targetLine.geometry.dispose();
  24780. this.targetLine.material.dispose();
  24781. };
  24782. DirectionalLightHelper.prototype.update = function () {
  24783. var v1 = new Vector3();
  24784. var v2 = new Vector3();
  24785. var v3 = new Vector3();
  24786. return function update() {
  24787. v1.setFromMatrixPosition( this.light.matrixWorld );
  24788. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  24789. v3.subVectors( v2, v1 );
  24790. this.lightPlane.lookAt( v3 );
  24791. if ( this.color !== undefined ) {
  24792. this.lightPlane.material.color.set( this.color );
  24793. this.targetLine.material.color.set( this.color );
  24794. } else {
  24795. this.lightPlane.material.color.copy( this.light.color );
  24796. this.targetLine.material.color.copy( this.light.color );
  24797. }
  24798. this.targetLine.lookAt( v3 );
  24799. this.targetLine.scale.z = v3.length();
  24800. };
  24801. }();
  24802. /**
  24803. * @author alteredq / http://alteredqualia.com/
  24804. * @author Mugen87 / https://github.com/Mugen87
  24805. *
  24806. * - shows frustum, line of sight and up of the camera
  24807. * - suitable for fast updates
  24808. * - based on frustum visualization in lightgl.js shadowmap example
  24809. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  24810. */
  24811. function CameraHelper( camera ) {
  24812. var geometry = new BufferGeometry();
  24813. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  24814. var vertices = [];
  24815. var colors = [];
  24816. var pointMap = {};
  24817. // colors
  24818. var colorFrustum = new Color( 0xffaa00 );
  24819. var colorCone = new Color( 0xff0000 );
  24820. var colorUp = new Color( 0x00aaff );
  24821. var colorTarget = new Color( 0xffffff );
  24822. var colorCross = new Color( 0x333333 );
  24823. // near
  24824. addLine( "n1", "n2", colorFrustum );
  24825. addLine( "n2", "n4", colorFrustum );
  24826. addLine( "n4", "n3", colorFrustum );
  24827. addLine( "n3", "n1", colorFrustum );
  24828. // far
  24829. addLine( "f1", "f2", colorFrustum );
  24830. addLine( "f2", "f4", colorFrustum );
  24831. addLine( "f4", "f3", colorFrustum );
  24832. addLine( "f3", "f1", colorFrustum );
  24833. // sides
  24834. addLine( "n1", "f1", colorFrustum );
  24835. addLine( "n2", "f2", colorFrustum );
  24836. addLine( "n3", "f3", colorFrustum );
  24837. addLine( "n4", "f4", colorFrustum );
  24838. // cone
  24839. addLine( "p", "n1", colorCone );
  24840. addLine( "p", "n2", colorCone );
  24841. addLine( "p", "n3", colorCone );
  24842. addLine( "p", "n4", colorCone );
  24843. // up
  24844. addLine( "u1", "u2", colorUp );
  24845. addLine( "u2", "u3", colorUp );
  24846. addLine( "u3", "u1", colorUp );
  24847. // target
  24848. addLine( "c", "t", colorTarget );
  24849. addLine( "p", "c", colorCross );
  24850. // cross
  24851. addLine( "cn1", "cn2", colorCross );
  24852. addLine( "cn3", "cn4", colorCross );
  24853. addLine( "cf1", "cf2", colorCross );
  24854. addLine( "cf3", "cf4", colorCross );
  24855. function addLine( a, b, color ) {
  24856. addPoint( a, color );
  24857. addPoint( b, color );
  24858. }
  24859. function addPoint( id, color ) {
  24860. vertices.push( 0, 0, 0 );
  24861. colors.push( color.r, color.g, color.b );
  24862. if ( pointMap[ id ] === undefined ) {
  24863. pointMap[ id ] = [];
  24864. }
  24865. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  24866. }
  24867. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24868. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24869. LineSegments.call( this, geometry, material );
  24870. this.camera = camera;
  24871. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  24872. this.matrix = camera.matrixWorld;
  24873. this.matrixAutoUpdate = false;
  24874. this.pointMap = pointMap;
  24875. this.update();
  24876. }
  24877. CameraHelper.prototype = Object.create( LineSegments.prototype );
  24878. CameraHelper.prototype.constructor = CameraHelper;
  24879. CameraHelper.prototype.update = function () {
  24880. var geometry, pointMap;
  24881. var vector = new Vector3();
  24882. var camera = new Camera();
  24883. function setPoint( point, x, y, z ) {
  24884. vector.set( x, y, z ).unproject( camera );
  24885. var points = pointMap[ point ];
  24886. if ( points !== undefined ) {
  24887. var position = geometry.getAttribute( 'position' );
  24888. for ( var i = 0, l = points.length; i < l; i ++ ) {
  24889. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  24890. }
  24891. }
  24892. }
  24893. return function update() {
  24894. geometry = this.geometry;
  24895. pointMap = this.pointMap;
  24896. var w = 1, h = 1;
  24897. // we need just camera projection matrix
  24898. // world matrix must be identity
  24899. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  24900. // center / target
  24901. setPoint( "c", 0, 0, - 1 );
  24902. setPoint( "t", 0, 0, 1 );
  24903. // near
  24904. setPoint( "n1", - w, - h, - 1 );
  24905. setPoint( "n2", w, - h, - 1 );
  24906. setPoint( "n3", - w, h, - 1 );
  24907. setPoint( "n4", w, h, - 1 );
  24908. // far
  24909. setPoint( "f1", - w, - h, 1 );
  24910. setPoint( "f2", w, - h, 1 );
  24911. setPoint( "f3", - w, h, 1 );
  24912. setPoint( "f4", w, h, 1 );
  24913. // up
  24914. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  24915. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  24916. setPoint( "u3", 0, h * 2, - 1 );
  24917. // cross
  24918. setPoint( "cf1", - w, 0, 1 );
  24919. setPoint( "cf2", w, 0, 1 );
  24920. setPoint( "cf3", 0, - h, 1 );
  24921. setPoint( "cf4", 0, h, 1 );
  24922. setPoint( "cn1", - w, 0, - 1 );
  24923. setPoint( "cn2", w, 0, - 1 );
  24924. setPoint( "cn3", 0, - h, - 1 );
  24925. setPoint( "cn4", 0, h, - 1 );
  24926. geometry.getAttribute( 'position' ).needsUpdate = true;
  24927. };
  24928. }();
  24929. /**
  24930. * @author mrdoob / http://mrdoob.com/
  24931. * @author Mugen87 / http://github.com/Mugen87
  24932. */
  24933. function BoxHelper( object, color ) {
  24934. this.object = object;
  24935. if ( color === undefined ) color = 0xffff00;
  24936. 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 ] );
  24937. var positions = new Float32Array( 8 * 3 );
  24938. var geometry = new BufferGeometry();
  24939. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  24940. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  24941. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  24942. this.matrixAutoUpdate = false;
  24943. this.update();
  24944. }
  24945. BoxHelper.prototype = Object.create( LineSegments.prototype );
  24946. BoxHelper.prototype.constructor = BoxHelper;
  24947. BoxHelper.prototype.update = ( function () {
  24948. var box = new Box3();
  24949. return function update( object ) {
  24950. if ( object !== undefined ) {
  24951. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  24952. }
  24953. if ( this.object !== undefined ) {
  24954. box.setFromObject( this.object );
  24955. }
  24956. if ( box.isEmpty() ) return;
  24957. var min = box.min;
  24958. var max = box.max;
  24959. /*
  24960. 5____4
  24961. 1/___0/|
  24962. | 6__|_7
  24963. 2/___3/
  24964. 0: max.x, max.y, max.z
  24965. 1: min.x, max.y, max.z
  24966. 2: min.x, min.y, max.z
  24967. 3: max.x, min.y, max.z
  24968. 4: max.x, max.y, min.z
  24969. 5: min.x, max.y, min.z
  24970. 6: min.x, min.y, min.z
  24971. 7: max.x, min.y, min.z
  24972. */
  24973. var position = this.geometry.attributes.position;
  24974. var array = position.array;
  24975. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  24976. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  24977. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  24978. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  24979. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  24980. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  24981. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  24982. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  24983. position.needsUpdate = true;
  24984. this.geometry.computeBoundingSphere();
  24985. };
  24986. } )();
  24987. BoxHelper.prototype.setFromObject = function ( object ) {
  24988. this.object = object;
  24989. this.update();
  24990. return this;
  24991. };
  24992. /**
  24993. * @author WestLangley / http://github.com/WestLangley
  24994. */
  24995. function Box3Helper( box, hex ) {
  24996. this.type = 'Box3Helper';
  24997. this.box = box;
  24998. var color = ( hex !== undefined ) ? hex : 0xffff00;
  24999. 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 ] );
  25000. 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 ];
  25001. var geometry = new BufferGeometry();
  25002. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  25003. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  25004. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  25005. this.geometry.computeBoundingSphere();
  25006. this.onBeforeRender();
  25007. }
  25008. Box3Helper.prototype = Object.create( LineSegments.prototype );
  25009. Box3Helper.prototype.constructor = Box3Helper;
  25010. Box3Helper.prototype.onBeforeRender = function () {
  25011. var box = this.box;
  25012. if ( box.isEmpty() ) return;
  25013. box.getCenter( this.position );
  25014. box.getSize( this.scale );
  25015. this.scale.multiplyScalar( 0.5 );
  25016. };
  25017. /**
  25018. * @author WestLangley / http://github.com/WestLangley
  25019. */
  25020. function PlaneHelper( plane, size, hex ) {
  25021. this.type = 'PlaneHelper';
  25022. this.plane = plane;
  25023. this.size = ( size === undefined ) ? 1 : size;
  25024. var color = ( hex !== undefined ) ? hex : 0xffff00;
  25025. 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 ];
  25026. var geometry = new BufferGeometry();
  25027. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  25028. geometry.computeBoundingSphere();
  25029. Line.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  25030. //
  25031. var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  25032. var geometry2 = new BufferGeometry();
  25033. geometry2.addAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  25034. geometry2.computeBoundingSphere();
  25035. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false } ) ) );
  25036. //
  25037. this.onBeforeRender();
  25038. }
  25039. PlaneHelper.prototype = Object.create( Line.prototype );
  25040. PlaneHelper.prototype.constructor = PlaneHelper;
  25041. PlaneHelper.prototype.onBeforeRender = function () {
  25042. var scale = - this.plane.constant;
  25043. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  25044. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  25045. this.lookAt( this.plane.normal );
  25046. this.updateMatrixWorld();
  25047. };
  25048. /**
  25049. * @author WestLangley / http://github.com/WestLangley
  25050. * @author zz85 / http://github.com/zz85
  25051. * @author bhouston / http://clara.io
  25052. *
  25053. * Creates an arrow for visualizing directions
  25054. *
  25055. * Parameters:
  25056. * dir - Vector3
  25057. * origin - Vector3
  25058. * length - Number
  25059. * color - color in hex value
  25060. * headLength - Number
  25061. * headWidth - Number
  25062. */
  25063. var lineGeometry;
  25064. var coneGeometry;
  25065. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  25066. // dir is assumed to be normalized
  25067. Object3D.call( this );
  25068. if ( color === undefined ) color = 0xffff00;
  25069. if ( length === undefined ) length = 1;
  25070. if ( headLength === undefined ) headLength = 0.2 * length;
  25071. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  25072. if ( lineGeometry === undefined ) {
  25073. lineGeometry = new BufferGeometry();
  25074. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  25075. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  25076. coneGeometry.translate( 0, - 0.5, 0 );
  25077. }
  25078. this.position.copy( origin );
  25079. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  25080. this.line.matrixAutoUpdate = false;
  25081. this.add( this.line );
  25082. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  25083. this.cone.matrixAutoUpdate = false;
  25084. this.add( this.cone );
  25085. this.setDirection( dir );
  25086. this.setLength( length, headLength, headWidth );
  25087. }
  25088. ArrowHelper.prototype = Object.create( Object3D.prototype );
  25089. ArrowHelper.prototype.constructor = ArrowHelper;
  25090. ArrowHelper.prototype.setDirection = ( function () {
  25091. var axis = new Vector3();
  25092. var radians;
  25093. return function setDirection( dir ) {
  25094. // dir is assumed to be normalized
  25095. if ( dir.y > 0.99999 ) {
  25096. this.quaternion.set( 0, 0, 0, 1 );
  25097. } else if ( dir.y < - 0.99999 ) {
  25098. this.quaternion.set( 1, 0, 0, 0 );
  25099. } else {
  25100. axis.set( dir.z, 0, - dir.x ).normalize();
  25101. radians = Math.acos( dir.y );
  25102. this.quaternion.setFromAxisAngle( axis, radians );
  25103. }
  25104. };
  25105. }() );
  25106. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  25107. if ( headLength === undefined ) headLength = 0.2 * length;
  25108. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  25109. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  25110. this.line.updateMatrix();
  25111. this.cone.scale.set( headWidth, headLength, headWidth );
  25112. this.cone.position.y = length;
  25113. this.cone.updateMatrix();
  25114. };
  25115. ArrowHelper.prototype.setColor = function ( color ) {
  25116. this.line.material.color.copy( color );
  25117. this.cone.material.color.copy( color );
  25118. };
  25119. /**
  25120. * @author sroucheray / http://sroucheray.org/
  25121. * @author mrdoob / http://mrdoob.com/
  25122. */
  25123. function AxisHelper( size ) {
  25124. size = size || 1;
  25125. var vertices = [
  25126. 0, 0, 0, size, 0, 0,
  25127. 0, 0, 0, 0, size, 0,
  25128. 0, 0, 0, 0, 0, size
  25129. ];
  25130. var colors = [
  25131. 1, 0, 0, 1, 0.6, 0,
  25132. 0, 1, 0, 0.6, 1, 0,
  25133. 0, 0, 1, 0, 0.6, 1
  25134. ];
  25135. var geometry = new BufferGeometry();
  25136. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25137. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  25138. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  25139. LineSegments.call( this, geometry, material );
  25140. }
  25141. AxisHelper.prototype = Object.create( LineSegments.prototype );
  25142. AxisHelper.prototype.constructor = AxisHelper;
  25143. /**
  25144. * @author zz85 https://github.com/zz85
  25145. *
  25146. * Centripetal CatmullRom Curve - which is useful for avoiding
  25147. * cusps and self-intersections in non-uniform catmull rom curves.
  25148. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  25149. *
  25150. * curve.type accepts centripetal(default), chordal and catmullrom
  25151. * curve.tension is used for catmullrom which defaults to 0.5
  25152. */
  25153. /*
  25154. Based on an optimized c++ solution in
  25155. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  25156. - http://ideone.com/NoEbVM
  25157. This CubicPoly class could be used for reusing some variables and calculations,
  25158. but for three.js curve use, it could be possible inlined and flatten into a single function call
  25159. which can be placed in CurveUtils.
  25160. */
  25161. function CubicPoly() {
  25162. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  25163. /*
  25164. * Compute coefficients for a cubic polynomial
  25165. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  25166. * such that
  25167. * p(0) = x0, p(1) = x1
  25168. * and
  25169. * p'(0) = t0, p'(1) = t1.
  25170. */
  25171. function init( x0, x1, t0, t1 ) {
  25172. c0 = x0;
  25173. c1 = t0;
  25174. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  25175. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  25176. }
  25177. return {
  25178. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  25179. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  25180. },
  25181. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  25182. // compute tangents when parameterized in [t1,t2]
  25183. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  25184. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  25185. // rescale tangents for parametrization in [0,1]
  25186. t1 *= dt1;
  25187. t2 *= dt1;
  25188. init( x1, x2, t1, t2 );
  25189. },
  25190. calc: function ( t ) {
  25191. var t2 = t * t;
  25192. var t3 = t2 * t;
  25193. return c0 + c1 * t + c2 * t2 + c3 * t3;
  25194. }
  25195. };
  25196. }
  25197. //
  25198. var tmp = new Vector3();
  25199. var px = new CubicPoly();
  25200. var py = new CubicPoly();
  25201. var pz = new CubicPoly();
  25202. function CatmullRomCurve3( points ) {
  25203. Curve.call( this );
  25204. if ( points.length < 2 ) console.warn( 'THREE.CatmullRomCurve3: Points array needs at least two entries.' );
  25205. this.points = points || [];
  25206. this.closed = false;
  25207. }
  25208. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  25209. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  25210. CatmullRomCurve3.prototype.getPoint = function ( t ) {
  25211. var points = this.points;
  25212. var l = points.length;
  25213. var point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  25214. var intPoint = Math.floor( point );
  25215. var weight = point - intPoint;
  25216. if ( this.closed ) {
  25217. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  25218. } else if ( weight === 0 && intPoint === l - 1 ) {
  25219. intPoint = l - 2;
  25220. weight = 1;
  25221. }
  25222. var p0, p1, p2, p3; // 4 points
  25223. if ( this.closed || intPoint > 0 ) {
  25224. p0 = points[ ( intPoint - 1 ) % l ];
  25225. } else {
  25226. // extrapolate first point
  25227. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  25228. p0 = tmp;
  25229. }
  25230. p1 = points[ intPoint % l ];
  25231. p2 = points[ ( intPoint + 1 ) % l ];
  25232. if ( this.closed || intPoint + 2 < l ) {
  25233. p3 = points[ ( intPoint + 2 ) % l ];
  25234. } else {
  25235. // extrapolate last point
  25236. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  25237. p3 = tmp;
  25238. }
  25239. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  25240. // init Centripetal / Chordal Catmull-Rom
  25241. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  25242. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  25243. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  25244. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  25245. // safety check for repeated points
  25246. if ( dt1 < 1e-4 ) dt1 = 1.0;
  25247. if ( dt0 < 1e-4 ) dt0 = dt1;
  25248. if ( dt2 < 1e-4 ) dt2 = dt1;
  25249. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  25250. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  25251. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  25252. } else if ( this.type === 'catmullrom' ) {
  25253. var tension = this.tension !== undefined ? this.tension : 0.5;
  25254. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  25255. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  25256. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  25257. }
  25258. return new Vector3( px.calc( weight ), py.calc( weight ), pz.calc( weight ) );
  25259. };
  25260. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  25261. Curve.call( this );
  25262. this.v0 = v0;
  25263. this.v1 = v1;
  25264. this.v2 = v2;
  25265. this.v3 = v3;
  25266. }
  25267. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  25268. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  25269. CubicBezierCurve3.prototype.getPoint = function ( t ) {
  25270. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  25271. return new Vector3(
  25272. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  25273. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  25274. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  25275. );
  25276. };
  25277. function QuadraticBezierCurve3( v0, v1, v2 ) {
  25278. Curve.call( this );
  25279. this.v0 = v0;
  25280. this.v1 = v1;
  25281. this.v2 = v2;
  25282. }
  25283. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  25284. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  25285. QuadraticBezierCurve3.prototype.getPoint = function ( t ) {
  25286. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  25287. return new Vector3(
  25288. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  25289. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  25290. QuadraticBezier( t, v0.z, v1.z, v2.z )
  25291. );
  25292. };
  25293. function LineCurve3( v1, v2 ) {
  25294. Curve.call( this );
  25295. this.v1 = v1;
  25296. this.v2 = v2;
  25297. }
  25298. LineCurve3.prototype = Object.create( Curve.prototype );
  25299. LineCurve3.prototype.constructor = LineCurve3;
  25300. LineCurve3.prototype.getPoint = function ( t ) {
  25301. if ( t === 1 ) {
  25302. return this.v2.clone();
  25303. }
  25304. var vector = new Vector3();
  25305. vector.subVectors( this.v2, this.v1 ); // diff
  25306. vector.multiplyScalar( t );
  25307. vector.add( this.v1 );
  25308. return vector;
  25309. };
  25310. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25311. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25312. }
  25313. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  25314. ArcCurve.prototype.constructor = ArcCurve;
  25315. /**
  25316. * @author alteredq / http://alteredqualia.com/
  25317. */
  25318. var SceneUtils = {
  25319. createMultiMaterialObject: function ( geometry, materials ) {
  25320. var group = new Group();
  25321. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  25322. group.add( new Mesh( geometry, materials[ i ] ) );
  25323. }
  25324. return group;
  25325. },
  25326. detach: function ( child, parent, scene ) {
  25327. child.applyMatrix( parent.matrixWorld );
  25328. parent.remove( child );
  25329. scene.add( child );
  25330. },
  25331. attach: function ( child, scene, parent ) {
  25332. child.applyMatrix( new Matrix4().getInverse( parent.matrixWorld ) );
  25333. scene.remove( child );
  25334. parent.add( child );
  25335. }
  25336. };
  25337. /**
  25338. * @author mrdoob / http://mrdoob.com/
  25339. */
  25340. function Face4( a, b, c, d, normal, color, materialIndex ) {
  25341. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  25342. return new Face3( a, b, c, normal, color, materialIndex );
  25343. }
  25344. var LineStrip = 0;
  25345. var LinePieces = 1;
  25346. function MeshFaceMaterial( materials ) {
  25347. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  25348. return materials;
  25349. }
  25350. function MultiMaterial( materials ) {
  25351. if ( materials === undefined ) materials = [];
  25352. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  25353. materials.isMultiMaterial = true;
  25354. materials.materials = materials;
  25355. materials.clone = function () {
  25356. return materials.slice();
  25357. };
  25358. return materials;
  25359. }
  25360. function PointCloud( geometry, material ) {
  25361. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  25362. return new Points( geometry, material );
  25363. }
  25364. function Particle( material ) {
  25365. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  25366. return new Sprite( material );
  25367. }
  25368. function ParticleSystem( geometry, material ) {
  25369. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  25370. return new Points( geometry, material );
  25371. }
  25372. function PointCloudMaterial( parameters ) {
  25373. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  25374. return new PointsMaterial( parameters );
  25375. }
  25376. function ParticleBasicMaterial( parameters ) {
  25377. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  25378. return new PointsMaterial( parameters );
  25379. }
  25380. function ParticleSystemMaterial( parameters ) {
  25381. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  25382. return new PointsMaterial( parameters );
  25383. }
  25384. function Vertex( x, y, z ) {
  25385. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  25386. return new Vector3( x, y, z );
  25387. }
  25388. //
  25389. function DynamicBufferAttribute( array, itemSize ) {
  25390. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  25391. return new BufferAttribute( array, itemSize ).setDynamic( true );
  25392. }
  25393. function Int8Attribute( array, itemSize ) {
  25394. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  25395. return new Int8BufferAttribute( array, itemSize );
  25396. }
  25397. function Uint8Attribute( array, itemSize ) {
  25398. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  25399. return new Uint8BufferAttribute( array, itemSize );
  25400. }
  25401. function Uint8ClampedAttribute( array, itemSize ) {
  25402. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  25403. return new Uint8ClampedBufferAttribute( array, itemSize );
  25404. }
  25405. function Int16Attribute( array, itemSize ) {
  25406. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  25407. return new Int16BufferAttribute( array, itemSize );
  25408. }
  25409. function Uint16Attribute( array, itemSize ) {
  25410. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  25411. return new Uint16BufferAttribute( array, itemSize );
  25412. }
  25413. function Int32Attribute( array, itemSize ) {
  25414. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  25415. return new Int32BufferAttribute( array, itemSize );
  25416. }
  25417. function Uint32Attribute( array, itemSize ) {
  25418. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  25419. return new Uint32BufferAttribute( array, itemSize );
  25420. }
  25421. function Float32Attribute( array, itemSize ) {
  25422. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  25423. return new Float32BufferAttribute( array, itemSize );
  25424. }
  25425. function Float64Attribute( array, itemSize ) {
  25426. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  25427. return new Float64BufferAttribute( array, itemSize );
  25428. }
  25429. //
  25430. Curve.create = function ( construct, getPoint ) {
  25431. console.log( 'THREE.Curve.create() has been deprecated' );
  25432. construct.prototype = Object.create( Curve.prototype );
  25433. construct.prototype.constructor = construct;
  25434. construct.prototype.getPoint = getPoint;
  25435. return construct;
  25436. };
  25437. //
  25438. function ClosedSplineCurve3( points ) {
  25439. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25440. CatmullRomCurve3.call( this, points );
  25441. this.type = 'catmullrom';
  25442. this.closed = true;
  25443. }
  25444. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25445. //
  25446. function SplineCurve3( points ) {
  25447. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25448. CatmullRomCurve3.call( this, points );
  25449. this.type = 'catmullrom';
  25450. }
  25451. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25452. //
  25453. function Spline( points ) {
  25454. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  25455. CatmullRomCurve3.call( this, points );
  25456. this.type = 'catmullrom';
  25457. }
  25458. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  25459. Object.assign( Spline.prototype, {
  25460. initFromArray: function ( a ) {
  25461. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  25462. },
  25463. getControlPointsArray: function ( optionalTarget ) {
  25464. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  25465. },
  25466. reparametrizeByArcLength: function ( samplingCoef ) {
  25467. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  25468. }
  25469. } );
  25470. //
  25471. function BoundingBoxHelper( object, color ) {
  25472. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  25473. return new BoxHelper( object, color );
  25474. }
  25475. function EdgesHelper( object, hex ) {
  25476. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  25477. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25478. }
  25479. GridHelper.prototype.setColors = function () {
  25480. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  25481. };
  25482. SkeletonHelper.prototype.update = function () {
  25483. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  25484. };
  25485. function WireframeHelper( object, hex ) {
  25486. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  25487. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25488. }
  25489. //
  25490. function XHRLoader( manager ) {
  25491. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  25492. return new FileLoader( manager );
  25493. }
  25494. function BinaryTextureLoader( manager ) {
  25495. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  25496. return new DataTextureLoader( manager );
  25497. }
  25498. //
  25499. Object.assign( Box2.prototype, {
  25500. center: function ( optionalTarget ) {
  25501. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  25502. return this.getCenter( optionalTarget );
  25503. },
  25504. empty: function () {
  25505. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  25506. return this.isEmpty();
  25507. },
  25508. isIntersectionBox: function ( box ) {
  25509. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25510. return this.intersectsBox( box );
  25511. },
  25512. size: function ( optionalTarget ) {
  25513. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  25514. return this.getSize( optionalTarget );
  25515. }
  25516. } );
  25517. Object.assign( Box3.prototype, {
  25518. center: function ( optionalTarget ) {
  25519. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  25520. return this.getCenter( optionalTarget );
  25521. },
  25522. empty: function () {
  25523. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  25524. return this.isEmpty();
  25525. },
  25526. isIntersectionBox: function ( box ) {
  25527. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25528. return this.intersectsBox( box );
  25529. },
  25530. isIntersectionSphere: function ( sphere ) {
  25531. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25532. return this.intersectsSphere( sphere );
  25533. },
  25534. size: function ( optionalTarget ) {
  25535. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  25536. return this.getSize( optionalTarget );
  25537. }
  25538. } );
  25539. Line3.prototype.center = function ( optionalTarget ) {
  25540. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  25541. return this.getCenter( optionalTarget );
  25542. };
  25543. _Math.random16 = function () {
  25544. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  25545. return Math.random();
  25546. };
  25547. Object.assign( Matrix3.prototype, {
  25548. flattenToArrayOffset: function ( array, offset ) {
  25549. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25550. return this.toArray( array, offset );
  25551. },
  25552. multiplyVector3: function ( vector ) {
  25553. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  25554. return vector.applyMatrix3( this );
  25555. },
  25556. multiplyVector3Array: function ( a ) {
  25557. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  25558. },
  25559. applyToBuffer: function( buffer, offset, length ) {
  25560. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25561. return this.applyToBufferAttribute( buffer );
  25562. },
  25563. applyToVector3Array: function( array, offset, length ) {
  25564. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  25565. }
  25566. } );
  25567. Object.assign( Matrix4.prototype, {
  25568. extractPosition: function ( m ) {
  25569. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  25570. return this.copyPosition( m );
  25571. },
  25572. flattenToArrayOffset: function ( array, offset ) {
  25573. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25574. return this.toArray( array, offset );
  25575. },
  25576. getPosition: function () {
  25577. var v1;
  25578. return function getPosition() {
  25579. if ( v1 === undefined ) v1 = new Vector3();
  25580. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  25581. return v1.setFromMatrixColumn( this, 3 );
  25582. };
  25583. }(),
  25584. setRotationFromQuaternion: function ( q ) {
  25585. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  25586. return this.makeRotationFromQuaternion( q );
  25587. },
  25588. multiplyToArray: function () {
  25589. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  25590. },
  25591. multiplyVector3: function ( vector ) {
  25592. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25593. return vector.applyMatrix4( this );
  25594. },
  25595. multiplyVector4: function ( vector ) {
  25596. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25597. return vector.applyMatrix4( this );
  25598. },
  25599. multiplyVector3Array: function ( a ) {
  25600. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  25601. },
  25602. rotateAxis: function ( v ) {
  25603. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  25604. v.transformDirection( this );
  25605. },
  25606. crossVector: function ( vector ) {
  25607. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25608. return vector.applyMatrix4( this );
  25609. },
  25610. translate: function () {
  25611. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  25612. },
  25613. rotateX: function () {
  25614. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  25615. },
  25616. rotateY: function () {
  25617. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  25618. },
  25619. rotateZ: function () {
  25620. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  25621. },
  25622. rotateByAxis: function () {
  25623. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  25624. },
  25625. applyToBuffer: function( buffer, offset, length ) {
  25626. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25627. return this.applyToBufferAttribute( buffer );
  25628. },
  25629. applyToVector3Array: function( array, offset, length ) {
  25630. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  25631. },
  25632. makeFrustum: function( left, right, bottom, top, near, far ) {
  25633. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  25634. return this.makePerspective( left, right, top, bottom, near, far );
  25635. }
  25636. } );
  25637. Plane.prototype.isIntersectionLine = function ( line ) {
  25638. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  25639. return this.intersectsLine( line );
  25640. };
  25641. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  25642. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  25643. return vector.applyQuaternion( this );
  25644. };
  25645. Object.assign( Ray.prototype, {
  25646. isIntersectionBox: function ( box ) {
  25647. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25648. return this.intersectsBox( box );
  25649. },
  25650. isIntersectionPlane: function ( plane ) {
  25651. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  25652. return this.intersectsPlane( plane );
  25653. },
  25654. isIntersectionSphere: function ( sphere ) {
  25655. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25656. return this.intersectsSphere( sphere );
  25657. }
  25658. } );
  25659. Object.assign( Shape.prototype, {
  25660. extrude: function ( options ) {
  25661. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  25662. return new ExtrudeGeometry( this, options );
  25663. },
  25664. makeGeometry: function ( options ) {
  25665. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  25666. return new ShapeGeometry( this, options );
  25667. }
  25668. } );
  25669. Object.assign( Vector2.prototype, {
  25670. fromAttribute: function ( attribute, index, offset ) {
  25671. console.error( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25672. return this.fromBufferAttribute( attribute, index, offset );
  25673. }
  25674. } );
  25675. Object.assign( Vector3.prototype, {
  25676. setEulerFromRotationMatrix: function () {
  25677. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  25678. },
  25679. setEulerFromQuaternion: function () {
  25680. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  25681. },
  25682. getPositionFromMatrix: function ( m ) {
  25683. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  25684. return this.setFromMatrixPosition( m );
  25685. },
  25686. getScaleFromMatrix: function ( m ) {
  25687. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  25688. return this.setFromMatrixScale( m );
  25689. },
  25690. getColumnFromMatrix: function ( index, matrix ) {
  25691. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  25692. return this.setFromMatrixColumn( matrix, index );
  25693. },
  25694. applyProjection: function ( m ) {
  25695. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  25696. return this.applyMatrix4( m );
  25697. },
  25698. fromAttribute: function ( attribute, index, offset ) {
  25699. console.error( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25700. return this.fromBufferAttribute( attribute, index, offset );
  25701. }
  25702. } );
  25703. Object.assign( Vector4.prototype, {
  25704. fromAttribute: function ( attribute, index, offset ) {
  25705. console.error( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25706. return this.fromBufferAttribute( attribute, index, offset );
  25707. }
  25708. } );
  25709. //
  25710. Geometry.prototype.computeTangents = function () {
  25711. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  25712. };
  25713. Object.assign( Object3D.prototype, {
  25714. getChildByName: function ( name ) {
  25715. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  25716. return this.getObjectByName( name );
  25717. },
  25718. renderDepth: function () {
  25719. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  25720. },
  25721. translate: function ( distance, axis ) {
  25722. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  25723. return this.translateOnAxis( axis, distance );
  25724. }
  25725. } );
  25726. Object.defineProperties( Object3D.prototype, {
  25727. eulerOrder: {
  25728. get: function () {
  25729. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25730. return this.rotation.order;
  25731. },
  25732. set: function ( value ) {
  25733. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25734. this.rotation.order = value;
  25735. }
  25736. },
  25737. useQuaternion: {
  25738. get: function () {
  25739. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25740. },
  25741. set: function () {
  25742. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25743. }
  25744. }
  25745. } );
  25746. Object.defineProperties( LOD.prototype, {
  25747. objects: {
  25748. get: function () {
  25749. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  25750. return this.levels;
  25751. }
  25752. }
  25753. } );
  25754. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  25755. get: function () {
  25756. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  25757. },
  25758. set: function () {
  25759. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  25760. }
  25761. } );
  25762. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  25763. get: function () {
  25764. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  25765. return this.arcLengthDivisions;
  25766. },
  25767. set: function ( value ) {
  25768. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  25769. this.arcLengthDivisions = value;
  25770. }
  25771. } );
  25772. //
  25773. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  25774. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  25775. "Use .setFocalLength and .filmGauge for a photographic setup." );
  25776. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  25777. this.setFocalLength( focalLength );
  25778. };
  25779. //
  25780. Object.defineProperties( Light.prototype, {
  25781. onlyShadow: {
  25782. set: function () {
  25783. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  25784. }
  25785. },
  25786. shadowCameraFov: {
  25787. set: function ( value ) {
  25788. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  25789. this.shadow.camera.fov = value;
  25790. }
  25791. },
  25792. shadowCameraLeft: {
  25793. set: function ( value ) {
  25794. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  25795. this.shadow.camera.left = value;
  25796. }
  25797. },
  25798. shadowCameraRight: {
  25799. set: function ( value ) {
  25800. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  25801. this.shadow.camera.right = value;
  25802. }
  25803. },
  25804. shadowCameraTop: {
  25805. set: function ( value ) {
  25806. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  25807. this.shadow.camera.top = value;
  25808. }
  25809. },
  25810. shadowCameraBottom: {
  25811. set: function ( value ) {
  25812. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  25813. this.shadow.camera.bottom = value;
  25814. }
  25815. },
  25816. shadowCameraNear: {
  25817. set: function ( value ) {
  25818. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  25819. this.shadow.camera.near = value;
  25820. }
  25821. },
  25822. shadowCameraFar: {
  25823. set: function ( value ) {
  25824. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  25825. this.shadow.camera.far = value;
  25826. }
  25827. },
  25828. shadowCameraVisible: {
  25829. set: function () {
  25830. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  25831. }
  25832. },
  25833. shadowBias: {
  25834. set: function ( value ) {
  25835. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  25836. this.shadow.bias = value;
  25837. }
  25838. },
  25839. shadowDarkness: {
  25840. set: function () {
  25841. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  25842. }
  25843. },
  25844. shadowMapWidth: {
  25845. set: function ( value ) {
  25846. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  25847. this.shadow.mapSize.width = value;
  25848. }
  25849. },
  25850. shadowMapHeight: {
  25851. set: function ( value ) {
  25852. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  25853. this.shadow.mapSize.height = value;
  25854. }
  25855. }
  25856. } );
  25857. //
  25858. Object.defineProperties( BufferAttribute.prototype, {
  25859. length: {
  25860. get: function () {
  25861. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  25862. return this.array.length;
  25863. }
  25864. }
  25865. } );
  25866. Object.assign( BufferGeometry.prototype, {
  25867. addIndex: function ( index ) {
  25868. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  25869. this.setIndex( index );
  25870. },
  25871. addDrawCall: function ( start, count, indexOffset ) {
  25872. if ( indexOffset !== undefined ) {
  25873. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  25874. }
  25875. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  25876. this.addGroup( start, count );
  25877. },
  25878. clearDrawCalls: function () {
  25879. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  25880. this.clearGroups();
  25881. },
  25882. computeTangents: function () {
  25883. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  25884. },
  25885. computeOffsets: function () {
  25886. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  25887. }
  25888. } );
  25889. Object.defineProperties( BufferGeometry.prototype, {
  25890. drawcalls: {
  25891. get: function () {
  25892. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  25893. return this.groups;
  25894. }
  25895. },
  25896. offsets: {
  25897. get: function () {
  25898. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  25899. return this.groups;
  25900. }
  25901. }
  25902. } );
  25903. //
  25904. Object.defineProperties( Uniform.prototype, {
  25905. dynamic: {
  25906. set: function () {
  25907. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  25908. }
  25909. },
  25910. onUpdate: {
  25911. value: function () {
  25912. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  25913. return this;
  25914. }
  25915. }
  25916. } );
  25917. //
  25918. Object.defineProperties( Material.prototype, {
  25919. wrapAround: {
  25920. get: function () {
  25921. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  25922. },
  25923. set: function () {
  25924. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  25925. }
  25926. },
  25927. wrapRGB: {
  25928. get: function () {
  25929. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  25930. return new Color();
  25931. }
  25932. },
  25933. shading: {
  25934. get: function () {
  25935. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  25936. },
  25937. set: function ( value ) {
  25938. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  25939. this.flatShading = ( value === FlatShading );
  25940. }
  25941. }
  25942. } );
  25943. Object.defineProperties( MeshPhongMaterial.prototype, {
  25944. metal: {
  25945. get: function () {
  25946. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  25947. return false;
  25948. },
  25949. set: function () {
  25950. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  25951. }
  25952. }
  25953. } );
  25954. Object.defineProperties( ShaderMaterial.prototype, {
  25955. derivatives: {
  25956. get: function () {
  25957. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25958. return this.extensions.derivatives;
  25959. },
  25960. set: function ( value ) {
  25961. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25962. this.extensions.derivatives = value;
  25963. }
  25964. }
  25965. } );
  25966. //
  25967. Object.assign( WebGLRenderer.prototype, {
  25968. getCurrentRenderTarget: function () {
  25969. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  25970. return this.getRenderTarget();
  25971. },
  25972. getMaxAnisotropy: function () {
  25973. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  25974. return this.capabilities.getMaxAnisotropy();
  25975. },
  25976. getPrecision: function () {
  25977. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  25978. return this.capabilities.precision;
  25979. },
  25980. supportsFloatTextures: function () {
  25981. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  25982. return this.extensions.get( 'OES_texture_float' );
  25983. },
  25984. supportsHalfFloatTextures: function () {
  25985. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  25986. return this.extensions.get( 'OES_texture_half_float' );
  25987. },
  25988. supportsStandardDerivatives: function () {
  25989. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  25990. return this.extensions.get( 'OES_standard_derivatives' );
  25991. },
  25992. supportsCompressedTextureS3TC: function () {
  25993. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  25994. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  25995. },
  25996. supportsCompressedTexturePVRTC: function () {
  25997. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  25998. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  25999. },
  26000. supportsBlendMinMax: function () {
  26001. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  26002. return this.extensions.get( 'EXT_blend_minmax' );
  26003. },
  26004. supportsVertexTextures: function () {
  26005. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  26006. return this.capabilities.vertexTextures;
  26007. },
  26008. supportsInstancedArrays: function () {
  26009. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  26010. return this.extensions.get( 'ANGLE_instanced_arrays' );
  26011. },
  26012. enableScissorTest: function ( boolean ) {
  26013. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  26014. this.setScissorTest( boolean );
  26015. },
  26016. initMaterial: function () {
  26017. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  26018. },
  26019. addPrePlugin: function () {
  26020. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  26021. },
  26022. addPostPlugin: function () {
  26023. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  26024. },
  26025. updateShadowMap: function () {
  26026. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  26027. }
  26028. } );
  26029. Object.defineProperties( WebGLRenderer.prototype, {
  26030. shadowMapEnabled: {
  26031. get: function () {
  26032. return this.shadowMap.enabled;
  26033. },
  26034. set: function ( value ) {
  26035. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  26036. this.shadowMap.enabled = value;
  26037. }
  26038. },
  26039. shadowMapType: {
  26040. get: function () {
  26041. return this.shadowMap.type;
  26042. },
  26043. set: function ( value ) {
  26044. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  26045. this.shadowMap.type = value;
  26046. }
  26047. },
  26048. shadowMapCullFace: {
  26049. get: function () {
  26050. return this.shadowMap.cullFace;
  26051. },
  26052. set: function ( value ) {
  26053. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  26054. this.shadowMap.cullFace = value;
  26055. }
  26056. }
  26057. } );
  26058. Object.defineProperties( WebGLShadowMap.prototype, {
  26059. cullFace: {
  26060. get: function () {
  26061. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  26062. },
  26063. set: function ( cullFace ) {
  26064. var value = ( cullFace !== CullFaceBack );
  26065. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  26066. this.renderReverseSided = value;
  26067. }
  26068. }
  26069. } );
  26070. //
  26071. Object.defineProperties( WebGLRenderTarget.prototype, {
  26072. wrapS: {
  26073. get: function () {
  26074. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  26075. return this.texture.wrapS;
  26076. },
  26077. set: function ( value ) {
  26078. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  26079. this.texture.wrapS = value;
  26080. }
  26081. },
  26082. wrapT: {
  26083. get: function () {
  26084. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  26085. return this.texture.wrapT;
  26086. },
  26087. set: function ( value ) {
  26088. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  26089. this.texture.wrapT = value;
  26090. }
  26091. },
  26092. magFilter: {
  26093. get: function () {
  26094. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  26095. return this.texture.magFilter;
  26096. },
  26097. set: function ( value ) {
  26098. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  26099. this.texture.magFilter = value;
  26100. }
  26101. },
  26102. minFilter: {
  26103. get: function () {
  26104. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  26105. return this.texture.minFilter;
  26106. },
  26107. set: function ( value ) {
  26108. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  26109. this.texture.minFilter = value;
  26110. }
  26111. },
  26112. anisotropy: {
  26113. get: function () {
  26114. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  26115. return this.texture.anisotropy;
  26116. },
  26117. set: function ( value ) {
  26118. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  26119. this.texture.anisotropy = value;
  26120. }
  26121. },
  26122. offset: {
  26123. get: function () {
  26124. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  26125. return this.texture.offset;
  26126. },
  26127. set: function ( value ) {
  26128. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  26129. this.texture.offset = value;
  26130. }
  26131. },
  26132. repeat: {
  26133. get: function () {
  26134. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  26135. return this.texture.repeat;
  26136. },
  26137. set: function ( value ) {
  26138. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  26139. this.texture.repeat = value;
  26140. }
  26141. },
  26142. format: {
  26143. get: function () {
  26144. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  26145. return this.texture.format;
  26146. },
  26147. set: function ( value ) {
  26148. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  26149. this.texture.format = value;
  26150. }
  26151. },
  26152. type: {
  26153. get: function () {
  26154. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  26155. return this.texture.type;
  26156. },
  26157. set: function ( value ) {
  26158. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  26159. this.texture.type = value;
  26160. }
  26161. },
  26162. generateMipmaps: {
  26163. get: function () {
  26164. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  26165. return this.texture.generateMipmaps;
  26166. },
  26167. set: function ( value ) {
  26168. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  26169. this.texture.generateMipmaps = value;
  26170. }
  26171. }
  26172. } );
  26173. //
  26174. Audio.prototype.load = function ( file ) {
  26175. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  26176. var scope = this;
  26177. var audioLoader = new AudioLoader();
  26178. audioLoader.load( file, function ( buffer ) {
  26179. scope.setBuffer( buffer );
  26180. } );
  26181. return this;
  26182. };
  26183. AudioAnalyser.prototype.getData = function () {
  26184. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  26185. return this.getFrequencyData();
  26186. };
  26187. //
  26188. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  26189. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  26190. return this.update( renderer, scene );
  26191. };
  26192. //
  26193. var GeometryUtils = {
  26194. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  26195. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  26196. var matrix;
  26197. if ( geometry2.isMesh ) {
  26198. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  26199. matrix = geometry2.matrix;
  26200. geometry2 = geometry2.geometry;
  26201. }
  26202. geometry1.merge( geometry2, matrix, materialIndexOffset );
  26203. },
  26204. center: function ( geometry ) {
  26205. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  26206. return geometry.center();
  26207. }
  26208. };
  26209. var ImageUtils = {
  26210. crossOrigin: undefined,
  26211. loadTexture: function ( url, mapping, onLoad, onError ) {
  26212. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  26213. var loader = new TextureLoader();
  26214. loader.setCrossOrigin( this.crossOrigin );
  26215. var texture = loader.load( url, onLoad, undefined, onError );
  26216. if ( mapping ) texture.mapping = mapping;
  26217. return texture;
  26218. },
  26219. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  26220. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  26221. var loader = new CubeTextureLoader();
  26222. loader.setCrossOrigin( this.crossOrigin );
  26223. var texture = loader.load( urls, onLoad, undefined, onError );
  26224. if ( mapping ) texture.mapping = mapping;
  26225. return texture;
  26226. },
  26227. loadCompressedTexture: function () {
  26228. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  26229. },
  26230. loadCompressedTextureCube: function () {
  26231. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  26232. }
  26233. };
  26234. //
  26235. function Projector() {
  26236. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  26237. this.projectVector = function ( vector, camera ) {
  26238. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  26239. vector.project( camera );
  26240. };
  26241. this.unprojectVector = function ( vector, camera ) {
  26242. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  26243. vector.unproject( camera );
  26244. };
  26245. this.pickingRay = function () {
  26246. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  26247. };
  26248. }
  26249. //
  26250. function CanvasRenderer() {
  26251. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  26252. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  26253. this.clear = function () {};
  26254. this.render = function () {};
  26255. this.setClearColor = function () {};
  26256. this.setSize = function () {};
  26257. }
  26258. 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, 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, WebGLUtils, 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 };