three.js 1008 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.THREE = global.THREE || {})));
  5. }(this, (function (exports) { 'use strict';
  6. // Polyfills
  7. if ( Number.EPSILON === undefined ) {
  8. Number.EPSILON = Math.pow( 2, - 52 );
  9. }
  10. //
  11. if ( Math.sign === undefined ) {
  12. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  13. Math.sign = function ( x ) {
  14. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  15. };
  16. }
  17. if ( Function.prototype.name === undefined ) {
  18. // Missing in IE9-11.
  19. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  20. Object.defineProperty( Function.prototype, 'name', {
  21. get: function () {
  22. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  23. }
  24. } );
  25. }
  26. if ( Object.assign === undefined ) {
  27. // Missing in IE.
  28. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  29. ( function () {
  30. Object.assign = function ( target ) {
  31. 'use strict';
  32. if ( target === undefined || target === null ) {
  33. throw new TypeError( 'Cannot convert undefined or null to object' );
  34. }
  35. var output = Object( target );
  36. for ( var index = 1; index < arguments.length; index ++ ) {
  37. var source = arguments[ index ];
  38. if ( source !== undefined && source !== null ) {
  39. for ( var nextKey in source ) {
  40. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  41. output[ nextKey ] = source[ nextKey ];
  42. }
  43. }
  44. }
  45. }
  46. return output;
  47. };
  48. } )();
  49. }
  50. /**
  51. * https://github.com/mrdoob/eventdispatcher.js/
  52. */
  53. function EventDispatcher() {}
  54. Object.assign( EventDispatcher.prototype, {
  55. addEventListener: function ( type, listener ) {
  56. if ( this._listeners === undefined ) this._listeners = {};
  57. var listeners = this._listeners;
  58. if ( listeners[ type ] === undefined ) {
  59. listeners[ type ] = [];
  60. }
  61. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  62. listeners[ type ].push( listener );
  63. }
  64. },
  65. hasEventListener: function ( type, listener ) {
  66. if ( this._listeners === undefined ) return false;
  67. var listeners = this._listeners;
  68. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  69. return true;
  70. }
  71. return false;
  72. },
  73. removeEventListener: function ( type, listener ) {
  74. if ( this._listeners === undefined ) return;
  75. var listeners = this._listeners;
  76. var listenerArray = listeners[ type ];
  77. if ( listenerArray !== undefined ) {
  78. var index = listenerArray.indexOf( listener );
  79. if ( index !== - 1 ) {
  80. listenerArray.splice( index, 1 );
  81. }
  82. }
  83. },
  84. dispatchEvent: function ( event ) {
  85. if ( this._listeners === undefined ) return;
  86. var listeners = this._listeners;
  87. var listenerArray = listeners[ event.type ];
  88. if ( listenerArray !== undefined ) {
  89. event.target = this;
  90. var array = [], i = 0;
  91. var length = listenerArray.length;
  92. for ( i = 0; i < length; i ++ ) {
  93. array[ i ] = listenerArray[ i ];
  94. }
  95. for ( i = 0; i < length; i ++ ) {
  96. array[ i ].call( this, event );
  97. }
  98. }
  99. }
  100. } );
  101. var REVISION = '83dev';
  102. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  103. var CullFaceNone = 0;
  104. var CullFaceBack = 1;
  105. var CullFaceFront = 2;
  106. var CullFaceFrontBack = 3;
  107. var FrontFaceDirectionCW = 0;
  108. var FrontFaceDirectionCCW = 1;
  109. var BasicShadowMap = 0;
  110. var PCFShadowMap = 1;
  111. var PCFSoftShadowMap = 2;
  112. var FrontSide = 0;
  113. var BackSide = 1;
  114. var DoubleSide = 2;
  115. var FlatShading = 1;
  116. var SmoothShading = 2;
  117. var NoColors = 0;
  118. var FaceColors = 1;
  119. var VertexColors = 2;
  120. var NoBlending = 0;
  121. var NormalBlending = 1;
  122. var AdditiveBlending = 2;
  123. var SubtractiveBlending = 3;
  124. var MultiplyBlending = 4;
  125. var CustomBlending = 5;
  126. var BlendingMode = {
  127. NoBlending: NoBlending,
  128. NormalBlending: NormalBlending,
  129. AdditiveBlending: AdditiveBlending,
  130. SubtractiveBlending: SubtractiveBlending,
  131. MultiplyBlending: MultiplyBlending,
  132. CustomBlending: CustomBlending
  133. };
  134. var AddEquation = 100;
  135. var SubtractEquation = 101;
  136. var ReverseSubtractEquation = 102;
  137. var MinEquation = 103;
  138. var MaxEquation = 104;
  139. var ZeroFactor = 200;
  140. var OneFactor = 201;
  141. var SrcColorFactor = 202;
  142. var OneMinusSrcColorFactor = 203;
  143. var SrcAlphaFactor = 204;
  144. var OneMinusSrcAlphaFactor = 205;
  145. var DstAlphaFactor = 206;
  146. var OneMinusDstAlphaFactor = 207;
  147. var DstColorFactor = 208;
  148. var OneMinusDstColorFactor = 209;
  149. var SrcAlphaSaturateFactor = 210;
  150. var NeverDepth = 0;
  151. var AlwaysDepth = 1;
  152. var LessDepth = 2;
  153. var LessEqualDepth = 3;
  154. var EqualDepth = 4;
  155. var GreaterEqualDepth = 5;
  156. var GreaterDepth = 6;
  157. var NotEqualDepth = 7;
  158. var MultiplyOperation = 0;
  159. var MixOperation = 1;
  160. var AddOperation = 2;
  161. var NoToneMapping = 0;
  162. var LinearToneMapping = 1;
  163. var ReinhardToneMapping = 2;
  164. var Uncharted2ToneMapping = 3;
  165. var CineonToneMapping = 4;
  166. var UVMapping = 300;
  167. var CubeReflectionMapping = 301;
  168. var CubeRefractionMapping = 302;
  169. var EquirectangularReflectionMapping = 303;
  170. var EquirectangularRefractionMapping = 304;
  171. var SphericalReflectionMapping = 305;
  172. var CubeUVReflectionMapping = 306;
  173. var CubeUVRefractionMapping = 307;
  174. var TextureMapping = {
  175. UVMapping: UVMapping,
  176. CubeReflectionMapping: CubeReflectionMapping,
  177. CubeRefractionMapping: CubeRefractionMapping,
  178. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  179. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  180. SphericalReflectionMapping: SphericalReflectionMapping,
  181. CubeUVReflectionMapping: CubeUVReflectionMapping,
  182. CubeUVRefractionMapping: CubeUVRefractionMapping
  183. };
  184. var RepeatWrapping = 1000;
  185. var ClampToEdgeWrapping = 1001;
  186. var MirroredRepeatWrapping = 1002;
  187. var TextureWrapping = {
  188. RepeatWrapping: RepeatWrapping,
  189. ClampToEdgeWrapping: ClampToEdgeWrapping,
  190. MirroredRepeatWrapping: MirroredRepeatWrapping
  191. };
  192. var NearestFilter = 1003;
  193. var NearestMipMapNearestFilter = 1004;
  194. var NearestMipMapLinearFilter = 1005;
  195. var LinearFilter = 1006;
  196. var LinearMipMapNearestFilter = 1007;
  197. var LinearMipMapLinearFilter = 1008;
  198. var TextureFilter = {
  199. NearestFilter: NearestFilter,
  200. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  201. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  202. LinearFilter: LinearFilter,
  203. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  204. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  205. };
  206. var UnsignedByteType = 1009;
  207. var ByteType = 1010;
  208. var ShortType = 1011;
  209. var UnsignedShortType = 1012;
  210. var IntType = 1013;
  211. var UnsignedIntType = 1014;
  212. var FloatType = 1015;
  213. var HalfFloatType = 1016;
  214. var UnsignedShort4444Type = 1017;
  215. var UnsignedShort5551Type = 1018;
  216. var UnsignedShort565Type = 1019;
  217. var UnsignedInt248Type = 1020;
  218. var AlphaFormat = 1021;
  219. var RGBFormat = 1022;
  220. var RGBAFormat = 1023;
  221. var LuminanceFormat = 1024;
  222. var LuminanceAlphaFormat = 1025;
  223. var RGBEFormat = RGBAFormat;
  224. var DepthFormat = 1026;
  225. var DepthStencilFormat = 1027;
  226. var RGB_S3TC_DXT1_Format = 2001;
  227. var RGBA_S3TC_DXT1_Format = 2002;
  228. var RGBA_S3TC_DXT3_Format = 2003;
  229. var RGBA_S3TC_DXT5_Format = 2004;
  230. var RGB_PVRTC_4BPPV1_Format = 2100;
  231. var RGB_PVRTC_2BPPV1_Format = 2101;
  232. var RGBA_PVRTC_4BPPV1_Format = 2102;
  233. var RGBA_PVRTC_2BPPV1_Format = 2103;
  234. var RGB_ETC1_Format = 2151;
  235. var LoopOnce = 2200;
  236. var LoopRepeat = 2201;
  237. var LoopPingPong = 2202;
  238. var InterpolateDiscrete = 2300;
  239. var InterpolateLinear = 2301;
  240. var InterpolateSmooth = 2302;
  241. var ZeroCurvatureEnding = 2400;
  242. var ZeroSlopeEnding = 2401;
  243. var WrapAroundEnding = 2402;
  244. var TrianglesDrawMode = 0;
  245. var TriangleStripDrawMode = 1;
  246. var TriangleFanDrawMode = 2;
  247. var LinearEncoding = 3000;
  248. var sRGBEncoding = 3001;
  249. var GammaEncoding = 3007;
  250. var RGBEEncoding = 3002;
  251. var LogLuvEncoding = 3003;
  252. var RGBM7Encoding = 3004;
  253. var RGBM16Encoding = 3005;
  254. var RGBDEncoding = 3006;
  255. var BasicDepthPacking = 3200;
  256. var RGBADepthPacking = 3201;
  257. /**
  258. * @author alteredq / http://alteredqualia.com/
  259. * @author mrdoob / http://mrdoob.com/
  260. */
  261. var _Math = {
  262. DEG2RAD: Math.PI / 180,
  263. RAD2DEG: 180 / Math.PI,
  264. generateUUID: function () {
  265. // http://www.broofa.com/Tools/Math.uuid.htm
  266. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  267. var uuid = new Array( 36 );
  268. var rnd = 0, r;
  269. return function generateUUID() {
  270. for ( var i = 0; i < 36; i ++ ) {
  271. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  272. uuid[ i ] = '-';
  273. } else if ( i === 14 ) {
  274. uuid[ i ] = '4';
  275. } else {
  276. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  277. r = rnd & 0xf;
  278. rnd = rnd >> 4;
  279. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  280. }
  281. }
  282. return uuid.join( '' );
  283. };
  284. }(),
  285. clamp: function ( value, min, max ) {
  286. return Math.max( min, Math.min( max, value ) );
  287. },
  288. // compute euclidian modulo of m % n
  289. // https://en.wikipedia.org/wiki/Modulo_operation
  290. euclideanModulo: function ( n, m ) {
  291. return ( ( n % m ) + m ) % m;
  292. },
  293. // Linear mapping from range <a1, a2> to range <b1, b2>
  294. mapLinear: function ( x, a1, a2, b1, b2 ) {
  295. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  296. },
  297. // https://en.wikipedia.org/wiki/Linear_interpolation
  298. lerp: function ( x, y, t ) {
  299. return ( 1 - t ) * x + t * y;
  300. },
  301. // http://en.wikipedia.org/wiki/Smoothstep
  302. smoothstep: function ( x, min, max ) {
  303. if ( x <= min ) return 0;
  304. if ( x >= max ) return 1;
  305. x = ( x - min ) / ( max - min );
  306. return x * x * ( 3 - 2 * x );
  307. },
  308. smootherstep: function ( x, min, max ) {
  309. if ( x <= min ) return 0;
  310. if ( x >= max ) return 1;
  311. x = ( x - min ) / ( max - min );
  312. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  313. },
  314. // Random integer from <low, high> interval
  315. randInt: function ( low, high ) {
  316. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  317. },
  318. // Random float from <low, high> interval
  319. randFloat: function ( low, high ) {
  320. return low + Math.random() * ( high - low );
  321. },
  322. // Random float from <-range/2, range/2> interval
  323. randFloatSpread: function ( range ) {
  324. return range * ( 0.5 - Math.random() );
  325. },
  326. degToRad: function ( degrees ) {
  327. return degrees * _Math.DEG2RAD;
  328. },
  329. radToDeg: function ( radians ) {
  330. return radians * _Math.RAD2DEG;
  331. },
  332. isPowerOfTwo: function ( value ) {
  333. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  334. },
  335. nearestPowerOfTwo: function ( value ) {
  336. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  337. },
  338. nextPowerOfTwo: function ( value ) {
  339. value --;
  340. value |= value >> 1;
  341. value |= value >> 2;
  342. value |= value >> 4;
  343. value |= value >> 8;
  344. value |= value >> 16;
  345. value ++;
  346. return value;
  347. }
  348. };
  349. /**
  350. * @author mrdoob / http://mrdoob.com/
  351. * @author philogb / http://blog.thejit.org/
  352. * @author egraether / http://egraether.com/
  353. * @author zz85 / http://www.lab4games.net/zz85/blog
  354. */
  355. function Vector2( x, y ) {
  356. this.x = x || 0;
  357. this.y = y || 0;
  358. }
  359. Vector2.prototype = {
  360. constructor: Vector2,
  361. isVector2: true,
  362. get width() {
  363. return this.x;
  364. },
  365. set width( value ) {
  366. this.x = value;
  367. },
  368. get height() {
  369. return this.y;
  370. },
  371. set height( value ) {
  372. this.y = value;
  373. },
  374. //
  375. set: function ( x, y ) {
  376. this.x = x;
  377. this.y = y;
  378. return this;
  379. },
  380. setScalar: function ( scalar ) {
  381. this.x = scalar;
  382. this.y = scalar;
  383. return this;
  384. },
  385. setX: function ( x ) {
  386. this.x = x;
  387. return this;
  388. },
  389. setY: function ( y ) {
  390. this.y = y;
  391. return this;
  392. },
  393. setComponent: function ( index, value ) {
  394. switch ( index ) {
  395. case 0: this.x = value; break;
  396. case 1: this.y = value; break;
  397. default: throw new Error( 'index is out of range: ' + index );
  398. }
  399. return this;
  400. },
  401. getComponent: function ( index ) {
  402. switch ( index ) {
  403. case 0: return this.x;
  404. case 1: return this.y;
  405. default: throw new Error( 'index is out of range: ' + index );
  406. }
  407. },
  408. clone: function () {
  409. return new this.constructor( this.x, this.y );
  410. },
  411. copy: function ( v ) {
  412. this.x = v.x;
  413. this.y = v.y;
  414. return this;
  415. },
  416. add: function ( v, w ) {
  417. if ( w !== undefined ) {
  418. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  419. return this.addVectors( v, w );
  420. }
  421. this.x += v.x;
  422. this.y += v.y;
  423. return this;
  424. },
  425. addScalar: function ( s ) {
  426. this.x += s;
  427. this.y += s;
  428. return this;
  429. },
  430. addVectors: function ( a, b ) {
  431. this.x = a.x + b.x;
  432. this.y = a.y + b.y;
  433. return this;
  434. },
  435. addScaledVector: function ( v, s ) {
  436. this.x += v.x * s;
  437. this.y += v.y * s;
  438. return this;
  439. },
  440. sub: function ( v, w ) {
  441. if ( w !== undefined ) {
  442. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  443. return this.subVectors( v, w );
  444. }
  445. this.x -= v.x;
  446. this.y -= v.y;
  447. return this;
  448. },
  449. subScalar: function ( s ) {
  450. this.x -= s;
  451. this.y -= s;
  452. return this;
  453. },
  454. subVectors: function ( a, b ) {
  455. this.x = a.x - b.x;
  456. this.y = a.y - b.y;
  457. return this;
  458. },
  459. multiply: function ( v ) {
  460. this.x *= v.x;
  461. this.y *= v.y;
  462. return this;
  463. },
  464. multiplyScalar: function ( scalar ) {
  465. if ( isFinite( scalar ) ) {
  466. this.x *= scalar;
  467. this.y *= scalar;
  468. } else {
  469. this.x = 0;
  470. this.y = 0;
  471. }
  472. return this;
  473. },
  474. divide: function ( v ) {
  475. this.x /= v.x;
  476. this.y /= v.y;
  477. return this;
  478. },
  479. divideScalar: function ( scalar ) {
  480. return this.multiplyScalar( 1 / scalar );
  481. },
  482. min: function ( v ) {
  483. this.x = Math.min( this.x, v.x );
  484. this.y = Math.min( this.y, v.y );
  485. return this;
  486. },
  487. max: function ( v ) {
  488. this.x = Math.max( this.x, v.x );
  489. this.y = Math.max( this.y, v.y );
  490. return this;
  491. },
  492. clamp: function ( min, max ) {
  493. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  494. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  495. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  496. return this;
  497. },
  498. clampScalar: function () {
  499. var min, max;
  500. return function clampScalar( minVal, maxVal ) {
  501. if ( min === undefined ) {
  502. min = new Vector2();
  503. max = new Vector2();
  504. }
  505. min.set( minVal, minVal );
  506. max.set( maxVal, maxVal );
  507. return this.clamp( min, max );
  508. };
  509. }(),
  510. clampLength: function ( min, max ) {
  511. var length = this.length();
  512. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  513. },
  514. floor: function () {
  515. this.x = Math.floor( this.x );
  516. this.y = Math.floor( this.y );
  517. return this;
  518. },
  519. ceil: function () {
  520. this.x = Math.ceil( this.x );
  521. this.y = Math.ceil( this.y );
  522. return this;
  523. },
  524. round: function () {
  525. this.x = Math.round( this.x );
  526. this.y = Math.round( this.y );
  527. return this;
  528. },
  529. roundToZero: function () {
  530. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  531. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  532. return this;
  533. },
  534. negate: function () {
  535. this.x = - this.x;
  536. this.y = - this.y;
  537. return this;
  538. },
  539. dot: function ( v ) {
  540. return this.x * v.x + this.y * v.y;
  541. },
  542. lengthSq: function () {
  543. return this.x * this.x + this.y * this.y;
  544. },
  545. length: function () {
  546. return Math.sqrt( this.x * this.x + this.y * this.y );
  547. },
  548. lengthManhattan: function() {
  549. return Math.abs( this.x ) + Math.abs( this.y );
  550. },
  551. normalize: function () {
  552. return this.divideScalar( this.length() );
  553. },
  554. angle: function () {
  555. // computes the angle in radians with respect to the positive x-axis
  556. var angle = Math.atan2( this.y, this.x );
  557. if ( angle < 0 ) angle += 2 * Math.PI;
  558. return angle;
  559. },
  560. distanceTo: function ( v ) {
  561. return Math.sqrt( this.distanceToSquared( v ) );
  562. },
  563. distanceToSquared: function ( v ) {
  564. var dx = this.x - v.x, dy = this.y - v.y;
  565. return dx * dx + dy * dy;
  566. },
  567. distanceToManhattan: function ( v ) {
  568. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  569. },
  570. setLength: function ( length ) {
  571. return this.multiplyScalar( length / this.length() );
  572. },
  573. lerp: function ( v, alpha ) {
  574. this.x += ( v.x - this.x ) * alpha;
  575. this.y += ( v.y - this.y ) * alpha;
  576. return this;
  577. },
  578. lerpVectors: function ( v1, v2, alpha ) {
  579. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  580. },
  581. equals: function ( v ) {
  582. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  583. },
  584. fromArray: function ( array, offset ) {
  585. if ( offset === undefined ) offset = 0;
  586. this.x = array[ offset ];
  587. this.y = array[ offset + 1 ];
  588. return this;
  589. },
  590. toArray: function ( array, offset ) {
  591. if ( array === undefined ) array = [];
  592. if ( offset === undefined ) offset = 0;
  593. array[ offset ] = this.x;
  594. array[ offset + 1 ] = this.y;
  595. return array;
  596. },
  597. fromAttribute: function ( attribute, index, offset ) {
  598. if ( offset === undefined ) offset = 0;
  599. index = index * attribute.itemSize + offset;
  600. this.x = attribute.array[ index ];
  601. this.y = attribute.array[ index + 1 ];
  602. return this;
  603. },
  604. rotateAround: function ( center, angle ) {
  605. var c = Math.cos( angle ), s = Math.sin( angle );
  606. var x = this.x - center.x;
  607. var y = this.y - center.y;
  608. this.x = x * c - y * s + center.x;
  609. this.y = x * s + y * c + center.y;
  610. return this;
  611. }
  612. };
  613. /**
  614. * @author mrdoob / http://mrdoob.com/
  615. * @author alteredq / http://alteredqualia.com/
  616. * @author szimek / https://github.com/szimek/
  617. */
  618. var textureId = 0;
  619. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  620. Object.defineProperty( this, 'id', { value: textureId ++ } );
  621. this.uuid = _Math.generateUUID();
  622. this.name = '';
  623. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  624. this.mipmaps = [];
  625. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  626. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  627. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  628. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  629. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  630. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  631. this.format = format !== undefined ? format : RGBAFormat;
  632. this.type = type !== undefined ? type : UnsignedByteType;
  633. this.offset = new Vector2( 0, 0 );
  634. this.repeat = new Vector2( 1, 1 );
  635. this.generateMipmaps = true;
  636. this.premultiplyAlpha = false;
  637. this.flipY = true;
  638. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  639. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  640. //
  641. // Also changing the encoding after already used by a Material will not automatically make the Material
  642. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  643. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  644. this.version = 0;
  645. this.onUpdate = null;
  646. }
  647. Texture.DEFAULT_IMAGE = undefined;
  648. Texture.DEFAULT_MAPPING = UVMapping;
  649. Texture.prototype = {
  650. constructor: Texture,
  651. isTexture: true,
  652. set needsUpdate( value ) {
  653. if ( value === true ) this.version ++;
  654. },
  655. clone: function () {
  656. return new this.constructor().copy( this );
  657. },
  658. copy: function ( source ) {
  659. this.image = source.image;
  660. this.mipmaps = source.mipmaps.slice( 0 );
  661. this.mapping = source.mapping;
  662. this.wrapS = source.wrapS;
  663. this.wrapT = source.wrapT;
  664. this.magFilter = source.magFilter;
  665. this.minFilter = source.minFilter;
  666. this.anisotropy = source.anisotropy;
  667. this.format = source.format;
  668. this.type = source.type;
  669. this.offset.copy( source.offset );
  670. this.repeat.copy( source.repeat );
  671. this.generateMipmaps = source.generateMipmaps;
  672. this.premultiplyAlpha = source.premultiplyAlpha;
  673. this.flipY = source.flipY;
  674. this.unpackAlignment = source.unpackAlignment;
  675. this.encoding = source.encoding;
  676. return this;
  677. },
  678. toJSON: function ( meta ) {
  679. if ( meta.textures[ this.uuid ] !== undefined ) {
  680. return meta.textures[ this.uuid ];
  681. }
  682. function getDataURL( image ) {
  683. var canvas;
  684. if ( image.toDataURL !== undefined ) {
  685. canvas = image;
  686. } else {
  687. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  688. canvas.width = image.width;
  689. canvas.height = image.height;
  690. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  691. }
  692. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  693. return canvas.toDataURL( 'image/jpeg', 0.6 );
  694. } else {
  695. return canvas.toDataURL( 'image/png' );
  696. }
  697. }
  698. var output = {
  699. metadata: {
  700. version: 4.4,
  701. type: 'Texture',
  702. generator: 'Texture.toJSON'
  703. },
  704. uuid: this.uuid,
  705. name: this.name,
  706. mapping: this.mapping,
  707. repeat: [ this.repeat.x, this.repeat.y ],
  708. offset: [ this.offset.x, this.offset.y ],
  709. wrap: [ this.wrapS, this.wrapT ],
  710. minFilter: this.minFilter,
  711. magFilter: this.magFilter,
  712. anisotropy: this.anisotropy,
  713. flipY: this.flipY
  714. };
  715. if ( this.image !== undefined ) {
  716. // TODO: Move to THREE.Image
  717. var image = this.image;
  718. if ( image.uuid === undefined ) {
  719. image.uuid = _Math.generateUUID(); // UGH
  720. }
  721. if ( meta.images[ image.uuid ] === undefined ) {
  722. meta.images[ image.uuid ] = {
  723. uuid: image.uuid,
  724. url: getDataURL( image )
  725. };
  726. }
  727. output.image = image.uuid;
  728. }
  729. meta.textures[ this.uuid ] = output;
  730. return output;
  731. },
  732. dispose: function () {
  733. this.dispatchEvent( { type: 'dispose' } );
  734. },
  735. transformUv: function ( uv ) {
  736. if ( this.mapping !== UVMapping ) return;
  737. uv.multiply( this.repeat );
  738. uv.add( this.offset );
  739. if ( uv.x < 0 || uv.x > 1 ) {
  740. switch ( this.wrapS ) {
  741. case RepeatWrapping:
  742. uv.x = uv.x - Math.floor( uv.x );
  743. break;
  744. case ClampToEdgeWrapping:
  745. uv.x = uv.x < 0 ? 0 : 1;
  746. break;
  747. case MirroredRepeatWrapping:
  748. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  749. uv.x = Math.ceil( uv.x ) - uv.x;
  750. } else {
  751. uv.x = uv.x - Math.floor( uv.x );
  752. }
  753. break;
  754. }
  755. }
  756. if ( uv.y < 0 || uv.y > 1 ) {
  757. switch ( this.wrapT ) {
  758. case RepeatWrapping:
  759. uv.y = uv.y - Math.floor( uv.y );
  760. break;
  761. case ClampToEdgeWrapping:
  762. uv.y = uv.y < 0 ? 0 : 1;
  763. break;
  764. case MirroredRepeatWrapping:
  765. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  766. uv.y = Math.ceil( uv.y ) - uv.y;
  767. } else {
  768. uv.y = uv.y - Math.floor( uv.y );
  769. }
  770. break;
  771. }
  772. }
  773. if ( this.flipY ) {
  774. uv.y = 1 - uv.y;
  775. }
  776. }
  777. };
  778. Object.assign( Texture.prototype, EventDispatcher.prototype );
  779. /**
  780. * @author supereggbert / http://www.paulbrunt.co.uk/
  781. * @author philogb / http://blog.thejit.org/
  782. * @author mikael emtinger / http://gomo.se/
  783. * @author egraether / http://egraether.com/
  784. * @author WestLangley / http://github.com/WestLangley
  785. */
  786. function Vector4( x, y, z, w ) {
  787. this.x = x || 0;
  788. this.y = y || 0;
  789. this.z = z || 0;
  790. this.w = ( w !== undefined ) ? w : 1;
  791. }
  792. Vector4.prototype = {
  793. constructor: Vector4,
  794. isVector4: true,
  795. set: function ( x, y, z, w ) {
  796. this.x = x;
  797. this.y = y;
  798. this.z = z;
  799. this.w = w;
  800. return this;
  801. },
  802. setScalar: function ( scalar ) {
  803. this.x = scalar;
  804. this.y = scalar;
  805. this.z = scalar;
  806. this.w = scalar;
  807. return this;
  808. },
  809. setX: function ( x ) {
  810. this.x = x;
  811. return this;
  812. },
  813. setY: function ( y ) {
  814. this.y = y;
  815. return this;
  816. },
  817. setZ: function ( z ) {
  818. this.z = z;
  819. return this;
  820. },
  821. setW: function ( w ) {
  822. this.w = w;
  823. return this;
  824. },
  825. setComponent: function ( index, value ) {
  826. switch ( index ) {
  827. case 0: this.x = value; break;
  828. case 1: this.y = value; break;
  829. case 2: this.z = value; break;
  830. case 3: this.w = value; break;
  831. default: throw new Error( 'index is out of range: ' + index );
  832. }
  833. return this;
  834. },
  835. getComponent: function ( index ) {
  836. switch ( index ) {
  837. case 0: return this.x;
  838. case 1: return this.y;
  839. case 2: return this.z;
  840. case 3: return this.w;
  841. default: throw new Error( 'index is out of range: ' + index );
  842. }
  843. },
  844. clone: function () {
  845. return new this.constructor( this.x, this.y, this.z, this.w );
  846. },
  847. copy: function ( v ) {
  848. this.x = v.x;
  849. this.y = v.y;
  850. this.z = v.z;
  851. this.w = ( v.w !== undefined ) ? v.w : 1;
  852. return this;
  853. },
  854. add: function ( v, w ) {
  855. if ( w !== undefined ) {
  856. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  857. return this.addVectors( v, w );
  858. }
  859. this.x += v.x;
  860. this.y += v.y;
  861. this.z += v.z;
  862. this.w += v.w;
  863. return this;
  864. },
  865. addScalar: function ( s ) {
  866. this.x += s;
  867. this.y += s;
  868. this.z += s;
  869. this.w += s;
  870. return this;
  871. },
  872. addVectors: function ( a, b ) {
  873. this.x = a.x + b.x;
  874. this.y = a.y + b.y;
  875. this.z = a.z + b.z;
  876. this.w = a.w + b.w;
  877. return this;
  878. },
  879. addScaledVector: function ( v, s ) {
  880. this.x += v.x * s;
  881. this.y += v.y * s;
  882. this.z += v.z * s;
  883. this.w += v.w * s;
  884. return this;
  885. },
  886. sub: function ( v, w ) {
  887. if ( w !== undefined ) {
  888. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  889. return this.subVectors( v, w );
  890. }
  891. this.x -= v.x;
  892. this.y -= v.y;
  893. this.z -= v.z;
  894. this.w -= v.w;
  895. return this;
  896. },
  897. subScalar: function ( s ) {
  898. this.x -= s;
  899. this.y -= s;
  900. this.z -= s;
  901. this.w -= s;
  902. return this;
  903. },
  904. subVectors: function ( a, b ) {
  905. this.x = a.x - b.x;
  906. this.y = a.y - b.y;
  907. this.z = a.z - b.z;
  908. this.w = a.w - b.w;
  909. return this;
  910. },
  911. multiplyScalar: function ( scalar ) {
  912. if ( isFinite( scalar ) ) {
  913. this.x *= scalar;
  914. this.y *= scalar;
  915. this.z *= scalar;
  916. this.w *= scalar;
  917. } else {
  918. this.x = 0;
  919. this.y = 0;
  920. this.z = 0;
  921. this.w = 0;
  922. }
  923. return this;
  924. },
  925. applyMatrix4: function ( m ) {
  926. var x = this.x, y = this.y, z = this.z, w = this.w;
  927. var e = m.elements;
  928. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  929. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  930. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  931. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  932. return this;
  933. },
  934. divideScalar: function ( scalar ) {
  935. return this.multiplyScalar( 1 / scalar );
  936. },
  937. setAxisAngleFromQuaternion: function ( q ) {
  938. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  939. // q is assumed to be normalized
  940. this.w = 2 * Math.acos( q.w );
  941. var s = Math.sqrt( 1 - q.w * q.w );
  942. if ( s < 0.0001 ) {
  943. this.x = 1;
  944. this.y = 0;
  945. this.z = 0;
  946. } else {
  947. this.x = q.x / s;
  948. this.y = q.y / s;
  949. this.z = q.z / s;
  950. }
  951. return this;
  952. },
  953. setAxisAngleFromRotationMatrix: function ( m ) {
  954. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  955. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  956. var angle, x, y, z, // variables for result
  957. epsilon = 0.01, // margin to allow for rounding errors
  958. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  959. te = m.elements,
  960. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  961. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  962. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  963. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  964. ( Math.abs( m13 - m31 ) < epsilon ) &&
  965. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  966. // singularity found
  967. // first check for identity matrix which must have +1 for all terms
  968. // in leading diagonal and zero in other terms
  969. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  970. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  971. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  972. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  973. // this singularity is identity matrix so angle = 0
  974. this.set( 1, 0, 0, 0 );
  975. return this; // zero angle, arbitrary axis
  976. }
  977. // otherwise this singularity is angle = 180
  978. angle = Math.PI;
  979. var xx = ( m11 + 1 ) / 2;
  980. var yy = ( m22 + 1 ) / 2;
  981. var zz = ( m33 + 1 ) / 2;
  982. var xy = ( m12 + m21 ) / 4;
  983. var xz = ( m13 + m31 ) / 4;
  984. var yz = ( m23 + m32 ) / 4;
  985. if ( ( xx > yy ) && ( xx > zz ) ) {
  986. // m11 is the largest diagonal term
  987. if ( xx < epsilon ) {
  988. x = 0;
  989. y = 0.707106781;
  990. z = 0.707106781;
  991. } else {
  992. x = Math.sqrt( xx );
  993. y = xy / x;
  994. z = xz / x;
  995. }
  996. } else if ( yy > zz ) {
  997. // m22 is the largest diagonal term
  998. if ( yy < epsilon ) {
  999. x = 0.707106781;
  1000. y = 0;
  1001. z = 0.707106781;
  1002. } else {
  1003. y = Math.sqrt( yy );
  1004. x = xy / y;
  1005. z = yz / y;
  1006. }
  1007. } else {
  1008. // m33 is the largest diagonal term so base result on this
  1009. if ( zz < epsilon ) {
  1010. x = 0.707106781;
  1011. y = 0.707106781;
  1012. z = 0;
  1013. } else {
  1014. z = Math.sqrt( zz );
  1015. x = xz / z;
  1016. y = yz / z;
  1017. }
  1018. }
  1019. this.set( x, y, z, angle );
  1020. return this; // return 180 deg rotation
  1021. }
  1022. // as we have reached here there are no singularities so we can handle normally
  1023. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1024. ( m13 - m31 ) * ( m13 - m31 ) +
  1025. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1026. if ( Math.abs( s ) < 0.001 ) s = 1;
  1027. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1028. // caught by singularity test above, but I've left it in just in case
  1029. this.x = ( m32 - m23 ) / s;
  1030. this.y = ( m13 - m31 ) / s;
  1031. this.z = ( m21 - m12 ) / s;
  1032. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1033. return this;
  1034. },
  1035. min: function ( v ) {
  1036. this.x = Math.min( this.x, v.x );
  1037. this.y = Math.min( this.y, v.y );
  1038. this.z = Math.min( this.z, v.z );
  1039. this.w = Math.min( this.w, v.w );
  1040. return this;
  1041. },
  1042. max: function ( v ) {
  1043. this.x = Math.max( this.x, v.x );
  1044. this.y = Math.max( this.y, v.y );
  1045. this.z = Math.max( this.z, v.z );
  1046. this.w = Math.max( this.w, v.w );
  1047. return this;
  1048. },
  1049. clamp: function ( min, max ) {
  1050. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1051. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1052. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1053. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1054. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1055. return this;
  1056. },
  1057. clampScalar: function () {
  1058. var min, max;
  1059. return function clampScalar( minVal, maxVal ) {
  1060. if ( min === undefined ) {
  1061. min = new Vector4();
  1062. max = new Vector4();
  1063. }
  1064. min.set( minVal, minVal, minVal, minVal );
  1065. max.set( maxVal, maxVal, maxVal, maxVal );
  1066. return this.clamp( min, max );
  1067. };
  1068. }(),
  1069. floor: function () {
  1070. this.x = Math.floor( this.x );
  1071. this.y = Math.floor( this.y );
  1072. this.z = Math.floor( this.z );
  1073. this.w = Math.floor( this.w );
  1074. return this;
  1075. },
  1076. ceil: function () {
  1077. this.x = Math.ceil( this.x );
  1078. this.y = Math.ceil( this.y );
  1079. this.z = Math.ceil( this.z );
  1080. this.w = Math.ceil( this.w );
  1081. return this;
  1082. },
  1083. round: function () {
  1084. this.x = Math.round( this.x );
  1085. this.y = Math.round( this.y );
  1086. this.z = Math.round( this.z );
  1087. this.w = Math.round( this.w );
  1088. return this;
  1089. },
  1090. roundToZero: function () {
  1091. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1092. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1093. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1094. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1095. return this;
  1096. },
  1097. negate: function () {
  1098. this.x = - this.x;
  1099. this.y = - this.y;
  1100. this.z = - this.z;
  1101. this.w = - this.w;
  1102. return this;
  1103. },
  1104. dot: function ( v ) {
  1105. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1106. },
  1107. lengthSq: function () {
  1108. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1109. },
  1110. length: function () {
  1111. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1112. },
  1113. lengthManhattan: function () {
  1114. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1115. },
  1116. normalize: function () {
  1117. return this.divideScalar( this.length() );
  1118. },
  1119. setLength: function ( length ) {
  1120. return this.multiplyScalar( length / this.length() );
  1121. },
  1122. lerp: function ( v, alpha ) {
  1123. this.x += ( v.x - this.x ) * alpha;
  1124. this.y += ( v.y - this.y ) * alpha;
  1125. this.z += ( v.z - this.z ) * alpha;
  1126. this.w += ( v.w - this.w ) * alpha;
  1127. return this;
  1128. },
  1129. lerpVectors: function ( v1, v2, alpha ) {
  1130. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1131. },
  1132. equals: function ( v ) {
  1133. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1134. },
  1135. fromArray: function ( array, offset ) {
  1136. if ( offset === undefined ) offset = 0;
  1137. this.x = array[ offset ];
  1138. this.y = array[ offset + 1 ];
  1139. this.z = array[ offset + 2 ];
  1140. this.w = array[ offset + 3 ];
  1141. return this;
  1142. },
  1143. toArray: function ( array, offset ) {
  1144. if ( array === undefined ) array = [];
  1145. if ( offset === undefined ) offset = 0;
  1146. array[ offset ] = this.x;
  1147. array[ offset + 1 ] = this.y;
  1148. array[ offset + 2 ] = this.z;
  1149. array[ offset + 3 ] = this.w;
  1150. return array;
  1151. },
  1152. fromAttribute: function ( attribute, index, offset ) {
  1153. if ( offset === undefined ) offset = 0;
  1154. index = index * attribute.itemSize + offset;
  1155. this.x = attribute.array[ index ];
  1156. this.y = attribute.array[ index + 1 ];
  1157. this.z = attribute.array[ index + 2 ];
  1158. this.w = attribute.array[ index + 3 ];
  1159. return this;
  1160. }
  1161. };
  1162. /**
  1163. * @author szimek / https://github.com/szimek/
  1164. * @author alteredq / http://alteredqualia.com/
  1165. * @author Marius Kintel / https://github.com/kintel
  1166. */
  1167. /*
  1168. In options, we can specify:
  1169. * Texture parameters for an auto-generated target texture
  1170. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1171. */
  1172. function WebGLRenderTarget( width, height, options ) {
  1173. this.uuid = _Math.generateUUID();
  1174. this.width = width;
  1175. this.height = height;
  1176. this.scissor = new Vector4( 0, 0, width, height );
  1177. this.scissorTest = false;
  1178. this.viewport = new Vector4( 0, 0, width, height );
  1179. options = options || {};
  1180. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  1181. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1182. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1183. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  1184. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1185. }
  1186. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, {
  1187. isWebGLRenderTarget: true,
  1188. setSize: function ( width, height ) {
  1189. if ( this.width !== width || this.height !== height ) {
  1190. this.width = width;
  1191. this.height = height;
  1192. this.dispose();
  1193. }
  1194. this.viewport.set( 0, 0, width, height );
  1195. this.scissor.set( 0, 0, width, height );
  1196. },
  1197. clone: function () {
  1198. return new this.constructor().copy( this );
  1199. },
  1200. copy: function ( source ) {
  1201. this.width = source.width;
  1202. this.height = source.height;
  1203. this.viewport.copy( source.viewport );
  1204. this.texture = source.texture.clone();
  1205. this.depthBuffer = source.depthBuffer;
  1206. this.stencilBuffer = source.stencilBuffer;
  1207. this.depthTexture = source.depthTexture;
  1208. return this;
  1209. },
  1210. dispose: function () {
  1211. this.dispatchEvent( { type: 'dispose' } );
  1212. }
  1213. } );
  1214. /**
  1215. * @author alteredq / http://alteredqualia.com
  1216. */
  1217. function WebGLRenderTargetCube( width, height, options ) {
  1218. WebGLRenderTarget.call( this, width, height, options );
  1219. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  1220. this.activeMipMapLevel = 0;
  1221. }
  1222. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  1223. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  1224. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  1225. /**
  1226. * @author mikael emtinger / http://gomo.se/
  1227. * @author alteredq / http://alteredqualia.com/
  1228. * @author WestLangley / http://github.com/WestLangley
  1229. * @author bhouston / http://clara.io
  1230. */
  1231. function Quaternion( x, y, z, w ) {
  1232. this._x = x || 0;
  1233. this._y = y || 0;
  1234. this._z = z || 0;
  1235. this._w = ( w !== undefined ) ? w : 1;
  1236. }
  1237. Quaternion.prototype = {
  1238. constructor: Quaternion,
  1239. get x () {
  1240. return this._x;
  1241. },
  1242. set x ( value ) {
  1243. this._x = value;
  1244. this.onChangeCallback();
  1245. },
  1246. get y () {
  1247. return this._y;
  1248. },
  1249. set y ( value ) {
  1250. this._y = value;
  1251. this.onChangeCallback();
  1252. },
  1253. get z () {
  1254. return this._z;
  1255. },
  1256. set z ( value ) {
  1257. this._z = value;
  1258. this.onChangeCallback();
  1259. },
  1260. get w () {
  1261. return this._w;
  1262. },
  1263. set w ( value ) {
  1264. this._w = value;
  1265. this.onChangeCallback();
  1266. },
  1267. set: function ( x, y, z, w ) {
  1268. this._x = x;
  1269. this._y = y;
  1270. this._z = z;
  1271. this._w = w;
  1272. this.onChangeCallback();
  1273. return this;
  1274. },
  1275. clone: function () {
  1276. return new this.constructor( this._x, this._y, this._z, this._w );
  1277. },
  1278. copy: function ( quaternion ) {
  1279. this._x = quaternion.x;
  1280. this._y = quaternion.y;
  1281. this._z = quaternion.z;
  1282. this._w = quaternion.w;
  1283. this.onChangeCallback();
  1284. return this;
  1285. },
  1286. setFromEuler: function ( euler, update ) {
  1287. if ( (euler && euler.isEuler) === false ) {
  1288. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1289. }
  1290. // http://www.mathworks.com/matlabcentral/fileexchange/
  1291. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1292. // content/SpinCalc.m
  1293. var c1 = Math.cos( euler._x / 2 );
  1294. var c2 = Math.cos( euler._y / 2 );
  1295. var c3 = Math.cos( euler._z / 2 );
  1296. var s1 = Math.sin( euler._x / 2 );
  1297. var s2 = Math.sin( euler._y / 2 );
  1298. var s3 = Math.sin( euler._z / 2 );
  1299. var order = euler.order;
  1300. if ( order === 'XYZ' ) {
  1301. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1302. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1303. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1304. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1305. } else if ( order === 'YXZ' ) {
  1306. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1307. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1308. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1309. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1310. } else if ( order === 'ZXY' ) {
  1311. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1312. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1313. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1314. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1315. } else if ( order === 'ZYX' ) {
  1316. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1317. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1318. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1319. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1320. } else if ( order === 'YZX' ) {
  1321. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1322. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1323. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1324. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1325. } else if ( order === 'XZY' ) {
  1326. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1327. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1328. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1329. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1330. }
  1331. if ( update !== false ) this.onChangeCallback();
  1332. return this;
  1333. },
  1334. setFromAxisAngle: function ( axis, angle ) {
  1335. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1336. // assumes axis is normalized
  1337. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  1338. this._x = axis.x * s;
  1339. this._y = axis.y * s;
  1340. this._z = axis.z * s;
  1341. this._w = Math.cos( halfAngle );
  1342. this.onChangeCallback();
  1343. return this;
  1344. },
  1345. setFromRotationMatrix: function ( m ) {
  1346. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1347. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1348. var te = m.elements,
  1349. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1350. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1351. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1352. trace = m11 + m22 + m33,
  1353. s;
  1354. if ( trace > 0 ) {
  1355. s = 0.5 / Math.sqrt( trace + 1.0 );
  1356. this._w = 0.25 / s;
  1357. this._x = ( m32 - m23 ) * s;
  1358. this._y = ( m13 - m31 ) * s;
  1359. this._z = ( m21 - m12 ) * s;
  1360. } else if ( m11 > m22 && m11 > m33 ) {
  1361. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1362. this._w = ( m32 - m23 ) / s;
  1363. this._x = 0.25 * s;
  1364. this._y = ( m12 + m21 ) / s;
  1365. this._z = ( m13 + m31 ) / s;
  1366. } else if ( m22 > m33 ) {
  1367. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1368. this._w = ( m13 - m31 ) / s;
  1369. this._x = ( m12 + m21 ) / s;
  1370. this._y = 0.25 * s;
  1371. this._z = ( m23 + m32 ) / s;
  1372. } else {
  1373. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1374. this._w = ( m21 - m12 ) / s;
  1375. this._x = ( m13 + m31 ) / s;
  1376. this._y = ( m23 + m32 ) / s;
  1377. this._z = 0.25 * s;
  1378. }
  1379. this.onChangeCallback();
  1380. return this;
  1381. },
  1382. setFromUnitVectors: function () {
  1383. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  1384. // assumes direction vectors vFrom and vTo are normalized
  1385. var v1, r;
  1386. var EPS = 0.000001;
  1387. return function setFromUnitVectors( vFrom, vTo ) {
  1388. if ( v1 === undefined ) v1 = new Vector3();
  1389. r = vFrom.dot( vTo ) + 1;
  1390. if ( r < EPS ) {
  1391. r = 0;
  1392. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1393. v1.set( - vFrom.y, vFrom.x, 0 );
  1394. } else {
  1395. v1.set( 0, - vFrom.z, vFrom.y );
  1396. }
  1397. } else {
  1398. v1.crossVectors( vFrom, vTo );
  1399. }
  1400. this._x = v1.x;
  1401. this._y = v1.y;
  1402. this._z = v1.z;
  1403. this._w = r;
  1404. return this.normalize();
  1405. };
  1406. }(),
  1407. inverse: function () {
  1408. return this.conjugate().normalize();
  1409. },
  1410. conjugate: function () {
  1411. this._x *= - 1;
  1412. this._y *= - 1;
  1413. this._z *= - 1;
  1414. this.onChangeCallback();
  1415. return this;
  1416. },
  1417. dot: function ( v ) {
  1418. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1419. },
  1420. lengthSq: function () {
  1421. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1422. },
  1423. length: function () {
  1424. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1425. },
  1426. normalize: function () {
  1427. var l = this.length();
  1428. if ( l === 0 ) {
  1429. this._x = 0;
  1430. this._y = 0;
  1431. this._z = 0;
  1432. this._w = 1;
  1433. } else {
  1434. l = 1 / l;
  1435. this._x = this._x * l;
  1436. this._y = this._y * l;
  1437. this._z = this._z * l;
  1438. this._w = this._w * l;
  1439. }
  1440. this.onChangeCallback();
  1441. return this;
  1442. },
  1443. multiply: function ( q, p ) {
  1444. if ( p !== undefined ) {
  1445. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1446. return this.multiplyQuaternions( q, p );
  1447. }
  1448. return this.multiplyQuaternions( this, q );
  1449. },
  1450. premultiply: function ( q ) {
  1451. return this.multiplyQuaternions( q, this );
  1452. },
  1453. multiplyQuaternions: function ( a, b ) {
  1454. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1455. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1456. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1457. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1458. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1459. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1460. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1461. this.onChangeCallback();
  1462. return this;
  1463. },
  1464. slerp: function ( qb, t ) {
  1465. if ( t === 0 ) return this;
  1466. if ( t === 1 ) return this.copy( qb );
  1467. var x = this._x, y = this._y, z = this._z, w = this._w;
  1468. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1469. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1470. if ( cosHalfTheta < 0 ) {
  1471. this._w = - qb._w;
  1472. this._x = - qb._x;
  1473. this._y = - qb._y;
  1474. this._z = - qb._z;
  1475. cosHalfTheta = - cosHalfTheta;
  1476. } else {
  1477. this.copy( qb );
  1478. }
  1479. if ( cosHalfTheta >= 1.0 ) {
  1480. this._w = w;
  1481. this._x = x;
  1482. this._y = y;
  1483. this._z = z;
  1484. return this;
  1485. }
  1486. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  1487. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  1488. this._w = 0.5 * ( w + this._w );
  1489. this._x = 0.5 * ( x + this._x );
  1490. this._y = 0.5 * ( y + this._y );
  1491. this._z = 0.5 * ( z + this._z );
  1492. return this;
  1493. }
  1494. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1495. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1496. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1497. this._w = ( w * ratioA + this._w * ratioB );
  1498. this._x = ( x * ratioA + this._x * ratioB );
  1499. this._y = ( y * ratioA + this._y * ratioB );
  1500. this._z = ( z * ratioA + this._z * ratioB );
  1501. this.onChangeCallback();
  1502. return this;
  1503. },
  1504. equals: function ( quaternion ) {
  1505. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1506. },
  1507. fromArray: function ( array, offset ) {
  1508. if ( offset === undefined ) offset = 0;
  1509. this._x = array[ offset ];
  1510. this._y = array[ offset + 1 ];
  1511. this._z = array[ offset + 2 ];
  1512. this._w = array[ offset + 3 ];
  1513. this.onChangeCallback();
  1514. return this;
  1515. },
  1516. toArray: function ( array, offset ) {
  1517. if ( array === undefined ) array = [];
  1518. if ( offset === undefined ) offset = 0;
  1519. array[ offset ] = this._x;
  1520. array[ offset + 1 ] = this._y;
  1521. array[ offset + 2 ] = this._z;
  1522. array[ offset + 3 ] = this._w;
  1523. return array;
  1524. },
  1525. onChange: function ( callback ) {
  1526. this.onChangeCallback = callback;
  1527. return this;
  1528. },
  1529. onChangeCallback: function () {}
  1530. };
  1531. Object.assign( Quaternion, {
  1532. slerp: function( qa, qb, qm, t ) {
  1533. return qm.copy( qa ).slerp( qb, t );
  1534. },
  1535. slerpFlat: function(
  1536. dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1537. // fuzz-free, array-based Quaternion SLERP operation
  1538. var x0 = src0[ srcOffset0 + 0 ],
  1539. y0 = src0[ srcOffset0 + 1 ],
  1540. z0 = src0[ srcOffset0 + 2 ],
  1541. w0 = src0[ srcOffset0 + 3 ],
  1542. x1 = src1[ srcOffset1 + 0 ],
  1543. y1 = src1[ srcOffset1 + 1 ],
  1544. z1 = src1[ srcOffset1 + 2 ],
  1545. w1 = src1[ srcOffset1 + 3 ];
  1546. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1547. var s = 1 - t,
  1548. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1549. dir = ( cos >= 0 ? 1 : - 1 ),
  1550. sqrSin = 1 - cos * cos;
  1551. // Skip the Slerp for tiny steps to avoid numeric problems:
  1552. if ( sqrSin > Number.EPSILON ) {
  1553. var sin = Math.sqrt( sqrSin ),
  1554. len = Math.atan2( sin, cos * dir );
  1555. s = Math.sin( s * len ) / sin;
  1556. t = Math.sin( t * len ) / sin;
  1557. }
  1558. var tDir = t * dir;
  1559. x0 = x0 * s + x1 * tDir;
  1560. y0 = y0 * s + y1 * tDir;
  1561. z0 = z0 * s + z1 * tDir;
  1562. w0 = w0 * s + w1 * tDir;
  1563. // Normalize in case we just did a lerp:
  1564. if ( s === 1 - t ) {
  1565. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1566. x0 *= f;
  1567. y0 *= f;
  1568. z0 *= f;
  1569. w0 *= f;
  1570. }
  1571. }
  1572. dst[ dstOffset ] = x0;
  1573. dst[ dstOffset + 1 ] = y0;
  1574. dst[ dstOffset + 2 ] = z0;
  1575. dst[ dstOffset + 3 ] = w0;
  1576. }
  1577. } );
  1578. /**
  1579. * @author mrdoob / http://mrdoob.com/
  1580. * @author *kile / http://kile.stravaganza.org/
  1581. * @author philogb / http://blog.thejit.org/
  1582. * @author mikael emtinger / http://gomo.se/
  1583. * @author egraether / http://egraether.com/
  1584. * @author WestLangley / http://github.com/WestLangley
  1585. */
  1586. function Vector3( x, y, z ) {
  1587. this.x = x || 0;
  1588. this.y = y || 0;
  1589. this.z = z || 0;
  1590. }
  1591. Vector3.prototype = {
  1592. constructor: Vector3,
  1593. isVector3: true,
  1594. set: function ( x, y, z ) {
  1595. this.x = x;
  1596. this.y = y;
  1597. this.z = z;
  1598. return this;
  1599. },
  1600. setScalar: function ( scalar ) {
  1601. this.x = scalar;
  1602. this.y = scalar;
  1603. this.z = scalar;
  1604. return this;
  1605. },
  1606. setX: function ( x ) {
  1607. this.x = x;
  1608. return this;
  1609. },
  1610. setY: function ( y ) {
  1611. this.y = y;
  1612. return this;
  1613. },
  1614. setZ: function ( z ) {
  1615. this.z = z;
  1616. return this;
  1617. },
  1618. setComponent: function ( index, value ) {
  1619. switch ( index ) {
  1620. case 0: this.x = value; break;
  1621. case 1: this.y = value; break;
  1622. case 2: this.z = value; break;
  1623. default: throw new Error( 'index is out of range: ' + index );
  1624. }
  1625. return this;
  1626. },
  1627. getComponent: function ( index ) {
  1628. switch ( index ) {
  1629. case 0: return this.x;
  1630. case 1: return this.y;
  1631. case 2: return this.z;
  1632. default: throw new Error( 'index is out of range: ' + index );
  1633. }
  1634. },
  1635. clone: function () {
  1636. return new this.constructor( this.x, this.y, this.z );
  1637. },
  1638. copy: function ( v ) {
  1639. this.x = v.x;
  1640. this.y = v.y;
  1641. this.z = v.z;
  1642. return this;
  1643. },
  1644. add: function ( v, w ) {
  1645. if ( w !== undefined ) {
  1646. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1647. return this.addVectors( v, w );
  1648. }
  1649. this.x += v.x;
  1650. this.y += v.y;
  1651. this.z += v.z;
  1652. return this;
  1653. },
  1654. addScalar: function ( s ) {
  1655. this.x += s;
  1656. this.y += s;
  1657. this.z += s;
  1658. return this;
  1659. },
  1660. addVectors: function ( a, b ) {
  1661. this.x = a.x + b.x;
  1662. this.y = a.y + b.y;
  1663. this.z = a.z + b.z;
  1664. return this;
  1665. },
  1666. addScaledVector: function ( v, s ) {
  1667. this.x += v.x * s;
  1668. this.y += v.y * s;
  1669. this.z += v.z * s;
  1670. return this;
  1671. },
  1672. sub: function ( v, w ) {
  1673. if ( w !== undefined ) {
  1674. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1675. return this.subVectors( v, w );
  1676. }
  1677. this.x -= v.x;
  1678. this.y -= v.y;
  1679. this.z -= v.z;
  1680. return this;
  1681. },
  1682. subScalar: function ( s ) {
  1683. this.x -= s;
  1684. this.y -= s;
  1685. this.z -= s;
  1686. return this;
  1687. },
  1688. subVectors: function ( a, b ) {
  1689. this.x = a.x - b.x;
  1690. this.y = a.y - b.y;
  1691. this.z = a.z - b.z;
  1692. return this;
  1693. },
  1694. multiply: function ( v, w ) {
  1695. if ( w !== undefined ) {
  1696. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1697. return this.multiplyVectors( v, w );
  1698. }
  1699. this.x *= v.x;
  1700. this.y *= v.y;
  1701. this.z *= v.z;
  1702. return this;
  1703. },
  1704. multiplyScalar: function ( scalar ) {
  1705. if ( isFinite( scalar ) ) {
  1706. this.x *= scalar;
  1707. this.y *= scalar;
  1708. this.z *= scalar;
  1709. } else {
  1710. this.x = 0;
  1711. this.y = 0;
  1712. this.z = 0;
  1713. }
  1714. return this;
  1715. },
  1716. multiplyVectors: function ( a, b ) {
  1717. this.x = a.x * b.x;
  1718. this.y = a.y * b.y;
  1719. this.z = a.z * b.z;
  1720. return this;
  1721. },
  1722. applyEuler: function () {
  1723. var quaternion;
  1724. return function applyEuler( euler ) {
  1725. if ( (euler && euler.isEuler) === false ) {
  1726. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1727. }
  1728. if ( quaternion === undefined ) quaternion = new Quaternion();
  1729. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1730. };
  1731. }(),
  1732. applyAxisAngle: function () {
  1733. var quaternion;
  1734. return function applyAxisAngle( axis, angle ) {
  1735. if ( quaternion === undefined ) quaternion = new Quaternion();
  1736. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1737. };
  1738. }(),
  1739. applyMatrix3: function ( m ) {
  1740. var x = this.x, y = this.y, z = this.z;
  1741. var e = m.elements;
  1742. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1743. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1744. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1745. return this;
  1746. },
  1747. applyMatrix4: function ( m ) {
  1748. // input: THREE.Matrix4 affine matrix
  1749. var x = this.x, y = this.y, z = this.z;
  1750. var e = m.elements;
  1751. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1752. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1753. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1754. return this;
  1755. },
  1756. applyProjection: function ( m ) {
  1757. // input: THREE.Matrix4 projection matrix
  1758. var x = this.x, y = this.y, z = this.z;
  1759. var e = m.elements;
  1760. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1761. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1762. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1763. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1764. return this;
  1765. },
  1766. applyQuaternion: function ( q ) {
  1767. var x = this.x, y = this.y, z = this.z;
  1768. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1769. // calculate quat * vector
  1770. var ix = qw * x + qy * z - qz * y;
  1771. var iy = qw * y + qz * x - qx * z;
  1772. var iz = qw * z + qx * y - qy * x;
  1773. var iw = - qx * x - qy * y - qz * z;
  1774. // calculate result * inverse quat
  1775. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1776. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1777. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1778. return this;
  1779. },
  1780. project: function () {
  1781. var matrix;
  1782. return function project( camera ) {
  1783. if ( matrix === undefined ) matrix = new Matrix4();
  1784. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1785. return this.applyProjection( matrix );
  1786. };
  1787. }(),
  1788. unproject: function () {
  1789. var matrix;
  1790. return function unproject( camera ) {
  1791. if ( matrix === undefined ) matrix = new Matrix4();
  1792. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1793. return this.applyProjection( matrix );
  1794. };
  1795. }(),
  1796. transformDirection: function ( m ) {
  1797. // input: THREE.Matrix4 affine matrix
  1798. // vector interpreted as a direction
  1799. var x = this.x, y = this.y, z = this.z;
  1800. var e = m.elements;
  1801. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1802. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1803. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1804. return this.normalize();
  1805. },
  1806. divide: function ( v ) {
  1807. this.x /= v.x;
  1808. this.y /= v.y;
  1809. this.z /= v.z;
  1810. return this;
  1811. },
  1812. divideScalar: function ( scalar ) {
  1813. return this.multiplyScalar( 1 / scalar );
  1814. },
  1815. min: function ( v ) {
  1816. this.x = Math.min( this.x, v.x );
  1817. this.y = Math.min( this.y, v.y );
  1818. this.z = Math.min( this.z, v.z );
  1819. return this;
  1820. },
  1821. max: function ( v ) {
  1822. this.x = Math.max( this.x, v.x );
  1823. this.y = Math.max( this.y, v.y );
  1824. this.z = Math.max( this.z, v.z );
  1825. return this;
  1826. },
  1827. clamp: function ( min, max ) {
  1828. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1829. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1830. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1831. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1832. return this;
  1833. },
  1834. clampScalar: function () {
  1835. var min, max;
  1836. return function clampScalar( minVal, maxVal ) {
  1837. if ( min === undefined ) {
  1838. min = new Vector3();
  1839. max = new Vector3();
  1840. }
  1841. min.set( minVal, minVal, minVal );
  1842. max.set( maxVal, maxVal, maxVal );
  1843. return this.clamp( min, max );
  1844. };
  1845. }(),
  1846. clampLength: function ( min, max ) {
  1847. var length = this.length();
  1848. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1849. },
  1850. floor: function () {
  1851. this.x = Math.floor( this.x );
  1852. this.y = Math.floor( this.y );
  1853. this.z = Math.floor( this.z );
  1854. return this;
  1855. },
  1856. ceil: function () {
  1857. this.x = Math.ceil( this.x );
  1858. this.y = Math.ceil( this.y );
  1859. this.z = Math.ceil( this.z );
  1860. return this;
  1861. },
  1862. round: function () {
  1863. this.x = Math.round( this.x );
  1864. this.y = Math.round( this.y );
  1865. this.z = Math.round( this.z );
  1866. return this;
  1867. },
  1868. roundToZero: function () {
  1869. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1870. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1871. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1872. return this;
  1873. },
  1874. negate: function () {
  1875. this.x = - this.x;
  1876. this.y = - this.y;
  1877. this.z = - this.z;
  1878. return this;
  1879. },
  1880. dot: function ( v ) {
  1881. return this.x * v.x + this.y * v.y + this.z * v.z;
  1882. },
  1883. lengthSq: function () {
  1884. return this.x * this.x + this.y * this.y + this.z * this.z;
  1885. },
  1886. length: function () {
  1887. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1888. },
  1889. lengthManhattan: function () {
  1890. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1891. },
  1892. normalize: function () {
  1893. return this.divideScalar( this.length() );
  1894. },
  1895. setLength: function ( length ) {
  1896. return this.multiplyScalar( length / this.length() );
  1897. },
  1898. lerp: function ( v, alpha ) {
  1899. this.x += ( v.x - this.x ) * alpha;
  1900. this.y += ( v.y - this.y ) * alpha;
  1901. this.z += ( v.z - this.z ) * alpha;
  1902. return this;
  1903. },
  1904. lerpVectors: function ( v1, v2, alpha ) {
  1905. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1906. },
  1907. cross: function ( v, w ) {
  1908. if ( w !== undefined ) {
  1909. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1910. return this.crossVectors( v, w );
  1911. }
  1912. var x = this.x, y = this.y, z = this.z;
  1913. this.x = y * v.z - z * v.y;
  1914. this.y = z * v.x - x * v.z;
  1915. this.z = x * v.y - y * v.x;
  1916. return this;
  1917. },
  1918. crossVectors: function ( a, b ) {
  1919. var ax = a.x, ay = a.y, az = a.z;
  1920. var bx = b.x, by = b.y, bz = b.z;
  1921. this.x = ay * bz - az * by;
  1922. this.y = az * bx - ax * bz;
  1923. this.z = ax * by - ay * bx;
  1924. return this;
  1925. },
  1926. projectOnVector: function ( vector ) {
  1927. var scalar = vector.dot( this ) / vector.lengthSq();
  1928. return this.copy( vector ).multiplyScalar( scalar );
  1929. },
  1930. projectOnPlane: function () {
  1931. var v1;
  1932. return function projectOnPlane( planeNormal ) {
  1933. if ( v1 === undefined ) v1 = new Vector3();
  1934. v1.copy( this ).projectOnVector( planeNormal );
  1935. return this.sub( v1 );
  1936. };
  1937. }(),
  1938. reflect: function () {
  1939. // reflect incident vector off plane orthogonal to normal
  1940. // normal is assumed to have unit length
  1941. var v1;
  1942. return function reflect( normal ) {
  1943. if ( v1 === undefined ) v1 = new Vector3();
  1944. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1945. };
  1946. }(),
  1947. angleTo: function ( v ) {
  1948. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1949. // clamp, to handle numerical problems
  1950. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  1951. },
  1952. distanceTo: function ( v ) {
  1953. return Math.sqrt( this.distanceToSquared( v ) );
  1954. },
  1955. distanceToSquared: function ( v ) {
  1956. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  1957. return dx * dx + dy * dy + dz * dz;
  1958. },
  1959. distanceToManhattan: function ( v ) {
  1960. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  1961. },
  1962. setFromSpherical: function( s ) {
  1963. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  1964. this.x = sinPhiRadius * Math.sin( s.theta );
  1965. this.y = Math.cos( s.phi ) * s.radius;
  1966. this.z = sinPhiRadius * Math.cos( s.theta );
  1967. return this;
  1968. },
  1969. setFromCylindrical: function( c ) {
  1970. this.x = c.radius * Math.sin( c.theta );
  1971. this.y = c.y;
  1972. this.z = c.radius * Math.cos( c.theta );
  1973. return this;
  1974. },
  1975. setFromMatrixPosition: function ( m ) {
  1976. return this.setFromMatrixColumn( m, 3 );
  1977. },
  1978. setFromMatrixScale: function ( m ) {
  1979. var sx = this.setFromMatrixColumn( m, 0 ).length();
  1980. var sy = this.setFromMatrixColumn( m, 1 ).length();
  1981. var sz = this.setFromMatrixColumn( m, 2 ).length();
  1982. this.x = sx;
  1983. this.y = sy;
  1984. this.z = sz;
  1985. return this;
  1986. },
  1987. setFromMatrixColumn: function ( m, index ) {
  1988. if ( typeof m === 'number' ) {
  1989. console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' );
  1990. var temp = m;
  1991. m = index;
  1992. index = temp;
  1993. }
  1994. return this.fromArray( m.elements, index * 4 );
  1995. },
  1996. equals: function ( v ) {
  1997. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1998. },
  1999. fromArray: function ( array, offset ) {
  2000. if ( offset === undefined ) offset = 0;
  2001. this.x = array[ offset ];
  2002. this.y = array[ offset + 1 ];
  2003. this.z = array[ offset + 2 ];
  2004. return this;
  2005. },
  2006. toArray: function ( array, offset ) {
  2007. if ( array === undefined ) array = [];
  2008. if ( offset === undefined ) offset = 0;
  2009. array[ offset ] = this.x;
  2010. array[ offset + 1 ] = this.y;
  2011. array[ offset + 2 ] = this.z;
  2012. return array;
  2013. },
  2014. fromAttribute: function ( attribute, index, offset ) {
  2015. if ( offset === undefined ) offset = 0;
  2016. index = index * attribute.itemSize + offset;
  2017. this.x = attribute.array[ index ];
  2018. this.y = attribute.array[ index + 1 ];
  2019. this.z = attribute.array[ index + 2 ];
  2020. return this;
  2021. }
  2022. };
  2023. /**
  2024. * @author mrdoob / http://mrdoob.com/
  2025. * @author supereggbert / http://www.paulbrunt.co.uk/
  2026. * @author philogb / http://blog.thejit.org/
  2027. * @author jordi_ros / http://plattsoft.com
  2028. * @author D1plo1d / http://github.com/D1plo1d
  2029. * @author alteredq / http://alteredqualia.com/
  2030. * @author mikael emtinger / http://gomo.se/
  2031. * @author timknip / http://www.floorplanner.com/
  2032. * @author bhouston / http://clara.io
  2033. * @author WestLangley / http://github.com/WestLangley
  2034. */
  2035. function Matrix4() {
  2036. this.elements = new Float32Array( [
  2037. 1, 0, 0, 0,
  2038. 0, 1, 0, 0,
  2039. 0, 0, 1, 0,
  2040. 0, 0, 0, 1
  2041. ] );
  2042. if ( arguments.length > 0 ) {
  2043. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2044. }
  2045. }
  2046. Matrix4.prototype = {
  2047. constructor: Matrix4,
  2048. isMatrix4: true,
  2049. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2050. var te = this.elements;
  2051. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2052. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2053. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2054. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2055. return this;
  2056. },
  2057. identity: function () {
  2058. this.set(
  2059. 1, 0, 0, 0,
  2060. 0, 1, 0, 0,
  2061. 0, 0, 1, 0,
  2062. 0, 0, 0, 1
  2063. );
  2064. return this;
  2065. },
  2066. clone: function () {
  2067. return new Matrix4().fromArray( this.elements );
  2068. },
  2069. copy: function ( m ) {
  2070. this.elements.set( m.elements );
  2071. return this;
  2072. },
  2073. copyPosition: function ( m ) {
  2074. var te = this.elements;
  2075. var me = m.elements;
  2076. te[ 12 ] = me[ 12 ];
  2077. te[ 13 ] = me[ 13 ];
  2078. te[ 14 ] = me[ 14 ];
  2079. return this;
  2080. },
  2081. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2082. xAxis.setFromMatrixColumn( this, 0 );
  2083. yAxis.setFromMatrixColumn( this, 1 );
  2084. zAxis.setFromMatrixColumn( this, 2 );
  2085. return this;
  2086. },
  2087. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2088. this.set(
  2089. xAxis.x, yAxis.x, zAxis.x, 0,
  2090. xAxis.y, yAxis.y, zAxis.y, 0,
  2091. xAxis.z, yAxis.z, zAxis.z, 0,
  2092. 0, 0, 0, 1
  2093. );
  2094. return this;
  2095. },
  2096. extractRotation: function () {
  2097. var v1;
  2098. return function extractRotation( m ) {
  2099. if ( v1 === undefined ) v1 = new Vector3();
  2100. var te = this.elements;
  2101. var me = m.elements;
  2102. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  2103. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  2104. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  2105. te[ 0 ] = me[ 0 ] * scaleX;
  2106. te[ 1 ] = me[ 1 ] * scaleX;
  2107. te[ 2 ] = me[ 2 ] * scaleX;
  2108. te[ 4 ] = me[ 4 ] * scaleY;
  2109. te[ 5 ] = me[ 5 ] * scaleY;
  2110. te[ 6 ] = me[ 6 ] * scaleY;
  2111. te[ 8 ] = me[ 8 ] * scaleZ;
  2112. te[ 9 ] = me[ 9 ] * scaleZ;
  2113. te[ 10 ] = me[ 10 ] * scaleZ;
  2114. return this;
  2115. };
  2116. }(),
  2117. makeRotationFromEuler: function ( euler ) {
  2118. if ( (euler && euler.isEuler) === false ) {
  2119. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2120. }
  2121. var te = this.elements;
  2122. var x = euler.x, y = euler.y, z = euler.z;
  2123. var a = Math.cos( x ), b = Math.sin( x );
  2124. var c = Math.cos( y ), d = Math.sin( y );
  2125. var e = Math.cos( z ), f = Math.sin( z );
  2126. if ( euler.order === 'XYZ' ) {
  2127. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2128. te[ 0 ] = c * e;
  2129. te[ 4 ] = - c * f;
  2130. te[ 8 ] = d;
  2131. te[ 1 ] = af + be * d;
  2132. te[ 5 ] = ae - bf * d;
  2133. te[ 9 ] = - b * c;
  2134. te[ 2 ] = bf - ae * d;
  2135. te[ 6 ] = be + af * d;
  2136. te[ 10 ] = a * c;
  2137. } else if ( euler.order === 'YXZ' ) {
  2138. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2139. te[ 0 ] = ce + df * b;
  2140. te[ 4 ] = de * b - cf;
  2141. te[ 8 ] = a * d;
  2142. te[ 1 ] = a * f;
  2143. te[ 5 ] = a * e;
  2144. te[ 9 ] = - b;
  2145. te[ 2 ] = cf * b - de;
  2146. te[ 6 ] = df + ce * b;
  2147. te[ 10 ] = a * c;
  2148. } else if ( euler.order === 'ZXY' ) {
  2149. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2150. te[ 0 ] = ce - df * b;
  2151. te[ 4 ] = - a * f;
  2152. te[ 8 ] = de + cf * b;
  2153. te[ 1 ] = cf + de * b;
  2154. te[ 5 ] = a * e;
  2155. te[ 9 ] = df - ce * b;
  2156. te[ 2 ] = - a * d;
  2157. te[ 6 ] = b;
  2158. te[ 10 ] = a * c;
  2159. } else if ( euler.order === 'ZYX' ) {
  2160. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2161. te[ 0 ] = c * e;
  2162. te[ 4 ] = be * d - af;
  2163. te[ 8 ] = ae * d + bf;
  2164. te[ 1 ] = c * f;
  2165. te[ 5 ] = bf * d + ae;
  2166. te[ 9 ] = af * d - be;
  2167. te[ 2 ] = - d;
  2168. te[ 6 ] = b * c;
  2169. te[ 10 ] = a * c;
  2170. } else if ( euler.order === 'YZX' ) {
  2171. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2172. te[ 0 ] = c * e;
  2173. te[ 4 ] = bd - ac * f;
  2174. te[ 8 ] = bc * f + ad;
  2175. te[ 1 ] = f;
  2176. te[ 5 ] = a * e;
  2177. te[ 9 ] = - b * e;
  2178. te[ 2 ] = - d * e;
  2179. te[ 6 ] = ad * f + bc;
  2180. te[ 10 ] = ac - bd * f;
  2181. } else if ( euler.order === 'XZY' ) {
  2182. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2183. te[ 0 ] = c * e;
  2184. te[ 4 ] = - f;
  2185. te[ 8 ] = d * e;
  2186. te[ 1 ] = ac * f + bd;
  2187. te[ 5 ] = a * e;
  2188. te[ 9 ] = ad * f - bc;
  2189. te[ 2 ] = bc * f - ad;
  2190. te[ 6 ] = b * e;
  2191. te[ 10 ] = bd * f + ac;
  2192. }
  2193. // last column
  2194. te[ 3 ] = 0;
  2195. te[ 7 ] = 0;
  2196. te[ 11 ] = 0;
  2197. // bottom row
  2198. te[ 12 ] = 0;
  2199. te[ 13 ] = 0;
  2200. te[ 14 ] = 0;
  2201. te[ 15 ] = 1;
  2202. return this;
  2203. },
  2204. makeRotationFromQuaternion: function ( q ) {
  2205. var te = this.elements;
  2206. var x = q.x, y = q.y, z = q.z, w = q.w;
  2207. var x2 = x + x, y2 = y + y, z2 = z + z;
  2208. var xx = x * x2, xy = x * y2, xz = x * z2;
  2209. var yy = y * y2, yz = y * z2, zz = z * z2;
  2210. var wx = w * x2, wy = w * y2, wz = w * z2;
  2211. te[ 0 ] = 1 - ( yy + zz );
  2212. te[ 4 ] = xy - wz;
  2213. te[ 8 ] = xz + wy;
  2214. te[ 1 ] = xy + wz;
  2215. te[ 5 ] = 1 - ( xx + zz );
  2216. te[ 9 ] = yz - wx;
  2217. te[ 2 ] = xz - wy;
  2218. te[ 6 ] = yz + wx;
  2219. te[ 10 ] = 1 - ( xx + yy );
  2220. // last column
  2221. te[ 3 ] = 0;
  2222. te[ 7 ] = 0;
  2223. te[ 11 ] = 0;
  2224. // bottom row
  2225. te[ 12 ] = 0;
  2226. te[ 13 ] = 0;
  2227. te[ 14 ] = 0;
  2228. te[ 15 ] = 1;
  2229. return this;
  2230. },
  2231. lookAt: function () {
  2232. var x, y, z;
  2233. return function lookAt( eye, target, up ) {
  2234. if ( x === undefined ) {
  2235. x = new Vector3();
  2236. y = new Vector3();
  2237. z = new Vector3();
  2238. }
  2239. var te = this.elements;
  2240. z.subVectors( eye, target ).normalize();
  2241. if ( z.lengthSq() === 0 ) {
  2242. z.z = 1;
  2243. }
  2244. x.crossVectors( up, z ).normalize();
  2245. if ( x.lengthSq() === 0 ) {
  2246. z.z += 0.0001;
  2247. x.crossVectors( up, z ).normalize();
  2248. }
  2249. y.crossVectors( z, x );
  2250. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2251. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2252. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2253. return this;
  2254. };
  2255. }(),
  2256. multiply: function ( m, n ) {
  2257. if ( n !== undefined ) {
  2258. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2259. return this.multiplyMatrices( m, n );
  2260. }
  2261. return this.multiplyMatrices( this, m );
  2262. },
  2263. premultiply: function ( m ) {
  2264. return this.multiplyMatrices( m, this );
  2265. },
  2266. multiplyMatrices: function ( a, b ) {
  2267. var ae = a.elements;
  2268. var be = b.elements;
  2269. var te = this.elements;
  2270. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2271. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2272. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2273. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2274. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2275. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2276. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2277. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2278. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2279. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2280. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2281. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2282. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2283. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2284. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2285. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2286. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2287. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2288. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2289. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2290. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2291. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2292. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2293. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2294. return this;
  2295. },
  2296. multiplyToArray: function ( a, b, r ) {
  2297. var te = this.elements;
  2298. this.multiplyMatrices( a, b );
  2299. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  2300. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  2301. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  2302. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  2303. return this;
  2304. },
  2305. multiplyScalar: function ( s ) {
  2306. var te = this.elements;
  2307. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2308. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2309. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2310. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2311. return this;
  2312. },
  2313. applyToVector3Array: function () {
  2314. var v1;
  2315. return function applyToVector3Array( array, offset, length ) {
  2316. if ( v1 === undefined ) v1 = new Vector3();
  2317. if ( offset === undefined ) offset = 0;
  2318. if ( length === undefined ) length = array.length;
  2319. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2320. v1.fromArray( array, j );
  2321. v1.applyMatrix4( this );
  2322. v1.toArray( array, j );
  2323. }
  2324. return array;
  2325. };
  2326. }(),
  2327. applyToBuffer: function () {
  2328. var v1;
  2329. return function applyToBuffer( buffer, offset, length ) {
  2330. if ( v1 === undefined ) v1 = new Vector3();
  2331. if ( offset === undefined ) offset = 0;
  2332. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  2333. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  2334. v1.x = buffer.getX( j );
  2335. v1.y = buffer.getY( j );
  2336. v1.z = buffer.getZ( j );
  2337. v1.applyMatrix4( this );
  2338. buffer.setXYZ( j, v1.x, v1.y, v1.z );
  2339. }
  2340. return buffer;
  2341. };
  2342. }(),
  2343. determinant: function () {
  2344. var te = this.elements;
  2345. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2346. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2347. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2348. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2349. //TODO: make this more efficient
  2350. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2351. return (
  2352. n41 * (
  2353. + n14 * n23 * n32
  2354. - n13 * n24 * n32
  2355. - n14 * n22 * n33
  2356. + n12 * n24 * n33
  2357. + n13 * n22 * n34
  2358. - n12 * n23 * n34
  2359. ) +
  2360. n42 * (
  2361. + n11 * n23 * n34
  2362. - n11 * n24 * n33
  2363. + n14 * n21 * n33
  2364. - n13 * n21 * n34
  2365. + n13 * n24 * n31
  2366. - n14 * n23 * n31
  2367. ) +
  2368. n43 * (
  2369. + n11 * n24 * n32
  2370. - n11 * n22 * n34
  2371. - n14 * n21 * n32
  2372. + n12 * n21 * n34
  2373. + n14 * n22 * n31
  2374. - n12 * n24 * n31
  2375. ) +
  2376. n44 * (
  2377. - n13 * n22 * n31
  2378. - n11 * n23 * n32
  2379. + n11 * n22 * n33
  2380. + n13 * n21 * n32
  2381. - n12 * n21 * n33
  2382. + n12 * n23 * n31
  2383. )
  2384. );
  2385. },
  2386. transpose: function () {
  2387. var te = this.elements;
  2388. var tmp;
  2389. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  2390. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  2391. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  2392. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  2393. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  2394. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  2395. return this;
  2396. },
  2397. setPosition: function ( v ) {
  2398. var te = this.elements;
  2399. te[ 12 ] = v.x;
  2400. te[ 13 ] = v.y;
  2401. te[ 14 ] = v.z;
  2402. return this;
  2403. },
  2404. getInverse: function ( m, throwOnDegenerate ) {
  2405. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2406. var te = this.elements,
  2407. me = m.elements,
  2408. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  2409. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  2410. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  2411. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  2412. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  2413. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  2414. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  2415. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  2416. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  2417. if ( det === 0 ) {
  2418. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2419. if ( throwOnDegenerate === true ) {
  2420. throw new Error( msg );
  2421. } else {
  2422. console.warn( msg );
  2423. }
  2424. return this.identity();
  2425. }
  2426. var detInv = 1 / det;
  2427. te[ 0 ] = t11 * detInv;
  2428. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  2429. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  2430. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  2431. te[ 4 ] = t12 * detInv;
  2432. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  2433. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  2434. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  2435. te[ 8 ] = t13 * detInv;
  2436. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  2437. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  2438. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  2439. te[ 12 ] = t14 * detInv;
  2440. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  2441. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  2442. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  2443. return this;
  2444. },
  2445. scale: function ( v ) {
  2446. var te = this.elements;
  2447. var x = v.x, y = v.y, z = v.z;
  2448. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  2449. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  2450. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  2451. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  2452. return this;
  2453. },
  2454. getMaxScaleOnAxis: function () {
  2455. var te = this.elements;
  2456. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  2457. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  2458. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  2459. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  2460. },
  2461. makeTranslation: function ( x, y, z ) {
  2462. this.set(
  2463. 1, 0, 0, x,
  2464. 0, 1, 0, y,
  2465. 0, 0, 1, z,
  2466. 0, 0, 0, 1
  2467. );
  2468. return this;
  2469. },
  2470. makeRotationX: function ( theta ) {
  2471. var c = Math.cos( theta ), s = Math.sin( theta );
  2472. this.set(
  2473. 1, 0, 0, 0,
  2474. 0, c, - s, 0,
  2475. 0, s, c, 0,
  2476. 0, 0, 0, 1
  2477. );
  2478. return this;
  2479. },
  2480. makeRotationY: function ( theta ) {
  2481. var c = Math.cos( theta ), s = Math.sin( theta );
  2482. this.set(
  2483. c, 0, s, 0,
  2484. 0, 1, 0, 0,
  2485. - s, 0, c, 0,
  2486. 0, 0, 0, 1
  2487. );
  2488. return this;
  2489. },
  2490. makeRotationZ: function ( theta ) {
  2491. var c = Math.cos( theta ), s = Math.sin( theta );
  2492. this.set(
  2493. c, - s, 0, 0,
  2494. s, c, 0, 0,
  2495. 0, 0, 1, 0,
  2496. 0, 0, 0, 1
  2497. );
  2498. return this;
  2499. },
  2500. makeRotationAxis: function ( axis, angle ) {
  2501. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2502. var c = Math.cos( angle );
  2503. var s = Math.sin( angle );
  2504. var t = 1 - c;
  2505. var x = axis.x, y = axis.y, z = axis.z;
  2506. var tx = t * x, ty = t * y;
  2507. this.set(
  2508. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2509. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2510. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2511. 0, 0, 0, 1
  2512. );
  2513. return this;
  2514. },
  2515. makeScale: function ( x, y, z ) {
  2516. this.set(
  2517. x, 0, 0, 0,
  2518. 0, y, 0, 0,
  2519. 0, 0, z, 0,
  2520. 0, 0, 0, 1
  2521. );
  2522. return this;
  2523. },
  2524. makeShear: function ( x, y, z ) {
  2525. this.set(
  2526. 1, y, z, 0,
  2527. x, 1, z, 0,
  2528. x, y, 1, 0,
  2529. 0, 0, 0, 1
  2530. );
  2531. return this;
  2532. },
  2533. compose: function ( position, quaternion, scale ) {
  2534. this.makeRotationFromQuaternion( quaternion );
  2535. this.scale( scale );
  2536. this.setPosition( position );
  2537. return this;
  2538. },
  2539. decompose: function () {
  2540. var vector, matrix;
  2541. return function decompose( position, quaternion, scale ) {
  2542. if ( vector === undefined ) {
  2543. vector = new Vector3();
  2544. matrix = new Matrix4();
  2545. }
  2546. var te = this.elements;
  2547. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  2548. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  2549. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  2550. // if determine is negative, we need to invert one scale
  2551. var det = this.determinant();
  2552. if ( det < 0 ) {
  2553. sx = - sx;
  2554. }
  2555. position.x = te[ 12 ];
  2556. position.y = te[ 13 ];
  2557. position.z = te[ 14 ];
  2558. // scale the rotation part
  2559. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  2560. var invSX = 1 / sx;
  2561. var invSY = 1 / sy;
  2562. var invSZ = 1 / sz;
  2563. matrix.elements[ 0 ] *= invSX;
  2564. matrix.elements[ 1 ] *= invSX;
  2565. matrix.elements[ 2 ] *= invSX;
  2566. matrix.elements[ 4 ] *= invSY;
  2567. matrix.elements[ 5 ] *= invSY;
  2568. matrix.elements[ 6 ] *= invSY;
  2569. matrix.elements[ 8 ] *= invSZ;
  2570. matrix.elements[ 9 ] *= invSZ;
  2571. matrix.elements[ 10 ] *= invSZ;
  2572. quaternion.setFromRotationMatrix( matrix );
  2573. scale.x = sx;
  2574. scale.y = sy;
  2575. scale.z = sz;
  2576. return this;
  2577. };
  2578. }(),
  2579. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2580. var te = this.elements;
  2581. var x = 2 * near / ( right - left );
  2582. var y = 2 * near / ( top - bottom );
  2583. var a = ( right + left ) / ( right - left );
  2584. var b = ( top + bottom ) / ( top - bottom );
  2585. var c = - ( far + near ) / ( far - near );
  2586. var d = - 2 * far * near / ( far - near );
  2587. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  2588. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  2589. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  2590. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  2591. return this;
  2592. },
  2593. makePerspective: function ( fov, aspect, near, far ) {
  2594. var ymax = near * Math.tan( _Math.DEG2RAD * fov * 0.5 );
  2595. var ymin = - ymax;
  2596. var xmin = ymin * aspect;
  2597. var xmax = ymax * aspect;
  2598. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2599. },
  2600. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2601. var te = this.elements;
  2602. var w = 1.0 / ( right - left );
  2603. var h = 1.0 / ( top - bottom );
  2604. var p = 1.0 / ( far - near );
  2605. var x = ( right + left ) * w;
  2606. var y = ( top + bottom ) * h;
  2607. var z = ( far + near ) * p;
  2608. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  2609. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  2610. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  2611. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  2612. return this;
  2613. },
  2614. equals: function ( matrix ) {
  2615. var te = this.elements;
  2616. var me = matrix.elements;
  2617. for ( var i = 0; i < 16; i ++ ) {
  2618. if ( te[ i ] !== me[ i ] ) return false;
  2619. }
  2620. return true;
  2621. },
  2622. fromArray: function ( array, offset ) {
  2623. if ( offset === undefined ) offset = 0;
  2624. for( var i = 0; i < 16; i ++ ) {
  2625. this.elements[ i ] = array[ i + offset ];
  2626. }
  2627. return this;
  2628. },
  2629. toArray: function ( array, offset ) {
  2630. if ( array === undefined ) array = [];
  2631. if ( offset === undefined ) offset = 0;
  2632. var te = this.elements;
  2633. array[ offset ] = te[ 0 ];
  2634. array[ offset + 1 ] = te[ 1 ];
  2635. array[ offset + 2 ] = te[ 2 ];
  2636. array[ offset + 3 ] = te[ 3 ];
  2637. array[ offset + 4 ] = te[ 4 ];
  2638. array[ offset + 5 ] = te[ 5 ];
  2639. array[ offset + 6 ] = te[ 6 ];
  2640. array[ offset + 7 ] = te[ 7 ];
  2641. array[ offset + 8 ] = te[ 8 ];
  2642. array[ offset + 9 ] = te[ 9 ];
  2643. array[ offset + 10 ] = te[ 10 ];
  2644. array[ offset + 11 ] = te[ 11 ];
  2645. array[ offset + 12 ] = te[ 12 ];
  2646. array[ offset + 13 ] = te[ 13 ];
  2647. array[ offset + 14 ] = te[ 14 ];
  2648. array[ offset + 15 ] = te[ 15 ];
  2649. return array;
  2650. }
  2651. };
  2652. /**
  2653. * @author mrdoob / http://mrdoob.com/
  2654. */
  2655. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  2656. images = images !== undefined ? images : [];
  2657. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  2658. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2659. this.flipY = false;
  2660. }
  2661. CubeTexture.prototype = Object.create( Texture.prototype );
  2662. CubeTexture.prototype.constructor = CubeTexture;
  2663. CubeTexture.prototype.isCubeTexture = true;
  2664. Object.defineProperty( CubeTexture.prototype, 'images', {
  2665. get: function () {
  2666. return this.image;
  2667. },
  2668. set: function ( value ) {
  2669. this.image = value;
  2670. }
  2671. } );
  2672. /**
  2673. * @author tschw
  2674. *
  2675. * Uniforms of a program.
  2676. * Those form a tree structure with a special top-level container for the root,
  2677. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  2678. *
  2679. *
  2680. * Properties of inner nodes including the top-level container:
  2681. *
  2682. * .seq - array of nested uniforms
  2683. * .map - nested uniforms by name
  2684. *
  2685. *
  2686. * Methods of all nodes except the top-level container:
  2687. *
  2688. * .setValue( gl, value, [renderer] )
  2689. *
  2690. * uploads a uniform value(s)
  2691. * the 'renderer' parameter is needed for sampler uniforms
  2692. *
  2693. *
  2694. * Static methods of the top-level container (renderer factorizations):
  2695. *
  2696. * .upload( gl, seq, values, renderer )
  2697. *
  2698. * sets uniforms in 'seq' to 'values[id].value'
  2699. *
  2700. * .seqWithValue( seq, values ) : filteredSeq
  2701. *
  2702. * filters 'seq' entries with corresponding entry in values
  2703. *
  2704. *
  2705. * Methods of the top-level container (renderer factorizations):
  2706. *
  2707. * .setValue( gl, name, value )
  2708. *
  2709. * sets uniform with name 'name' to 'value'
  2710. *
  2711. * .set( gl, obj, prop )
  2712. *
  2713. * sets uniform from object and property with same name than uniform
  2714. *
  2715. * .setOptional( gl, obj, prop )
  2716. *
  2717. * like .set for an optional property of the object
  2718. *
  2719. */
  2720. var emptyTexture = new Texture();
  2721. var emptyCubeTexture = new CubeTexture();
  2722. // --- Base for inner nodes (including the root) ---
  2723. function UniformContainer() {
  2724. this.seq = [];
  2725. this.map = {};
  2726. }
  2727. // --- Utilities ---
  2728. // Array Caches (provide typed arrays for temporary by size)
  2729. var arrayCacheF32 = [];
  2730. var arrayCacheI32 = [];
  2731. // Flattening for arrays of vectors and matrices
  2732. function flatten( array, nBlocks, blockSize ) {
  2733. var firstElem = array[ 0 ];
  2734. if ( firstElem <= 0 || firstElem > 0 ) return array;
  2735. // unoptimized: ! isNaN( firstElem )
  2736. // see http://jacksondunstan.com/articles/983
  2737. var n = nBlocks * blockSize,
  2738. r = arrayCacheF32[ n ];
  2739. if ( r === undefined ) {
  2740. r = new Float32Array( n );
  2741. arrayCacheF32[ n ] = r;
  2742. }
  2743. if ( nBlocks !== 0 ) {
  2744. firstElem.toArray( r, 0 );
  2745. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  2746. offset += blockSize;
  2747. array[ i ].toArray( r, offset );
  2748. }
  2749. }
  2750. return r;
  2751. }
  2752. // Texture unit allocation
  2753. function allocTexUnits( renderer, n ) {
  2754. var r = arrayCacheI32[ n ];
  2755. if ( r === undefined ) {
  2756. r = new Int32Array( n );
  2757. arrayCacheI32[ n ] = r;
  2758. }
  2759. for ( var i = 0; i !== n; ++ i )
  2760. r[ i ] = renderer.allocTextureUnit();
  2761. return r;
  2762. }
  2763. // --- Setters ---
  2764. // Note: Defining these methods externally, because they come in a bunch
  2765. // and this way their names minify.
  2766. // Single scalar
  2767. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  2768. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  2769. // Single float vector (from flat array or THREE.VectorN)
  2770. function setValue2fv( gl, v ) {
  2771. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  2772. else gl.uniform2f( this.addr, v.x, v.y );
  2773. }
  2774. function setValue3fv( gl, v ) {
  2775. if ( v.x !== undefined )
  2776. gl.uniform3f( this.addr, v.x, v.y, v.z );
  2777. else if ( v.r !== undefined )
  2778. gl.uniform3f( this.addr, v.r, v.g, v.b );
  2779. else
  2780. gl.uniform3fv( this.addr, v );
  2781. }
  2782. function setValue4fv( gl, v ) {
  2783. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  2784. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  2785. }
  2786. // Single matrix (from flat array or MatrixN)
  2787. function setValue2fm( gl, v ) {
  2788. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  2789. }
  2790. function setValue3fm( gl, v ) {
  2791. gl.uniformMatrix3fv( this.addr, false, v.elements || v );
  2792. }
  2793. function setValue4fm( gl, v ) {
  2794. gl.uniformMatrix4fv( this.addr, false, v.elements || v );
  2795. }
  2796. // Single texture (2D / Cube)
  2797. function setValueT1( gl, v, renderer ) {
  2798. var unit = renderer.allocTextureUnit();
  2799. gl.uniform1i( this.addr, unit );
  2800. renderer.setTexture2D( v || emptyTexture, unit );
  2801. }
  2802. function setValueT6( gl, v, renderer ) {
  2803. var unit = renderer.allocTextureUnit();
  2804. gl.uniform1i( this.addr, unit );
  2805. renderer.setTextureCube( v || emptyCubeTexture, unit );
  2806. }
  2807. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  2808. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  2809. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  2810. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  2811. // Helper to pick the right setter for the singular case
  2812. function getSingularSetter( type ) {
  2813. switch ( type ) {
  2814. case 0x1406: return setValue1f; // FLOAT
  2815. case 0x8b50: return setValue2fv; // _VEC2
  2816. case 0x8b51: return setValue3fv; // _VEC3
  2817. case 0x8b52: return setValue4fv; // _VEC4
  2818. case 0x8b5a: return setValue2fm; // _MAT2
  2819. case 0x8b5b: return setValue3fm; // _MAT3
  2820. case 0x8b5c: return setValue4fm; // _MAT4
  2821. case 0x8b5e: return setValueT1; // SAMPLER_2D
  2822. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  2823. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  2824. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2825. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2826. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2827. }
  2828. }
  2829. // Array of scalars
  2830. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  2831. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  2832. // Array of vectors (flat or from THREE classes)
  2833. function setValueV2a( gl, v ) {
  2834. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  2835. }
  2836. function setValueV3a( gl, v ) {
  2837. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  2838. }
  2839. function setValueV4a( gl, v ) {
  2840. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  2841. }
  2842. // Array of matrices (flat or from THREE clases)
  2843. function setValueM2a( gl, v ) {
  2844. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  2845. }
  2846. function setValueM3a( gl, v ) {
  2847. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  2848. }
  2849. function setValueM4a( gl, v ) {
  2850. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  2851. }
  2852. // Array of textures (2D / Cube)
  2853. function setValueT1a( gl, v, renderer ) {
  2854. var n = v.length,
  2855. units = allocTexUnits( renderer, n );
  2856. gl.uniform1iv( this.addr, units );
  2857. for ( var i = 0; i !== n; ++ i ) {
  2858. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  2859. }
  2860. }
  2861. function setValueT6a( gl, v, renderer ) {
  2862. var n = v.length,
  2863. units = allocTexUnits( renderer, n );
  2864. gl.uniform1iv( this.addr, units );
  2865. for ( var i = 0; i !== n; ++ i ) {
  2866. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  2867. }
  2868. }
  2869. // Helper to pick the right setter for a pure (bottom-level) array
  2870. function getPureArraySetter( type ) {
  2871. switch ( type ) {
  2872. case 0x1406: return setValue1fv; // FLOAT
  2873. case 0x8b50: return setValueV2a; // _VEC2
  2874. case 0x8b51: return setValueV3a; // _VEC3
  2875. case 0x8b52: return setValueV4a; // _VEC4
  2876. case 0x8b5a: return setValueM2a; // _MAT2
  2877. case 0x8b5b: return setValueM3a; // _MAT3
  2878. case 0x8b5c: return setValueM4a; // _MAT4
  2879. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  2880. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  2881. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  2882. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2883. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2884. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2885. }
  2886. }
  2887. // --- Uniform Classes ---
  2888. function SingleUniform( id, activeInfo, addr ) {
  2889. this.id = id;
  2890. this.addr = addr;
  2891. this.setValue = getSingularSetter( activeInfo.type );
  2892. // this.path = activeInfo.name; // DEBUG
  2893. }
  2894. function PureArrayUniform( id, activeInfo, addr ) {
  2895. this.id = id;
  2896. this.addr = addr;
  2897. this.size = activeInfo.size;
  2898. this.setValue = getPureArraySetter( activeInfo.type );
  2899. // this.path = activeInfo.name; // DEBUG
  2900. }
  2901. function StructuredUniform( id ) {
  2902. this.id = id;
  2903. UniformContainer.call( this ); // mix-in
  2904. }
  2905. StructuredUniform.prototype.setValue = function( gl, value ) {
  2906. // Note: Don't need an extra 'renderer' parameter, since samplers
  2907. // are not allowed in structured uniforms.
  2908. var seq = this.seq;
  2909. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2910. var u = seq[ i ];
  2911. u.setValue( gl, value[ u.id ] );
  2912. }
  2913. };
  2914. // --- Top-level ---
  2915. // Parser - builds up the property tree from the path strings
  2916. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  2917. // extracts
  2918. // - the identifier (member name or array index)
  2919. // - followed by an optional right bracket (found when array index)
  2920. // - followed by an optional left bracket or dot (type of subscript)
  2921. //
  2922. // Note: These portions can be read in a non-overlapping fashion and
  2923. // allow straightforward parsing of the hierarchy that WebGL encodes
  2924. // in the uniform names.
  2925. function addUniform( container, uniformObject ) {
  2926. container.seq.push( uniformObject );
  2927. container.map[ uniformObject.id ] = uniformObject;
  2928. }
  2929. function parseUniform( activeInfo, addr, container ) {
  2930. var path = activeInfo.name,
  2931. pathLength = path.length;
  2932. // reset RegExp object, because of the early exit of a previous run
  2933. RePathPart.lastIndex = 0;
  2934. for (; ;) {
  2935. var match = RePathPart.exec( path ),
  2936. matchEnd = RePathPart.lastIndex,
  2937. id = match[ 1 ],
  2938. idIsIndex = match[ 2 ] === ']',
  2939. subscript = match[ 3 ];
  2940. if ( idIsIndex ) id = id | 0; // convert to integer
  2941. if ( subscript === undefined ||
  2942. subscript === '[' && matchEnd + 2 === pathLength ) {
  2943. // bare name or "pure" bottom-level array "[0]" suffix
  2944. addUniform( container, subscript === undefined ?
  2945. new SingleUniform( id, activeInfo, addr ) :
  2946. new PureArrayUniform( id, activeInfo, addr ) );
  2947. break;
  2948. } else {
  2949. // step into inner node / create it in case it doesn't exist
  2950. var map = container.map,
  2951. next = map[ id ];
  2952. if ( next === undefined ) {
  2953. next = new StructuredUniform( id );
  2954. addUniform( container, next );
  2955. }
  2956. container = next;
  2957. }
  2958. }
  2959. }
  2960. // Root Container
  2961. function WebGLUniforms( gl, program, renderer ) {
  2962. UniformContainer.call( this );
  2963. this.renderer = renderer;
  2964. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  2965. for ( var i = 0; i !== n; ++ i ) {
  2966. var info = gl.getActiveUniform( program, i ),
  2967. path = info.name,
  2968. addr = gl.getUniformLocation( program, path );
  2969. parseUniform( info, addr, this );
  2970. }
  2971. }
  2972. WebGLUniforms.prototype.setValue = function( gl, name, value ) {
  2973. var u = this.map[ name ];
  2974. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  2975. };
  2976. WebGLUniforms.prototype.set = function( gl, object, name ) {
  2977. var u = this.map[ name ];
  2978. if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer );
  2979. };
  2980. WebGLUniforms.prototype.setOptional = function( gl, object, name ) {
  2981. var v = object[ name ];
  2982. if ( v !== undefined ) this.setValue( gl, name, v );
  2983. };
  2984. // Static interface
  2985. WebGLUniforms.upload = function( gl, seq, values, renderer ) {
  2986. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2987. var u = seq[ i ],
  2988. v = values[ u.id ];
  2989. if ( v.needsUpdate !== false ) {
  2990. // note: always updating when .needsUpdate is undefined
  2991. u.setValue( gl, v.value, renderer );
  2992. }
  2993. }
  2994. };
  2995. WebGLUniforms.seqWithValue = function( seq, values ) {
  2996. var r = [];
  2997. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2998. var u = seq[ i ];
  2999. if ( u.id in values ) r.push( u );
  3000. }
  3001. return r;
  3002. };
  3003. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  3004. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  3005. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  3006. 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";
  3007. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  3008. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  3009. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  3010. var bsdfs = "float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t\t}\n\t\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 ltcTextureCoords( const in GeometricContext geometry, 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\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\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}\nvoid clipQuadToHorizon( inout vec3 L[5], out int n ) {\n\tint config = 0;\n\tif ( L[0].z > 0.0 ) config += 1;\n\tif ( L[1].z > 0.0 ) config += 2;\n\tif ( L[2].z > 0.0 ) config += 4;\n\tif ( L[3].z > 0.0 ) config += 8;\n\tn = 0;\n\tif ( config == 0 ) {\n\t} else if ( config == 1 ) {\n\t\tn = 3;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 2 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 3 ) {\n\t\tn = 4;\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t\tL[3] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 4 ) {\n\t\tn = 3;\n\t\tL[0] = -L[3].z * L[2] + L[2].z * L[3];\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t} else if ( config == 5 ) {\n\t\tn = 0;\n\t} else if ( config == 6 ) {\n\t\tn = 4;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 7 ) {\n\t\tn = 5;\n\t\tL[4] = -L[3].z * L[0] + L[0].z * L[3];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 8 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[1] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] = L[3];\n\t} else if ( config == 9 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[2].z * L[3] + L[3].z * L[2];\n\t} else if ( config == 10 ) {\n\t\tn = 0;\n\t} else if ( config == 11 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 12 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t} else if ( config == 13 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = L[2];\n\t\tL[2] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t} else if ( config == 14 ) {\n\t\tn = 5;\n\t\tL[4] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t} else if ( config == 15 ) {\n\t\tn = 4;\n\t}\n\tif ( n == 3 )\n\t\tL[3] = L[0];\n\tif ( n == 4 )\n\t\tL[4] = L[0];\n}\nfloat integrateLtcBrdfOverRectEdge( vec3 v1, vec3 v2 ) {\n\tfloat cosTheta = dot( v1, v2 );\n\tfloat theta = acos( cosTheta );\n\tfloat res = cross( v1, v2 ).z * ( ( theta > 0.001 ) ? theta / sin( theta ) : 1.0 );\n\treturn res;\n}\nvoid initRectPoints( const in vec3 pos, const in vec3 halfWidth, const in vec3 halfHeight, out vec3 rectPoints[4] ) {\n\trectPoints[0] = pos - halfWidth - halfHeight;\n\trectPoints[1] = pos + halfWidth - halfHeight;\n\trectPoints[2] = pos + halfWidth + halfHeight;\n\trectPoints[3] = pos - halfWidth + halfHeight;\n}\nvec3 integrateLtcBrdfOverRect( const in GeometricContext geometry, const in mat3 brdfMat, const in vec3 rectPoints[4] ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\n\tvec3 T1, T2;\n\tT1 = normalize(V - N * dot( V, N ));\n\tT2 = - cross( N, T1 );\n\tmat3 brdfWrtSurface = brdfMat * transpose( mat3( T1, T2, N ) );\n\tvec3 clippedRect[5];\n\tclippedRect[0] = brdfWrtSurface * ( rectPoints[0] - P );\n\tclippedRect[1] = brdfWrtSurface * ( rectPoints[1] - P );\n\tclippedRect[2] = brdfWrtSurface * ( rectPoints[2] - P );\n\tclippedRect[3] = brdfWrtSurface * ( rectPoints[3] - P );\n\tint n;\n\tclipQuadToHorizon(clippedRect, n);\n\tif ( n == 0 )\n\t\treturn vec3( 0, 0, 0 );\n\tclippedRect[0] = normalize( clippedRect[0] );\n\tclippedRect[1] = normalize( clippedRect[1] );\n\tclippedRect[2] = normalize( clippedRect[2] );\n\tclippedRect[3] = normalize( clippedRect[3] );\n\tclippedRect[4] = normalize( clippedRect[4] );\n\tfloat sum = 0.0;\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[0], clippedRect[1] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[1], clippedRect[2] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[2], clippedRect[3] );\n\tif (n >= 4)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[3], clippedRect[4] );\n\tif (n == 5)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[4], clippedRect[0] );\n\tsum = max( 0.0, sum );\n\tvec3 Lo_i = vec3( sum, sum, sum );\n\treturn Lo_i;\n}\nvec3 Rect_Area_Light_Specular_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight,\n\t\tconst in float roughness,\n\t\tconst in sampler2D ltcMat, const in sampler2D ltcMag ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tvec2 uv = ltcTextureCoords( geometry, roughness );\n\tvec4 brdfLtcApproxParams, t;\n\tbrdfLtcApproxParams = texture2D( ltcMat, uv );\n\tt = texture2D( ltcMat, uv );\n\tfloat brdfLtcScalar = texture2D( ltcMag, uv ).a;\n\tmat3 brdfLtcApproxMat = mat3(\n\t\tvec3( 1, 0, t.y ),\n\t\tvec3( 0, t.z, 0 ),\n\t\tvec3( t.w, 0, t.x )\n\t);\n\tvec3 specularReflectance = integrateLtcBrdfOverRect( geometry, brdfLtcApproxMat, rectPoints );\n\tspecularReflectance *= brdfLtcScalar;\n\treturn specularReflectance;\n}\nvec3 Rect_Area_Light_Diffuse_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tmat3 diffuseBrdfMat = mat3(1);\n\tvec3 diffuseReflectance = integrateLtcBrdfOverRect( geometry, diffuseBrdfMat, rectPoints );\n\treturn diffuseReflectance;\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";
  3011. 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 = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\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";
  3012. 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";
  3013. 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";
  3014. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  3015. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  3016. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  3017. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  3018. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  3019. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  3020. 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";
  3021. 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";
  3022. var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  3023. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  3024. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  3025. 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";
  3026. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  3027. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  3028. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n return 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 return 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 return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return 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 vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return 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 float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n";
  3029. 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, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * 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";
  3030. 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";
  3031. 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";
  3032. 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";
  3033. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tfloat depth = gl_FragDepthEXT / gl_FragCoord.w;\n\t#else\n\t\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\t#endif\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, depth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n";
  3034. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\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";
  3035. 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";
  3036. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  3037. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  3038. 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_RECT_AREA_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\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";
  3039. 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};\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\t#include <normal_flip>\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = flipNormal * 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 = flipNormal * 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\t#include <normal_flip>\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 = flipNormal * 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 = flipNormal * 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 = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * 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 = flipNormal * 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";
  3040. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  3041. 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};\n#if NUM_RECT_AREA_LIGHTS > 0\n void RE_Direct_RectArea_BlinnPhong( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 matDiffColor = material.diffuseColor;\n vec3 matSpecColor = material.specularColor;\n vec3 lightColor = rectAreaLight.color;\n float roughness = BlinnExponentToGGXRoughness( material.specularShininess );\n vec3 spec = Rect_Area_Light_Specular_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n roughness,\n ltcMat, ltcMag );\n vec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n reflectedLight.directSpecular += lightColor * matSpecColor * spec / PI2;\n reflectedLight.directDiffuse += lightColor * matDiffColor * diff / PI2;\n }\n#endif\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_Direct_RectArea\t\tRE_Direct_RectArea_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n";
  3042. 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";
  3043. 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 void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 matDiffColor = material.diffuseColor;\n vec3 matSpecColor = material.specularColor;\n vec3 lightColor = rectAreaLight.color;\n float roughness = material.specularRoughness;\n vec3 spec = Rect_Area_Light_Specular_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n roughness,\n ltcMat, ltcMag );\n vec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n reflectedLight.directSpecular += lightColor * matSpecColor * spec;\n reflectedLight.directDiffuse += lightColor * matDiffColor * diff;\n }\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";
  3044. 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 ] ) : 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\t\t\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n";
  3045. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  3046. 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";
  3047. 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";
  3048. 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";
  3049. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  3050. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  3051. 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";
  3052. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  3053. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n#endif\n";
  3054. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  3055. 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";
  3056. 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";
  3057. 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";
  3058. var normal_flip = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n";
  3059. 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 ) * flipNormal;\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";
  3060. 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 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\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";
  3061. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 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 return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n";
  3062. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  3063. var project_vertex = "#ifdef USE_SKINNING\n\tvec4 mvPosition = modelViewMatrix * skinned;\n#else\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n";
  3064. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n";
  3065. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  3066. 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 #if NUM_RECT_AREA_LIGHTS > 0\n #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\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\treturn (\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\treturn (\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\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\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 ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\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";
  3067. 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 #if NUM_RECT_AREA_LIGHTS > 0\n #endif\n#endif\n";
  3068. 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 #if NUM_RECT_AREA_LIGHTS > 0\n #endif\n#endif\n";
  3069. 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 ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_RECT_AREA_LIGHTS > 0\n\t#endif\n\t#endif\n\treturn shadow;\n}\n";
  3070. 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";
  3071. 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 boneTextureWidth;\n\t\tuniform int boneTextureHeight;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\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";
  3072. 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\tskinned = bindMatrixInverse * skinned;\n#endif\n";
  3073. 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";
  3074. 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";
  3075. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  3076. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  3077. var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n return toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return 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 color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n";
  3078. 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";
  3079. 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";
  3080. 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";
  3081. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  3082. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  3083. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  3084. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\t#ifdef USE_SKINNING\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\t#else\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\t#endif\n#endif\n";
  3085. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n";
  3086. 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";
  3087. 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";
  3088. 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#include <begin_vertex>\n\t#include <displacementmap_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}\n";
  3089. var distanceRGBA_frag = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include <common>\n#include <packing>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n";
  3090. var distanceRGBA_vert = "varying vec4 vWorldPosition;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition;\n}\n";
  3091. var equirect_frag = "uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n";
  3092. 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";
  3093. 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";
  3094. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_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}\n";
  3095. 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 <normal_flip>\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";
  3096. 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 <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}\n";
  3097. 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 <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 <normal_flip>\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";
  3098. 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 <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}\n";
  3099. 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 <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_flip>\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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3100. 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 <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 <displacementmap_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\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3101. 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 <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 <specularmap_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_flip>\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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3102. 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 <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <specularmap_pars_fragment>\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 <displacementmap_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\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3103. var normal_frag = "uniform float opacity;\nvarying vec3 vNormal;\n#include <common>\n#include <packing>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( vNormal ), opacity );\n\t#include <logdepthbuf_fragment>\n}\n";
  3104. var normal_vert = "varying vec3 vNormal;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvNormal = normalize( normalMatrix * normal );\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  3105. 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";
  3106. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_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}\n";
  3107. var shadow_frag = "uniform float opacity;\n#include <common>\n#include <packing>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n";
  3108. 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";
  3109. var ShaderChunk = {
  3110. alphamap_fragment: alphamap_fragment,
  3111. alphamap_pars_fragment: alphamap_pars_fragment,
  3112. alphatest_fragment: alphatest_fragment,
  3113. aomap_fragment: aomap_fragment,
  3114. aomap_pars_fragment: aomap_pars_fragment,
  3115. begin_vertex: begin_vertex,
  3116. beginnormal_vertex: beginnormal_vertex,
  3117. bsdfs: bsdfs,
  3118. bumpmap_pars_fragment: bumpmap_pars_fragment,
  3119. clipping_planes_fragment: clipping_planes_fragment,
  3120. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  3121. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  3122. clipping_planes_vertex: clipping_planes_vertex,
  3123. color_fragment: color_fragment,
  3124. color_pars_fragment: color_pars_fragment,
  3125. color_pars_vertex: color_pars_vertex,
  3126. color_vertex: color_vertex,
  3127. common: common,
  3128. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  3129. defaultnormal_vertex: defaultnormal_vertex,
  3130. displacementmap_pars_vertex: displacementmap_pars_vertex,
  3131. displacementmap_vertex: displacementmap_vertex,
  3132. emissivemap_fragment: emissivemap_fragment,
  3133. emissivemap_pars_fragment: emissivemap_pars_fragment,
  3134. encodings_fragment: encodings_fragment,
  3135. encodings_pars_fragment: encodings_pars_fragment,
  3136. envmap_fragment: envmap_fragment,
  3137. envmap_pars_fragment: envmap_pars_fragment,
  3138. envmap_pars_vertex: envmap_pars_vertex,
  3139. envmap_vertex: envmap_vertex,
  3140. fog_fragment: fog_fragment,
  3141. fog_pars_fragment: fog_pars_fragment,
  3142. gradientmap_pars_fragment: gradientmap_pars_fragment,
  3143. lightmap_fragment: lightmap_fragment,
  3144. lightmap_pars_fragment: lightmap_pars_fragment,
  3145. lights_lambert_vertex: lights_lambert_vertex,
  3146. lights_pars: lights_pars,
  3147. lights_phong_fragment: lights_phong_fragment,
  3148. lights_phong_pars_fragment: lights_phong_pars_fragment,
  3149. lights_physical_fragment: lights_physical_fragment,
  3150. lights_physical_pars_fragment: lights_physical_pars_fragment,
  3151. lights_template: lights_template,
  3152. logdepthbuf_fragment: logdepthbuf_fragment,
  3153. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  3154. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  3155. logdepthbuf_vertex: logdepthbuf_vertex,
  3156. map_fragment: map_fragment,
  3157. map_pars_fragment: map_pars_fragment,
  3158. map_particle_fragment: map_particle_fragment,
  3159. map_particle_pars_fragment: map_particle_pars_fragment,
  3160. metalnessmap_fragment: metalnessmap_fragment,
  3161. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  3162. morphnormal_vertex: morphnormal_vertex,
  3163. morphtarget_pars_vertex: morphtarget_pars_vertex,
  3164. morphtarget_vertex: morphtarget_vertex,
  3165. normal_flip: normal_flip,
  3166. normal_fragment: normal_fragment,
  3167. normalmap_pars_fragment: normalmap_pars_fragment,
  3168. packing: packing,
  3169. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  3170. project_vertex: project_vertex,
  3171. roughnessmap_fragment: roughnessmap_fragment,
  3172. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  3173. shadowmap_pars_fragment: shadowmap_pars_fragment,
  3174. shadowmap_pars_vertex: shadowmap_pars_vertex,
  3175. shadowmap_vertex: shadowmap_vertex,
  3176. shadowmask_pars_fragment: shadowmask_pars_fragment,
  3177. skinbase_vertex: skinbase_vertex,
  3178. skinning_pars_vertex: skinning_pars_vertex,
  3179. skinning_vertex: skinning_vertex,
  3180. skinnormal_vertex: skinnormal_vertex,
  3181. specularmap_fragment: specularmap_fragment,
  3182. specularmap_pars_fragment: specularmap_pars_fragment,
  3183. tonemapping_fragment: tonemapping_fragment,
  3184. tonemapping_pars_fragment: tonemapping_pars_fragment,
  3185. uv_pars_fragment: uv_pars_fragment,
  3186. uv_pars_vertex: uv_pars_vertex,
  3187. uv_vertex: uv_vertex,
  3188. uv2_pars_fragment: uv2_pars_fragment,
  3189. uv2_pars_vertex: uv2_pars_vertex,
  3190. uv2_vertex: uv2_vertex,
  3191. worldpos_vertex: worldpos_vertex,
  3192. cube_frag: cube_frag,
  3193. cube_vert: cube_vert,
  3194. depth_frag: depth_frag,
  3195. depth_vert: depth_vert,
  3196. distanceRGBA_frag: distanceRGBA_frag,
  3197. distanceRGBA_vert: distanceRGBA_vert,
  3198. equirect_frag: equirect_frag,
  3199. equirect_vert: equirect_vert,
  3200. linedashed_frag: linedashed_frag,
  3201. linedashed_vert: linedashed_vert,
  3202. meshbasic_frag: meshbasic_frag,
  3203. meshbasic_vert: meshbasic_vert,
  3204. meshlambert_frag: meshlambert_frag,
  3205. meshlambert_vert: meshlambert_vert,
  3206. meshphong_frag: meshphong_frag,
  3207. meshphong_vert: meshphong_vert,
  3208. meshphysical_frag: meshphysical_frag,
  3209. meshphysical_vert: meshphysical_vert,
  3210. normal_frag: normal_frag,
  3211. normal_vert: normal_vert,
  3212. points_frag: points_frag,
  3213. points_vert: points_vert,
  3214. shadow_frag: shadow_frag,
  3215. shadow_vert: shadow_vert
  3216. };
  3217. /**
  3218. * @author mrdoob / http://mrdoob.com/
  3219. */
  3220. function Color( r, g, b ) {
  3221. if ( g === undefined && b === undefined ) {
  3222. // r is THREE.Color, hex or string
  3223. return this.set( r );
  3224. }
  3225. return this.setRGB( r, g, b );
  3226. }
  3227. Color.prototype = {
  3228. constructor: Color,
  3229. isColor: true,
  3230. r: 1, g: 1, b: 1,
  3231. set: function ( value ) {
  3232. if ( value && value.isColor ) {
  3233. this.copy( value );
  3234. } else if ( typeof value === 'number' ) {
  3235. this.setHex( value );
  3236. } else if ( typeof value === 'string' ) {
  3237. this.setStyle( value );
  3238. }
  3239. return this;
  3240. },
  3241. setScalar: function ( scalar ) {
  3242. this.r = scalar;
  3243. this.g = scalar;
  3244. this.b = scalar;
  3245. return this;
  3246. },
  3247. setHex: function ( hex ) {
  3248. hex = Math.floor( hex );
  3249. this.r = ( hex >> 16 & 255 ) / 255;
  3250. this.g = ( hex >> 8 & 255 ) / 255;
  3251. this.b = ( hex & 255 ) / 255;
  3252. return this;
  3253. },
  3254. setRGB: function ( r, g, b ) {
  3255. this.r = r;
  3256. this.g = g;
  3257. this.b = b;
  3258. return this;
  3259. },
  3260. setHSL: function () {
  3261. function hue2rgb( p, q, t ) {
  3262. if ( t < 0 ) t += 1;
  3263. if ( t > 1 ) t -= 1;
  3264. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  3265. if ( t < 1 / 2 ) return q;
  3266. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  3267. return p;
  3268. }
  3269. return function setHSL( h, s, l ) {
  3270. // h,s,l ranges are in 0.0 - 1.0
  3271. h = _Math.euclideanModulo( h, 1 );
  3272. s = _Math.clamp( s, 0, 1 );
  3273. l = _Math.clamp( l, 0, 1 );
  3274. if ( s === 0 ) {
  3275. this.r = this.g = this.b = l;
  3276. } else {
  3277. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  3278. var q = ( 2 * l ) - p;
  3279. this.r = hue2rgb( q, p, h + 1 / 3 );
  3280. this.g = hue2rgb( q, p, h );
  3281. this.b = hue2rgb( q, p, h - 1 / 3 );
  3282. }
  3283. return this;
  3284. };
  3285. }(),
  3286. setStyle: function ( style ) {
  3287. function handleAlpha( string ) {
  3288. if ( string === undefined ) return;
  3289. if ( parseFloat( string ) < 1 ) {
  3290. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  3291. }
  3292. }
  3293. var m;
  3294. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  3295. // rgb / hsl
  3296. var color;
  3297. var name = m[ 1 ];
  3298. var components = m[ 2 ];
  3299. switch ( name ) {
  3300. case 'rgb':
  3301. case 'rgba':
  3302. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3303. // rgb(255,0,0) rgba(255,0,0,0.5)
  3304. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  3305. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  3306. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  3307. handleAlpha( color[ 5 ] );
  3308. return this;
  3309. }
  3310. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3311. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  3312. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  3313. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  3314. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  3315. handleAlpha( color[ 5 ] );
  3316. return this;
  3317. }
  3318. break;
  3319. case 'hsl':
  3320. case 'hsla':
  3321. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3322. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  3323. var h = parseFloat( color[ 1 ] ) / 360;
  3324. var s = parseInt( color[ 2 ], 10 ) / 100;
  3325. var l = parseInt( color[ 3 ], 10 ) / 100;
  3326. handleAlpha( color[ 5 ] );
  3327. return this.setHSL( h, s, l );
  3328. }
  3329. break;
  3330. }
  3331. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  3332. // hex color
  3333. var hex = m[ 1 ];
  3334. var size = hex.length;
  3335. if ( size === 3 ) {
  3336. // #ff0
  3337. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  3338. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  3339. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  3340. return this;
  3341. } else if ( size === 6 ) {
  3342. // #ff0000
  3343. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  3344. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  3345. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  3346. return this;
  3347. }
  3348. }
  3349. if ( style && style.length > 0 ) {
  3350. // color keywords
  3351. var hex = ColorKeywords[ style ];
  3352. if ( hex !== undefined ) {
  3353. // red
  3354. this.setHex( hex );
  3355. } else {
  3356. // unknown color
  3357. console.warn( 'THREE.Color: Unknown color ' + style );
  3358. }
  3359. }
  3360. return this;
  3361. },
  3362. clone: function () {
  3363. return new this.constructor( this.r, this.g, this.b );
  3364. },
  3365. copy: function ( color ) {
  3366. this.r = color.r;
  3367. this.g = color.g;
  3368. this.b = color.b;
  3369. return this;
  3370. },
  3371. copyGammaToLinear: function ( color, gammaFactor ) {
  3372. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3373. this.r = Math.pow( color.r, gammaFactor );
  3374. this.g = Math.pow( color.g, gammaFactor );
  3375. this.b = Math.pow( color.b, gammaFactor );
  3376. return this;
  3377. },
  3378. copyLinearToGamma: function ( color, gammaFactor ) {
  3379. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3380. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  3381. this.r = Math.pow( color.r, safeInverse );
  3382. this.g = Math.pow( color.g, safeInverse );
  3383. this.b = Math.pow( color.b, safeInverse );
  3384. return this;
  3385. },
  3386. convertGammaToLinear: function () {
  3387. var r = this.r, g = this.g, b = this.b;
  3388. this.r = r * r;
  3389. this.g = g * g;
  3390. this.b = b * b;
  3391. return this;
  3392. },
  3393. convertLinearToGamma: function () {
  3394. this.r = Math.sqrt( this.r );
  3395. this.g = Math.sqrt( this.g );
  3396. this.b = Math.sqrt( this.b );
  3397. return this;
  3398. },
  3399. getHex: function () {
  3400. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  3401. },
  3402. getHexString: function () {
  3403. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  3404. },
  3405. getHSL: function ( optionalTarget ) {
  3406. // h,s,l ranges are in 0.0 - 1.0
  3407. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  3408. var r = this.r, g = this.g, b = this.b;
  3409. var max = Math.max( r, g, b );
  3410. var min = Math.min( r, g, b );
  3411. var hue, saturation;
  3412. var lightness = ( min + max ) / 2.0;
  3413. if ( min === max ) {
  3414. hue = 0;
  3415. saturation = 0;
  3416. } else {
  3417. var delta = max - min;
  3418. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  3419. switch ( max ) {
  3420. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  3421. case g: hue = ( b - r ) / delta + 2; break;
  3422. case b: hue = ( r - g ) / delta + 4; break;
  3423. }
  3424. hue /= 6;
  3425. }
  3426. hsl.h = hue;
  3427. hsl.s = saturation;
  3428. hsl.l = lightness;
  3429. return hsl;
  3430. },
  3431. getStyle: function () {
  3432. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  3433. },
  3434. offsetHSL: function ( h, s, l ) {
  3435. var hsl = this.getHSL();
  3436. hsl.h += h; hsl.s += s; hsl.l += l;
  3437. this.setHSL( hsl.h, hsl.s, hsl.l );
  3438. return this;
  3439. },
  3440. add: function ( color ) {
  3441. this.r += color.r;
  3442. this.g += color.g;
  3443. this.b += color.b;
  3444. return this;
  3445. },
  3446. addColors: function ( color1, color2 ) {
  3447. this.r = color1.r + color2.r;
  3448. this.g = color1.g + color2.g;
  3449. this.b = color1.b + color2.b;
  3450. return this;
  3451. },
  3452. addScalar: function ( s ) {
  3453. this.r += s;
  3454. this.g += s;
  3455. this.b += s;
  3456. return this;
  3457. },
  3458. sub: function( color ) {
  3459. this.r = Math.max( 0, this.r - color.r );
  3460. this.g = Math.max( 0, this.g - color.g );
  3461. this.b = Math.max( 0, this.b - color.b );
  3462. return this;
  3463. },
  3464. multiply: function ( color ) {
  3465. this.r *= color.r;
  3466. this.g *= color.g;
  3467. this.b *= color.b;
  3468. return this;
  3469. },
  3470. multiplyScalar: function ( s ) {
  3471. this.r *= s;
  3472. this.g *= s;
  3473. this.b *= s;
  3474. return this;
  3475. },
  3476. lerp: function ( color, alpha ) {
  3477. this.r += ( color.r - this.r ) * alpha;
  3478. this.g += ( color.g - this.g ) * alpha;
  3479. this.b += ( color.b - this.b ) * alpha;
  3480. return this;
  3481. },
  3482. equals: function ( c ) {
  3483. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  3484. },
  3485. fromArray: function ( array, offset ) {
  3486. if ( offset === undefined ) offset = 0;
  3487. this.r = array[ offset ];
  3488. this.g = array[ offset + 1 ];
  3489. this.b = array[ offset + 2 ];
  3490. return this;
  3491. },
  3492. toArray: function ( array, offset ) {
  3493. if ( array === undefined ) array = [];
  3494. if ( offset === undefined ) offset = 0;
  3495. array[ offset ] = this.r;
  3496. array[ offset + 1 ] = this.g;
  3497. array[ offset + 2 ] = this.b;
  3498. return array;
  3499. },
  3500. toJSON: function () {
  3501. return this.getHex();
  3502. }
  3503. };
  3504. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  3505. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  3506. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  3507. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  3508. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  3509. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  3510. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  3511. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  3512. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  3513. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  3514. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  3515. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  3516. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  3517. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  3518. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  3519. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  3520. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  3521. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  3522. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  3523. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  3524. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  3525. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  3526. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  3527. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  3528. /**
  3529. * @author alteredq / http://alteredqualia.com/
  3530. */
  3531. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  3532. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  3533. this.image = { data: data, width: width, height: height };
  3534. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  3535. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  3536. this.generateMipmaps = false;
  3537. this.flipY = false;
  3538. this.unpackAlignment = 1;
  3539. }
  3540. DataTexture.prototype = Object.create( Texture.prototype );
  3541. DataTexture.prototype.constructor = DataTexture;
  3542. DataTexture.prototype.isDataTexture = true;
  3543. /**
  3544. * Uniforms library for shared webgl shaders
  3545. */
  3546. var UniformsLib = {
  3547. common: {
  3548. diffuse: { value: new Color( 0xeeeeee ) },
  3549. opacity: { value: 1.0 },
  3550. map: { value: null },
  3551. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) },
  3552. specularMap: { value: null },
  3553. alphaMap: { value: null },
  3554. envMap: { value: null },
  3555. flipEnvMap: { value: - 1 },
  3556. reflectivity: { value: 1.0 },
  3557. refractionRatio: { value: 0.98 }
  3558. },
  3559. aomap: {
  3560. aoMap: { value: null },
  3561. aoMapIntensity: { value: 1 }
  3562. },
  3563. lightmap: {
  3564. lightMap: { value: null },
  3565. lightMapIntensity: { value: 1 }
  3566. },
  3567. emissivemap: {
  3568. emissiveMap: { value: null }
  3569. },
  3570. bumpmap: {
  3571. bumpMap: { value: null },
  3572. bumpScale: { value: 1 }
  3573. },
  3574. normalmap: {
  3575. normalMap: { value: null },
  3576. normalScale: { value: new Vector2( 1, 1 ) }
  3577. },
  3578. displacementmap: {
  3579. displacementMap: { value: null },
  3580. displacementScale: { value: 1 },
  3581. displacementBias: { value: 0 }
  3582. },
  3583. roughnessmap: {
  3584. roughnessMap: { value: null }
  3585. },
  3586. metalnessmap: {
  3587. metalnessMap: { value: null }
  3588. },
  3589. gradientmap: {
  3590. gradientMap: { value: null }
  3591. },
  3592. fog: {
  3593. fogDensity: { value: 0.00025 },
  3594. fogNear: { value: 1 },
  3595. fogFar: { value: 2000 },
  3596. fogColor: { value: new Color( 0xffffff ) }
  3597. },
  3598. lights: {
  3599. ambientLightColor: { value: [] },
  3600. directionalLights: { value: [], properties: {
  3601. direction: {},
  3602. color: {},
  3603. shadow: {},
  3604. shadowBias: {},
  3605. shadowRadius: {},
  3606. shadowMapSize: {}
  3607. } },
  3608. directionalShadowMap: { value: [] },
  3609. directionalShadowMatrix: { value: [] },
  3610. spotLights: { value: [], properties: {
  3611. color: {},
  3612. position: {},
  3613. direction: {},
  3614. distance: {},
  3615. coneCos: {},
  3616. penumbraCos: {},
  3617. decay: {},
  3618. shadow: {},
  3619. shadowBias: {},
  3620. shadowRadius: {},
  3621. shadowMapSize: {}
  3622. } },
  3623. spotShadowMap: { value: [] },
  3624. spotShadowMatrix: { value: [] },
  3625. pointLights: { value: [], properties: {
  3626. color: {},
  3627. position: {},
  3628. decay: {},
  3629. distance: {},
  3630. shadow: {},
  3631. shadowBias: {},
  3632. shadowRadius: {},
  3633. shadowMapSize: {}
  3634. } },
  3635. pointShadowMap: { value: [] },
  3636. pointShadowMatrix: { value: [] },
  3637. hemisphereLights: { value: [], properties: {
  3638. direction: {},
  3639. skyColor: {},
  3640. groundColor: {}
  3641. } },
  3642. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  3643. rectAreaLights: { value: [], properties: {
  3644. color: {},
  3645. position: {},
  3646. width: {},
  3647. height: {},
  3648. } }
  3649. },
  3650. points: {
  3651. diffuse: { value: new Color( 0xeeeeee ) },
  3652. opacity: { value: 1.0 },
  3653. size: { value: 1.0 },
  3654. scale: { value: 1.0 },
  3655. map: { value: null },
  3656. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }
  3657. }
  3658. };
  3659. /**
  3660. * @author alteredq / http://alteredqualia.com/
  3661. * @author mrdoob / http://mrdoob.com/
  3662. * @author mikael emtinger / http://gomo.se/
  3663. */
  3664. var ShaderLib = {
  3665. basic: {
  3666. uniforms: Object.assign( {},
  3667. UniformsLib.common,
  3668. UniformsLib.aomap,
  3669. UniformsLib.lightmap,
  3670. UniformsLib.fog
  3671. ),
  3672. vertexShader: ShaderChunk.meshbasic_vert,
  3673. fragmentShader: ShaderChunk.meshbasic_frag
  3674. },
  3675. lambert: {
  3676. uniforms: Object.assign( {},
  3677. UniformsLib.common,
  3678. UniformsLib.aomap,
  3679. UniformsLib.lightmap,
  3680. UniformsLib.emissivemap,
  3681. UniformsLib.fog,
  3682. UniformsLib.lights,
  3683. {
  3684. emissive : { value: new Color( 0x000000 ) }
  3685. }
  3686. ),
  3687. vertexShader: ShaderChunk.meshlambert_vert,
  3688. fragmentShader: ShaderChunk.meshlambert_frag
  3689. },
  3690. phong: {
  3691. uniforms: Object.assign( {},
  3692. UniformsLib.common,
  3693. UniformsLib.aomap,
  3694. UniformsLib.lightmap,
  3695. UniformsLib.emissivemap,
  3696. UniformsLib.bumpmap,
  3697. UniformsLib.normalmap,
  3698. UniformsLib.displacementmap,
  3699. UniformsLib.gradientmap,
  3700. UniformsLib.fog,
  3701. UniformsLib.lights,
  3702. {
  3703. emissive : { value: new Color( 0x000000 ) },
  3704. specular : { value: new Color( 0x111111 ) },
  3705. shininess: { value: 30 }
  3706. }
  3707. ),
  3708. vertexShader: ShaderChunk.meshphong_vert,
  3709. fragmentShader: ShaderChunk.meshphong_frag
  3710. },
  3711. standard: {
  3712. uniforms: Object.assign( {},
  3713. UniformsLib.common,
  3714. UniformsLib.aomap,
  3715. UniformsLib.lightmap,
  3716. UniformsLib.emissivemap,
  3717. UniformsLib.bumpmap,
  3718. UniformsLib.normalmap,
  3719. UniformsLib.displacementmap,
  3720. UniformsLib.roughnessmap,
  3721. UniformsLib.metalnessmap,
  3722. UniformsLib.fog,
  3723. UniformsLib.lights,
  3724. {
  3725. emissive : { value: new Color( 0x000000 ) },
  3726. roughness: { value: 0.5 },
  3727. metalness: { value: 0 },
  3728. envMapIntensity : { value: 1 }, // temporary
  3729. }
  3730. ),
  3731. vertexShader: ShaderChunk.meshphysical_vert,
  3732. fragmentShader: ShaderChunk.meshphysical_frag
  3733. },
  3734. points: {
  3735. uniforms: Object.assign( {},
  3736. UniformsLib.points,
  3737. UniformsLib.fog
  3738. ),
  3739. vertexShader: ShaderChunk.points_vert,
  3740. fragmentShader: ShaderChunk.points_frag
  3741. },
  3742. dashed: {
  3743. uniforms: Object.assign( {},
  3744. UniformsLib.common,
  3745. UniformsLib.fog,
  3746. {
  3747. scale : { value: 1 },
  3748. dashSize : { value: 1 },
  3749. totalSize: { value: 2 }
  3750. }
  3751. ),
  3752. vertexShader: ShaderChunk.linedashed_vert,
  3753. fragmentShader: ShaderChunk.linedashed_frag
  3754. },
  3755. depth: {
  3756. uniforms: Object.assign( {},
  3757. UniformsLib.common,
  3758. UniformsLib.displacementmap
  3759. ),
  3760. vertexShader: ShaderChunk.depth_vert,
  3761. fragmentShader: ShaderChunk.depth_frag
  3762. },
  3763. normal: {
  3764. uniforms: {
  3765. opacity : { value: 1.0 }
  3766. },
  3767. vertexShader: ShaderChunk.normal_vert,
  3768. fragmentShader: ShaderChunk.normal_frag
  3769. },
  3770. /* -------------------------------------------------------------------------
  3771. // Cube map shader
  3772. ------------------------------------------------------------------------- */
  3773. cube: {
  3774. uniforms: {
  3775. tCube: { value: null },
  3776. tFlip: { value: - 1 },
  3777. opacity: { value: 1.0 }
  3778. },
  3779. vertexShader: ShaderChunk.cube_vert,
  3780. fragmentShader: ShaderChunk.cube_frag
  3781. },
  3782. /* -------------------------------------------------------------------------
  3783. // Cube map shader
  3784. ------------------------------------------------------------------------- */
  3785. equirect: {
  3786. uniforms: {
  3787. tEquirect: { value: null },
  3788. tFlip: { value: - 1 }
  3789. },
  3790. vertexShader: ShaderChunk.equirect_vert,
  3791. fragmentShader: ShaderChunk.equirect_frag
  3792. },
  3793. distanceRGBA: {
  3794. uniforms: {
  3795. lightPos: { value: new Vector3() }
  3796. },
  3797. vertexShader: ShaderChunk.distanceRGBA_vert,
  3798. fragmentShader: ShaderChunk.distanceRGBA_frag
  3799. }
  3800. };
  3801. ShaderLib.physical = {
  3802. uniforms: Object.assign( {},
  3803. ShaderLib.standard.uniforms,
  3804. {
  3805. clearCoat: { value: 0 },
  3806. clearCoatRoughness: { value: 0 }
  3807. }
  3808. ),
  3809. vertexShader: ShaderChunk.meshphysical_vert,
  3810. fragmentShader: ShaderChunk.meshphysical_frag
  3811. };
  3812. /**
  3813. * @author bhouston / http://clara.io
  3814. */
  3815. function Box2( min, max ) {
  3816. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  3817. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  3818. }
  3819. Box2.prototype = {
  3820. constructor: Box2,
  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. if ( point.x < this.min.x || point.x > this.max.x ||
  3884. point.y < this.min.y || point.y > this.max.y ) {
  3885. return false;
  3886. }
  3887. return true;
  3888. },
  3889. containsBox: function ( box ) {
  3890. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  3891. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  3892. return true;
  3893. }
  3894. return false;
  3895. },
  3896. getParameter: function ( point, optionalTarget ) {
  3897. // This can potentially have a divide by zero if the box
  3898. // has a size dimension of 0.
  3899. var result = optionalTarget || new Vector2();
  3900. return result.set(
  3901. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3902. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  3903. );
  3904. },
  3905. intersectsBox: function ( box ) {
  3906. // using 6 splitting planes to rule out intersections.
  3907. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  3908. box.max.y < this.min.y || box.min.y > this.max.y ) {
  3909. return false;
  3910. }
  3911. return true;
  3912. },
  3913. clampPoint: function ( point, optionalTarget ) {
  3914. var result = optionalTarget || new Vector2();
  3915. return result.copy( point ).clamp( this.min, this.max );
  3916. },
  3917. distanceToPoint: function () {
  3918. var v1 = new Vector2();
  3919. return function distanceToPoint( point ) {
  3920. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  3921. return clampedPoint.sub( point ).length();
  3922. };
  3923. }(),
  3924. intersect: function ( box ) {
  3925. this.min.max( box.min );
  3926. this.max.min( box.max );
  3927. return this;
  3928. },
  3929. union: function ( box ) {
  3930. this.min.min( box.min );
  3931. this.max.max( box.max );
  3932. return this;
  3933. },
  3934. translate: function ( offset ) {
  3935. this.min.add( offset );
  3936. this.max.add( offset );
  3937. return this;
  3938. },
  3939. equals: function ( box ) {
  3940. return box.min.equals( this.min ) && box.max.equals( this.max );
  3941. }
  3942. };
  3943. /**
  3944. * @author mikael emtinger / http://gomo.se/
  3945. * @author alteredq / http://alteredqualia.com/
  3946. */
  3947. function LensFlarePlugin( renderer, flares ) {
  3948. var gl = renderer.context;
  3949. var state = renderer.state;
  3950. var vertexBuffer, elementBuffer;
  3951. var shader, program, attributes, uniforms;
  3952. var tempTexture, occlusionTexture;
  3953. function init() {
  3954. var vertices = new Float32Array( [
  3955. - 1, - 1, 0, 0,
  3956. 1, - 1, 1, 0,
  3957. 1, 1, 1, 1,
  3958. - 1, 1, 0, 1
  3959. ] );
  3960. var faces = new Uint16Array( [
  3961. 0, 1, 2,
  3962. 0, 2, 3
  3963. ] );
  3964. // buffers
  3965. vertexBuffer = gl.createBuffer();
  3966. elementBuffer = gl.createBuffer();
  3967. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  3968. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  3969. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  3970. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  3971. // textures
  3972. tempTexture = gl.createTexture();
  3973. occlusionTexture = gl.createTexture();
  3974. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  3975. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  3976. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3977. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3978. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3979. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3980. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  3981. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  3982. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3983. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3984. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3985. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3986. shader = {
  3987. vertexShader: [
  3988. "uniform lowp int renderType;",
  3989. "uniform vec3 screenPosition;",
  3990. "uniform vec2 scale;",
  3991. "uniform float rotation;",
  3992. "uniform sampler2D occlusionMap;",
  3993. "attribute vec2 position;",
  3994. "attribute vec2 uv;",
  3995. "varying vec2 vUV;",
  3996. "varying float vVisibility;",
  3997. "void main() {",
  3998. "vUV = uv;",
  3999. "vec2 pos = position;",
  4000. "if ( renderType == 2 ) {",
  4001. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  4002. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  4003. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  4004. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  4005. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  4006. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  4007. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  4008. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  4009. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  4010. "vVisibility = visibility.r / 9.0;",
  4011. "vVisibility *= 1.0 - visibility.g / 9.0;",
  4012. "vVisibility *= visibility.b / 9.0;",
  4013. "vVisibility *= 1.0 - visibility.a / 9.0;",
  4014. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  4015. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  4016. "}",
  4017. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  4018. "}"
  4019. ].join( "\n" ),
  4020. fragmentShader: [
  4021. "uniform lowp int renderType;",
  4022. "uniform sampler2D map;",
  4023. "uniform float opacity;",
  4024. "uniform vec3 color;",
  4025. "varying vec2 vUV;",
  4026. "varying float vVisibility;",
  4027. "void main() {",
  4028. // pink square
  4029. "if ( renderType == 0 ) {",
  4030. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  4031. // restore
  4032. "} else if ( renderType == 1 ) {",
  4033. "gl_FragColor = texture2D( map, vUV );",
  4034. // flare
  4035. "} else {",
  4036. "vec4 texture = texture2D( map, vUV );",
  4037. "texture.a *= opacity * vVisibility;",
  4038. "gl_FragColor = texture;",
  4039. "gl_FragColor.rgb *= color;",
  4040. "}",
  4041. "}"
  4042. ].join( "\n" )
  4043. };
  4044. program = createProgram( shader );
  4045. attributes = {
  4046. vertex: gl.getAttribLocation ( program, "position" ),
  4047. uv: gl.getAttribLocation ( program, "uv" )
  4048. };
  4049. uniforms = {
  4050. renderType: gl.getUniformLocation( program, "renderType" ),
  4051. map: gl.getUniformLocation( program, "map" ),
  4052. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  4053. opacity: gl.getUniformLocation( program, "opacity" ),
  4054. color: gl.getUniformLocation( program, "color" ),
  4055. scale: gl.getUniformLocation( program, "scale" ),
  4056. rotation: gl.getUniformLocation( program, "rotation" ),
  4057. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  4058. };
  4059. }
  4060. /*
  4061. * Render lens flares
  4062. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  4063. * reads these back and calculates occlusion.
  4064. */
  4065. this.render = function ( scene, camera, viewport ) {
  4066. if ( flares.length === 0 ) return;
  4067. var tempPosition = new Vector3();
  4068. var invAspect = viewport.w / viewport.z,
  4069. halfViewportWidth = viewport.z * 0.5,
  4070. halfViewportHeight = viewport.w * 0.5;
  4071. var size = 16 / viewport.w,
  4072. scale = new Vector2( size * invAspect, size );
  4073. var screenPosition = new Vector3( 1, 1, 0 ),
  4074. screenPositionPixels = new Vector2( 1, 1 );
  4075. var validArea = new Box2();
  4076. validArea.min.set( viewport.x, viewport.y );
  4077. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  4078. if ( program === undefined ) {
  4079. init();
  4080. }
  4081. gl.useProgram( program );
  4082. state.initAttributes();
  4083. state.enableAttribute( attributes.vertex );
  4084. state.enableAttribute( attributes.uv );
  4085. state.disableUnusedAttributes();
  4086. // loop through all lens flares to update their occlusion and positions
  4087. // setup gl and common used attribs/uniforms
  4088. gl.uniform1i( uniforms.occlusionMap, 0 );
  4089. gl.uniform1i( uniforms.map, 1 );
  4090. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4091. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  4092. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4093. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4094. state.disable( gl.CULL_FACE );
  4095. state.setDepthWrite( false );
  4096. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  4097. size = 16 / viewport.w;
  4098. scale.set( size * invAspect, size );
  4099. // calc object screen position
  4100. var flare = flares[ i ];
  4101. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  4102. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  4103. tempPosition.applyProjection( camera.projectionMatrix );
  4104. // setup arrays for gl programs
  4105. screenPosition.copy( tempPosition );
  4106. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  4107. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  4108. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  4109. // screen cull
  4110. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  4111. // save current RGB to temp texture
  4112. state.activeTexture( gl.TEXTURE0 );
  4113. state.bindTexture( gl.TEXTURE_2D, null );
  4114. state.activeTexture( gl.TEXTURE1 );
  4115. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4116. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4117. // render pink quad
  4118. gl.uniform1i( uniforms.renderType, 0 );
  4119. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4120. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4121. state.disable( gl.BLEND );
  4122. state.enable( gl.DEPTH_TEST );
  4123. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4124. // copy result to occlusionMap
  4125. state.activeTexture( gl.TEXTURE0 );
  4126. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  4127. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4128. // restore graphics
  4129. gl.uniform1i( uniforms.renderType, 1 );
  4130. state.disable( gl.DEPTH_TEST );
  4131. state.activeTexture( gl.TEXTURE1 );
  4132. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4133. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4134. // update object positions
  4135. flare.positionScreen.copy( screenPosition );
  4136. if ( flare.customUpdateCallback ) {
  4137. flare.customUpdateCallback( flare );
  4138. } else {
  4139. flare.updateLensFlares();
  4140. }
  4141. // render flares
  4142. gl.uniform1i( uniforms.renderType, 2 );
  4143. state.enable( gl.BLEND );
  4144. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  4145. var sprite = flare.lensFlares[ j ];
  4146. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  4147. screenPosition.x = sprite.x;
  4148. screenPosition.y = sprite.y;
  4149. screenPosition.z = sprite.z;
  4150. size = sprite.size * sprite.scale / viewport.w;
  4151. scale.x = size * invAspect;
  4152. scale.y = size;
  4153. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4154. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4155. gl.uniform1f( uniforms.rotation, sprite.rotation );
  4156. gl.uniform1f( uniforms.opacity, sprite.opacity );
  4157. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  4158. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  4159. renderer.setTexture2D( sprite.texture, 1 );
  4160. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4161. }
  4162. }
  4163. }
  4164. }
  4165. // restore gl
  4166. state.enable( gl.CULL_FACE );
  4167. state.enable( gl.DEPTH_TEST );
  4168. state.setDepthWrite( true );
  4169. renderer.resetGLState();
  4170. };
  4171. function createProgram( shader ) {
  4172. var program = gl.createProgram();
  4173. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4174. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4175. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  4176. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  4177. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  4178. gl.compileShader( fragmentShader );
  4179. gl.compileShader( vertexShader );
  4180. gl.attachShader( program, fragmentShader );
  4181. gl.attachShader( program, vertexShader );
  4182. gl.linkProgram( program );
  4183. return program;
  4184. }
  4185. }
  4186. /**
  4187. * @author mikael emtinger / http://gomo.se/
  4188. * @author alteredq / http://alteredqualia.com/
  4189. */
  4190. function SpritePlugin( renderer, sprites ) {
  4191. var gl = renderer.context;
  4192. var state = renderer.state;
  4193. var vertexBuffer, elementBuffer;
  4194. var program, attributes, uniforms;
  4195. var texture;
  4196. // decompose matrixWorld
  4197. var spritePosition = new Vector3();
  4198. var spriteRotation = new Quaternion();
  4199. var spriteScale = new Vector3();
  4200. function init() {
  4201. var vertices = new Float32Array( [
  4202. - 0.5, - 0.5, 0, 0,
  4203. 0.5, - 0.5, 1, 0,
  4204. 0.5, 0.5, 1, 1,
  4205. - 0.5, 0.5, 0, 1
  4206. ] );
  4207. var faces = new Uint16Array( [
  4208. 0, 1, 2,
  4209. 0, 2, 3
  4210. ] );
  4211. vertexBuffer = gl.createBuffer();
  4212. elementBuffer = gl.createBuffer();
  4213. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4214. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  4215. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4216. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  4217. program = createProgram();
  4218. attributes = {
  4219. position: gl.getAttribLocation ( program, 'position' ),
  4220. uv: gl.getAttribLocation ( program, 'uv' )
  4221. };
  4222. uniforms = {
  4223. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  4224. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  4225. rotation: gl.getUniformLocation( program, 'rotation' ),
  4226. scale: gl.getUniformLocation( program, 'scale' ),
  4227. color: gl.getUniformLocation( program, 'color' ),
  4228. map: gl.getUniformLocation( program, 'map' ),
  4229. opacity: gl.getUniformLocation( program, 'opacity' ),
  4230. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  4231. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  4232. fogType: gl.getUniformLocation( program, 'fogType' ),
  4233. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  4234. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  4235. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  4236. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  4237. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  4238. };
  4239. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  4240. canvas.width = 8;
  4241. canvas.height = 8;
  4242. var context = canvas.getContext( '2d' );
  4243. context.fillStyle = 'white';
  4244. context.fillRect( 0, 0, 8, 8 );
  4245. texture = new Texture( canvas );
  4246. texture.needsUpdate = true;
  4247. }
  4248. this.render = function ( scene, camera ) {
  4249. if ( sprites.length === 0 ) return;
  4250. // setup gl
  4251. if ( program === undefined ) {
  4252. init();
  4253. }
  4254. gl.useProgram( program );
  4255. state.initAttributes();
  4256. state.enableAttribute( attributes.position );
  4257. state.enableAttribute( attributes.uv );
  4258. state.disableUnusedAttributes();
  4259. state.disable( gl.CULL_FACE );
  4260. state.enable( gl.BLEND );
  4261. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4262. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  4263. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4264. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4265. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  4266. state.activeTexture( gl.TEXTURE0 );
  4267. gl.uniform1i( uniforms.map, 0 );
  4268. var oldFogType = 0;
  4269. var sceneFogType = 0;
  4270. var fog = scene.fog;
  4271. if ( fog ) {
  4272. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  4273. if ( fog.isFog ) {
  4274. gl.uniform1f( uniforms.fogNear, fog.near );
  4275. gl.uniform1f( uniforms.fogFar, fog.far );
  4276. gl.uniform1i( uniforms.fogType, 1 );
  4277. oldFogType = 1;
  4278. sceneFogType = 1;
  4279. } else if ( fog.isFogExp2 ) {
  4280. gl.uniform1f( uniforms.fogDensity, fog.density );
  4281. gl.uniform1i( uniforms.fogType, 2 );
  4282. oldFogType = 2;
  4283. sceneFogType = 2;
  4284. }
  4285. } else {
  4286. gl.uniform1i( uniforms.fogType, 0 );
  4287. oldFogType = 0;
  4288. sceneFogType = 0;
  4289. }
  4290. // update positions and sort
  4291. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4292. var sprite = sprites[ i ];
  4293. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  4294. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  4295. }
  4296. sprites.sort( painterSortStable );
  4297. // render all sprites
  4298. var scale = [];
  4299. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4300. var sprite = sprites[ i ];
  4301. var material = sprite.material;
  4302. if ( material.visible === false ) continue;
  4303. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  4304. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  4305. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  4306. scale[ 0 ] = spriteScale.x;
  4307. scale[ 1 ] = spriteScale.y;
  4308. var fogType = 0;
  4309. if ( scene.fog && material.fog ) {
  4310. fogType = sceneFogType;
  4311. }
  4312. if ( oldFogType !== fogType ) {
  4313. gl.uniform1i( uniforms.fogType, fogType );
  4314. oldFogType = fogType;
  4315. }
  4316. if ( material.map !== null ) {
  4317. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  4318. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  4319. } else {
  4320. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  4321. gl.uniform2f( uniforms.uvScale, 1, 1 );
  4322. }
  4323. gl.uniform1f( uniforms.opacity, material.opacity );
  4324. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  4325. gl.uniform1f( uniforms.rotation, material.rotation );
  4326. gl.uniform2fv( uniforms.scale, scale );
  4327. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  4328. state.setDepthTest( material.depthTest );
  4329. state.setDepthWrite( material.depthWrite );
  4330. if ( material.map ) {
  4331. renderer.setTexture2D( material.map, 0 );
  4332. } else {
  4333. renderer.setTexture2D( texture, 0 );
  4334. }
  4335. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4336. }
  4337. // restore gl
  4338. state.enable( gl.CULL_FACE );
  4339. renderer.resetGLState();
  4340. };
  4341. function createProgram() {
  4342. var program = gl.createProgram();
  4343. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4344. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4345. gl.shaderSource( vertexShader, [
  4346. 'precision ' + renderer.getPrecision() + ' float;',
  4347. 'uniform mat4 modelViewMatrix;',
  4348. 'uniform mat4 projectionMatrix;',
  4349. 'uniform float rotation;',
  4350. 'uniform vec2 scale;',
  4351. 'uniform vec2 uvOffset;',
  4352. 'uniform vec2 uvScale;',
  4353. 'attribute vec2 position;',
  4354. 'attribute vec2 uv;',
  4355. 'varying vec2 vUV;',
  4356. 'void main() {',
  4357. 'vUV = uvOffset + uv * uvScale;',
  4358. 'vec2 alignedPosition = position * scale;',
  4359. 'vec2 rotatedPosition;',
  4360. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  4361. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  4362. 'vec4 finalPosition;',
  4363. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  4364. 'finalPosition.xy += rotatedPosition;',
  4365. 'finalPosition = projectionMatrix * finalPosition;',
  4366. 'gl_Position = finalPosition;',
  4367. '}'
  4368. ].join( '\n' ) );
  4369. gl.shaderSource( fragmentShader, [
  4370. 'precision ' + renderer.getPrecision() + ' float;',
  4371. 'uniform vec3 color;',
  4372. 'uniform sampler2D map;',
  4373. 'uniform float opacity;',
  4374. 'uniform int fogType;',
  4375. 'uniform vec3 fogColor;',
  4376. 'uniform float fogDensity;',
  4377. 'uniform float fogNear;',
  4378. 'uniform float fogFar;',
  4379. 'uniform float alphaTest;',
  4380. 'varying vec2 vUV;',
  4381. 'void main() {',
  4382. 'vec4 texture = texture2D( map, vUV );',
  4383. 'if ( texture.a < alphaTest ) discard;',
  4384. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  4385. 'if ( fogType > 0 ) {',
  4386. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  4387. 'float fogFactor = 0.0;',
  4388. 'if ( fogType == 1 ) {',
  4389. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  4390. '} else {',
  4391. 'const float LOG2 = 1.442695;',
  4392. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  4393. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  4394. '}',
  4395. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  4396. '}',
  4397. '}'
  4398. ].join( '\n' ) );
  4399. gl.compileShader( vertexShader );
  4400. gl.compileShader( fragmentShader );
  4401. gl.attachShader( program, vertexShader );
  4402. gl.attachShader( program, fragmentShader );
  4403. gl.linkProgram( program );
  4404. return program;
  4405. }
  4406. function painterSortStable( a, b ) {
  4407. if ( a.renderOrder !== b.renderOrder ) {
  4408. return a.renderOrder - b.renderOrder;
  4409. } else if ( a.z !== b.z ) {
  4410. return b.z - a.z;
  4411. } else {
  4412. return b.id - a.id;
  4413. }
  4414. }
  4415. }
  4416. /**
  4417. * @author mrdoob / http://mrdoob.com/
  4418. * @author alteredq / http://alteredqualia.com/
  4419. */
  4420. var materialId = 0;
  4421. function Material() {
  4422. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4423. this.uuid = _Math.generateUUID();
  4424. this.name = '';
  4425. this.type = 'Material';
  4426. this.fog = true;
  4427. this.lights = true;
  4428. this.blending = NormalBlending;
  4429. this.side = FrontSide;
  4430. this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading
  4431. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  4432. this.opacity = 1;
  4433. this.transparent = false;
  4434. this.blendSrc = SrcAlphaFactor;
  4435. this.blendDst = OneMinusSrcAlphaFactor;
  4436. this.blendEquation = AddEquation;
  4437. this.blendSrcAlpha = null;
  4438. this.blendDstAlpha = null;
  4439. this.blendEquationAlpha = null;
  4440. this.depthFunc = LessEqualDepth;
  4441. this.depthTest = true;
  4442. this.depthWrite = true;
  4443. this.clippingPlanes = null;
  4444. this.clipIntersection = false;
  4445. this.clipShadows = false;
  4446. this.colorWrite = true;
  4447. this.precision = null; // override the renderer's default precision for this material
  4448. this.polygonOffset = false;
  4449. this.polygonOffsetFactor = 0;
  4450. this.polygonOffsetUnits = 0;
  4451. this.alphaTest = 0;
  4452. this.premultipliedAlpha = false;
  4453. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  4454. this.visible = true;
  4455. this._needsUpdate = true;
  4456. }
  4457. Material.prototype = {
  4458. constructor: Material,
  4459. isMaterial: true,
  4460. get needsUpdate() {
  4461. return this._needsUpdate;
  4462. },
  4463. set needsUpdate( value ) {
  4464. if ( value === true ) this.update();
  4465. this._needsUpdate = value;
  4466. },
  4467. setValues: function ( values ) {
  4468. if ( values === undefined ) return;
  4469. for ( var key in values ) {
  4470. var newValue = values[ key ];
  4471. if ( newValue === undefined ) {
  4472. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  4473. continue;
  4474. }
  4475. var currentValue = this[ key ];
  4476. if ( currentValue === undefined ) {
  4477. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  4478. continue;
  4479. }
  4480. if ( currentValue && currentValue.isColor ) {
  4481. currentValue.set( newValue );
  4482. } else if ( (currentValue && currentValue.isVector3) && (newValue && newValue.isVector3) ) {
  4483. currentValue.copy( newValue );
  4484. } else if ( key === 'overdraw' ) {
  4485. // ensure overdraw is backwards-compatible with legacy boolean type
  4486. this[ key ] = Number( newValue );
  4487. } else {
  4488. this[ key ] = newValue;
  4489. }
  4490. }
  4491. },
  4492. toJSON: function ( meta ) {
  4493. var isRoot = meta === undefined;
  4494. if ( isRoot ) {
  4495. meta = {
  4496. textures: {},
  4497. images: {}
  4498. };
  4499. }
  4500. var data = {
  4501. metadata: {
  4502. version: 4.4,
  4503. type: 'Material',
  4504. generator: 'Material.toJSON'
  4505. }
  4506. };
  4507. // standard Material serialization
  4508. data.uuid = this.uuid;
  4509. data.type = this.type;
  4510. if ( this.name !== '' ) data.name = this.name;
  4511. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4512. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4513. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4514. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4515. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4516. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4517. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  4518. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  4519. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4520. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4521. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4522. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4523. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4524. data.bumpScale = this.bumpScale;
  4525. }
  4526. if ( this.normalMap && this.normalMap.isTexture ) {
  4527. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4528. data.normalScale = this.normalScale.toArray();
  4529. }
  4530. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4531. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4532. data.displacementScale = this.displacementScale;
  4533. data.displacementBias = this.displacementBias;
  4534. }
  4535. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4536. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4537. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4538. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4539. if ( this.envMap && this.envMap.isTexture ) {
  4540. data.envMap = this.envMap.toJSON( meta ).uuid;
  4541. data.reflectivity = this.reflectivity; // Scale behind envMap
  4542. }
  4543. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4544. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4545. }
  4546. if ( this.size !== undefined ) data.size = this.size;
  4547. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4548. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4549. if ( this.shading !== SmoothShading ) data.shading = this.shading;
  4550. if ( this.side !== FrontSide ) data.side = this.side;
  4551. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  4552. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4553. if ( this.transparent === true ) data.transparent = this.transparent;
  4554. data.depthFunc = this.depthFunc;
  4555. data.depthTest = this.depthTest;
  4556. data.depthWrite = this.depthWrite;
  4557. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4558. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4559. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4560. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4561. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4562. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4563. data.skinning = this.skinning;
  4564. data.morphTargets = this.morphTargets;
  4565. // TODO: Copied from Object3D.toJSON
  4566. function extractFromCache( cache ) {
  4567. var values = [];
  4568. for ( var key in cache ) {
  4569. var data = cache[ key ];
  4570. delete data.metadata;
  4571. values.push( data );
  4572. }
  4573. return values;
  4574. }
  4575. if ( isRoot ) {
  4576. var textures = extractFromCache( meta.textures );
  4577. var images = extractFromCache( meta.images );
  4578. if ( textures.length > 0 ) data.textures = textures;
  4579. if ( images.length > 0 ) data.images = images;
  4580. }
  4581. return data;
  4582. },
  4583. clone: function () {
  4584. return new this.constructor().copy( this );
  4585. },
  4586. copy: function ( source ) {
  4587. this.name = source.name;
  4588. this.fog = source.fog;
  4589. this.lights = source.lights;
  4590. this.blending = source.blending;
  4591. this.side = source.side;
  4592. this.shading = source.shading;
  4593. this.vertexColors = source.vertexColors;
  4594. this.opacity = source.opacity;
  4595. this.transparent = source.transparent;
  4596. this.blendSrc = source.blendSrc;
  4597. this.blendDst = source.blendDst;
  4598. this.blendEquation = source.blendEquation;
  4599. this.blendSrcAlpha = source.blendSrcAlpha;
  4600. this.blendDstAlpha = source.blendDstAlpha;
  4601. this.blendEquationAlpha = source.blendEquationAlpha;
  4602. this.depthFunc = source.depthFunc;
  4603. this.depthTest = source.depthTest;
  4604. this.depthWrite = source.depthWrite;
  4605. this.colorWrite = source.colorWrite;
  4606. this.precision = source.precision;
  4607. this.polygonOffset = source.polygonOffset;
  4608. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4609. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4610. this.alphaTest = source.alphaTest;
  4611. this.premultipliedAlpha = source.premultipliedAlpha;
  4612. this.overdraw = source.overdraw;
  4613. this.visible = source.visible;
  4614. this.clipShadows = source.clipShadows;
  4615. this.clipIntersection = source.clipIntersection;
  4616. var srcPlanes = source.clippingPlanes,
  4617. dstPlanes = null;
  4618. if ( srcPlanes !== null ) {
  4619. var n = srcPlanes.length;
  4620. dstPlanes = new Array( n );
  4621. for ( var i = 0; i !== n; ++ i )
  4622. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4623. }
  4624. this.clippingPlanes = dstPlanes;
  4625. return this;
  4626. },
  4627. update: function () {
  4628. this.dispatchEvent( { type: 'update' } );
  4629. },
  4630. dispose: function () {
  4631. this.dispatchEvent( { type: 'dispose' } );
  4632. }
  4633. };
  4634. Object.assign( Material.prototype, EventDispatcher.prototype );
  4635. /**
  4636. * @author alteredq / http://alteredqualia.com/
  4637. *
  4638. * parameters = {
  4639. * defines: { "label" : "value" },
  4640. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  4641. *
  4642. * fragmentShader: <string>,
  4643. * vertexShader: <string>,
  4644. *
  4645. * wireframe: <boolean>,
  4646. * wireframeLinewidth: <float>,
  4647. *
  4648. * lights: <bool>,
  4649. *
  4650. * skinning: <bool>,
  4651. * morphTargets: <bool>,
  4652. * morphNormals: <bool>
  4653. * }
  4654. */
  4655. function ShaderMaterial( parameters ) {
  4656. Material.call( this );
  4657. this.type = 'ShaderMaterial';
  4658. this.defines = {};
  4659. this.uniforms = {};
  4660. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  4661. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  4662. this.linewidth = 1;
  4663. this.wireframe = false;
  4664. this.wireframeLinewidth = 1;
  4665. this.fog = false; // set to use scene fog
  4666. this.lights = false; // set to use scene lights
  4667. this.clipping = false; // set to use user-defined clipping planes
  4668. this.skinning = false; // set to use skinning attribute streams
  4669. this.morphTargets = false; // set to use morph targets
  4670. this.morphNormals = false; // set to use morph normals
  4671. this.extensions = {
  4672. derivatives: false, // set to use derivatives
  4673. fragDepth: false, // set to use fragment depth values
  4674. drawBuffers: false, // set to use draw buffers
  4675. shaderTextureLOD: false // set to use shader texture LOD
  4676. };
  4677. // When rendered geometry doesn't include these attributes but the material does,
  4678. // use these default values in WebGL. This avoids errors when buffer data is missing.
  4679. this.defaultAttributeValues = {
  4680. 'color': [ 1, 1, 1 ],
  4681. 'uv': [ 0, 0 ],
  4682. 'uv2': [ 0, 0 ]
  4683. };
  4684. this.index0AttributeName = undefined;
  4685. if ( parameters !== undefined ) {
  4686. if ( parameters.attributes !== undefined ) {
  4687. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  4688. }
  4689. this.setValues( parameters );
  4690. }
  4691. }
  4692. ShaderMaterial.prototype = Object.create( Material.prototype );
  4693. ShaderMaterial.prototype.constructor = ShaderMaterial;
  4694. ShaderMaterial.prototype.isShaderMaterial = true;
  4695. ShaderMaterial.prototype.copy = function ( source ) {
  4696. Material.prototype.copy.call( this, source );
  4697. this.fragmentShader = source.fragmentShader;
  4698. this.vertexShader = source.vertexShader;
  4699. this.uniforms = Object.assign( {}, source.uniforms );
  4700. this.defines = source.defines;
  4701. this.wireframe = source.wireframe;
  4702. this.wireframeLinewidth = source.wireframeLinewidth;
  4703. this.lights = source.lights;
  4704. this.clipping = source.clipping;
  4705. this.skinning = source.skinning;
  4706. this.morphTargets = source.morphTargets;
  4707. this.morphNormals = source.morphNormals;
  4708. this.extensions = source.extensions;
  4709. return this;
  4710. };
  4711. ShaderMaterial.prototype.toJSON = function ( meta ) {
  4712. var data = Material.prototype.toJSON.call( this, meta );
  4713. data.uniforms = this.uniforms;
  4714. data.vertexShader = this.vertexShader;
  4715. data.fragmentShader = this.fragmentShader;
  4716. return data;
  4717. };
  4718. /**
  4719. * @author mrdoob / http://mrdoob.com/
  4720. * @author alteredq / http://alteredqualia.com/
  4721. * @author bhouston / https://clara.io
  4722. * @author WestLangley / http://github.com/WestLangley
  4723. *
  4724. * parameters = {
  4725. *
  4726. * opacity: <float>,
  4727. *
  4728. * map: new THREE.Texture( <Image> ),
  4729. *
  4730. * alphaMap: new THREE.Texture( <Image> ),
  4731. *
  4732. * displacementMap: new THREE.Texture( <Image> ),
  4733. * displacementScale: <float>,
  4734. * displacementBias: <float>,
  4735. *
  4736. * wireframe: <boolean>,
  4737. * wireframeLinewidth: <float>
  4738. * }
  4739. */
  4740. function MeshDepthMaterial( parameters ) {
  4741. Material.call( this );
  4742. this.type = 'MeshDepthMaterial';
  4743. this.depthPacking = BasicDepthPacking;
  4744. this.skinning = false;
  4745. this.morphTargets = false;
  4746. this.map = null;
  4747. this.alphaMap = null;
  4748. this.displacementMap = null;
  4749. this.displacementScale = 1;
  4750. this.displacementBias = 0;
  4751. this.wireframe = false;
  4752. this.wireframeLinewidth = 1;
  4753. this.fog = false;
  4754. this.lights = false;
  4755. this.setValues( parameters );
  4756. }
  4757. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  4758. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  4759. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  4760. MeshDepthMaterial.prototype.copy = function ( source ) {
  4761. Material.prototype.copy.call( this, source );
  4762. this.depthPacking = source.depthPacking;
  4763. this.skinning = source.skinning;
  4764. this.morphTargets = source.morphTargets;
  4765. this.map = source.map;
  4766. this.alphaMap = source.alphaMap;
  4767. this.displacementMap = source.displacementMap;
  4768. this.displacementScale = source.displacementScale;
  4769. this.displacementBias = source.displacementBias;
  4770. this.wireframe = source.wireframe;
  4771. this.wireframeLinewidth = source.wireframeLinewidth;
  4772. return this;
  4773. };
  4774. /**
  4775. * @author bhouston / http://clara.io
  4776. * @author WestLangley / http://github.com/WestLangley
  4777. */
  4778. function Box3( min, max ) {
  4779. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  4780. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  4781. }
  4782. Box3.prototype = {
  4783. constructor: Box3,
  4784. isBox3: true,
  4785. set: function ( min, max ) {
  4786. this.min.copy( min );
  4787. this.max.copy( max );
  4788. return this;
  4789. },
  4790. setFromArray: function ( array ) {
  4791. var minX = + Infinity;
  4792. var minY = + Infinity;
  4793. var minZ = + Infinity;
  4794. var maxX = - Infinity;
  4795. var maxY = - Infinity;
  4796. var maxZ = - Infinity;
  4797. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  4798. var x = array[ i ];
  4799. var y = array[ i + 1 ];
  4800. var z = array[ i + 2 ];
  4801. if ( x < minX ) minX = x;
  4802. if ( y < minY ) minY = y;
  4803. if ( z < minZ ) minZ = z;
  4804. if ( x > maxX ) maxX = x;
  4805. if ( y > maxY ) maxY = y;
  4806. if ( z > maxZ ) maxZ = z;
  4807. }
  4808. this.min.set( minX, minY, minZ );
  4809. this.max.set( maxX, maxY, maxZ );
  4810. },
  4811. setFromBufferAttribute: function ( attribute ) {
  4812. var minX = + Infinity;
  4813. var minY = + Infinity;
  4814. var minZ = + Infinity;
  4815. var maxX = - Infinity;
  4816. var maxY = - Infinity;
  4817. var maxZ = - Infinity;
  4818. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  4819. var x = attribute.getX( i );
  4820. var y = attribute.getY( i );
  4821. var z = attribute.getZ( i );
  4822. if ( x < minX ) minX = x;
  4823. if ( y < minY ) minY = y;
  4824. if ( z < minZ ) minZ = z;
  4825. if ( x > maxX ) maxX = x;
  4826. if ( y > maxY ) maxY = y;
  4827. if ( z > maxZ ) maxZ = z;
  4828. }
  4829. this.min.set( minX, minY, minZ );
  4830. this.max.set( maxX, maxY, maxZ );
  4831. },
  4832. setFromPoints: function ( points ) {
  4833. this.makeEmpty();
  4834. for ( var i = 0, il = points.length; i < il; i ++ ) {
  4835. this.expandByPoint( points[ i ] );
  4836. }
  4837. return this;
  4838. },
  4839. setFromCenterAndSize: function () {
  4840. var v1 = new Vector3();
  4841. return function setFromCenterAndSize( center, size ) {
  4842. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  4843. this.min.copy( center ).sub( halfSize );
  4844. this.max.copy( center ).add( halfSize );
  4845. return this;
  4846. };
  4847. }(),
  4848. setFromObject: function () {
  4849. // Computes the world-axis-aligned bounding box of an object (including its children),
  4850. // accounting for both the object's, and children's, world transforms
  4851. var v1 = new Vector3();
  4852. return function setFromObject( object ) {
  4853. var scope = this;
  4854. object.updateMatrixWorld( true );
  4855. this.makeEmpty();
  4856. object.traverse( function ( node ) {
  4857. var geometry = node.geometry;
  4858. if ( geometry !== undefined ) {
  4859. if ( geometry.isGeometry ) {
  4860. var vertices = geometry.vertices;
  4861. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4862. v1.copy( vertices[ i ] );
  4863. v1.applyMatrix4( node.matrixWorld );
  4864. scope.expandByPoint( v1 );
  4865. }
  4866. } else if ( geometry.isBufferGeometry ) {
  4867. var attribute = geometry.attributes.position;
  4868. if ( attribute !== undefined ) {
  4869. var array, offset, stride;
  4870. if ( attribute.isInterleavedBufferAttribute ) {
  4871. array = attribute.data.array;
  4872. offset = attribute.offset;
  4873. stride = attribute.data.stride;
  4874. } else {
  4875. array = attribute.array;
  4876. offset = 0;
  4877. stride = 3;
  4878. }
  4879. for ( var i = offset, il = array.length; i < il; i += stride ) {
  4880. v1.fromArray( array, i );
  4881. v1.applyMatrix4( node.matrixWorld );
  4882. scope.expandByPoint( v1 );
  4883. }
  4884. }
  4885. }
  4886. }
  4887. } );
  4888. return this;
  4889. };
  4890. }(),
  4891. clone: function () {
  4892. return new this.constructor().copy( this );
  4893. },
  4894. copy: function ( box ) {
  4895. this.min.copy( box.min );
  4896. this.max.copy( box.max );
  4897. return this;
  4898. },
  4899. makeEmpty: function () {
  4900. this.min.x = this.min.y = this.min.z = + Infinity;
  4901. this.max.x = this.max.y = this.max.z = - Infinity;
  4902. return this;
  4903. },
  4904. isEmpty: function () {
  4905. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4906. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  4907. },
  4908. getCenter: function ( optionalTarget ) {
  4909. var result = optionalTarget || new Vector3();
  4910. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  4911. },
  4912. getSize: function ( optionalTarget ) {
  4913. var result = optionalTarget || new Vector3();
  4914. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  4915. },
  4916. expandByPoint: function ( point ) {
  4917. this.min.min( point );
  4918. this.max.max( point );
  4919. return this;
  4920. },
  4921. expandByVector: function ( vector ) {
  4922. this.min.sub( vector );
  4923. this.max.add( vector );
  4924. return this;
  4925. },
  4926. expandByScalar: function ( scalar ) {
  4927. this.min.addScalar( - scalar );
  4928. this.max.addScalar( scalar );
  4929. return this;
  4930. },
  4931. containsPoint: function ( point ) {
  4932. if ( point.x < this.min.x || point.x > this.max.x ||
  4933. point.y < this.min.y || point.y > this.max.y ||
  4934. point.z < this.min.z || point.z > this.max.z ) {
  4935. return false;
  4936. }
  4937. return true;
  4938. },
  4939. containsBox: function ( box ) {
  4940. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  4941. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  4942. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  4943. return true;
  4944. }
  4945. return false;
  4946. },
  4947. getParameter: function ( point, optionalTarget ) {
  4948. // This can potentially have a divide by zero if the box
  4949. // has a size dimension of 0.
  4950. var result = optionalTarget || new Vector3();
  4951. return result.set(
  4952. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  4953. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  4954. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  4955. );
  4956. },
  4957. intersectsBox: function ( box ) {
  4958. // using 6 splitting planes to rule out intersections.
  4959. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  4960. box.max.y < this.min.y || box.min.y > this.max.y ||
  4961. box.max.z < this.min.z || box.min.z > this.max.z ) {
  4962. return false;
  4963. }
  4964. return true;
  4965. },
  4966. intersectsSphere: ( function () {
  4967. var closestPoint;
  4968. return function intersectsSphere( sphere ) {
  4969. if ( closestPoint === undefined ) closestPoint = new Vector3();
  4970. // Find the point on the AABB closest to the sphere center.
  4971. this.clampPoint( sphere.center, closestPoint );
  4972. // If that point is inside the sphere, the AABB and sphere intersect.
  4973. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  4974. };
  4975. } )(),
  4976. intersectsPlane: function ( plane ) {
  4977. // We compute the minimum and maximum dot product values. If those values
  4978. // are on the same side (back or front) of the plane, then there is no intersection.
  4979. var min, max;
  4980. if ( plane.normal.x > 0 ) {
  4981. min = plane.normal.x * this.min.x;
  4982. max = plane.normal.x * this.max.x;
  4983. } else {
  4984. min = plane.normal.x * this.max.x;
  4985. max = plane.normal.x * this.min.x;
  4986. }
  4987. if ( plane.normal.y > 0 ) {
  4988. min += plane.normal.y * this.min.y;
  4989. max += plane.normal.y * this.max.y;
  4990. } else {
  4991. min += plane.normal.y * this.max.y;
  4992. max += plane.normal.y * this.min.y;
  4993. }
  4994. if ( plane.normal.z > 0 ) {
  4995. min += plane.normal.z * this.min.z;
  4996. max += plane.normal.z * this.max.z;
  4997. } else {
  4998. min += plane.normal.z * this.max.z;
  4999. max += plane.normal.z * this.min.z;
  5000. }
  5001. return ( min <= plane.constant && max >= plane.constant );
  5002. },
  5003. clampPoint: function ( point, optionalTarget ) {
  5004. var result = optionalTarget || new Vector3();
  5005. return result.copy( point ).clamp( this.min, this.max );
  5006. },
  5007. distanceToPoint: function () {
  5008. var v1 = new Vector3();
  5009. return function distanceToPoint( point ) {
  5010. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  5011. return clampedPoint.sub( point ).length();
  5012. };
  5013. }(),
  5014. getBoundingSphere: function () {
  5015. var v1 = new Vector3();
  5016. return function getBoundingSphere( optionalTarget ) {
  5017. var result = optionalTarget || new Sphere();
  5018. this.getCenter( result.center );
  5019. result.radius = this.getSize( v1 ).length() * 0.5;
  5020. return result;
  5021. };
  5022. }(),
  5023. intersect: function ( box ) {
  5024. this.min.max( box.min );
  5025. this.max.min( box.max );
  5026. // 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.
  5027. if( this.isEmpty() ) this.makeEmpty();
  5028. return this;
  5029. },
  5030. union: function ( box ) {
  5031. this.min.min( box.min );
  5032. this.max.max( box.max );
  5033. return this;
  5034. },
  5035. applyMatrix4: function () {
  5036. var points = [
  5037. new Vector3(),
  5038. new Vector3(),
  5039. new Vector3(),
  5040. new Vector3(),
  5041. new Vector3(),
  5042. new Vector3(),
  5043. new Vector3(),
  5044. new Vector3()
  5045. ];
  5046. return function applyMatrix4( matrix ) {
  5047. // transform of empty box is an empty box.
  5048. if( this.isEmpty() ) return this;
  5049. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5050. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  5051. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  5052. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  5053. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  5054. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  5055. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  5056. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  5057. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  5058. this.setFromPoints( points );
  5059. return this;
  5060. };
  5061. }(),
  5062. translate: function ( offset ) {
  5063. this.min.add( offset );
  5064. this.max.add( offset );
  5065. return this;
  5066. },
  5067. equals: function ( box ) {
  5068. return box.min.equals( this.min ) && box.max.equals( this.max );
  5069. }
  5070. };
  5071. /**
  5072. * @author bhouston / http://clara.io
  5073. * @author mrdoob / http://mrdoob.com/
  5074. */
  5075. function Sphere( center, radius ) {
  5076. this.center = ( center !== undefined ) ? center : new Vector3();
  5077. this.radius = ( radius !== undefined ) ? radius : 0;
  5078. }
  5079. Sphere.prototype = {
  5080. constructor: Sphere,
  5081. set: function ( center, radius ) {
  5082. this.center.copy( center );
  5083. this.radius = radius;
  5084. return this;
  5085. },
  5086. setFromPoints: function () {
  5087. var box = new Box3();
  5088. return function setFromPoints( points, optionalCenter ) {
  5089. var center = this.center;
  5090. if ( optionalCenter !== undefined ) {
  5091. center.copy( optionalCenter );
  5092. } else {
  5093. box.setFromPoints( points ).getCenter( center );
  5094. }
  5095. var maxRadiusSq = 0;
  5096. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5097. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5098. }
  5099. this.radius = Math.sqrt( maxRadiusSq );
  5100. return this;
  5101. };
  5102. }(),
  5103. clone: function () {
  5104. return new this.constructor().copy( this );
  5105. },
  5106. copy: function ( sphere ) {
  5107. this.center.copy( sphere.center );
  5108. this.radius = sphere.radius;
  5109. return this;
  5110. },
  5111. empty: function () {
  5112. return ( this.radius <= 0 );
  5113. },
  5114. containsPoint: function ( point ) {
  5115. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5116. },
  5117. distanceToPoint: function ( point ) {
  5118. return ( point.distanceTo( this.center ) - this.radius );
  5119. },
  5120. intersectsSphere: function ( sphere ) {
  5121. var radiusSum = this.radius + sphere.radius;
  5122. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5123. },
  5124. intersectsBox: function ( box ) {
  5125. return box.intersectsSphere( this );
  5126. },
  5127. intersectsPlane: function ( plane ) {
  5128. // We use the following equation to compute the signed distance from
  5129. // the center of the sphere to the plane.
  5130. //
  5131. // distance = q * n - d
  5132. //
  5133. // If this distance is greater than the radius of the sphere,
  5134. // then there is no intersection.
  5135. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  5136. },
  5137. clampPoint: function ( point, optionalTarget ) {
  5138. var deltaLengthSq = this.center.distanceToSquared( point );
  5139. var result = optionalTarget || new Vector3();
  5140. result.copy( point );
  5141. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5142. result.sub( this.center ).normalize();
  5143. result.multiplyScalar( this.radius ).add( this.center );
  5144. }
  5145. return result;
  5146. },
  5147. getBoundingBox: function ( optionalTarget ) {
  5148. var box = optionalTarget || new Box3();
  5149. box.set( this.center, this.center );
  5150. box.expandByScalar( this.radius );
  5151. return box;
  5152. },
  5153. applyMatrix4: function ( matrix ) {
  5154. this.center.applyMatrix4( matrix );
  5155. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5156. return this;
  5157. },
  5158. translate: function ( offset ) {
  5159. this.center.add( offset );
  5160. return this;
  5161. },
  5162. equals: function ( sphere ) {
  5163. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  5164. }
  5165. };
  5166. /**
  5167. * @author alteredq / http://alteredqualia.com/
  5168. * @author WestLangley / http://github.com/WestLangley
  5169. * @author bhouston / http://clara.io
  5170. * @author tschw
  5171. */
  5172. function Matrix3() {
  5173. this.elements = new Float32Array( [
  5174. 1, 0, 0,
  5175. 0, 1, 0,
  5176. 0, 0, 1
  5177. ] );
  5178. if ( arguments.length > 0 ) {
  5179. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  5180. }
  5181. }
  5182. Matrix3.prototype = {
  5183. constructor: Matrix3,
  5184. isMatrix3: true,
  5185. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  5186. var te = this.elements;
  5187. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  5188. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  5189. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  5190. return this;
  5191. },
  5192. identity: function () {
  5193. this.set(
  5194. 1, 0, 0,
  5195. 0, 1, 0,
  5196. 0, 0, 1
  5197. );
  5198. return this;
  5199. },
  5200. clone: function () {
  5201. return new this.constructor().fromArray( this.elements );
  5202. },
  5203. copy: function ( m ) {
  5204. var me = m.elements;
  5205. this.set(
  5206. me[ 0 ], me[ 3 ], me[ 6 ],
  5207. me[ 1 ], me[ 4 ], me[ 7 ],
  5208. me[ 2 ], me[ 5 ], me[ 8 ]
  5209. );
  5210. return this;
  5211. },
  5212. setFromMatrix4: function( m ) {
  5213. var me = m.elements;
  5214. this.set(
  5215. me[ 0 ], me[ 4 ], me[ 8 ],
  5216. me[ 1 ], me[ 5 ], me[ 9 ],
  5217. me[ 2 ], me[ 6 ], me[ 10 ]
  5218. );
  5219. return this;
  5220. },
  5221. applyToVector3Array: function () {
  5222. var v1;
  5223. return function applyToVector3Array( array, offset, length ) {
  5224. if ( v1 === undefined ) v1 = new Vector3();
  5225. if ( offset === undefined ) offset = 0;
  5226. if ( length === undefined ) length = array.length;
  5227. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  5228. v1.fromArray( array, j );
  5229. v1.applyMatrix3( this );
  5230. v1.toArray( array, j );
  5231. }
  5232. return array;
  5233. };
  5234. }(),
  5235. applyToBuffer: function () {
  5236. var v1;
  5237. return function applyToBuffer( buffer, offset, length ) {
  5238. if ( v1 === undefined ) v1 = new Vector3();
  5239. if ( offset === undefined ) offset = 0;
  5240. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  5241. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  5242. v1.x = buffer.getX( j );
  5243. v1.y = buffer.getY( j );
  5244. v1.z = buffer.getZ( j );
  5245. v1.applyMatrix3( this );
  5246. buffer.setXYZ( j, v1.x, v1.y, v1.z );
  5247. }
  5248. return buffer;
  5249. };
  5250. }(),
  5251. multiplyScalar: function ( s ) {
  5252. var te = this.elements;
  5253. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  5254. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  5255. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  5256. return this;
  5257. },
  5258. determinant: function () {
  5259. var te = this.elements;
  5260. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  5261. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  5262. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  5263. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  5264. },
  5265. getInverse: function ( matrix, throwOnDegenerate ) {
  5266. if ( matrix && matrix.isMatrix4 ) {
  5267. console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." );
  5268. }
  5269. var me = matrix.elements,
  5270. te = this.elements,
  5271. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  5272. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  5273. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  5274. t11 = n33 * n22 - n32 * n23,
  5275. t12 = n32 * n13 - n33 * n12,
  5276. t13 = n23 * n12 - n22 * n13,
  5277. det = n11 * t11 + n21 * t12 + n31 * t13;
  5278. if ( det === 0 ) {
  5279. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  5280. if ( throwOnDegenerate === true ) {
  5281. throw new Error( msg );
  5282. } else {
  5283. console.warn( msg );
  5284. }
  5285. return this.identity();
  5286. }
  5287. var detInv = 1 / det;
  5288. te[ 0 ] = t11 * detInv;
  5289. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  5290. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  5291. te[ 3 ] = t12 * detInv;
  5292. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  5293. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  5294. te[ 6 ] = t13 * detInv;
  5295. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  5296. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  5297. return this;
  5298. },
  5299. transpose: function () {
  5300. var tmp, m = this.elements;
  5301. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  5302. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  5303. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  5304. return this;
  5305. },
  5306. getNormalMatrix: function ( matrix4 ) {
  5307. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  5308. },
  5309. transposeIntoArray: function ( r ) {
  5310. var m = this.elements;
  5311. r[ 0 ] = m[ 0 ];
  5312. r[ 1 ] = m[ 3 ];
  5313. r[ 2 ] = m[ 6 ];
  5314. r[ 3 ] = m[ 1 ];
  5315. r[ 4 ] = m[ 4 ];
  5316. r[ 5 ] = m[ 7 ];
  5317. r[ 6 ] = m[ 2 ];
  5318. r[ 7 ] = m[ 5 ];
  5319. r[ 8 ] = m[ 8 ];
  5320. return this;
  5321. },
  5322. fromArray: function ( array, offset ) {
  5323. if ( offset === undefined ) offset = 0;
  5324. for( var i = 0; i < 9; i ++ ) {
  5325. this.elements[ i ] = array[ i + offset ];
  5326. }
  5327. return this;
  5328. },
  5329. toArray: function ( array, offset ) {
  5330. if ( array === undefined ) array = [];
  5331. if ( offset === undefined ) offset = 0;
  5332. var te = this.elements;
  5333. array[ offset ] = te[ 0 ];
  5334. array[ offset + 1 ] = te[ 1 ];
  5335. array[ offset + 2 ] = te[ 2 ];
  5336. array[ offset + 3 ] = te[ 3 ];
  5337. array[ offset + 4 ] = te[ 4 ];
  5338. array[ offset + 5 ] = te[ 5 ];
  5339. array[ offset + 6 ] = te[ 6 ];
  5340. array[ offset + 7 ] = te[ 7 ];
  5341. array[ offset + 8 ] = te[ 8 ];
  5342. return array;
  5343. }
  5344. };
  5345. /**
  5346. * @author bhouston / http://clara.io
  5347. */
  5348. function Plane( normal, constant ) {
  5349. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  5350. this.constant = ( constant !== undefined ) ? constant : 0;
  5351. }
  5352. Plane.prototype = {
  5353. constructor: Plane,
  5354. set: function ( normal, constant ) {
  5355. this.normal.copy( normal );
  5356. this.constant = constant;
  5357. return this;
  5358. },
  5359. setComponents: function ( x, y, z, w ) {
  5360. this.normal.set( x, y, z );
  5361. this.constant = w;
  5362. return this;
  5363. },
  5364. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  5365. this.normal.copy( normal );
  5366. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  5367. return this;
  5368. },
  5369. setFromCoplanarPoints: function () {
  5370. var v1 = new Vector3();
  5371. var v2 = new Vector3();
  5372. return function setFromCoplanarPoints( a, b, c ) {
  5373. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  5374. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5375. this.setFromNormalAndCoplanarPoint( normal, a );
  5376. return this;
  5377. };
  5378. }(),
  5379. clone: function () {
  5380. return new this.constructor().copy( this );
  5381. },
  5382. copy: function ( plane ) {
  5383. this.normal.copy( plane.normal );
  5384. this.constant = plane.constant;
  5385. return this;
  5386. },
  5387. normalize: function () {
  5388. // Note: will lead to a divide by zero if the plane is invalid.
  5389. var inverseNormalLength = 1.0 / this.normal.length();
  5390. this.normal.multiplyScalar( inverseNormalLength );
  5391. this.constant *= inverseNormalLength;
  5392. return this;
  5393. },
  5394. negate: function () {
  5395. this.constant *= - 1;
  5396. this.normal.negate();
  5397. return this;
  5398. },
  5399. distanceToPoint: function ( point ) {
  5400. return this.normal.dot( point ) + this.constant;
  5401. },
  5402. distanceToSphere: function ( sphere ) {
  5403. return this.distanceToPoint( sphere.center ) - sphere.radius;
  5404. },
  5405. projectPoint: function ( point, optionalTarget ) {
  5406. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  5407. },
  5408. orthoPoint: function ( point, optionalTarget ) {
  5409. var perpendicularMagnitude = this.distanceToPoint( point );
  5410. var result = optionalTarget || new Vector3();
  5411. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  5412. },
  5413. intersectLine: function () {
  5414. var v1 = new Vector3();
  5415. return function intersectLine( line, optionalTarget ) {
  5416. var result = optionalTarget || new Vector3();
  5417. var direction = line.delta( v1 );
  5418. var denominator = this.normal.dot( direction );
  5419. if ( denominator === 0 ) {
  5420. // line is coplanar, return origin
  5421. if ( this.distanceToPoint( line.start ) === 0 ) {
  5422. return result.copy( line.start );
  5423. }
  5424. // Unsure if this is the correct method to handle this case.
  5425. return undefined;
  5426. }
  5427. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  5428. if ( t < 0 || t > 1 ) {
  5429. return undefined;
  5430. }
  5431. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  5432. };
  5433. }(),
  5434. intersectsLine: function ( line ) {
  5435. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5436. var startSign = this.distanceToPoint( line.start );
  5437. var endSign = this.distanceToPoint( line.end );
  5438. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  5439. },
  5440. intersectsBox: function ( box ) {
  5441. return box.intersectsPlane( this );
  5442. },
  5443. intersectsSphere: function ( sphere ) {
  5444. return sphere.intersectsPlane( this );
  5445. },
  5446. coplanarPoint: function ( optionalTarget ) {
  5447. var result = optionalTarget || new Vector3();
  5448. return result.copy( this.normal ).multiplyScalar( - this.constant );
  5449. },
  5450. applyMatrix4: function () {
  5451. var v1 = new Vector3();
  5452. var m1 = new Matrix3();
  5453. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  5454. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  5455. // transform normal based on theory here:
  5456. // http://www.songho.ca/opengl/gl_normaltransform.html
  5457. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  5458. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  5459. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  5460. this.constant = - referencePoint.dot( normal );
  5461. return this;
  5462. };
  5463. }(),
  5464. translate: function ( offset ) {
  5465. this.constant = this.constant - offset.dot( this.normal );
  5466. return this;
  5467. },
  5468. equals: function ( plane ) {
  5469. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  5470. }
  5471. };
  5472. /**
  5473. * @author mrdoob / http://mrdoob.com/
  5474. * @author alteredq / http://alteredqualia.com/
  5475. * @author bhouston / http://clara.io
  5476. */
  5477. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  5478. this.planes = [
  5479. ( p0 !== undefined ) ? p0 : new Plane(),
  5480. ( p1 !== undefined ) ? p1 : new Plane(),
  5481. ( p2 !== undefined ) ? p2 : new Plane(),
  5482. ( p3 !== undefined ) ? p3 : new Plane(),
  5483. ( p4 !== undefined ) ? p4 : new Plane(),
  5484. ( p5 !== undefined ) ? p5 : new Plane()
  5485. ];
  5486. }
  5487. Frustum.prototype = {
  5488. constructor: Frustum,
  5489. set: function ( p0, p1, p2, p3, p4, p5 ) {
  5490. var planes = this.planes;
  5491. planes[ 0 ].copy( p0 );
  5492. planes[ 1 ].copy( p1 );
  5493. planes[ 2 ].copy( p2 );
  5494. planes[ 3 ].copy( p3 );
  5495. planes[ 4 ].copy( p4 );
  5496. planes[ 5 ].copy( p5 );
  5497. return this;
  5498. },
  5499. clone: function () {
  5500. return new this.constructor().copy( this );
  5501. },
  5502. copy: function ( frustum ) {
  5503. var planes = this.planes;
  5504. for ( var i = 0; i < 6; i ++ ) {
  5505. planes[ i ].copy( frustum.planes[ i ] );
  5506. }
  5507. return this;
  5508. },
  5509. setFromMatrix: function ( m ) {
  5510. var planes = this.planes;
  5511. var me = m.elements;
  5512. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  5513. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  5514. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  5515. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  5516. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  5517. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  5518. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  5519. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  5520. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  5521. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  5522. return this;
  5523. },
  5524. intersectsObject: function () {
  5525. var sphere = new Sphere();
  5526. return function intersectsObject( object ) {
  5527. var geometry = object.geometry;
  5528. if ( geometry.boundingSphere === null )
  5529. geometry.computeBoundingSphere();
  5530. sphere.copy( geometry.boundingSphere )
  5531. .applyMatrix4( object.matrixWorld );
  5532. return this.intersectsSphere( sphere );
  5533. };
  5534. }(),
  5535. intersectsSprite: function () {
  5536. var sphere = new Sphere();
  5537. return function intersectsSprite( sprite ) {
  5538. sphere.center.set( 0, 0, 0 );
  5539. sphere.radius = 0.7071067811865476;
  5540. sphere.applyMatrix4( sprite.matrixWorld );
  5541. return this.intersectsSphere( sphere );
  5542. };
  5543. }(),
  5544. intersectsSphere: function ( sphere ) {
  5545. var planes = this.planes;
  5546. var center = sphere.center;
  5547. var negRadius = - sphere.radius;
  5548. for ( var i = 0; i < 6; i ++ ) {
  5549. var distance = planes[ i ].distanceToPoint( center );
  5550. if ( distance < negRadius ) {
  5551. return false;
  5552. }
  5553. }
  5554. return true;
  5555. },
  5556. intersectsBox: function () {
  5557. var p1 = new Vector3(),
  5558. p2 = new Vector3();
  5559. return function intersectsBox( box ) {
  5560. var planes = this.planes;
  5561. for ( var i = 0; i < 6 ; i ++ ) {
  5562. var plane = planes[ i ];
  5563. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  5564. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  5565. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  5566. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  5567. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  5568. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  5569. var d1 = plane.distanceToPoint( p1 );
  5570. var d2 = plane.distanceToPoint( p2 );
  5571. // if both outside plane, no intersection
  5572. if ( d1 < 0 && d2 < 0 ) {
  5573. return false;
  5574. }
  5575. }
  5576. return true;
  5577. };
  5578. }(),
  5579. containsPoint: function ( point ) {
  5580. var planes = this.planes;
  5581. for ( var i = 0; i < 6; i ++ ) {
  5582. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  5583. return false;
  5584. }
  5585. }
  5586. return true;
  5587. }
  5588. };
  5589. /**
  5590. * @author alteredq / http://alteredqualia.com/
  5591. * @author mrdoob / http://mrdoob.com/
  5592. */
  5593. function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) {
  5594. var _gl = _renderer.context,
  5595. _state = _renderer.state,
  5596. _frustum = new Frustum(),
  5597. _projScreenMatrix = new Matrix4(),
  5598. _lightShadows = _lights.shadows,
  5599. _shadowMapSize = new Vector2(),
  5600. _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ),
  5601. _lookTarget = new Vector3(),
  5602. _lightPositionWorld = new Vector3(),
  5603. _renderList = [],
  5604. _MorphingFlag = 1,
  5605. _SkinningFlag = 2,
  5606. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  5607. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  5608. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  5609. _materialCache = {};
  5610. var cubeDirections = [
  5611. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  5612. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  5613. ];
  5614. var cubeUps = [
  5615. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  5616. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  5617. ];
  5618. var cube2DViewPorts = [
  5619. new Vector4(), new Vector4(), new Vector4(),
  5620. new Vector4(), new Vector4(), new Vector4()
  5621. ];
  5622. // init
  5623. var depthMaterialTemplate = new MeshDepthMaterial();
  5624. depthMaterialTemplate.depthPacking = RGBADepthPacking;
  5625. depthMaterialTemplate.clipping = true;
  5626. var distanceShader = ShaderLib[ "distanceRGBA" ];
  5627. var distanceUniforms = Object.assign( {}, distanceShader.uniforms );
  5628. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  5629. var useMorphing = ( i & _MorphingFlag ) !== 0;
  5630. var useSkinning = ( i & _SkinningFlag ) !== 0;
  5631. var depthMaterial = depthMaterialTemplate.clone();
  5632. depthMaterial.morphTargets = useMorphing;
  5633. depthMaterial.skinning = useSkinning;
  5634. _depthMaterials[ i ] = depthMaterial;
  5635. var distanceMaterial = new ShaderMaterial( {
  5636. defines: {
  5637. 'USE_SHADOWMAP': ''
  5638. },
  5639. uniforms: distanceUniforms,
  5640. vertexShader: distanceShader.vertexShader,
  5641. fragmentShader: distanceShader.fragmentShader,
  5642. morphTargets: useMorphing,
  5643. skinning: useSkinning,
  5644. clipping: true
  5645. } );
  5646. _distanceMaterials[ i ] = distanceMaterial;
  5647. }
  5648. //
  5649. var scope = this;
  5650. this.enabled = false;
  5651. this.autoUpdate = true;
  5652. this.needsUpdate = false;
  5653. this.type = PCFShadowMap;
  5654. this.renderReverseSided = true;
  5655. this.renderSingleSided = true;
  5656. this.render = function ( scene, camera ) {
  5657. if ( scope.enabled === false ) return;
  5658. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  5659. if ( _lightShadows.length === 0 ) return;
  5660. // Set GL state for depth map.
  5661. _state.buffers.color.setClear( 1, 1, 1, 1 );
  5662. _state.disable( _gl.BLEND );
  5663. _state.setDepthTest( true );
  5664. _state.setScissorTest( false );
  5665. // render depth map
  5666. var faceCount, isPointLight;
  5667. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  5668. var light = _lightShadows[ i ];
  5669. var shadow = light.shadow;
  5670. if ( shadow === undefined ) {
  5671. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  5672. continue;
  5673. }
  5674. var shadowCamera = shadow.camera;
  5675. _shadowMapSize.copy( shadow.mapSize );
  5676. _shadowMapSize.min( _maxShadowMapSize );
  5677. if ( light && light.isPointLight ) {
  5678. faceCount = 6;
  5679. isPointLight = true;
  5680. var vpWidth = _shadowMapSize.x;
  5681. var vpHeight = _shadowMapSize.y;
  5682. // These viewports map a cube-map onto a 2D texture with the
  5683. // following orientation:
  5684. //
  5685. // xzXZ
  5686. // y Y
  5687. //
  5688. // X - Positive x direction
  5689. // x - Negative x direction
  5690. // Y - Positive y direction
  5691. // y - Negative y direction
  5692. // Z - Positive z direction
  5693. // z - Negative z direction
  5694. // positive X
  5695. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  5696. // negative X
  5697. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  5698. // positive Z
  5699. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  5700. // negative Z
  5701. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  5702. // positive Y
  5703. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  5704. // negative Y
  5705. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  5706. _shadowMapSize.x *= 4.0;
  5707. _shadowMapSize.y *= 2.0;
  5708. } else {
  5709. faceCount = 1;
  5710. isPointLight = false;
  5711. }
  5712. if ( shadow.map === null ) {
  5713. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  5714. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  5715. shadowCamera.updateProjectionMatrix();
  5716. }
  5717. if ( shadow.isSpotLightShadow ) {
  5718. shadow.update( light );
  5719. }
  5720. // TODO (abelnation / sam-g-steel): is this needed?
  5721. if (shadow && shadow.isRectAreaLightShadow ) {
  5722. shadow.update( light );
  5723. }
  5724. var shadowMap = shadow.map;
  5725. var shadowMatrix = shadow.matrix;
  5726. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  5727. shadowCamera.position.copy( _lightPositionWorld );
  5728. _renderer.setRenderTarget( shadowMap );
  5729. _renderer.clear();
  5730. // render shadow map for each cube face (if omni-directional) or
  5731. // run a single pass if not
  5732. for ( var face = 0; face < faceCount; face ++ ) {
  5733. if ( isPointLight ) {
  5734. _lookTarget.copy( shadowCamera.position );
  5735. _lookTarget.add( cubeDirections[ face ] );
  5736. shadowCamera.up.copy( cubeUps[ face ] );
  5737. shadowCamera.lookAt( _lookTarget );
  5738. var vpDimensions = cube2DViewPorts[ face ];
  5739. _state.viewport( vpDimensions );
  5740. } else {
  5741. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  5742. shadowCamera.lookAt( _lookTarget );
  5743. }
  5744. shadowCamera.updateMatrixWorld();
  5745. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  5746. // compute shadow matrix
  5747. shadowMatrix.set(
  5748. 0.5, 0.0, 0.0, 0.5,
  5749. 0.0, 0.5, 0.0, 0.5,
  5750. 0.0, 0.0, 0.5, 0.5,
  5751. 0.0, 0.0, 0.0, 1.0
  5752. );
  5753. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  5754. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  5755. // update camera matrices and frustum
  5756. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  5757. _frustum.setFromMatrix( _projScreenMatrix );
  5758. // set object matrices & frustum culling
  5759. _renderList.length = 0;
  5760. projectObject( scene, camera, shadowCamera );
  5761. // render shadow map
  5762. // render regular objects
  5763. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  5764. var object = _renderList[ j ];
  5765. var geometry = _objects.update( object );
  5766. var material = object.material;
  5767. if ( material && material.isMultiMaterial ) {
  5768. var groups = geometry.groups;
  5769. var materials = material.materials;
  5770. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  5771. var group = groups[ k ];
  5772. var groupMaterial = materials[ group.materialIndex ];
  5773. if ( groupMaterial.visible === true ) {
  5774. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  5775. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  5776. }
  5777. }
  5778. } else {
  5779. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  5780. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  5781. }
  5782. }
  5783. }
  5784. }
  5785. // Restore GL state.
  5786. var clearColor = _renderer.getClearColor(),
  5787. clearAlpha = _renderer.getClearAlpha();
  5788. _renderer.setClearColor( clearColor, clearAlpha );
  5789. scope.needsUpdate = false;
  5790. };
  5791. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  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. var useSkinning = object.isSkinnedMesh && material.skinning;
  5810. var variantIndex = 0;
  5811. if ( useMorphing ) variantIndex |= _MorphingFlag;
  5812. if ( useSkinning ) variantIndex |= _SkinningFlag;
  5813. result = materialVariants[ variantIndex ];
  5814. } else {
  5815. result = customMaterial;
  5816. }
  5817. if ( _renderer.localClippingEnabled &&
  5818. material.clipShadows === true &&
  5819. material.clippingPlanes.length !== 0 ) {
  5820. // in this case we need a unique material instance reflecting the
  5821. // appropriate state
  5822. var keyA = result.uuid, keyB = material.uuid;
  5823. var materialsForVariant = _materialCache[ keyA ];
  5824. if ( materialsForVariant === undefined ) {
  5825. materialsForVariant = {};
  5826. _materialCache[ keyA ] = materialsForVariant;
  5827. }
  5828. var cachedMaterial = materialsForVariant[ keyB ];
  5829. if ( cachedMaterial === undefined ) {
  5830. cachedMaterial = result.clone();
  5831. materialsForVariant[ keyB ] = cachedMaterial;
  5832. }
  5833. result = cachedMaterial;
  5834. }
  5835. result.visible = material.visible;
  5836. result.wireframe = material.wireframe;
  5837. var side = material.side;
  5838. if ( scope.renderSingleSided && side == DoubleSide ) {
  5839. side = FrontSide;
  5840. }
  5841. if ( scope.renderReverseSided ) {
  5842. if ( side === FrontSide ) side = BackSide;
  5843. else if ( side === BackSide ) side = FrontSide;
  5844. }
  5845. result.side = side;
  5846. result.clipShadows = material.clipShadows;
  5847. result.clippingPlanes = material.clippingPlanes;
  5848. result.wireframeLinewidth = material.wireframeLinewidth;
  5849. result.linewidth = material.linewidth;
  5850. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  5851. result.uniforms.lightPos.value.copy( lightPositionWorld );
  5852. }
  5853. return result;
  5854. }
  5855. function projectObject( object, camera, shadowCamera ) {
  5856. if ( object.visible === false ) return;
  5857. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  5858. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  5859. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  5860. var material = object.material;
  5861. if ( material.visible === true ) {
  5862. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  5863. _renderList.push( object );
  5864. }
  5865. }
  5866. }
  5867. var children = object.children;
  5868. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5869. projectObject( children[ i ], camera, shadowCamera );
  5870. }
  5871. }
  5872. }
  5873. /**
  5874. * @author bhouston / http://clara.io
  5875. */
  5876. function Ray( origin, direction ) {
  5877. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  5878. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  5879. }
  5880. Ray.prototype = {
  5881. constructor: Ray,
  5882. set: function ( origin, direction ) {
  5883. this.origin.copy( origin );
  5884. this.direction.copy( direction );
  5885. return this;
  5886. },
  5887. clone: function () {
  5888. return new this.constructor().copy( this );
  5889. },
  5890. copy: function ( ray ) {
  5891. this.origin.copy( ray.origin );
  5892. this.direction.copy( ray.direction );
  5893. return this;
  5894. },
  5895. at: function ( t, optionalTarget ) {
  5896. var result = optionalTarget || new Vector3();
  5897. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  5898. },
  5899. lookAt: function ( v ) {
  5900. this.direction.copy( v ).sub( this.origin ).normalize();
  5901. return this;
  5902. },
  5903. recast: function () {
  5904. var v1 = new Vector3();
  5905. return function recast( t ) {
  5906. this.origin.copy( this.at( t, v1 ) );
  5907. return this;
  5908. };
  5909. }(),
  5910. closestPointToPoint: function ( point, optionalTarget ) {
  5911. var result = optionalTarget || new Vector3();
  5912. result.subVectors( point, this.origin );
  5913. var directionDistance = result.dot( this.direction );
  5914. if ( directionDistance < 0 ) {
  5915. return result.copy( this.origin );
  5916. }
  5917. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  5918. },
  5919. distanceToPoint: function ( point ) {
  5920. return Math.sqrt( this.distanceSqToPoint( point ) );
  5921. },
  5922. distanceSqToPoint: function () {
  5923. var v1 = new Vector3();
  5924. return function distanceSqToPoint( point ) {
  5925. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  5926. // point behind the ray
  5927. if ( directionDistance < 0 ) {
  5928. return this.origin.distanceToSquared( point );
  5929. }
  5930. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  5931. return v1.distanceToSquared( point );
  5932. };
  5933. }(),
  5934. distanceSqToSegment: function () {
  5935. var segCenter = new Vector3();
  5936. var segDir = new Vector3();
  5937. var diff = new Vector3();
  5938. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  5939. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  5940. // It returns the min distance between the ray and the segment
  5941. // defined by v0 and v1
  5942. // It can also set two optional targets :
  5943. // - The closest point on the ray
  5944. // - The closest point on the segment
  5945. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  5946. segDir.copy( v1 ).sub( v0 ).normalize();
  5947. diff.copy( this.origin ).sub( segCenter );
  5948. var segExtent = v0.distanceTo( v1 ) * 0.5;
  5949. var a01 = - this.direction.dot( segDir );
  5950. var b0 = diff.dot( this.direction );
  5951. var b1 = - diff.dot( segDir );
  5952. var c = diff.lengthSq();
  5953. var det = Math.abs( 1 - a01 * a01 );
  5954. var s0, s1, sqrDist, extDet;
  5955. if ( det > 0 ) {
  5956. // The ray and segment are not parallel.
  5957. s0 = a01 * b1 - b0;
  5958. s1 = a01 * b0 - b1;
  5959. extDet = segExtent * det;
  5960. if ( s0 >= 0 ) {
  5961. if ( s1 >= - extDet ) {
  5962. if ( s1 <= extDet ) {
  5963. // region 0
  5964. // Minimum at interior points of ray and segment.
  5965. var invDet = 1 / det;
  5966. s0 *= invDet;
  5967. s1 *= invDet;
  5968. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  5969. } else {
  5970. // region 1
  5971. s1 = segExtent;
  5972. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5973. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5974. }
  5975. } else {
  5976. // region 5
  5977. s1 = - segExtent;
  5978. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5979. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5980. }
  5981. } else {
  5982. if ( s1 <= - extDet ) {
  5983. // region 4
  5984. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  5985. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5986. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5987. } else if ( s1 <= extDet ) {
  5988. // region 3
  5989. s0 = 0;
  5990. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5991. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  5992. } else {
  5993. // region 2
  5994. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  5995. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5996. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5997. }
  5998. }
  5999. } else {
  6000. // Ray and segment are parallel.
  6001. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  6002. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  6003. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6004. }
  6005. if ( optionalPointOnRay ) {
  6006. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  6007. }
  6008. if ( optionalPointOnSegment ) {
  6009. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  6010. }
  6011. return sqrDist;
  6012. };
  6013. }(),
  6014. intersectSphere: function () {
  6015. var v1 = new Vector3();
  6016. return function intersectSphere( sphere, optionalTarget ) {
  6017. v1.subVectors( sphere.center, this.origin );
  6018. var tca = v1.dot( this.direction );
  6019. var d2 = v1.dot( v1 ) - tca * tca;
  6020. var radius2 = sphere.radius * sphere.radius;
  6021. if ( d2 > radius2 ) return null;
  6022. var thc = Math.sqrt( radius2 - d2 );
  6023. // t0 = first intersect point - entrance on front of sphere
  6024. var t0 = tca - thc;
  6025. // t1 = second intersect point - exit point on back of sphere
  6026. var t1 = tca + thc;
  6027. // test to see if both t0 and t1 are behind the ray - if so, return null
  6028. if ( t0 < 0 && t1 < 0 ) return null;
  6029. // test to see if t0 is behind the ray:
  6030. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  6031. // in order to always return an intersect point that is in front of the ray.
  6032. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  6033. // else t0 is in front of the ray, so return the first collision point scaled by t0
  6034. return this.at( t0, optionalTarget );
  6035. };
  6036. }(),
  6037. intersectsSphere: function ( sphere ) {
  6038. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  6039. },
  6040. distanceToPlane: function ( plane ) {
  6041. var denominator = plane.normal.dot( this.direction );
  6042. if ( denominator === 0 ) {
  6043. // line is coplanar, return origin
  6044. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  6045. return 0;
  6046. }
  6047. // Null is preferable to undefined since undefined means.... it is undefined
  6048. return null;
  6049. }
  6050. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  6051. // Return if the ray never intersects the plane
  6052. return t >= 0 ? t : null;
  6053. },
  6054. intersectPlane: function ( plane, optionalTarget ) {
  6055. var t = this.distanceToPlane( plane );
  6056. if ( t === null ) {
  6057. return null;
  6058. }
  6059. return this.at( t, optionalTarget );
  6060. },
  6061. intersectsPlane: function ( plane ) {
  6062. // check if the ray lies on the plane first
  6063. var distToPoint = plane.distanceToPoint( this.origin );
  6064. if ( distToPoint === 0 ) {
  6065. return true;
  6066. }
  6067. var denominator = plane.normal.dot( this.direction );
  6068. if ( denominator * distToPoint < 0 ) {
  6069. return true;
  6070. }
  6071. // ray origin is behind the plane (and is pointing behind it)
  6072. return false;
  6073. },
  6074. intersectBox: function ( box, optionalTarget ) {
  6075. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  6076. var invdirx = 1 / this.direction.x,
  6077. invdiry = 1 / this.direction.y,
  6078. invdirz = 1 / this.direction.z;
  6079. var origin = this.origin;
  6080. if ( invdirx >= 0 ) {
  6081. tmin = ( box.min.x - origin.x ) * invdirx;
  6082. tmax = ( box.max.x - origin.x ) * invdirx;
  6083. } else {
  6084. tmin = ( box.max.x - origin.x ) * invdirx;
  6085. tmax = ( box.min.x - origin.x ) * invdirx;
  6086. }
  6087. if ( invdiry >= 0 ) {
  6088. tymin = ( box.min.y - origin.y ) * invdiry;
  6089. tymax = ( box.max.y - origin.y ) * invdiry;
  6090. } else {
  6091. tymin = ( box.max.y - origin.y ) * invdiry;
  6092. tymax = ( box.min.y - origin.y ) * invdiry;
  6093. }
  6094. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  6095. // These lines also handle the case where tmin or tmax is NaN
  6096. // (result of 0 * Infinity). x !== x returns true if x is NaN
  6097. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  6098. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  6099. if ( invdirz >= 0 ) {
  6100. tzmin = ( box.min.z - origin.z ) * invdirz;
  6101. tzmax = ( box.max.z - origin.z ) * invdirz;
  6102. } else {
  6103. tzmin = ( box.max.z - origin.z ) * invdirz;
  6104. tzmax = ( box.min.z - origin.z ) * invdirz;
  6105. }
  6106. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  6107. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  6108. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  6109. //return point closest to the ray (positive side)
  6110. if ( tmax < 0 ) return null;
  6111. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  6112. },
  6113. intersectsBox: ( function () {
  6114. var v = new Vector3();
  6115. return function intersectsBox( box ) {
  6116. return this.intersectBox( box, v ) !== null;
  6117. };
  6118. } )(),
  6119. intersectTriangle: function () {
  6120. // Compute the offset origin, edges, and normal.
  6121. var diff = new Vector3();
  6122. var edge1 = new Vector3();
  6123. var edge2 = new Vector3();
  6124. var normal = new Vector3();
  6125. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  6126. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6127. edge1.subVectors( b, a );
  6128. edge2.subVectors( c, a );
  6129. normal.crossVectors( edge1, edge2 );
  6130. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6131. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6132. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6133. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6134. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6135. var DdN = this.direction.dot( normal );
  6136. var sign;
  6137. if ( DdN > 0 ) {
  6138. if ( backfaceCulling ) return null;
  6139. sign = 1;
  6140. } else if ( DdN < 0 ) {
  6141. sign = - 1;
  6142. DdN = - DdN;
  6143. } else {
  6144. return null;
  6145. }
  6146. diff.subVectors( this.origin, a );
  6147. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  6148. // b1 < 0, no intersection
  6149. if ( DdQxE2 < 0 ) {
  6150. return null;
  6151. }
  6152. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  6153. // b2 < 0, no intersection
  6154. if ( DdE1xQ < 0 ) {
  6155. return null;
  6156. }
  6157. // b1+b2 > 1, no intersection
  6158. if ( DdQxE2 + DdE1xQ > DdN ) {
  6159. return null;
  6160. }
  6161. // Line intersects triangle, check if ray does.
  6162. var QdN = - sign * diff.dot( normal );
  6163. // t < 0, no intersection
  6164. if ( QdN < 0 ) {
  6165. return null;
  6166. }
  6167. // Ray intersects triangle.
  6168. return this.at( QdN / DdN, optionalTarget );
  6169. };
  6170. }(),
  6171. applyMatrix4: function ( matrix4 ) {
  6172. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  6173. this.origin.applyMatrix4( matrix4 );
  6174. this.direction.sub( this.origin );
  6175. this.direction.normalize();
  6176. return this;
  6177. },
  6178. equals: function ( ray ) {
  6179. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  6180. }
  6181. };
  6182. /**
  6183. * @author mrdoob / http://mrdoob.com/
  6184. * @author WestLangley / http://github.com/WestLangley
  6185. * @author bhouston / http://clara.io
  6186. */
  6187. function Euler( x, y, z, order ) {
  6188. this._x = x || 0;
  6189. this._y = y || 0;
  6190. this._z = z || 0;
  6191. this._order = order || Euler.DefaultOrder;
  6192. }
  6193. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  6194. Euler.DefaultOrder = 'XYZ';
  6195. Euler.prototype = {
  6196. constructor: Euler,
  6197. isEuler: true,
  6198. get x () {
  6199. return this._x;
  6200. },
  6201. set x ( value ) {
  6202. this._x = value;
  6203. this.onChangeCallback();
  6204. },
  6205. get y () {
  6206. return this._y;
  6207. },
  6208. set y ( value ) {
  6209. this._y = value;
  6210. this.onChangeCallback();
  6211. },
  6212. get z () {
  6213. return this._z;
  6214. },
  6215. set z ( value ) {
  6216. this._z = value;
  6217. this.onChangeCallback();
  6218. },
  6219. get order () {
  6220. return this._order;
  6221. },
  6222. set order ( value ) {
  6223. this._order = value;
  6224. this.onChangeCallback();
  6225. },
  6226. set: function ( x, y, z, order ) {
  6227. this._x = x;
  6228. this._y = y;
  6229. this._z = z;
  6230. this._order = order || this._order;
  6231. this.onChangeCallback();
  6232. return this;
  6233. },
  6234. clone: function () {
  6235. return new this.constructor( this._x, this._y, this._z, this._order );
  6236. },
  6237. copy: function ( euler ) {
  6238. this._x = euler._x;
  6239. this._y = euler._y;
  6240. this._z = euler._z;
  6241. this._order = euler._order;
  6242. this.onChangeCallback();
  6243. return this;
  6244. },
  6245. setFromRotationMatrix: function ( m, order, update ) {
  6246. var clamp = _Math.clamp;
  6247. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6248. var te = m.elements;
  6249. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  6250. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  6251. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6252. order = order || this._order;
  6253. if ( order === 'XYZ' ) {
  6254. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  6255. if ( Math.abs( m13 ) < 0.99999 ) {
  6256. this._x = Math.atan2( - m23, m33 );
  6257. this._z = Math.atan2( - m12, m11 );
  6258. } else {
  6259. this._x = Math.atan2( m32, m22 );
  6260. this._z = 0;
  6261. }
  6262. } else if ( order === 'YXZ' ) {
  6263. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  6264. if ( Math.abs( m23 ) < 0.99999 ) {
  6265. this._y = Math.atan2( m13, m33 );
  6266. this._z = Math.atan2( m21, m22 );
  6267. } else {
  6268. this._y = Math.atan2( - m31, m11 );
  6269. this._z = 0;
  6270. }
  6271. } else if ( order === 'ZXY' ) {
  6272. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  6273. if ( Math.abs( m32 ) < 0.99999 ) {
  6274. this._y = Math.atan2( - m31, m33 );
  6275. this._z = Math.atan2( - m12, m22 );
  6276. } else {
  6277. this._y = 0;
  6278. this._z = Math.atan2( m21, m11 );
  6279. }
  6280. } else if ( order === 'ZYX' ) {
  6281. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  6282. if ( Math.abs( m31 ) < 0.99999 ) {
  6283. this._x = Math.atan2( m32, m33 );
  6284. this._z = Math.atan2( m21, m11 );
  6285. } else {
  6286. this._x = 0;
  6287. this._z = Math.atan2( - m12, m22 );
  6288. }
  6289. } else if ( order === 'YZX' ) {
  6290. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  6291. if ( Math.abs( m21 ) < 0.99999 ) {
  6292. this._x = Math.atan2( - m23, m22 );
  6293. this._y = Math.atan2( - m31, m11 );
  6294. } else {
  6295. this._x = 0;
  6296. this._y = Math.atan2( m13, m33 );
  6297. }
  6298. } else if ( order === 'XZY' ) {
  6299. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  6300. if ( Math.abs( m12 ) < 0.99999 ) {
  6301. this._x = Math.atan2( m32, m22 );
  6302. this._y = Math.atan2( m13, m11 );
  6303. } else {
  6304. this._x = Math.atan2( - m23, m33 );
  6305. this._y = 0;
  6306. }
  6307. } else {
  6308. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  6309. }
  6310. this._order = order;
  6311. if ( update !== false ) this.onChangeCallback();
  6312. return this;
  6313. },
  6314. setFromQuaternion: function () {
  6315. var matrix;
  6316. return function setFromQuaternion( q, order, update ) {
  6317. if ( matrix === undefined ) matrix = new Matrix4();
  6318. matrix.makeRotationFromQuaternion( q );
  6319. return this.setFromRotationMatrix( matrix, order, update );
  6320. };
  6321. }(),
  6322. setFromVector3: function ( v, order ) {
  6323. return this.set( v.x, v.y, v.z, order || this._order );
  6324. },
  6325. reorder: function () {
  6326. // WARNING: this discards revolution information -bhouston
  6327. var q = new Quaternion();
  6328. return function reorder( newOrder ) {
  6329. q.setFromEuler( this );
  6330. return this.setFromQuaternion( q, newOrder );
  6331. };
  6332. }(),
  6333. equals: function ( euler ) {
  6334. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  6335. },
  6336. fromArray: function ( array ) {
  6337. this._x = array[ 0 ];
  6338. this._y = array[ 1 ];
  6339. this._z = array[ 2 ];
  6340. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  6341. this.onChangeCallback();
  6342. return this;
  6343. },
  6344. toArray: function ( array, offset ) {
  6345. if ( array === undefined ) array = [];
  6346. if ( offset === undefined ) offset = 0;
  6347. array[ offset ] = this._x;
  6348. array[ offset + 1 ] = this._y;
  6349. array[ offset + 2 ] = this._z;
  6350. array[ offset + 3 ] = this._order;
  6351. return array;
  6352. },
  6353. toVector3: function ( optionalResult ) {
  6354. if ( optionalResult ) {
  6355. return optionalResult.set( this._x, this._y, this._z );
  6356. } else {
  6357. return new Vector3( this._x, this._y, this._z );
  6358. }
  6359. },
  6360. onChange: function ( callback ) {
  6361. this.onChangeCallback = callback;
  6362. return this;
  6363. },
  6364. onChangeCallback: function () {}
  6365. };
  6366. /**
  6367. * @author mrdoob / http://mrdoob.com/
  6368. */
  6369. function Layers() {
  6370. this.mask = 1;
  6371. }
  6372. Layers.prototype = {
  6373. constructor: Layers,
  6374. set: function ( channel ) {
  6375. this.mask = 1 << channel;
  6376. },
  6377. enable: function ( channel ) {
  6378. this.mask |= 1 << channel;
  6379. },
  6380. toggle: function ( channel ) {
  6381. this.mask ^= 1 << channel;
  6382. },
  6383. disable: function ( channel ) {
  6384. this.mask &= ~ ( 1 << channel );
  6385. },
  6386. test: function ( layers ) {
  6387. return ( this.mask & layers.mask ) !== 0;
  6388. }
  6389. };
  6390. /**
  6391. * @author mrdoob / http://mrdoob.com/
  6392. * @author mikael emtinger / http://gomo.se/
  6393. * @author alteredq / http://alteredqualia.com/
  6394. * @author WestLangley / http://github.com/WestLangley
  6395. * @author elephantatwork / www.elephantatwork.ch
  6396. */
  6397. var object3DId = 0;
  6398. function Object3D() {
  6399. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  6400. this.uuid = _Math.generateUUID();
  6401. this.name = '';
  6402. this.type = 'Object3D';
  6403. this.parent = null;
  6404. this.children = [];
  6405. this.up = Object3D.DefaultUp.clone();
  6406. var position = new Vector3();
  6407. var rotation = new Euler();
  6408. var quaternion = new Quaternion();
  6409. var scale = new Vector3( 1, 1, 1 );
  6410. function onRotationChange() {
  6411. quaternion.setFromEuler( rotation, false );
  6412. }
  6413. function onQuaternionChange() {
  6414. rotation.setFromQuaternion( quaternion, undefined, false );
  6415. }
  6416. rotation.onChange( onRotationChange );
  6417. quaternion.onChange( onQuaternionChange );
  6418. Object.defineProperties( this, {
  6419. position: {
  6420. enumerable: true,
  6421. value: position
  6422. },
  6423. rotation: {
  6424. enumerable: true,
  6425. value: rotation
  6426. },
  6427. quaternion: {
  6428. enumerable: true,
  6429. value: quaternion
  6430. },
  6431. scale: {
  6432. enumerable: true,
  6433. value: scale
  6434. },
  6435. modelViewMatrix: {
  6436. value: new Matrix4()
  6437. },
  6438. normalMatrix: {
  6439. value: new Matrix3()
  6440. }
  6441. } );
  6442. this.matrix = new Matrix4();
  6443. this.matrixWorld = new Matrix4();
  6444. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  6445. this.matrixWorldNeedsUpdate = false;
  6446. this.layers = new Layers();
  6447. this.visible = true;
  6448. this.castShadow = false;
  6449. this.receiveShadow = false;
  6450. this.frustumCulled = true;
  6451. this.renderOrder = 0;
  6452. this.userData = {};
  6453. this.onBeforeRender = function () {};
  6454. this.onAfterRender = function () {};
  6455. }
  6456. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  6457. Object3D.DefaultMatrixAutoUpdate = true;
  6458. Object.assign( Object3D.prototype, EventDispatcher.prototype, {
  6459. isObject3D: true,
  6460. applyMatrix: function ( matrix ) {
  6461. this.matrix.multiplyMatrices( matrix, this.matrix );
  6462. this.matrix.decompose( this.position, this.quaternion, this.scale );
  6463. },
  6464. setRotationFromAxisAngle: function ( axis, angle ) {
  6465. // assumes axis is normalized
  6466. this.quaternion.setFromAxisAngle( axis, angle );
  6467. },
  6468. setRotationFromEuler: function ( euler ) {
  6469. this.quaternion.setFromEuler( euler, true );
  6470. },
  6471. setRotationFromMatrix: function ( m ) {
  6472. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6473. this.quaternion.setFromRotationMatrix( m );
  6474. },
  6475. setRotationFromQuaternion: function ( q ) {
  6476. // assumes q is normalized
  6477. this.quaternion.copy( q );
  6478. },
  6479. rotateOnAxis: function () {
  6480. // rotate object on axis in object space
  6481. // axis is assumed to be normalized
  6482. var q1 = new Quaternion();
  6483. return function rotateOnAxis( axis, angle ) {
  6484. q1.setFromAxisAngle( axis, angle );
  6485. this.quaternion.multiply( q1 );
  6486. return this;
  6487. };
  6488. }(),
  6489. rotateX: function () {
  6490. var v1 = new Vector3( 1, 0, 0 );
  6491. return function rotateX( angle ) {
  6492. return this.rotateOnAxis( v1, angle );
  6493. };
  6494. }(),
  6495. rotateY: function () {
  6496. var v1 = new Vector3( 0, 1, 0 );
  6497. return function rotateY( angle ) {
  6498. return this.rotateOnAxis( v1, angle );
  6499. };
  6500. }(),
  6501. rotateZ: function () {
  6502. var v1 = new Vector3( 0, 0, 1 );
  6503. return function rotateZ( angle ) {
  6504. return this.rotateOnAxis( v1, angle );
  6505. };
  6506. }(),
  6507. translateOnAxis: function () {
  6508. // translate object by distance along axis in object space
  6509. // axis is assumed to be normalized
  6510. var v1 = new Vector3();
  6511. return function translateOnAxis( axis, distance ) {
  6512. v1.copy( axis ).applyQuaternion( this.quaternion );
  6513. this.position.add( v1.multiplyScalar( distance ) );
  6514. return this;
  6515. };
  6516. }(),
  6517. translateX: function () {
  6518. var v1 = new Vector3( 1, 0, 0 );
  6519. return function translateX( distance ) {
  6520. return this.translateOnAxis( v1, distance );
  6521. };
  6522. }(),
  6523. translateY: function () {
  6524. var v1 = new Vector3( 0, 1, 0 );
  6525. return function translateY( distance ) {
  6526. return this.translateOnAxis( v1, distance );
  6527. };
  6528. }(),
  6529. translateZ: function () {
  6530. var v1 = new Vector3( 0, 0, 1 );
  6531. return function translateZ( distance ) {
  6532. return this.translateOnAxis( v1, distance );
  6533. };
  6534. }(),
  6535. localToWorld: function ( vector ) {
  6536. return vector.applyMatrix4( this.matrixWorld );
  6537. },
  6538. worldToLocal: function () {
  6539. var m1 = new Matrix4();
  6540. return function worldToLocal( vector ) {
  6541. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  6542. };
  6543. }(),
  6544. lookAt: function () {
  6545. // This routine does not support objects with rotated and/or translated parent(s)
  6546. var m1 = new Matrix4();
  6547. return function lookAt( vector ) {
  6548. m1.lookAt( vector, this.position, this.up );
  6549. this.quaternion.setFromRotationMatrix( m1 );
  6550. };
  6551. }(),
  6552. add: function ( object ) {
  6553. if ( arguments.length > 1 ) {
  6554. for ( var i = 0; i < arguments.length; i ++ ) {
  6555. this.add( arguments[ i ] );
  6556. }
  6557. return this;
  6558. }
  6559. if ( object === this ) {
  6560. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  6561. return this;
  6562. }
  6563. if ( ( object && object.isObject3D ) ) {
  6564. if ( object.parent !== null ) {
  6565. object.parent.remove( object );
  6566. }
  6567. object.parent = this;
  6568. object.dispatchEvent( { type: 'added' } );
  6569. this.children.push( object );
  6570. } else {
  6571. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  6572. }
  6573. return this;
  6574. },
  6575. remove: function ( object ) {
  6576. if ( arguments.length > 1 ) {
  6577. for ( var i = 0; i < arguments.length; i ++ ) {
  6578. this.remove( arguments[ i ] );
  6579. }
  6580. }
  6581. var index = this.children.indexOf( object );
  6582. if ( index !== - 1 ) {
  6583. object.parent = null;
  6584. object.dispatchEvent( { type: 'removed' } );
  6585. this.children.splice( index, 1 );
  6586. }
  6587. },
  6588. getObjectById: function ( id ) {
  6589. return this.getObjectByProperty( 'id', id );
  6590. },
  6591. getObjectByName: function ( name ) {
  6592. return this.getObjectByProperty( 'name', name );
  6593. },
  6594. getObjectByProperty: function ( name, value ) {
  6595. if ( this[ name ] === value ) return this;
  6596. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6597. var child = this.children[ i ];
  6598. var object = child.getObjectByProperty( name, value );
  6599. if ( object !== undefined ) {
  6600. return object;
  6601. }
  6602. }
  6603. return undefined;
  6604. },
  6605. getWorldPosition: function ( optionalTarget ) {
  6606. var result = optionalTarget || new Vector3();
  6607. this.updateMatrixWorld( true );
  6608. return result.setFromMatrixPosition( this.matrixWorld );
  6609. },
  6610. getWorldQuaternion: function () {
  6611. var position = new Vector3();
  6612. var scale = new Vector3();
  6613. return function getWorldQuaternion( optionalTarget ) {
  6614. var result = optionalTarget || new Quaternion();
  6615. this.updateMatrixWorld( true );
  6616. this.matrixWorld.decompose( position, result, scale );
  6617. return result;
  6618. };
  6619. }(),
  6620. getWorldRotation: function () {
  6621. var quaternion = new Quaternion();
  6622. return function getWorldRotation( optionalTarget ) {
  6623. var result = optionalTarget || new Euler();
  6624. this.getWorldQuaternion( quaternion );
  6625. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  6626. };
  6627. }(),
  6628. getWorldScale: function () {
  6629. var position = new Vector3();
  6630. var quaternion = new Quaternion();
  6631. return function getWorldScale( optionalTarget ) {
  6632. var result = optionalTarget || new Vector3();
  6633. this.updateMatrixWorld( true );
  6634. this.matrixWorld.decompose( position, quaternion, result );
  6635. return result;
  6636. };
  6637. }(),
  6638. getWorldDirection: function () {
  6639. var quaternion = new Quaternion();
  6640. return function getWorldDirection( optionalTarget ) {
  6641. var result = optionalTarget || new Vector3();
  6642. this.getWorldQuaternion( quaternion );
  6643. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  6644. };
  6645. }(),
  6646. raycast: function () {},
  6647. traverse: function ( callback ) {
  6648. callback( this );
  6649. var children = this.children;
  6650. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6651. children[ i ].traverse( callback );
  6652. }
  6653. },
  6654. traverseVisible: function ( callback ) {
  6655. if ( this.visible === false ) return;
  6656. callback( this );
  6657. var children = this.children;
  6658. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6659. children[ i ].traverseVisible( callback );
  6660. }
  6661. },
  6662. traverseAncestors: function ( callback ) {
  6663. var parent = this.parent;
  6664. if ( parent !== null ) {
  6665. callback( parent );
  6666. parent.traverseAncestors( callback );
  6667. }
  6668. },
  6669. updateMatrix: function () {
  6670. this.matrix.compose( this.position, this.quaternion, this.scale );
  6671. this.matrixWorldNeedsUpdate = true;
  6672. },
  6673. updateMatrixWorld: function ( force ) {
  6674. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  6675. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  6676. if ( this.parent === null ) {
  6677. this.matrixWorld.copy( this.matrix );
  6678. } else {
  6679. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  6680. }
  6681. this.matrixWorldNeedsUpdate = false;
  6682. force = true;
  6683. }
  6684. // update children
  6685. var children = this.children;
  6686. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6687. children[ i ].updateMatrixWorld( force );
  6688. }
  6689. },
  6690. toJSON: function ( meta ) {
  6691. // meta is '' when called from JSON.stringify
  6692. var isRootObject = ( meta === undefined || meta === '' );
  6693. var output = {};
  6694. // meta is a hash used to collect geometries, materials.
  6695. // not providing it implies that this is the root object
  6696. // being serialized.
  6697. if ( isRootObject ) {
  6698. // initialize meta obj
  6699. meta = {
  6700. geometries: {},
  6701. materials: {},
  6702. textures: {},
  6703. images: {}
  6704. };
  6705. output.metadata = {
  6706. version: 4.4,
  6707. type: 'Object',
  6708. generator: 'Object3D.toJSON'
  6709. };
  6710. }
  6711. // standard Object3D serialization
  6712. var object = {};
  6713. object.uuid = this.uuid;
  6714. object.type = this.type;
  6715. if ( this.name !== '' ) object.name = this.name;
  6716. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  6717. if ( this.castShadow === true ) object.castShadow = true;
  6718. if ( this.receiveShadow === true ) object.receiveShadow = true;
  6719. if ( this.visible === false ) object.visible = false;
  6720. object.matrix = this.matrix.toArray();
  6721. //
  6722. if ( this.geometry !== undefined ) {
  6723. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  6724. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  6725. }
  6726. object.geometry = this.geometry.uuid;
  6727. }
  6728. if ( this.material !== undefined ) {
  6729. if ( meta.materials[ this.material.uuid ] === undefined ) {
  6730. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  6731. }
  6732. object.material = this.material.uuid;
  6733. }
  6734. //
  6735. if ( this.children.length > 0 ) {
  6736. object.children = [];
  6737. for ( var i = 0; i < this.children.length; i ++ ) {
  6738. object.children.push( this.children[ i ].toJSON( meta ).object );
  6739. }
  6740. }
  6741. if ( isRootObject ) {
  6742. var geometries = extractFromCache( meta.geometries );
  6743. var materials = extractFromCache( meta.materials );
  6744. var textures = extractFromCache( meta.textures );
  6745. var images = extractFromCache( meta.images );
  6746. if ( geometries.length > 0 ) output.geometries = geometries;
  6747. if ( materials.length > 0 ) output.materials = materials;
  6748. if ( textures.length > 0 ) output.textures = textures;
  6749. if ( images.length > 0 ) output.images = images;
  6750. }
  6751. output.object = object;
  6752. return output;
  6753. // extract data from the cache hash
  6754. // remove metadata on each item
  6755. // and return as array
  6756. function extractFromCache( cache ) {
  6757. var values = [];
  6758. for ( var key in cache ) {
  6759. var data = cache[ key ];
  6760. delete data.metadata;
  6761. values.push( data );
  6762. }
  6763. return values;
  6764. }
  6765. },
  6766. clone: function ( recursive ) {
  6767. return new this.constructor().copy( this, recursive );
  6768. },
  6769. copy: function ( source, recursive ) {
  6770. if ( recursive === undefined ) recursive = true;
  6771. this.name = source.name;
  6772. this.up.copy( source.up );
  6773. this.position.copy( source.position );
  6774. this.quaternion.copy( source.quaternion );
  6775. this.scale.copy( source.scale );
  6776. this.matrix.copy( source.matrix );
  6777. this.matrixWorld.copy( source.matrixWorld );
  6778. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6779. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  6780. this.layers.mask = source.layers.mask;
  6781. this.visible = source.visible;
  6782. this.castShadow = source.castShadow;
  6783. this.receiveShadow = source.receiveShadow;
  6784. this.frustumCulled = source.frustumCulled;
  6785. this.renderOrder = source.renderOrder;
  6786. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6787. if ( recursive === true ) {
  6788. for ( var i = 0; i < source.children.length; i ++ ) {
  6789. var child = source.children[ i ];
  6790. this.add( child.clone() );
  6791. }
  6792. }
  6793. return this;
  6794. }
  6795. } );
  6796. /**
  6797. * @author bhouston / http://clara.io
  6798. */
  6799. function Line3( start, end ) {
  6800. this.start = ( start !== undefined ) ? start : new Vector3();
  6801. this.end = ( end !== undefined ) ? end : new Vector3();
  6802. }
  6803. Line3.prototype = {
  6804. constructor: Line3,
  6805. set: function ( start, end ) {
  6806. this.start.copy( start );
  6807. this.end.copy( end );
  6808. return this;
  6809. },
  6810. clone: function () {
  6811. return new this.constructor().copy( this );
  6812. },
  6813. copy: function ( line ) {
  6814. this.start.copy( line.start );
  6815. this.end.copy( line.end );
  6816. return this;
  6817. },
  6818. getCenter: function ( optionalTarget ) {
  6819. var result = optionalTarget || new Vector3();
  6820. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  6821. },
  6822. delta: function ( optionalTarget ) {
  6823. var result = optionalTarget || new Vector3();
  6824. return result.subVectors( this.end, this.start );
  6825. },
  6826. distanceSq: function () {
  6827. return this.start.distanceToSquared( this.end );
  6828. },
  6829. distance: function () {
  6830. return this.start.distanceTo( this.end );
  6831. },
  6832. at: function ( t, optionalTarget ) {
  6833. var result = optionalTarget || new Vector3();
  6834. return this.delta( result ).multiplyScalar( t ).add( this.start );
  6835. },
  6836. closestPointToPointParameter: function () {
  6837. var startP = new Vector3();
  6838. var startEnd = new Vector3();
  6839. return function closestPointToPointParameter( point, clampToLine ) {
  6840. startP.subVectors( point, this.start );
  6841. startEnd.subVectors( this.end, this.start );
  6842. var startEnd2 = startEnd.dot( startEnd );
  6843. var startEnd_startP = startEnd.dot( startP );
  6844. var t = startEnd_startP / startEnd2;
  6845. if ( clampToLine ) {
  6846. t = _Math.clamp( t, 0, 1 );
  6847. }
  6848. return t;
  6849. };
  6850. }(),
  6851. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  6852. var t = this.closestPointToPointParameter( point, clampToLine );
  6853. var result = optionalTarget || new Vector3();
  6854. return this.delta( result ).multiplyScalar( t ).add( this.start );
  6855. },
  6856. applyMatrix4: function ( matrix ) {
  6857. this.start.applyMatrix4( matrix );
  6858. this.end.applyMatrix4( matrix );
  6859. return this;
  6860. },
  6861. equals: function ( line ) {
  6862. return line.start.equals( this.start ) && line.end.equals( this.end );
  6863. }
  6864. };
  6865. /**
  6866. * @author bhouston / http://clara.io
  6867. * @author mrdoob / http://mrdoob.com/
  6868. */
  6869. function Triangle( a, b, c ) {
  6870. this.a = ( a !== undefined ) ? a : new Vector3();
  6871. this.b = ( b !== undefined ) ? b : new Vector3();
  6872. this.c = ( c !== undefined ) ? c : new Vector3();
  6873. }
  6874. Triangle.normal = function () {
  6875. var v0 = new Vector3();
  6876. return function normal( a, b, c, optionalTarget ) {
  6877. var result = optionalTarget || new Vector3();
  6878. result.subVectors( c, b );
  6879. v0.subVectors( a, b );
  6880. result.cross( v0 );
  6881. var resultLengthSq = result.lengthSq();
  6882. if ( resultLengthSq > 0 ) {
  6883. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  6884. }
  6885. return result.set( 0, 0, 0 );
  6886. };
  6887. }();
  6888. // static/instance method to calculate barycentric coordinates
  6889. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  6890. Triangle.barycoordFromPoint = function () {
  6891. var v0 = new Vector3();
  6892. var v1 = new Vector3();
  6893. var v2 = new Vector3();
  6894. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  6895. v0.subVectors( c, a );
  6896. v1.subVectors( b, a );
  6897. v2.subVectors( point, a );
  6898. var dot00 = v0.dot( v0 );
  6899. var dot01 = v0.dot( v1 );
  6900. var dot02 = v0.dot( v2 );
  6901. var dot11 = v1.dot( v1 );
  6902. var dot12 = v1.dot( v2 );
  6903. var denom = ( dot00 * dot11 - dot01 * dot01 );
  6904. var result = optionalTarget || new Vector3();
  6905. // collinear or singular triangle
  6906. if ( denom === 0 ) {
  6907. // arbitrary location outside of triangle?
  6908. // not sure if this is the best idea, maybe should be returning undefined
  6909. return result.set( - 2, - 1, - 1 );
  6910. }
  6911. var invDenom = 1 / denom;
  6912. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  6913. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  6914. // barycentric coordinates must always sum to 1
  6915. return result.set( 1 - u - v, v, u );
  6916. };
  6917. }();
  6918. Triangle.containsPoint = function () {
  6919. var v1 = new Vector3();
  6920. return function containsPoint( point, a, b, c ) {
  6921. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  6922. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  6923. };
  6924. }();
  6925. Triangle.prototype = {
  6926. constructor: Triangle,
  6927. set: function ( a, b, c ) {
  6928. this.a.copy( a );
  6929. this.b.copy( b );
  6930. this.c.copy( c );
  6931. return this;
  6932. },
  6933. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  6934. this.a.copy( points[ i0 ] );
  6935. this.b.copy( points[ i1 ] );
  6936. this.c.copy( points[ i2 ] );
  6937. return this;
  6938. },
  6939. clone: function () {
  6940. return new this.constructor().copy( this );
  6941. },
  6942. copy: function ( triangle ) {
  6943. this.a.copy( triangle.a );
  6944. this.b.copy( triangle.b );
  6945. this.c.copy( triangle.c );
  6946. return this;
  6947. },
  6948. area: function () {
  6949. var v0 = new Vector3();
  6950. var v1 = new Vector3();
  6951. return function area() {
  6952. v0.subVectors( this.c, this.b );
  6953. v1.subVectors( this.a, this.b );
  6954. return v0.cross( v1 ).length() * 0.5;
  6955. };
  6956. }(),
  6957. midpoint: function ( optionalTarget ) {
  6958. var result = optionalTarget || new Vector3();
  6959. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  6960. },
  6961. normal: function ( optionalTarget ) {
  6962. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  6963. },
  6964. plane: function ( optionalTarget ) {
  6965. var result = optionalTarget || new Plane();
  6966. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  6967. },
  6968. barycoordFromPoint: function ( point, optionalTarget ) {
  6969. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  6970. },
  6971. containsPoint: function ( point ) {
  6972. return Triangle.containsPoint( point, this.a, this.b, this.c );
  6973. },
  6974. closestPointToPoint: function () {
  6975. var plane, edgeList, projectedPoint, closestPoint;
  6976. return function closestPointToPoint( point, optionalTarget ) {
  6977. if ( plane === undefined ) {
  6978. plane = new Plane();
  6979. edgeList = [ new Line3(), new Line3(), new Line3() ];
  6980. projectedPoint = new Vector3();
  6981. closestPoint = new Vector3();
  6982. }
  6983. var result = optionalTarget || new Vector3();
  6984. var minDistance = Infinity;
  6985. // project the point onto the plane of the triangle
  6986. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  6987. plane.projectPoint( point, projectedPoint );
  6988. // check if the projection lies within the triangle
  6989. if( this.containsPoint( projectedPoint ) === true ) {
  6990. // if so, this is the closest point
  6991. result.copy( projectedPoint );
  6992. } else {
  6993. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  6994. edgeList[ 0 ].set( this.a, this.b );
  6995. edgeList[ 1 ].set( this.b, this.c );
  6996. edgeList[ 2 ].set( this.c, this.a );
  6997. for( var i = 0; i < edgeList.length; i ++ ) {
  6998. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  6999. var distance = projectedPoint.distanceToSquared( closestPoint );
  7000. if( distance < minDistance ) {
  7001. minDistance = distance;
  7002. result.copy( closestPoint );
  7003. }
  7004. }
  7005. }
  7006. return result;
  7007. };
  7008. }(),
  7009. equals: function ( triangle ) {
  7010. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  7011. }
  7012. };
  7013. /**
  7014. * @author mrdoob / http://mrdoob.com/
  7015. * @author alteredq / http://alteredqualia.com/
  7016. */
  7017. function Face3( a, b, c, normal, color, materialIndex ) {
  7018. this.a = a;
  7019. this.b = b;
  7020. this.c = c;
  7021. this.normal = (normal && normal.isVector3) ? normal : new Vector3();
  7022. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  7023. this.color = (color && color.isColor) ? color : new Color();
  7024. this.vertexColors = Array.isArray( color ) ? color : [];
  7025. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  7026. }
  7027. Face3.prototype = {
  7028. constructor: Face3,
  7029. clone: function () {
  7030. return new this.constructor().copy( this );
  7031. },
  7032. copy: function ( source ) {
  7033. this.a = source.a;
  7034. this.b = source.b;
  7035. this.c = source.c;
  7036. this.normal.copy( source.normal );
  7037. this.color.copy( source.color );
  7038. this.materialIndex = source.materialIndex;
  7039. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  7040. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  7041. }
  7042. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  7043. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  7044. }
  7045. return this;
  7046. }
  7047. };
  7048. /**
  7049. * @author mrdoob / http://mrdoob.com/
  7050. * @author alteredq / http://alteredqualia.com/
  7051. *
  7052. * parameters = {
  7053. * color: <hex>,
  7054. * opacity: <float>,
  7055. * map: new THREE.Texture( <Image> ),
  7056. *
  7057. * lightMap: new THREE.Texture( <Image> ),
  7058. * lightMapIntensity: <float>
  7059. *
  7060. * aoMap: new THREE.Texture( <Image> ),
  7061. * aoMapIntensity: <float>
  7062. *
  7063. * specularMap: new THREE.Texture( <Image> ),
  7064. *
  7065. * alphaMap: new THREE.Texture( <Image> ),
  7066. *
  7067. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7068. * combine: THREE.Multiply,
  7069. * reflectivity: <float>,
  7070. * refractionRatio: <float>,
  7071. *
  7072. * shading: THREE.SmoothShading,
  7073. * depthTest: <bool>,
  7074. * depthWrite: <bool>,
  7075. *
  7076. * wireframe: <boolean>,
  7077. * wireframeLinewidth: <float>,
  7078. *
  7079. * skinning: <bool>,
  7080. * morphTargets: <bool>
  7081. * }
  7082. */
  7083. function MeshBasicMaterial( parameters ) {
  7084. Material.call( this );
  7085. this.type = 'MeshBasicMaterial';
  7086. this.color = new Color( 0xffffff ); // emissive
  7087. this.map = null;
  7088. this.lightMap = null;
  7089. this.lightMapIntensity = 1.0;
  7090. this.aoMap = null;
  7091. this.aoMapIntensity = 1.0;
  7092. this.specularMap = null;
  7093. this.alphaMap = null;
  7094. this.envMap = null;
  7095. this.combine = MultiplyOperation;
  7096. this.reflectivity = 1;
  7097. this.refractionRatio = 0.98;
  7098. this.wireframe = false;
  7099. this.wireframeLinewidth = 1;
  7100. this.wireframeLinecap = 'round';
  7101. this.wireframeLinejoin = 'round';
  7102. this.skinning = false;
  7103. this.morphTargets = false;
  7104. this.lights = false;
  7105. this.setValues( parameters );
  7106. }
  7107. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  7108. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  7109. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  7110. MeshBasicMaterial.prototype.copy = function ( source ) {
  7111. Material.prototype.copy.call( this, source );
  7112. this.color.copy( source.color );
  7113. this.map = source.map;
  7114. this.lightMap = source.lightMap;
  7115. this.lightMapIntensity = source.lightMapIntensity;
  7116. this.aoMap = source.aoMap;
  7117. this.aoMapIntensity = source.aoMapIntensity;
  7118. this.specularMap = source.specularMap;
  7119. this.alphaMap = source.alphaMap;
  7120. this.envMap = source.envMap;
  7121. this.combine = source.combine;
  7122. this.reflectivity = source.reflectivity;
  7123. this.refractionRatio = source.refractionRatio;
  7124. this.wireframe = source.wireframe;
  7125. this.wireframeLinewidth = source.wireframeLinewidth;
  7126. this.wireframeLinecap = source.wireframeLinecap;
  7127. this.wireframeLinejoin = source.wireframeLinejoin;
  7128. this.skinning = source.skinning;
  7129. this.morphTargets = source.morphTargets;
  7130. return this;
  7131. };
  7132. /**
  7133. * @author mrdoob / http://mrdoob.com/
  7134. */
  7135. function BufferAttribute( array, itemSize, normalized ) {
  7136. if ( Array.isArray( array ) ) {
  7137. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7138. }
  7139. this.uuid = _Math.generateUUID();
  7140. this.array = array;
  7141. this.itemSize = itemSize;
  7142. this.count = array !== undefined ? array.length / itemSize : 0;
  7143. this.normalized = normalized === true;
  7144. this.dynamic = false;
  7145. this.updateRange = { offset: 0, count: - 1 };
  7146. this.onUploadCallback = function () {};
  7147. this.version = 0;
  7148. }
  7149. BufferAttribute.prototype = {
  7150. constructor: BufferAttribute,
  7151. isBufferAttribute: true,
  7152. set needsUpdate( value ) {
  7153. if ( value === true ) this.version ++;
  7154. },
  7155. setArray: function ( array ) {
  7156. if ( Array.isArray( array ) ) {
  7157. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7158. }
  7159. this.count = array !== undefined ? array.length / this.itemSize : 0;
  7160. this.array = array;
  7161. },
  7162. setDynamic: function ( value ) {
  7163. this.dynamic = value;
  7164. return this;
  7165. },
  7166. copy: function ( source ) {
  7167. this.array = new source.array.constructor( source.array );
  7168. this.itemSize = source.itemSize;
  7169. this.count = source.count;
  7170. this.normalized = source.normalized;
  7171. this.dynamic = source.dynamic;
  7172. return this;
  7173. },
  7174. copyAt: function ( index1, attribute, index2 ) {
  7175. index1 *= this.itemSize;
  7176. index2 *= attribute.itemSize;
  7177. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  7178. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7179. }
  7180. return this;
  7181. },
  7182. copyArray: function ( array ) {
  7183. this.array.set( array );
  7184. return this;
  7185. },
  7186. copyColorsArray: function ( colors ) {
  7187. var array = this.array, offset = 0;
  7188. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  7189. var color = colors[ i ];
  7190. if ( color === undefined ) {
  7191. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  7192. color = new Color();
  7193. }
  7194. array[ offset ++ ] = color.r;
  7195. array[ offset ++ ] = color.g;
  7196. array[ offset ++ ] = color.b;
  7197. }
  7198. return this;
  7199. },
  7200. copyIndicesArray: function ( indices ) {
  7201. var array = this.array, offset = 0;
  7202. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  7203. var index = indices[ i ];
  7204. array[ offset ++ ] = index.a;
  7205. array[ offset ++ ] = index.b;
  7206. array[ offset ++ ] = index.c;
  7207. }
  7208. return this;
  7209. },
  7210. copyVector2sArray: function ( vectors ) {
  7211. var array = this.array, offset = 0;
  7212. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7213. var vector = vectors[ i ];
  7214. if ( vector === undefined ) {
  7215. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  7216. vector = new Vector2();
  7217. }
  7218. array[ offset ++ ] = vector.x;
  7219. array[ offset ++ ] = vector.y;
  7220. }
  7221. return this;
  7222. },
  7223. copyVector3sArray: function ( vectors ) {
  7224. var array = this.array, offset = 0;
  7225. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7226. var vector = vectors[ i ];
  7227. if ( vector === undefined ) {
  7228. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  7229. vector = new Vector3();
  7230. }
  7231. array[ offset ++ ] = vector.x;
  7232. array[ offset ++ ] = vector.y;
  7233. array[ offset ++ ] = vector.z;
  7234. }
  7235. return this;
  7236. },
  7237. copyVector4sArray: function ( vectors ) {
  7238. var array = this.array, offset = 0;
  7239. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7240. var vector = vectors[ i ];
  7241. if ( vector === undefined ) {
  7242. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  7243. vector = new Vector4();
  7244. }
  7245. array[ offset ++ ] = vector.x;
  7246. array[ offset ++ ] = vector.y;
  7247. array[ offset ++ ] = vector.z;
  7248. array[ offset ++ ] = vector.w;
  7249. }
  7250. return this;
  7251. },
  7252. set: function ( value, offset ) {
  7253. if ( offset === undefined ) offset = 0;
  7254. this.array.set( value, offset );
  7255. return this;
  7256. },
  7257. getX: function ( index ) {
  7258. return this.array[ index * this.itemSize ];
  7259. },
  7260. setX: function ( index, x ) {
  7261. this.array[ index * this.itemSize ] = x;
  7262. return this;
  7263. },
  7264. getY: function ( index ) {
  7265. return this.array[ index * this.itemSize + 1 ];
  7266. },
  7267. setY: function ( index, y ) {
  7268. this.array[ index * this.itemSize + 1 ] = y;
  7269. return this;
  7270. },
  7271. getZ: function ( index ) {
  7272. return this.array[ index * this.itemSize + 2 ];
  7273. },
  7274. setZ: function ( index, z ) {
  7275. this.array[ index * this.itemSize + 2 ] = z;
  7276. return this;
  7277. },
  7278. getW: function ( index ) {
  7279. return this.array[ index * this.itemSize + 3 ];
  7280. },
  7281. setW: function ( index, w ) {
  7282. this.array[ index * this.itemSize + 3 ] = w;
  7283. return this;
  7284. },
  7285. setXY: function ( index, x, y ) {
  7286. index *= this.itemSize;
  7287. this.array[ index + 0 ] = x;
  7288. this.array[ index + 1 ] = y;
  7289. return this;
  7290. },
  7291. setXYZ: function ( index, x, y, z ) {
  7292. index *= this.itemSize;
  7293. this.array[ index + 0 ] = x;
  7294. this.array[ index + 1 ] = y;
  7295. this.array[ index + 2 ] = z;
  7296. return this;
  7297. },
  7298. setXYZW: function ( index, x, y, z, w ) {
  7299. index *= this.itemSize;
  7300. this.array[ index + 0 ] = x;
  7301. this.array[ index + 1 ] = y;
  7302. this.array[ index + 2 ] = z;
  7303. this.array[ index + 3 ] = w;
  7304. return this;
  7305. },
  7306. onUpload: function ( callback ) {
  7307. this.onUploadCallback = callback;
  7308. return this;
  7309. },
  7310. clone: function () {
  7311. return new this.constructor().copy( this );
  7312. }
  7313. };
  7314. //
  7315. function Int8BufferAttribute( array, itemSize ) {
  7316. BufferAttribute.call( this, new Int8Array( array ), itemSize );
  7317. }
  7318. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7319. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7320. function Uint8BufferAttribute( array, itemSize ) {
  7321. BufferAttribute.call( this, new Uint8Array( array ), itemSize );
  7322. }
  7323. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7324. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7325. function Uint8ClampedBufferAttribute( array, itemSize ) {
  7326. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize );
  7327. }
  7328. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7329. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7330. function Int16BufferAttribute( array, itemSize ) {
  7331. BufferAttribute.call( this, new Int16Array( array ), itemSize );
  7332. }
  7333. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7334. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7335. function Uint16BufferAttribute( array, itemSize ) {
  7336. BufferAttribute.call( this, new Uint16Array( array ), itemSize );
  7337. }
  7338. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7339. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7340. function Int32BufferAttribute( array, itemSize ) {
  7341. BufferAttribute.call( this, new Int32Array( array ), itemSize );
  7342. }
  7343. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7344. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7345. function Uint32BufferAttribute( array, itemSize ) {
  7346. BufferAttribute.call( this, new Uint32Array( array ), itemSize );
  7347. }
  7348. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7349. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7350. function Float32BufferAttribute( array, itemSize ) {
  7351. BufferAttribute.call( this, new Float32Array( array ), itemSize );
  7352. }
  7353. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7354. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  7355. function Float64BufferAttribute( array, itemSize ) {
  7356. BufferAttribute.call( this, new Float64Array( array ), itemSize );
  7357. }
  7358. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7359. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  7360. /**
  7361. * @author mrdoob / http://mrdoob.com/
  7362. */
  7363. function DirectGeometry() {
  7364. this.indices = [];
  7365. this.vertices = [];
  7366. this.normals = [];
  7367. this.colors = [];
  7368. this.uvs = [];
  7369. this.uvs2 = [];
  7370. this.groups = [];
  7371. this.morphTargets = {};
  7372. this.skinWeights = [];
  7373. this.skinIndices = [];
  7374. // this.lineDistances = [];
  7375. this.boundingBox = null;
  7376. this.boundingSphere = null;
  7377. // update flags
  7378. this.verticesNeedUpdate = false;
  7379. this.normalsNeedUpdate = false;
  7380. this.colorsNeedUpdate = false;
  7381. this.uvsNeedUpdate = false;
  7382. this.groupsNeedUpdate = false;
  7383. }
  7384. Object.assign( DirectGeometry.prototype, {
  7385. computeGroups: function ( geometry ) {
  7386. var group;
  7387. var groups = [];
  7388. var materialIndex;
  7389. var faces = geometry.faces;
  7390. for ( var i = 0; i < faces.length; i ++ ) {
  7391. var face = faces[ i ];
  7392. // materials
  7393. if ( face.materialIndex !== materialIndex ) {
  7394. materialIndex = face.materialIndex;
  7395. if ( group !== undefined ) {
  7396. group.count = ( i * 3 ) - group.start;
  7397. groups.push( group );
  7398. }
  7399. group = {
  7400. start: i * 3,
  7401. materialIndex: materialIndex
  7402. };
  7403. }
  7404. }
  7405. if ( group !== undefined ) {
  7406. group.count = ( i * 3 ) - group.start;
  7407. groups.push( group );
  7408. }
  7409. this.groups = groups;
  7410. },
  7411. fromGeometry: function ( geometry ) {
  7412. var faces = geometry.faces;
  7413. var vertices = geometry.vertices;
  7414. var faceVertexUvs = geometry.faceVertexUvs;
  7415. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  7416. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  7417. // morphs
  7418. var morphTargets = geometry.morphTargets;
  7419. var morphTargetsLength = morphTargets.length;
  7420. var morphTargetsPosition;
  7421. if ( morphTargetsLength > 0 ) {
  7422. morphTargetsPosition = [];
  7423. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  7424. morphTargetsPosition[ i ] = [];
  7425. }
  7426. this.morphTargets.position = morphTargetsPosition;
  7427. }
  7428. var morphNormals = geometry.morphNormals;
  7429. var morphNormalsLength = morphNormals.length;
  7430. var morphTargetsNormal;
  7431. if ( morphNormalsLength > 0 ) {
  7432. morphTargetsNormal = [];
  7433. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  7434. morphTargetsNormal[ i ] = [];
  7435. }
  7436. this.morphTargets.normal = morphTargetsNormal;
  7437. }
  7438. // skins
  7439. var skinIndices = geometry.skinIndices;
  7440. var skinWeights = geometry.skinWeights;
  7441. var hasSkinIndices = skinIndices.length === vertices.length;
  7442. var hasSkinWeights = skinWeights.length === vertices.length;
  7443. //
  7444. for ( var i = 0; i < faces.length; i ++ ) {
  7445. var face = faces[ i ];
  7446. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  7447. var vertexNormals = face.vertexNormals;
  7448. if ( vertexNormals.length === 3 ) {
  7449. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  7450. } else {
  7451. var normal = face.normal;
  7452. this.normals.push( normal, normal, normal );
  7453. }
  7454. var vertexColors = face.vertexColors;
  7455. if ( vertexColors.length === 3 ) {
  7456. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  7457. } else {
  7458. var color = face.color;
  7459. this.colors.push( color, color, color );
  7460. }
  7461. if ( hasFaceVertexUv === true ) {
  7462. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  7463. if ( vertexUvs !== undefined ) {
  7464. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7465. } else {
  7466. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  7467. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  7468. }
  7469. }
  7470. if ( hasFaceVertexUv2 === true ) {
  7471. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  7472. if ( vertexUvs !== undefined ) {
  7473. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7474. } else {
  7475. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  7476. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  7477. }
  7478. }
  7479. // morphs
  7480. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  7481. var morphTarget = morphTargets[ j ].vertices;
  7482. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  7483. }
  7484. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  7485. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  7486. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  7487. }
  7488. // skins
  7489. if ( hasSkinIndices ) {
  7490. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  7491. }
  7492. if ( hasSkinWeights ) {
  7493. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  7494. }
  7495. }
  7496. this.computeGroups( geometry );
  7497. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7498. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7499. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7500. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7501. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7502. return this;
  7503. }
  7504. } );
  7505. /**
  7506. * @author mrdoob / http://mrdoob.com/
  7507. * @author kile / http://kile.stravaganza.org/
  7508. * @author alteredq / http://alteredqualia.com/
  7509. * @author mikael emtinger / http://gomo.se/
  7510. * @author zz85 / http://www.lab4games.net/zz85/blog
  7511. * @author bhouston / http://clara.io
  7512. */
  7513. function Geometry() {
  7514. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  7515. this.uuid = _Math.generateUUID();
  7516. this.name = '';
  7517. this.type = 'Geometry';
  7518. this.vertices = [];
  7519. this.colors = [];
  7520. this.faces = [];
  7521. this.faceVertexUvs = [ [] ];
  7522. this.morphTargets = [];
  7523. this.morphNormals = [];
  7524. this.skinWeights = [];
  7525. this.skinIndices = [];
  7526. this.lineDistances = [];
  7527. this.boundingBox = null;
  7528. this.boundingSphere = null;
  7529. // update flags
  7530. this.elementsNeedUpdate = false;
  7531. this.verticesNeedUpdate = false;
  7532. this.uvsNeedUpdate = false;
  7533. this.normalsNeedUpdate = false;
  7534. this.colorsNeedUpdate = false;
  7535. this.lineDistancesNeedUpdate = false;
  7536. this.groupsNeedUpdate = false;
  7537. }
  7538. Object.assign( Geometry.prototype, EventDispatcher.prototype, {
  7539. isGeometry: true,
  7540. applyMatrix: function ( matrix ) {
  7541. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7542. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  7543. var vertex = this.vertices[ i ];
  7544. vertex.applyMatrix4( matrix );
  7545. }
  7546. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  7547. var face = this.faces[ i ];
  7548. face.normal.applyMatrix3( normalMatrix ).normalize();
  7549. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  7550. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  7551. }
  7552. }
  7553. if ( this.boundingBox !== null ) {
  7554. this.computeBoundingBox();
  7555. }
  7556. if ( this.boundingSphere !== null ) {
  7557. this.computeBoundingSphere();
  7558. }
  7559. this.verticesNeedUpdate = true;
  7560. this.normalsNeedUpdate = true;
  7561. return this;
  7562. },
  7563. rotateX: function () {
  7564. // rotate geometry around world x-axis
  7565. var m1;
  7566. return function rotateX( angle ) {
  7567. if ( m1 === undefined ) m1 = new Matrix4();
  7568. m1.makeRotationX( angle );
  7569. this.applyMatrix( m1 );
  7570. return this;
  7571. };
  7572. }(),
  7573. rotateY: function () {
  7574. // rotate geometry around world y-axis
  7575. var m1;
  7576. return function rotateY( angle ) {
  7577. if ( m1 === undefined ) m1 = new Matrix4();
  7578. m1.makeRotationY( angle );
  7579. this.applyMatrix( m1 );
  7580. return this;
  7581. };
  7582. }(),
  7583. rotateZ: function () {
  7584. // rotate geometry around world z-axis
  7585. var m1;
  7586. return function rotateZ( angle ) {
  7587. if ( m1 === undefined ) m1 = new Matrix4();
  7588. m1.makeRotationZ( angle );
  7589. this.applyMatrix( m1 );
  7590. return this;
  7591. };
  7592. }(),
  7593. translate: function () {
  7594. // translate geometry
  7595. var m1;
  7596. return function translate( x, y, z ) {
  7597. if ( m1 === undefined ) m1 = new Matrix4();
  7598. m1.makeTranslation( x, y, z );
  7599. this.applyMatrix( m1 );
  7600. return this;
  7601. };
  7602. }(),
  7603. scale: function () {
  7604. // scale geometry
  7605. var m1;
  7606. return function scale( x, y, z ) {
  7607. if ( m1 === undefined ) m1 = new Matrix4();
  7608. m1.makeScale( x, y, z );
  7609. this.applyMatrix( m1 );
  7610. return this;
  7611. };
  7612. }(),
  7613. lookAt: function () {
  7614. var obj;
  7615. return function lookAt( vector ) {
  7616. if ( obj === undefined ) obj = new Object3D();
  7617. obj.lookAt( vector );
  7618. obj.updateMatrix();
  7619. this.applyMatrix( obj.matrix );
  7620. };
  7621. }(),
  7622. fromBufferGeometry: function ( geometry ) {
  7623. var scope = this;
  7624. var indices = geometry.index !== null ? geometry.index.array : undefined;
  7625. var attributes = geometry.attributes;
  7626. var positions = attributes.position.array;
  7627. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  7628. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  7629. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  7630. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  7631. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  7632. var tempNormals = [];
  7633. var tempUVs = [];
  7634. var tempUVs2 = [];
  7635. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  7636. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  7637. if ( normals !== undefined ) {
  7638. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  7639. }
  7640. if ( colors !== undefined ) {
  7641. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  7642. }
  7643. if ( uvs !== undefined ) {
  7644. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  7645. }
  7646. if ( uvs2 !== undefined ) {
  7647. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  7648. }
  7649. }
  7650. function addFace( a, b, c, materialIndex ) {
  7651. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  7652. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  7653. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  7654. scope.faces.push( face );
  7655. if ( uvs !== undefined ) {
  7656. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  7657. }
  7658. if ( uvs2 !== undefined ) {
  7659. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  7660. }
  7661. }
  7662. if ( indices !== undefined ) {
  7663. var groups = geometry.groups;
  7664. if ( groups.length > 0 ) {
  7665. for ( var i = 0; i < groups.length; i ++ ) {
  7666. var group = groups[ i ];
  7667. var start = group.start;
  7668. var count = group.count;
  7669. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  7670. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  7671. }
  7672. }
  7673. } else {
  7674. for ( var i = 0; i < indices.length; i += 3 ) {
  7675. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  7676. }
  7677. }
  7678. } else {
  7679. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  7680. addFace( i, i + 1, i + 2 );
  7681. }
  7682. }
  7683. this.computeFaceNormals();
  7684. if ( geometry.boundingBox !== null ) {
  7685. this.boundingBox = geometry.boundingBox.clone();
  7686. }
  7687. if ( geometry.boundingSphere !== null ) {
  7688. this.boundingSphere = geometry.boundingSphere.clone();
  7689. }
  7690. return this;
  7691. },
  7692. center: function () {
  7693. this.computeBoundingBox();
  7694. var offset = this.boundingBox.getCenter().negate();
  7695. this.translate( offset.x, offset.y, offset.z );
  7696. return offset;
  7697. },
  7698. normalize: function () {
  7699. this.computeBoundingSphere();
  7700. var center = this.boundingSphere.center;
  7701. var radius = this.boundingSphere.radius;
  7702. var s = radius === 0 ? 1 : 1.0 / radius;
  7703. var matrix = new Matrix4();
  7704. matrix.set(
  7705. s, 0, 0, - s * center.x,
  7706. 0, s, 0, - s * center.y,
  7707. 0, 0, s, - s * center.z,
  7708. 0, 0, 0, 1
  7709. );
  7710. this.applyMatrix( matrix );
  7711. return this;
  7712. },
  7713. computeFaceNormals: function () {
  7714. var cb = new Vector3(), ab = new Vector3();
  7715. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7716. var face = this.faces[ f ];
  7717. var vA = this.vertices[ face.a ];
  7718. var vB = this.vertices[ face.b ];
  7719. var vC = this.vertices[ face.c ];
  7720. cb.subVectors( vC, vB );
  7721. ab.subVectors( vA, vB );
  7722. cb.cross( ab );
  7723. cb.normalize();
  7724. face.normal.copy( cb );
  7725. }
  7726. },
  7727. computeVertexNormals: function ( areaWeighted ) {
  7728. if ( areaWeighted === undefined ) areaWeighted = true;
  7729. var v, vl, f, fl, face, vertices;
  7730. vertices = new Array( this.vertices.length );
  7731. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7732. vertices[ v ] = new Vector3();
  7733. }
  7734. if ( areaWeighted ) {
  7735. // vertex normals weighted by triangle areas
  7736. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7737. var vA, vB, vC;
  7738. var cb = new Vector3(), ab = new Vector3();
  7739. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7740. face = this.faces[ f ];
  7741. vA = this.vertices[ face.a ];
  7742. vB = this.vertices[ face.b ];
  7743. vC = this.vertices[ face.c ];
  7744. cb.subVectors( vC, vB );
  7745. ab.subVectors( vA, vB );
  7746. cb.cross( ab );
  7747. vertices[ face.a ].add( cb );
  7748. vertices[ face.b ].add( cb );
  7749. vertices[ face.c ].add( cb );
  7750. }
  7751. } else {
  7752. this.computeFaceNormals();
  7753. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7754. face = this.faces[ f ];
  7755. vertices[ face.a ].add( face.normal );
  7756. vertices[ face.b ].add( face.normal );
  7757. vertices[ face.c ].add( face.normal );
  7758. }
  7759. }
  7760. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7761. vertices[ v ].normalize();
  7762. }
  7763. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7764. face = this.faces[ f ];
  7765. var vertexNormals = face.vertexNormals;
  7766. if ( vertexNormals.length === 3 ) {
  7767. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  7768. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  7769. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  7770. } else {
  7771. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  7772. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  7773. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  7774. }
  7775. }
  7776. if ( this.faces.length > 0 ) {
  7777. this.normalsNeedUpdate = true;
  7778. }
  7779. },
  7780. computeFlatVertexNormals: function () {
  7781. var f, fl, face;
  7782. this.computeFaceNormals();
  7783. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7784. face = this.faces[ f ];
  7785. var vertexNormals = face.vertexNormals;
  7786. if ( vertexNormals.length === 3 ) {
  7787. vertexNormals[ 0 ].copy( face.normal );
  7788. vertexNormals[ 1 ].copy( face.normal );
  7789. vertexNormals[ 2 ].copy( face.normal );
  7790. } else {
  7791. vertexNormals[ 0 ] = face.normal.clone();
  7792. vertexNormals[ 1 ] = face.normal.clone();
  7793. vertexNormals[ 2 ] = face.normal.clone();
  7794. }
  7795. }
  7796. if ( this.faces.length > 0 ) {
  7797. this.normalsNeedUpdate = true;
  7798. }
  7799. },
  7800. computeMorphNormals: function () {
  7801. var i, il, f, fl, face;
  7802. // save original normals
  7803. // - create temp variables on first access
  7804. // otherwise just copy (for faster repeated calls)
  7805. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7806. face = this.faces[ f ];
  7807. if ( ! face.__originalFaceNormal ) {
  7808. face.__originalFaceNormal = face.normal.clone();
  7809. } else {
  7810. face.__originalFaceNormal.copy( face.normal );
  7811. }
  7812. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  7813. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  7814. if ( ! face.__originalVertexNormals[ i ] ) {
  7815. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  7816. } else {
  7817. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  7818. }
  7819. }
  7820. }
  7821. // use temp geometry to compute face and vertex normals for each morph
  7822. var tmpGeo = new Geometry();
  7823. tmpGeo.faces = this.faces;
  7824. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  7825. // create on first access
  7826. if ( ! this.morphNormals[ i ] ) {
  7827. this.morphNormals[ i ] = {};
  7828. this.morphNormals[ i ].faceNormals = [];
  7829. this.morphNormals[ i ].vertexNormals = [];
  7830. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  7831. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  7832. var faceNormal, vertexNormals;
  7833. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7834. faceNormal = new Vector3();
  7835. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  7836. dstNormalsFace.push( faceNormal );
  7837. dstNormalsVertex.push( vertexNormals );
  7838. }
  7839. }
  7840. var morphNormals = this.morphNormals[ i ];
  7841. // set vertices to morph target
  7842. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  7843. // compute morph normals
  7844. tmpGeo.computeFaceNormals();
  7845. tmpGeo.computeVertexNormals();
  7846. // store morph normals
  7847. var faceNormal, vertexNormals;
  7848. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7849. face = this.faces[ f ];
  7850. faceNormal = morphNormals.faceNormals[ f ];
  7851. vertexNormals = morphNormals.vertexNormals[ f ];
  7852. faceNormal.copy( face.normal );
  7853. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  7854. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  7855. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  7856. }
  7857. }
  7858. // restore original normals
  7859. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7860. face = this.faces[ f ];
  7861. face.normal = face.__originalFaceNormal;
  7862. face.vertexNormals = face.__originalVertexNormals;
  7863. }
  7864. },
  7865. computeLineDistances: function () {
  7866. var d = 0;
  7867. var vertices = this.vertices;
  7868. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  7869. if ( i > 0 ) {
  7870. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  7871. }
  7872. this.lineDistances[ i ] = d;
  7873. }
  7874. },
  7875. computeBoundingBox: function () {
  7876. if ( this.boundingBox === null ) {
  7877. this.boundingBox = new Box3();
  7878. }
  7879. this.boundingBox.setFromPoints( this.vertices );
  7880. },
  7881. computeBoundingSphere: function () {
  7882. if ( this.boundingSphere === null ) {
  7883. this.boundingSphere = new Sphere();
  7884. }
  7885. this.boundingSphere.setFromPoints( this.vertices );
  7886. },
  7887. merge: function ( geometry, matrix, materialIndexOffset ) {
  7888. if ( (geometry && geometry.isGeometry) === false ) {
  7889. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  7890. return;
  7891. }
  7892. var normalMatrix,
  7893. vertexOffset = this.vertices.length,
  7894. vertices1 = this.vertices,
  7895. vertices2 = geometry.vertices,
  7896. faces1 = this.faces,
  7897. faces2 = geometry.faces,
  7898. uvs1 = this.faceVertexUvs[ 0 ],
  7899. uvs2 = geometry.faceVertexUvs[ 0 ],
  7900. colors1 = this.colors,
  7901. colors2 = geometry.colors;
  7902. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  7903. if ( matrix !== undefined ) {
  7904. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7905. }
  7906. // vertices
  7907. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  7908. var vertex = vertices2[ i ];
  7909. var vertexCopy = vertex.clone();
  7910. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  7911. vertices1.push( vertexCopy );
  7912. }
  7913. // colors
  7914. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  7915. colors1.push( colors2[ i ].clone() );
  7916. }
  7917. // faces
  7918. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  7919. var face = faces2[ i ], faceCopy, normal, color,
  7920. faceVertexNormals = face.vertexNormals,
  7921. faceVertexColors = face.vertexColors;
  7922. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  7923. faceCopy.normal.copy( face.normal );
  7924. if ( normalMatrix !== undefined ) {
  7925. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  7926. }
  7927. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  7928. normal = faceVertexNormals[ j ].clone();
  7929. if ( normalMatrix !== undefined ) {
  7930. normal.applyMatrix3( normalMatrix ).normalize();
  7931. }
  7932. faceCopy.vertexNormals.push( normal );
  7933. }
  7934. faceCopy.color.copy( face.color );
  7935. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  7936. color = faceVertexColors[ j ];
  7937. faceCopy.vertexColors.push( color.clone() );
  7938. }
  7939. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  7940. faces1.push( faceCopy );
  7941. }
  7942. // uvs
  7943. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  7944. var uv = uvs2[ i ], uvCopy = [];
  7945. if ( uv === undefined ) {
  7946. continue;
  7947. }
  7948. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  7949. uvCopy.push( uv[ j ].clone() );
  7950. }
  7951. uvs1.push( uvCopy );
  7952. }
  7953. },
  7954. mergeMesh: function ( mesh ) {
  7955. if ( (mesh && mesh.isMesh) === false ) {
  7956. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  7957. return;
  7958. }
  7959. mesh.matrixAutoUpdate && mesh.updateMatrix();
  7960. this.merge( mesh.geometry, mesh.matrix );
  7961. },
  7962. /*
  7963. * Checks for duplicate vertices with hashmap.
  7964. * Duplicated vertices are removed
  7965. * and faces' vertices are updated.
  7966. */
  7967. mergeVertices: function () {
  7968. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  7969. var unique = [], changes = [];
  7970. var v, key;
  7971. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  7972. var precision = Math.pow( 10, precisionPoints );
  7973. var i, il, face;
  7974. var indices, j, jl;
  7975. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  7976. v = this.vertices[ i ];
  7977. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  7978. if ( verticesMap[ key ] === undefined ) {
  7979. verticesMap[ key ] = i;
  7980. unique.push( this.vertices[ i ] );
  7981. changes[ i ] = unique.length - 1;
  7982. } else {
  7983. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  7984. changes[ i ] = changes[ verticesMap[ key ] ];
  7985. }
  7986. }
  7987. // if faces are completely degenerate after merging vertices, we
  7988. // have to remove them from the geometry.
  7989. var faceIndicesToRemove = [];
  7990. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  7991. face = this.faces[ i ];
  7992. face.a = changes[ face.a ];
  7993. face.b = changes[ face.b ];
  7994. face.c = changes[ face.c ];
  7995. indices = [ face.a, face.b, face.c ];
  7996. var dupIndex = - 1;
  7997. // if any duplicate vertices are found in a Face3
  7998. // we have to remove the face as nothing can be saved
  7999. for ( var n = 0; n < 3; n ++ ) {
  8000. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  8001. dupIndex = n;
  8002. faceIndicesToRemove.push( i );
  8003. break;
  8004. }
  8005. }
  8006. }
  8007. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  8008. var idx = faceIndicesToRemove[ i ];
  8009. this.faces.splice( idx, 1 );
  8010. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  8011. this.faceVertexUvs[ j ].splice( idx, 1 );
  8012. }
  8013. }
  8014. // Use unique set of vertices
  8015. var diff = this.vertices.length - unique.length;
  8016. this.vertices = unique;
  8017. return diff;
  8018. },
  8019. sortFacesByMaterialIndex: function () {
  8020. var faces = this.faces;
  8021. var length = faces.length;
  8022. // tag faces
  8023. for ( var i = 0; i < length; i ++ ) {
  8024. faces[ i ]._id = i;
  8025. }
  8026. // sort faces
  8027. function materialIndexSort( a, b ) {
  8028. return a.materialIndex - b.materialIndex;
  8029. }
  8030. faces.sort( materialIndexSort );
  8031. // sort uvs
  8032. var uvs1 = this.faceVertexUvs[ 0 ];
  8033. var uvs2 = this.faceVertexUvs[ 1 ];
  8034. var newUvs1, newUvs2;
  8035. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  8036. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  8037. for ( var i = 0; i < length; i ++ ) {
  8038. var id = faces[ i ]._id;
  8039. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  8040. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  8041. }
  8042. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  8043. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  8044. },
  8045. toJSON: function () {
  8046. var data = {
  8047. metadata: {
  8048. version: 4.4,
  8049. type: 'Geometry',
  8050. generator: 'Geometry.toJSON'
  8051. }
  8052. };
  8053. // standard Geometry serialization
  8054. data.uuid = this.uuid;
  8055. data.type = this.type;
  8056. if ( this.name !== '' ) data.name = this.name;
  8057. if ( this.parameters !== undefined ) {
  8058. var parameters = this.parameters;
  8059. for ( var key in parameters ) {
  8060. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8061. }
  8062. return data;
  8063. }
  8064. var vertices = [];
  8065. for ( var i = 0; i < this.vertices.length; i ++ ) {
  8066. var vertex = this.vertices[ i ];
  8067. vertices.push( vertex.x, vertex.y, vertex.z );
  8068. }
  8069. var faces = [];
  8070. var normals = [];
  8071. var normalsHash = {};
  8072. var colors = [];
  8073. var colorsHash = {};
  8074. var uvs = [];
  8075. var uvsHash = {};
  8076. for ( var i = 0; i < this.faces.length; i ++ ) {
  8077. var face = this.faces[ i ];
  8078. var hasMaterial = true;
  8079. var hasFaceUv = false; // deprecated
  8080. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  8081. var hasFaceNormal = face.normal.length() > 0;
  8082. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  8083. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  8084. var hasFaceVertexColor = face.vertexColors.length > 0;
  8085. var faceType = 0;
  8086. faceType = setBit( faceType, 0, 0 ); // isQuad
  8087. faceType = setBit( faceType, 1, hasMaterial );
  8088. faceType = setBit( faceType, 2, hasFaceUv );
  8089. faceType = setBit( faceType, 3, hasFaceVertexUv );
  8090. faceType = setBit( faceType, 4, hasFaceNormal );
  8091. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  8092. faceType = setBit( faceType, 6, hasFaceColor );
  8093. faceType = setBit( faceType, 7, hasFaceVertexColor );
  8094. faces.push( faceType );
  8095. faces.push( face.a, face.b, face.c );
  8096. faces.push( face.materialIndex );
  8097. if ( hasFaceVertexUv ) {
  8098. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  8099. faces.push(
  8100. getUvIndex( faceVertexUvs[ 0 ] ),
  8101. getUvIndex( faceVertexUvs[ 1 ] ),
  8102. getUvIndex( faceVertexUvs[ 2 ] )
  8103. );
  8104. }
  8105. if ( hasFaceNormal ) {
  8106. faces.push( getNormalIndex( face.normal ) );
  8107. }
  8108. if ( hasFaceVertexNormal ) {
  8109. var vertexNormals = face.vertexNormals;
  8110. faces.push(
  8111. getNormalIndex( vertexNormals[ 0 ] ),
  8112. getNormalIndex( vertexNormals[ 1 ] ),
  8113. getNormalIndex( vertexNormals[ 2 ] )
  8114. );
  8115. }
  8116. if ( hasFaceColor ) {
  8117. faces.push( getColorIndex( face.color ) );
  8118. }
  8119. if ( hasFaceVertexColor ) {
  8120. var vertexColors = face.vertexColors;
  8121. faces.push(
  8122. getColorIndex( vertexColors[ 0 ] ),
  8123. getColorIndex( vertexColors[ 1 ] ),
  8124. getColorIndex( vertexColors[ 2 ] )
  8125. );
  8126. }
  8127. }
  8128. function setBit( value, position, enabled ) {
  8129. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  8130. }
  8131. function getNormalIndex( normal ) {
  8132. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  8133. if ( normalsHash[ hash ] !== undefined ) {
  8134. return normalsHash[ hash ];
  8135. }
  8136. normalsHash[ hash ] = normals.length / 3;
  8137. normals.push( normal.x, normal.y, normal.z );
  8138. return normalsHash[ hash ];
  8139. }
  8140. function getColorIndex( color ) {
  8141. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  8142. if ( colorsHash[ hash ] !== undefined ) {
  8143. return colorsHash[ hash ];
  8144. }
  8145. colorsHash[ hash ] = colors.length;
  8146. colors.push( color.getHex() );
  8147. return colorsHash[ hash ];
  8148. }
  8149. function getUvIndex( uv ) {
  8150. var hash = uv.x.toString() + uv.y.toString();
  8151. if ( uvsHash[ hash ] !== undefined ) {
  8152. return uvsHash[ hash ];
  8153. }
  8154. uvsHash[ hash ] = uvs.length / 2;
  8155. uvs.push( uv.x, uv.y );
  8156. return uvsHash[ hash ];
  8157. }
  8158. data.data = {};
  8159. data.data.vertices = vertices;
  8160. data.data.normals = normals;
  8161. if ( colors.length > 0 ) data.data.colors = colors;
  8162. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  8163. data.data.faces = faces;
  8164. return data;
  8165. },
  8166. clone: function () {
  8167. /*
  8168. // Handle primitives
  8169. var parameters = this.parameters;
  8170. if ( parameters !== undefined ) {
  8171. var values = [];
  8172. for ( var key in parameters ) {
  8173. values.push( parameters[ key ] );
  8174. }
  8175. var geometry = Object.create( this.constructor.prototype );
  8176. this.constructor.apply( geometry, values );
  8177. return geometry;
  8178. }
  8179. return new this.constructor().copy( this );
  8180. */
  8181. return new Geometry().copy( this );
  8182. },
  8183. copy: function ( source ) {
  8184. this.vertices = [];
  8185. this.faces = [];
  8186. this.faceVertexUvs = [ [] ];
  8187. this.colors = [];
  8188. var vertices = source.vertices;
  8189. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  8190. this.vertices.push( vertices[ i ].clone() );
  8191. }
  8192. var colors = source.colors;
  8193. for ( var i = 0, il = colors.length; i < il; i ++ ) {
  8194. this.colors.push( colors[ i ].clone() );
  8195. }
  8196. var faces = source.faces;
  8197. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  8198. this.faces.push( faces[ i ].clone() );
  8199. }
  8200. for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  8201. var faceVertexUvs = source.faceVertexUvs[ i ];
  8202. if ( this.faceVertexUvs[ i ] === undefined ) {
  8203. this.faceVertexUvs[ i ] = [];
  8204. }
  8205. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  8206. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  8207. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  8208. var uv = uvs[ k ];
  8209. uvsCopy.push( uv.clone() );
  8210. }
  8211. this.faceVertexUvs[ i ].push( uvsCopy );
  8212. }
  8213. }
  8214. return this;
  8215. },
  8216. dispose: function () {
  8217. this.dispatchEvent( { type: 'dispose' } );
  8218. }
  8219. } );
  8220. var count = 0;
  8221. function GeometryIdCount() { return count++; }
  8222. /**
  8223. * @author alteredq / http://alteredqualia.com/
  8224. * @author mrdoob / http://mrdoob.com/
  8225. */
  8226. function BufferGeometry() {
  8227. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  8228. this.uuid = _Math.generateUUID();
  8229. this.name = '';
  8230. this.type = 'BufferGeometry';
  8231. this.index = null;
  8232. this.attributes = {};
  8233. this.morphAttributes = {};
  8234. this.groups = [];
  8235. this.boundingBox = null;
  8236. this.boundingSphere = null;
  8237. this.drawRange = { start: 0, count: Infinity };
  8238. }
  8239. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, {
  8240. isBufferGeometry: true,
  8241. getIndex: function () {
  8242. return this.index;
  8243. },
  8244. setIndex: function ( index ) {
  8245. this.index = index;
  8246. },
  8247. addAttribute: function ( name, attribute ) {
  8248. if ( ( attribute && attribute.isBufferAttribute ) === false && ( attribute && attribute.isInterleavedBufferAttribute ) === false ) {
  8249. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  8250. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  8251. return;
  8252. }
  8253. if ( name === 'index' ) {
  8254. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  8255. this.setIndex( attribute );
  8256. return;
  8257. }
  8258. this.attributes[ name ] = attribute;
  8259. return this;
  8260. },
  8261. getAttribute: function ( name ) {
  8262. return this.attributes[ name ];
  8263. },
  8264. removeAttribute: function ( name ) {
  8265. delete this.attributes[ name ];
  8266. return this;
  8267. },
  8268. addGroup: function ( start, count, materialIndex ) {
  8269. this.groups.push( {
  8270. start: start,
  8271. count: count,
  8272. materialIndex: materialIndex !== undefined ? materialIndex : 0
  8273. } );
  8274. },
  8275. clearGroups: function () {
  8276. this.groups = [];
  8277. },
  8278. setDrawRange: function ( start, count ) {
  8279. this.drawRange.start = start;
  8280. this.drawRange.count = count;
  8281. },
  8282. applyMatrix: function ( matrix ) {
  8283. var position = this.attributes.position;
  8284. if ( position !== undefined ) {
  8285. matrix.applyToVector3Array( position.array );
  8286. position.needsUpdate = true;
  8287. }
  8288. var normal = this.attributes.normal;
  8289. if ( normal !== undefined ) {
  8290. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8291. normalMatrix.applyToVector3Array( normal.array );
  8292. normal.needsUpdate = true;
  8293. }
  8294. if ( this.boundingBox !== null ) {
  8295. this.computeBoundingBox();
  8296. }
  8297. if ( this.boundingSphere !== null ) {
  8298. this.computeBoundingSphere();
  8299. }
  8300. return this;
  8301. },
  8302. rotateX: function () {
  8303. // rotate geometry around world x-axis
  8304. var m1;
  8305. return function rotateX( angle ) {
  8306. if ( m1 === undefined ) m1 = new Matrix4();
  8307. m1.makeRotationX( angle );
  8308. this.applyMatrix( m1 );
  8309. return this;
  8310. };
  8311. }(),
  8312. rotateY: function () {
  8313. // rotate geometry around world y-axis
  8314. var m1;
  8315. return function rotateY( angle ) {
  8316. if ( m1 === undefined ) m1 = new Matrix4();
  8317. m1.makeRotationY( angle );
  8318. this.applyMatrix( m1 );
  8319. return this;
  8320. };
  8321. }(),
  8322. rotateZ: function () {
  8323. // rotate geometry around world z-axis
  8324. var m1;
  8325. return function rotateZ( angle ) {
  8326. if ( m1 === undefined ) m1 = new Matrix4();
  8327. m1.makeRotationZ( angle );
  8328. this.applyMatrix( m1 );
  8329. return this;
  8330. };
  8331. }(),
  8332. translate: function () {
  8333. // translate geometry
  8334. var m1;
  8335. return function translate( x, y, z ) {
  8336. if ( m1 === undefined ) m1 = new Matrix4();
  8337. m1.makeTranslation( x, y, z );
  8338. this.applyMatrix( m1 );
  8339. return this;
  8340. };
  8341. }(),
  8342. scale: function () {
  8343. // scale geometry
  8344. var m1;
  8345. return function scale( x, y, z ) {
  8346. if ( m1 === undefined ) m1 = new Matrix4();
  8347. m1.makeScale( x, y, z );
  8348. this.applyMatrix( m1 );
  8349. return this;
  8350. };
  8351. }(),
  8352. lookAt: function () {
  8353. var obj;
  8354. return function lookAt( vector ) {
  8355. if ( obj === undefined ) obj = new Object3D();
  8356. obj.lookAt( vector );
  8357. obj.updateMatrix();
  8358. this.applyMatrix( obj.matrix );
  8359. };
  8360. }(),
  8361. center: function () {
  8362. this.computeBoundingBox();
  8363. var offset = this.boundingBox.getCenter().negate();
  8364. this.translate( offset.x, offset.y, offset.z );
  8365. return offset;
  8366. },
  8367. setFromObject: function ( object ) {
  8368. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  8369. var geometry = object.geometry;
  8370. if ( object.isPoints || object.isLine ) {
  8371. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  8372. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  8373. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  8374. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  8375. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  8376. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  8377. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  8378. }
  8379. if ( geometry.boundingSphere !== null ) {
  8380. this.boundingSphere = geometry.boundingSphere.clone();
  8381. }
  8382. if ( geometry.boundingBox !== null ) {
  8383. this.boundingBox = geometry.boundingBox.clone();
  8384. }
  8385. } else if ( object.isMesh ) {
  8386. if ( geometry && geometry.isGeometry ) {
  8387. this.fromGeometry( geometry );
  8388. }
  8389. }
  8390. return this;
  8391. },
  8392. updateFromObject: function ( object ) {
  8393. var geometry = object.geometry;
  8394. if ( object.isMesh ) {
  8395. var direct = geometry.__directGeometry;
  8396. if ( geometry.elementsNeedUpdate === true ) {
  8397. direct = undefined;
  8398. geometry.elementsNeedUpdate = false;
  8399. }
  8400. if ( direct === undefined ) {
  8401. return this.fromGeometry( geometry );
  8402. }
  8403. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  8404. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  8405. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  8406. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  8407. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  8408. geometry.verticesNeedUpdate = false;
  8409. geometry.normalsNeedUpdate = false;
  8410. geometry.colorsNeedUpdate = false;
  8411. geometry.uvsNeedUpdate = false;
  8412. geometry.groupsNeedUpdate = false;
  8413. geometry = direct;
  8414. }
  8415. var attribute;
  8416. if ( geometry.verticesNeedUpdate === true ) {
  8417. attribute = this.attributes.position;
  8418. if ( attribute !== undefined ) {
  8419. attribute.copyVector3sArray( geometry.vertices );
  8420. attribute.needsUpdate = true;
  8421. }
  8422. geometry.verticesNeedUpdate = false;
  8423. }
  8424. if ( geometry.normalsNeedUpdate === true ) {
  8425. attribute = this.attributes.normal;
  8426. if ( attribute !== undefined ) {
  8427. attribute.copyVector3sArray( geometry.normals );
  8428. attribute.needsUpdate = true;
  8429. }
  8430. geometry.normalsNeedUpdate = false;
  8431. }
  8432. if ( geometry.colorsNeedUpdate === true ) {
  8433. attribute = this.attributes.color;
  8434. if ( attribute !== undefined ) {
  8435. attribute.copyColorsArray( geometry.colors );
  8436. attribute.needsUpdate = true;
  8437. }
  8438. geometry.colorsNeedUpdate = false;
  8439. }
  8440. if ( geometry.uvsNeedUpdate ) {
  8441. attribute = this.attributes.uv;
  8442. if ( attribute !== undefined ) {
  8443. attribute.copyVector2sArray( geometry.uvs );
  8444. attribute.needsUpdate = true;
  8445. }
  8446. geometry.uvsNeedUpdate = false;
  8447. }
  8448. if ( geometry.lineDistancesNeedUpdate ) {
  8449. attribute = this.attributes.lineDistance;
  8450. if ( attribute !== undefined ) {
  8451. attribute.copyArray( geometry.lineDistances );
  8452. attribute.needsUpdate = true;
  8453. }
  8454. geometry.lineDistancesNeedUpdate = false;
  8455. }
  8456. if ( geometry.groupsNeedUpdate ) {
  8457. geometry.computeGroups( object.geometry );
  8458. this.groups = geometry.groups;
  8459. geometry.groupsNeedUpdate = false;
  8460. }
  8461. return this;
  8462. },
  8463. fromGeometry: function ( geometry ) {
  8464. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  8465. return this.fromDirectGeometry( geometry.__directGeometry );
  8466. },
  8467. fromDirectGeometry: function ( geometry ) {
  8468. var positions = new Float32Array( geometry.vertices.length * 3 );
  8469. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  8470. if ( geometry.normals.length > 0 ) {
  8471. var normals = new Float32Array( geometry.normals.length * 3 );
  8472. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  8473. }
  8474. if ( geometry.colors.length > 0 ) {
  8475. var colors = new Float32Array( geometry.colors.length * 3 );
  8476. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  8477. }
  8478. if ( geometry.uvs.length > 0 ) {
  8479. var uvs = new Float32Array( geometry.uvs.length * 2 );
  8480. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  8481. }
  8482. if ( geometry.uvs2.length > 0 ) {
  8483. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  8484. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  8485. }
  8486. if ( geometry.indices.length > 0 ) {
  8487. var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array;
  8488. var indices = new TypeArray( geometry.indices.length * 3 );
  8489. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  8490. }
  8491. // groups
  8492. this.groups = geometry.groups;
  8493. // morphs
  8494. for ( var name in geometry.morphTargets ) {
  8495. var array = [];
  8496. var morphTargets = geometry.morphTargets[ name ];
  8497. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  8498. var morphTarget = morphTargets[ i ];
  8499. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  8500. array.push( attribute.copyVector3sArray( morphTarget ) );
  8501. }
  8502. this.morphAttributes[ name ] = array;
  8503. }
  8504. // skinning
  8505. if ( geometry.skinIndices.length > 0 ) {
  8506. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  8507. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  8508. }
  8509. if ( geometry.skinWeights.length > 0 ) {
  8510. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  8511. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  8512. }
  8513. //
  8514. if ( geometry.boundingSphere !== null ) {
  8515. this.boundingSphere = geometry.boundingSphere.clone();
  8516. }
  8517. if ( geometry.boundingBox !== null ) {
  8518. this.boundingBox = geometry.boundingBox.clone();
  8519. }
  8520. return this;
  8521. },
  8522. computeBoundingBox: function () {
  8523. if ( this.boundingBox === null ) {
  8524. this.boundingBox = new Box3();
  8525. }
  8526. var position = this.attributes.position;
  8527. if ( position !== undefined ) {
  8528. this.boundingBox.setFromBufferAttribute( position );
  8529. } else {
  8530. this.boundingBox.makeEmpty();
  8531. }
  8532. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  8533. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  8534. }
  8535. },
  8536. computeBoundingSphere: function () {
  8537. var box = new Box3();
  8538. var vector = new Vector3();
  8539. return function computeBoundingSphere() {
  8540. if ( this.boundingSphere === null ) {
  8541. this.boundingSphere = new Sphere();
  8542. }
  8543. var position = this.attributes.position;
  8544. if ( position ) {
  8545. var center = this.boundingSphere.center;
  8546. box.setFromBufferAttribute( position );
  8547. box.getCenter( center );
  8548. // hoping to find a boundingSphere with a radius smaller than the
  8549. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  8550. var maxRadiusSq = 0;
  8551. for ( var i = 0, il = position.count; i < il; i ++ ) {
  8552. vector.x = position.getX( i );
  8553. vector.y = position.getY( i );
  8554. vector.z = position.getZ( i );
  8555. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  8556. }
  8557. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  8558. if ( isNaN( this.boundingSphere.radius ) ) {
  8559. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  8560. }
  8561. }
  8562. };
  8563. }(),
  8564. computeFaceNormals: function () {
  8565. // backwards compatibility
  8566. },
  8567. computeVertexNormals: function () {
  8568. var index = this.index;
  8569. var attributes = this.attributes;
  8570. var groups = this.groups;
  8571. if ( attributes.position ) {
  8572. var positions = attributes.position.array;
  8573. if ( attributes.normal === undefined ) {
  8574. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  8575. } else {
  8576. // reset existing normals to zero
  8577. var array = attributes.normal.array;
  8578. for ( var i = 0, il = array.length; i < il; i ++ ) {
  8579. array[ i ] = 0;
  8580. }
  8581. }
  8582. var normals = attributes.normal.array;
  8583. var vA, vB, vC;
  8584. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  8585. var cb = new Vector3(), ab = new Vector3();
  8586. // indexed elements
  8587. if ( index ) {
  8588. var indices = index.array;
  8589. if ( groups.length === 0 ) {
  8590. this.addGroup( 0, indices.length );
  8591. }
  8592. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  8593. var group = groups[ j ];
  8594. var start = group.start;
  8595. var count = group.count;
  8596. for ( var i = start, il = start + count; i < il; i += 3 ) {
  8597. vA = indices[ i + 0 ] * 3;
  8598. vB = indices[ i + 1 ] * 3;
  8599. vC = indices[ i + 2 ] * 3;
  8600. pA.fromArray( positions, vA );
  8601. pB.fromArray( positions, vB );
  8602. pC.fromArray( positions, vC );
  8603. cb.subVectors( pC, pB );
  8604. ab.subVectors( pA, pB );
  8605. cb.cross( ab );
  8606. normals[ vA ] += cb.x;
  8607. normals[ vA + 1 ] += cb.y;
  8608. normals[ vA + 2 ] += cb.z;
  8609. normals[ vB ] += cb.x;
  8610. normals[ vB + 1 ] += cb.y;
  8611. normals[ vB + 2 ] += cb.z;
  8612. normals[ vC ] += cb.x;
  8613. normals[ vC + 1 ] += cb.y;
  8614. normals[ vC + 2 ] += cb.z;
  8615. }
  8616. }
  8617. } else {
  8618. // non-indexed elements (unconnected triangle soup)
  8619. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  8620. pA.fromArray( positions, i );
  8621. pB.fromArray( positions, i + 3 );
  8622. pC.fromArray( positions, i + 6 );
  8623. cb.subVectors( pC, pB );
  8624. ab.subVectors( pA, pB );
  8625. cb.cross( ab );
  8626. normals[ i ] = cb.x;
  8627. normals[ i + 1 ] = cb.y;
  8628. normals[ i + 2 ] = cb.z;
  8629. normals[ i + 3 ] = cb.x;
  8630. normals[ i + 4 ] = cb.y;
  8631. normals[ i + 5 ] = cb.z;
  8632. normals[ i + 6 ] = cb.x;
  8633. normals[ i + 7 ] = cb.y;
  8634. normals[ i + 8 ] = cb.z;
  8635. }
  8636. }
  8637. this.normalizeNormals();
  8638. attributes.normal.needsUpdate = true;
  8639. }
  8640. },
  8641. merge: function ( geometry, offset ) {
  8642. if ( ( geometry && geometry.isBufferGeometry ) === false ) {
  8643. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  8644. return;
  8645. }
  8646. if ( offset === undefined ) offset = 0;
  8647. var attributes = this.attributes;
  8648. for ( var key in attributes ) {
  8649. if ( geometry.attributes[ key ] === undefined ) continue;
  8650. var attribute1 = attributes[ key ];
  8651. var attributeArray1 = attribute1.array;
  8652. var attribute2 = geometry.attributes[ key ];
  8653. var attributeArray2 = attribute2.array;
  8654. var attributeSize = attribute2.itemSize;
  8655. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  8656. attributeArray1[ j ] = attributeArray2[ i ];
  8657. }
  8658. }
  8659. return this;
  8660. },
  8661. normalizeNormals: function () {
  8662. var normals = this.attributes.normal.array;
  8663. var x, y, z, n;
  8664. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  8665. x = normals[ i ];
  8666. y = normals[ i + 1 ];
  8667. z = normals[ i + 2 ];
  8668. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  8669. normals[ i ] *= n;
  8670. normals[ i + 1 ] *= n;
  8671. normals[ i + 2 ] *= n;
  8672. }
  8673. },
  8674. toNonIndexed: function () {
  8675. if ( this.index === null ) {
  8676. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  8677. return this;
  8678. }
  8679. var geometry2 = new BufferGeometry();
  8680. var indices = this.index.array;
  8681. var attributes = this.attributes;
  8682. for ( var name in attributes ) {
  8683. var attribute = attributes[ name ];
  8684. var array = attribute.array;
  8685. var itemSize = attribute.itemSize;
  8686. var array2 = new array.constructor( indices.length * itemSize );
  8687. var index = 0, index2 = 0;
  8688. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  8689. index = indices[ i ] * itemSize;
  8690. for ( var j = 0; j < itemSize; j ++ ) {
  8691. array2[ index2 ++ ] = array[ index ++ ];
  8692. }
  8693. }
  8694. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  8695. }
  8696. return geometry2;
  8697. },
  8698. toJSON: function () {
  8699. var data = {
  8700. metadata: {
  8701. version: 4.4,
  8702. type: 'BufferGeometry',
  8703. generator: 'BufferGeometry.toJSON'
  8704. }
  8705. };
  8706. // standard BufferGeometry serialization
  8707. data.uuid = this.uuid;
  8708. data.type = this.type;
  8709. if ( this.name !== '' ) data.name = this.name;
  8710. if ( this.parameters !== undefined ) {
  8711. var parameters = this.parameters;
  8712. for ( var key in parameters ) {
  8713. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8714. }
  8715. return data;
  8716. }
  8717. data.data = { attributes: {} };
  8718. var index = this.index;
  8719. if ( index !== null ) {
  8720. var array = Array.prototype.slice.call( index.array );
  8721. data.data.index = {
  8722. type: index.array.constructor.name,
  8723. array: array
  8724. };
  8725. }
  8726. var attributes = this.attributes;
  8727. for ( var key in attributes ) {
  8728. var attribute = attributes[ key ];
  8729. var array = Array.prototype.slice.call( attribute.array );
  8730. data.data.attributes[ key ] = {
  8731. itemSize: attribute.itemSize,
  8732. type: attribute.array.constructor.name,
  8733. array: array,
  8734. normalized: attribute.normalized
  8735. };
  8736. }
  8737. var groups = this.groups;
  8738. if ( groups.length > 0 ) {
  8739. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  8740. }
  8741. var boundingSphere = this.boundingSphere;
  8742. if ( boundingSphere !== null ) {
  8743. data.data.boundingSphere = {
  8744. center: boundingSphere.center.toArray(),
  8745. radius: boundingSphere.radius
  8746. };
  8747. }
  8748. return data;
  8749. },
  8750. clone: function () {
  8751. /*
  8752. // Handle primitives
  8753. var parameters = this.parameters;
  8754. if ( parameters !== undefined ) {
  8755. var values = [];
  8756. for ( var key in parameters ) {
  8757. values.push( parameters[ key ] );
  8758. }
  8759. var geometry = Object.create( this.constructor.prototype );
  8760. this.constructor.apply( geometry, values );
  8761. return geometry;
  8762. }
  8763. return new this.constructor().copy( this );
  8764. */
  8765. return new BufferGeometry().copy( this );
  8766. },
  8767. copy: function ( source ) {
  8768. var index = source.index;
  8769. if ( index !== null ) {
  8770. this.setIndex( index.clone() );
  8771. }
  8772. var attributes = source.attributes;
  8773. for ( var name in attributes ) {
  8774. var attribute = attributes[ name ];
  8775. this.addAttribute( name, attribute.clone() );
  8776. }
  8777. var groups = source.groups;
  8778. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  8779. var group = groups[ i ];
  8780. this.addGroup( group.start, group.count, group.materialIndex );
  8781. }
  8782. return this;
  8783. },
  8784. dispose: function () {
  8785. this.dispatchEvent( { type: 'dispose' } );
  8786. }
  8787. } );
  8788. BufferGeometry.MaxIndex = 65535;
  8789. /**
  8790. * @author mrdoob / http://mrdoob.com/
  8791. * @author alteredq / http://alteredqualia.com/
  8792. * @author mikael emtinger / http://gomo.se/
  8793. * @author jonobr1 / http://jonobr1.com/
  8794. */
  8795. function Mesh( geometry, material ) {
  8796. Object3D.call( this );
  8797. this.type = 'Mesh';
  8798. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  8799. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8800. this.drawMode = TrianglesDrawMode;
  8801. this.updateMorphTargets();
  8802. }
  8803. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  8804. constructor: Mesh,
  8805. isMesh: true,
  8806. setDrawMode: function ( value ) {
  8807. this.drawMode = value;
  8808. },
  8809. copy: function ( source ) {
  8810. Object3D.prototype.copy.call( this, source );
  8811. this.drawMode = source.drawMode;
  8812. return this;
  8813. },
  8814. updateMorphTargets: function () {
  8815. var morphTargets = this.geometry.morphTargets;
  8816. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  8817. this.morphTargetInfluences = [];
  8818. this.morphTargetDictionary = {};
  8819. for ( var m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  8820. this.morphTargetInfluences.push( 0 );
  8821. this.morphTargetDictionary[ morphTargets[ m ].name ] = m;
  8822. }
  8823. }
  8824. },
  8825. raycast: ( function () {
  8826. var inverseMatrix = new Matrix4();
  8827. var ray = new Ray();
  8828. var sphere = new Sphere();
  8829. var vA = new Vector3();
  8830. var vB = new Vector3();
  8831. var vC = new Vector3();
  8832. var tempA = new Vector3();
  8833. var tempB = new Vector3();
  8834. var tempC = new Vector3();
  8835. var uvA = new Vector2();
  8836. var uvB = new Vector2();
  8837. var uvC = new Vector2();
  8838. var barycoord = new Vector3();
  8839. var intersectionPoint = new Vector3();
  8840. var intersectionPointWorld = new Vector3();
  8841. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  8842. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  8843. uv1.multiplyScalar( barycoord.x );
  8844. uv2.multiplyScalar( barycoord.y );
  8845. uv3.multiplyScalar( barycoord.z );
  8846. uv1.add( uv2 ).add( uv3 );
  8847. return uv1.clone();
  8848. }
  8849. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  8850. var intersect;
  8851. var material = object.material;
  8852. if ( material.side === BackSide ) {
  8853. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  8854. } else {
  8855. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  8856. }
  8857. if ( intersect === null ) return null;
  8858. intersectionPointWorld.copy( point );
  8859. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  8860. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  8861. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  8862. return {
  8863. distance: distance,
  8864. point: intersectionPointWorld.clone(),
  8865. object: object
  8866. };
  8867. }
  8868. function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) {
  8869. vA.fromArray( positions, a * 3 );
  8870. vB.fromArray( positions, b * 3 );
  8871. vC.fromArray( positions, c * 3 );
  8872. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  8873. if ( intersection ) {
  8874. if ( uvs ) {
  8875. uvA.fromArray( uvs, a * 2 );
  8876. uvB.fromArray( uvs, b * 2 );
  8877. uvC.fromArray( uvs, c * 2 );
  8878. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  8879. }
  8880. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  8881. intersection.faceIndex = a;
  8882. }
  8883. return intersection;
  8884. }
  8885. return function raycast( raycaster, intersects ) {
  8886. var geometry = this.geometry;
  8887. var material = this.material;
  8888. var matrixWorld = this.matrixWorld;
  8889. if ( material === undefined ) return;
  8890. // Checking boundingSphere distance to ray
  8891. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8892. sphere.copy( geometry.boundingSphere );
  8893. sphere.applyMatrix4( matrixWorld );
  8894. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  8895. //
  8896. inverseMatrix.getInverse( matrixWorld );
  8897. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8898. // Check boundingBox before continuing
  8899. if ( geometry.boundingBox !== null ) {
  8900. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  8901. }
  8902. var uvs, intersection;
  8903. if ( geometry.isBufferGeometry ) {
  8904. var a, b, c;
  8905. var index = geometry.index;
  8906. var attributes = geometry.attributes;
  8907. var positions = attributes.position.array;
  8908. if ( attributes.uv !== undefined ) {
  8909. uvs = attributes.uv.array;
  8910. }
  8911. if ( index !== null ) {
  8912. var indices = index.array;
  8913. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  8914. a = indices[ i ];
  8915. b = indices[ i + 1 ];
  8916. c = indices[ i + 2 ];
  8917. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  8918. if ( intersection ) {
  8919. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  8920. intersects.push( intersection );
  8921. }
  8922. }
  8923. } else {
  8924. for ( var i = 0, l = positions.length; i < l; i += 9 ) {
  8925. a = i / 3;
  8926. b = a + 1;
  8927. c = a + 2;
  8928. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  8929. if ( intersection ) {
  8930. intersection.index = a; // triangle number in positions buffer semantics
  8931. intersects.push( intersection );
  8932. }
  8933. }
  8934. }
  8935. } else if ( geometry.isGeometry ) {
  8936. var fvA, fvB, fvC;
  8937. var isFaceMaterial = (material && material.isMultiMaterial);
  8938. var materials = isFaceMaterial === true ? material.materials : null;
  8939. var vertices = geometry.vertices;
  8940. var faces = geometry.faces;
  8941. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  8942. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  8943. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  8944. var face = faces[ f ];
  8945. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  8946. if ( faceMaterial === undefined ) continue;
  8947. fvA = vertices[ face.a ];
  8948. fvB = vertices[ face.b ];
  8949. fvC = vertices[ face.c ];
  8950. if ( faceMaterial.morphTargets === true ) {
  8951. var morphTargets = geometry.morphTargets;
  8952. var morphInfluences = this.morphTargetInfluences;
  8953. vA.set( 0, 0, 0 );
  8954. vB.set( 0, 0, 0 );
  8955. vC.set( 0, 0, 0 );
  8956. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  8957. var influence = morphInfluences[ t ];
  8958. if ( influence === 0 ) continue;
  8959. var targets = morphTargets[ t ].vertices;
  8960. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  8961. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  8962. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  8963. }
  8964. vA.add( fvA );
  8965. vB.add( fvB );
  8966. vC.add( fvC );
  8967. fvA = vA;
  8968. fvB = vB;
  8969. fvC = vC;
  8970. }
  8971. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  8972. if ( intersection ) {
  8973. if ( uvs ) {
  8974. var uvs_f = uvs[ f ];
  8975. uvA.copy( uvs_f[ 0 ] );
  8976. uvB.copy( uvs_f[ 1 ] );
  8977. uvC.copy( uvs_f[ 2 ] );
  8978. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  8979. }
  8980. intersection.face = face;
  8981. intersection.faceIndex = f;
  8982. intersects.push( intersection );
  8983. }
  8984. }
  8985. }
  8986. };
  8987. }() ),
  8988. clone: function () {
  8989. return new this.constructor( this.geometry, this.material ).copy( this );
  8990. }
  8991. } );
  8992. /**
  8993. * @author Mugen87 / https://github.com/Mugen87
  8994. */
  8995. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  8996. BufferGeometry.call( this );
  8997. this.type = 'BoxBufferGeometry';
  8998. this.parameters = {
  8999. width: width,
  9000. height: height,
  9001. depth: depth,
  9002. widthSegments: widthSegments,
  9003. heightSegments: heightSegments,
  9004. depthSegments: depthSegments
  9005. };
  9006. var scope = this;
  9007. // segments
  9008. widthSegments = Math.floor( widthSegments ) || 1;
  9009. heightSegments = Math.floor( heightSegments ) || 1;
  9010. depthSegments = Math.floor( depthSegments ) || 1;
  9011. // these are used to calculate buffer length
  9012. var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments );
  9013. var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments );
  9014. // buffers
  9015. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  9016. var vertices = new Float32Array( vertexCount * 3 );
  9017. var normals = new Float32Array( vertexCount * 3 );
  9018. var uvs = new Float32Array( vertexCount * 2 );
  9019. // offset variables
  9020. var vertexBufferOffset = 0;
  9021. var uvBufferOffset = 0;
  9022. var indexBufferOffset = 0;
  9023. var numberOfVertices = 0;
  9024. // group variables
  9025. var groupStart = 0;
  9026. // build each side of the box geometry
  9027. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  9028. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  9029. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  9030. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  9031. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  9032. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  9033. // build geometry
  9034. this.setIndex( new BufferAttribute( indices, 1 ) );
  9035. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  9036. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  9037. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  9038. // helper functions
  9039. function calculateVertexCount( w, h, d ) {
  9040. var vertices = 0;
  9041. // calculate the amount of vertices for each side (plane)
  9042. vertices += (w + 1) * (h + 1) * 2; // xy
  9043. vertices += (w + 1) * (d + 1) * 2; // xz
  9044. vertices += (d + 1) * (h + 1) * 2; // zy
  9045. return vertices;
  9046. }
  9047. function calculateIndexCount( w, h, d ) {
  9048. var index = 0;
  9049. // calculate the amount of squares for each side
  9050. index += w * h * 2; // xy
  9051. index += w * d * 2; // xz
  9052. index += d * h * 2; // zy
  9053. return index * 6; // two triangles per square => six vertices per square
  9054. }
  9055. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  9056. var segmentWidth = width / gridX;
  9057. var segmentHeight = height / gridY;
  9058. var widthHalf = width / 2;
  9059. var heightHalf = height / 2;
  9060. var depthHalf = depth / 2;
  9061. var gridX1 = gridX + 1;
  9062. var gridY1 = gridY + 1;
  9063. var vertexCounter = 0;
  9064. var groupCount = 0;
  9065. var vector = new Vector3();
  9066. // generate vertices, normals and uvs
  9067. for ( var iy = 0; iy < gridY1; iy ++ ) {
  9068. var y = iy * segmentHeight - heightHalf;
  9069. for ( var ix = 0; ix < gridX1; ix ++ ) {
  9070. var x = ix * segmentWidth - widthHalf;
  9071. // set values to correct vector component
  9072. vector[ u ] = x * udir;
  9073. vector[ v ] = y * vdir;
  9074. vector[ w ] = depthHalf;
  9075. // now apply vector to vertex buffer
  9076. vertices[ vertexBufferOffset ] = vector.x;
  9077. vertices[ vertexBufferOffset + 1 ] = vector.y;
  9078. vertices[ vertexBufferOffset + 2 ] = vector.z;
  9079. // set values to correct vector component
  9080. vector[ u ] = 0;
  9081. vector[ v ] = 0;
  9082. vector[ w ] = depth > 0 ? 1 : - 1;
  9083. // now apply vector to normal buffer
  9084. normals[ vertexBufferOffset ] = vector.x;
  9085. normals[ vertexBufferOffset + 1 ] = vector.y;
  9086. normals[ vertexBufferOffset + 2 ] = vector.z;
  9087. // uvs
  9088. uvs[ uvBufferOffset ] = ix / gridX;
  9089. uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY );
  9090. // update offsets and counters
  9091. vertexBufferOffset += 3;
  9092. uvBufferOffset += 2;
  9093. vertexCounter += 1;
  9094. }
  9095. }
  9096. // 1. you need three indices to draw a single face
  9097. // 2. a single segment consists of two faces
  9098. // 3. so we need to generate six (2*3) indices per segment
  9099. for ( iy = 0; iy < gridY; iy ++ ) {
  9100. for ( ix = 0; ix < gridX; ix ++ ) {
  9101. // indices
  9102. var a = numberOfVertices + ix + gridX1 * iy;
  9103. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  9104. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  9105. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  9106. // face one
  9107. indices[ indexBufferOffset ] = a;
  9108. indices[ indexBufferOffset + 1 ] = b;
  9109. indices[ indexBufferOffset + 2 ] = d;
  9110. // face two
  9111. indices[ indexBufferOffset + 3 ] = b;
  9112. indices[ indexBufferOffset + 4 ] = c;
  9113. indices[ indexBufferOffset + 5 ] = d;
  9114. // update offsets and counters
  9115. indexBufferOffset += 6;
  9116. groupCount += 6;
  9117. }
  9118. }
  9119. // add a group to the geometry. this will ensure multi material support
  9120. scope.addGroup( groupStart, groupCount, materialIndex );
  9121. // calculate new start value for groups
  9122. groupStart += groupCount;
  9123. // update total number of vertices
  9124. numberOfVertices += vertexCounter;
  9125. }
  9126. }
  9127. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  9128. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  9129. /**
  9130. * @author mrdoob / http://mrdoob.com/
  9131. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  9132. */
  9133. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  9134. BufferGeometry.call( this );
  9135. this.type = 'PlaneBufferGeometry';
  9136. this.parameters = {
  9137. width: width,
  9138. height: height,
  9139. widthSegments: widthSegments,
  9140. heightSegments: heightSegments
  9141. };
  9142. var width_half = width / 2;
  9143. var height_half = height / 2;
  9144. var gridX = Math.floor( widthSegments ) || 1;
  9145. var gridY = Math.floor( heightSegments ) || 1;
  9146. var gridX1 = gridX + 1;
  9147. var gridY1 = gridY + 1;
  9148. var segment_width = width / gridX;
  9149. var segment_height = height / gridY;
  9150. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  9151. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  9152. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  9153. var offset = 0;
  9154. var offset2 = 0;
  9155. for ( var iy = 0; iy < gridY1; iy ++ ) {
  9156. var y = iy * segment_height - height_half;
  9157. for ( var ix = 0; ix < gridX1; ix ++ ) {
  9158. var x = ix * segment_width - width_half;
  9159. vertices[ offset ] = x;
  9160. vertices[ offset + 1 ] = - y;
  9161. normals[ offset + 2 ] = 1;
  9162. uvs[ offset2 ] = ix / gridX;
  9163. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  9164. offset += 3;
  9165. offset2 += 2;
  9166. }
  9167. }
  9168. offset = 0;
  9169. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  9170. for ( var iy = 0; iy < gridY; iy ++ ) {
  9171. for ( var ix = 0; ix < gridX; ix ++ ) {
  9172. var a = ix + gridX1 * iy;
  9173. var b = ix + gridX1 * ( iy + 1 );
  9174. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  9175. var d = ( ix + 1 ) + gridX1 * iy;
  9176. indices[ offset ] = a;
  9177. indices[ offset + 1 ] = b;
  9178. indices[ offset + 2 ] = d;
  9179. indices[ offset + 3 ] = b;
  9180. indices[ offset + 4 ] = c;
  9181. indices[ offset + 5 ] = d;
  9182. offset += 6;
  9183. }
  9184. }
  9185. this.setIndex( new BufferAttribute( indices, 1 ) );
  9186. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  9187. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  9188. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  9189. }
  9190. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  9191. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  9192. /**
  9193. * @author mrdoob / http://mrdoob.com/
  9194. * @author mikael emtinger / http://gomo.se/
  9195. * @author WestLangley / http://github.com/WestLangley
  9196. */
  9197. function Camera() {
  9198. Object3D.call( this );
  9199. this.type = 'Camera';
  9200. this.matrixWorldInverse = new Matrix4();
  9201. this.projectionMatrix = new Matrix4();
  9202. }
  9203. Camera.prototype = Object.create( Object3D.prototype );
  9204. Camera.prototype.constructor = Camera;
  9205. Camera.prototype.isCamera = true;
  9206. Camera.prototype.getWorldDirection = function () {
  9207. var quaternion = new Quaternion();
  9208. return function getWorldDirection( optionalTarget ) {
  9209. var result = optionalTarget || new Vector3();
  9210. this.getWorldQuaternion( quaternion );
  9211. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9212. };
  9213. }();
  9214. Camera.prototype.lookAt = function () {
  9215. // This routine does not support cameras with rotated and/or translated parent(s)
  9216. var m1 = new Matrix4();
  9217. return function lookAt( vector ) {
  9218. m1.lookAt( this.position, vector, this.up );
  9219. this.quaternion.setFromRotationMatrix( m1 );
  9220. };
  9221. }();
  9222. Camera.prototype.clone = function () {
  9223. return new this.constructor().copy( this );
  9224. };
  9225. Camera.prototype.copy = function ( source ) {
  9226. Object3D.prototype.copy.call( this, source );
  9227. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9228. this.projectionMatrix.copy( source.projectionMatrix );
  9229. return this;
  9230. };
  9231. /**
  9232. * @author mrdoob / http://mrdoob.com/
  9233. * @author greggman / http://games.greggman.com/
  9234. * @author zz85 / http://www.lab4games.net/zz85/blog
  9235. * @author tschw
  9236. */
  9237. function PerspectiveCamera( fov, aspect, near, far ) {
  9238. Camera.call( this );
  9239. this.type = 'PerspectiveCamera';
  9240. this.fov = fov !== undefined ? fov : 50;
  9241. this.zoom = 1;
  9242. this.near = near !== undefined ? near : 0.1;
  9243. this.far = far !== undefined ? far : 2000;
  9244. this.focus = 10;
  9245. this.aspect = aspect !== undefined ? aspect : 1;
  9246. this.view = null;
  9247. this.filmGauge = 35; // width of the film (default in millimeters)
  9248. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  9249. this.updateProjectionMatrix();
  9250. }
  9251. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9252. constructor: PerspectiveCamera,
  9253. isPerspectiveCamera: true,
  9254. copy: function ( source ) {
  9255. Camera.prototype.copy.call( this, source );
  9256. this.fov = source.fov;
  9257. this.zoom = source.zoom;
  9258. this.near = source.near;
  9259. this.far = source.far;
  9260. this.focus = source.focus;
  9261. this.aspect = source.aspect;
  9262. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9263. this.filmGauge = source.filmGauge;
  9264. this.filmOffset = source.filmOffset;
  9265. return this;
  9266. },
  9267. /**
  9268. * Sets the FOV by focal length in respect to the current .filmGauge.
  9269. *
  9270. * The default film gauge is 35, so that the focal length can be specified for
  9271. * a 35mm (full frame) camera.
  9272. *
  9273. * Values for focal length and film gauge must have the same unit.
  9274. */
  9275. setFocalLength: function ( focalLength ) {
  9276. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  9277. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  9278. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  9279. this.updateProjectionMatrix();
  9280. },
  9281. /**
  9282. * Calculates the focal length from the current .fov and .filmGauge.
  9283. */
  9284. getFocalLength: function () {
  9285. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  9286. return 0.5 * this.getFilmHeight() / vExtentSlope;
  9287. },
  9288. getEffectiveFOV: function () {
  9289. return _Math.RAD2DEG * 2 * Math.atan(
  9290. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  9291. },
  9292. getFilmWidth: function () {
  9293. // film not completely covered in portrait format (aspect < 1)
  9294. return this.filmGauge * Math.min( this.aspect, 1 );
  9295. },
  9296. getFilmHeight: function () {
  9297. // film not completely covered in landscape format (aspect > 1)
  9298. return this.filmGauge / Math.max( this.aspect, 1 );
  9299. },
  9300. /**
  9301. * Sets an offset in a larger frustum. This is useful for multi-window or
  9302. * multi-monitor/multi-machine setups.
  9303. *
  9304. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9305. * the monitors are in grid like this
  9306. *
  9307. * +---+---+---+
  9308. * | A | B | C |
  9309. * +---+---+---+
  9310. * | D | E | F |
  9311. * +---+---+---+
  9312. *
  9313. * then for each monitor you would call it like this
  9314. *
  9315. * var w = 1920;
  9316. * var h = 1080;
  9317. * var fullWidth = w * 3;
  9318. * var fullHeight = h * 2;
  9319. *
  9320. * --A--
  9321. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9322. * --B--
  9323. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9324. * --C--
  9325. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9326. * --D--
  9327. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9328. * --E--
  9329. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9330. * --F--
  9331. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9332. *
  9333. * Note there is no reason monitors have to be the same size or in a grid.
  9334. */
  9335. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  9336. this.aspect = fullWidth / fullHeight;
  9337. this.view = {
  9338. fullWidth: fullWidth,
  9339. fullHeight: fullHeight,
  9340. offsetX: x,
  9341. offsetY: y,
  9342. width: width,
  9343. height: height
  9344. };
  9345. this.updateProjectionMatrix();
  9346. },
  9347. clearViewOffset: function() {
  9348. this.view = null;
  9349. this.updateProjectionMatrix();
  9350. },
  9351. updateProjectionMatrix: function () {
  9352. var near = this.near,
  9353. top = near * Math.tan(
  9354. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  9355. height = 2 * top,
  9356. width = this.aspect * height,
  9357. left = - 0.5 * width,
  9358. view = this.view;
  9359. if ( view !== null ) {
  9360. var fullWidth = view.fullWidth,
  9361. fullHeight = view.fullHeight;
  9362. left += view.offsetX * width / fullWidth;
  9363. top -= view.offsetY * height / fullHeight;
  9364. width *= view.width / fullWidth;
  9365. height *= view.height / fullHeight;
  9366. }
  9367. var skew = this.filmOffset;
  9368. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  9369. this.projectionMatrix.makeFrustum(
  9370. left, left + width, top - height, top, near, this.far );
  9371. },
  9372. toJSON: function ( meta ) {
  9373. var data = Object3D.prototype.toJSON.call( this, meta );
  9374. data.object.fov = this.fov;
  9375. data.object.zoom = this.zoom;
  9376. data.object.near = this.near;
  9377. data.object.far = this.far;
  9378. data.object.focus = this.focus;
  9379. data.object.aspect = this.aspect;
  9380. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9381. data.object.filmGauge = this.filmGauge;
  9382. data.object.filmOffset = this.filmOffset;
  9383. return data;
  9384. }
  9385. } );
  9386. /**
  9387. * @author alteredq / http://alteredqualia.com/
  9388. * @author arose / http://github.com/arose
  9389. */
  9390. function OrthographicCamera( left, right, top, bottom, near, far ) {
  9391. Camera.call( this );
  9392. this.type = 'OrthographicCamera';
  9393. this.zoom = 1;
  9394. this.view = null;
  9395. this.left = left;
  9396. this.right = right;
  9397. this.top = top;
  9398. this.bottom = bottom;
  9399. this.near = ( near !== undefined ) ? near : 0.1;
  9400. this.far = ( far !== undefined ) ? far : 2000;
  9401. this.updateProjectionMatrix();
  9402. }
  9403. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9404. constructor: OrthographicCamera,
  9405. isOrthographicCamera: true,
  9406. copy: function ( source ) {
  9407. Camera.prototype.copy.call( this, source );
  9408. this.left = source.left;
  9409. this.right = source.right;
  9410. this.top = source.top;
  9411. this.bottom = source.bottom;
  9412. this.near = source.near;
  9413. this.far = source.far;
  9414. this.zoom = source.zoom;
  9415. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9416. return this;
  9417. },
  9418. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  9419. this.view = {
  9420. fullWidth: fullWidth,
  9421. fullHeight: fullHeight,
  9422. offsetX: x,
  9423. offsetY: y,
  9424. width: width,
  9425. height: height
  9426. };
  9427. this.updateProjectionMatrix();
  9428. },
  9429. clearViewOffset: function() {
  9430. this.view = null;
  9431. this.updateProjectionMatrix();
  9432. },
  9433. updateProjectionMatrix: function () {
  9434. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9435. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9436. var cx = ( this.right + this.left ) / 2;
  9437. var cy = ( this.top + this.bottom ) / 2;
  9438. var left = cx - dx;
  9439. var right = cx + dx;
  9440. var top = cy + dy;
  9441. var bottom = cy - dy;
  9442. if ( this.view !== null ) {
  9443. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  9444. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  9445. var scaleW = ( this.right - this.left ) / this.view.width;
  9446. var scaleH = ( this.top - this.bottom ) / this.view.height;
  9447. left += scaleW * ( this.view.offsetX / zoomW );
  9448. right = left + scaleW * ( this.view.width / zoomW );
  9449. top -= scaleH * ( this.view.offsetY / zoomH );
  9450. bottom = top - scaleH * ( this.view.height / zoomH );
  9451. }
  9452. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9453. },
  9454. toJSON: function ( meta ) {
  9455. var data = Object3D.prototype.toJSON.call( this, meta );
  9456. data.object.zoom = this.zoom;
  9457. data.object.left = this.left;
  9458. data.object.right = this.right;
  9459. data.object.top = this.top;
  9460. data.object.bottom = this.bottom;
  9461. data.object.near = this.near;
  9462. data.object.far = this.far;
  9463. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9464. return data;
  9465. }
  9466. } );
  9467. /**
  9468. * @author mrdoob / http://mrdoob.com/
  9469. */
  9470. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  9471. var mode;
  9472. function setMode( value ) {
  9473. mode = value;
  9474. }
  9475. var type, size;
  9476. function setIndex( index ) {
  9477. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  9478. type = gl.UNSIGNED_INT;
  9479. size = 4;
  9480. } else if ( index.array instanceof Uint16Array ) {
  9481. type = gl.UNSIGNED_SHORT;
  9482. size = 2;
  9483. } else {
  9484. type = gl.UNSIGNED_BYTE;
  9485. size = 1;
  9486. }
  9487. }
  9488. function render( start, count ) {
  9489. gl.drawElements( mode, count, type, start * size );
  9490. infoRender.calls ++;
  9491. infoRender.vertices += count;
  9492. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9493. }
  9494. function renderInstances( geometry, start, count ) {
  9495. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9496. if ( extension === null ) {
  9497. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9498. return;
  9499. }
  9500. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  9501. infoRender.calls ++;
  9502. infoRender.vertices += count * geometry.maxInstancedCount;
  9503. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9504. }
  9505. return {
  9506. setMode: setMode,
  9507. setIndex: setIndex,
  9508. render: render,
  9509. renderInstances: renderInstances
  9510. };
  9511. }
  9512. /**
  9513. * @author mrdoob / http://mrdoob.com/
  9514. */
  9515. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  9516. var mode;
  9517. function setMode( value ) {
  9518. mode = value;
  9519. }
  9520. function render( start, count ) {
  9521. gl.drawArrays( mode, start, count );
  9522. infoRender.calls ++;
  9523. infoRender.vertices += count;
  9524. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9525. }
  9526. function renderInstances( geometry ) {
  9527. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9528. if ( extension === null ) {
  9529. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9530. return;
  9531. }
  9532. var position = geometry.attributes.position;
  9533. var count = 0;
  9534. if ( position.isInterleavedBufferAttribute ) {
  9535. count = position.data.count;
  9536. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  9537. } else {
  9538. count = position.count;
  9539. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  9540. }
  9541. infoRender.calls ++;
  9542. infoRender.vertices += count * geometry.maxInstancedCount;
  9543. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9544. }
  9545. return {
  9546. setMode: setMode,
  9547. render: render,
  9548. renderInstances: renderInstances
  9549. };
  9550. }
  9551. /**
  9552. * @author mrdoob / http://mrdoob.com/
  9553. */
  9554. function WebGLLights() {
  9555. var lights = {};
  9556. return {
  9557. get: function ( light ) {
  9558. if ( lights[ light.id ] !== undefined ) {
  9559. return lights[ light.id ];
  9560. }
  9561. var uniforms;
  9562. switch ( light.type ) {
  9563. case 'DirectionalLight':
  9564. uniforms = {
  9565. direction: new Vector3(),
  9566. color: new Color(),
  9567. shadow: false,
  9568. shadowBias: 0,
  9569. shadowRadius: 1,
  9570. shadowMapSize: new Vector2()
  9571. };
  9572. break;
  9573. case 'SpotLight':
  9574. uniforms = {
  9575. position: new Vector3(),
  9576. direction: new Vector3(),
  9577. color: new Color(),
  9578. distance: 0,
  9579. coneCos: 0,
  9580. penumbraCos: 0,
  9581. decay: 0,
  9582. shadow: false,
  9583. shadowBias: 0,
  9584. shadowRadius: 1,
  9585. shadowMapSize: new Vector2()
  9586. };
  9587. break;
  9588. case 'PointLight':
  9589. uniforms = {
  9590. position: new Vector3(),
  9591. color: new Color(),
  9592. distance: 0,
  9593. decay: 0,
  9594. shadow: false,
  9595. shadowBias: 0,
  9596. shadowRadius: 1,
  9597. shadowMapSize: new Vector2()
  9598. };
  9599. break;
  9600. case 'HemisphereLight':
  9601. uniforms = {
  9602. direction: new Vector3(),
  9603. skyColor: new Color(),
  9604. groundColor: new Color()
  9605. };
  9606. break;
  9607. case 'RectAreaLight':
  9608. uniforms = {
  9609. color: new Color(),
  9610. position: new Vector3(),
  9611. halfWidth: new Vector3(),
  9612. halfHeight: new Vector3()
  9613. // TODO (abelnation): set RectAreaLight shadow uniforms
  9614. };
  9615. break;
  9616. }
  9617. lights[ light.id ] = uniforms;
  9618. return uniforms;
  9619. }
  9620. };
  9621. }
  9622. /**
  9623. * @author mrdoob / http://mrdoob.com/
  9624. */
  9625. function addLineNumbers( string ) {
  9626. var lines = string.split( '\n' );
  9627. for ( var i = 0; i < lines.length; i ++ ) {
  9628. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  9629. }
  9630. return lines.join( '\n' );
  9631. }
  9632. function WebGLShader( gl, type, string ) {
  9633. var shader = gl.createShader( type );
  9634. gl.shaderSource( shader, string );
  9635. gl.compileShader( shader );
  9636. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  9637. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  9638. }
  9639. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  9640. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  9641. }
  9642. // --enable-privileged-webgl-extension
  9643. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  9644. return shader;
  9645. }
  9646. /**
  9647. * @author mrdoob / http://mrdoob.com/
  9648. */
  9649. var programIdCount = 0;
  9650. function getEncodingComponents( encoding ) {
  9651. switch ( encoding ) {
  9652. case LinearEncoding:
  9653. return [ 'Linear','( value )' ];
  9654. case sRGBEncoding:
  9655. return [ 'sRGB','( value )' ];
  9656. case RGBEEncoding:
  9657. return [ 'RGBE','( value )' ];
  9658. case RGBM7Encoding:
  9659. return [ 'RGBM','( value, 7.0 )' ];
  9660. case RGBM16Encoding:
  9661. return [ 'RGBM','( value, 16.0 )' ];
  9662. case RGBDEncoding:
  9663. return [ 'RGBD','( value, 256.0 )' ];
  9664. case GammaEncoding:
  9665. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  9666. default:
  9667. throw new Error( 'unsupported encoding: ' + encoding );
  9668. }
  9669. }
  9670. function getTexelDecodingFunction( functionName, encoding ) {
  9671. var components = getEncodingComponents( encoding );
  9672. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  9673. }
  9674. function getTexelEncodingFunction( functionName, encoding ) {
  9675. var components = getEncodingComponents( encoding );
  9676. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  9677. }
  9678. function getToneMappingFunction( functionName, toneMapping ) {
  9679. var toneMappingName;
  9680. switch ( toneMapping ) {
  9681. case LinearToneMapping:
  9682. toneMappingName = "Linear";
  9683. break;
  9684. case ReinhardToneMapping:
  9685. toneMappingName = "Reinhard";
  9686. break;
  9687. case Uncharted2ToneMapping:
  9688. toneMappingName = "Uncharted2";
  9689. break;
  9690. case CineonToneMapping:
  9691. toneMappingName = "OptimizedCineon";
  9692. break;
  9693. default:
  9694. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  9695. }
  9696. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  9697. }
  9698. function generateExtensions( extensions, parameters, rendererExtensions ) {
  9699. extensions = extensions || {};
  9700. var chunks = [
  9701. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  9702. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  9703. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  9704. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '',
  9705. ];
  9706. return chunks.filter( filterEmptyLine ).join( '\n' );
  9707. }
  9708. function generateDefines( defines ) {
  9709. var chunks = [];
  9710. for ( var name in defines ) {
  9711. var value = defines[ name ];
  9712. if ( value === false ) continue;
  9713. chunks.push( '#define ' + name + ' ' + value );
  9714. }
  9715. return chunks.join( '\n' );
  9716. }
  9717. function fetchAttributeLocations( gl, program, identifiers ) {
  9718. var attributes = {};
  9719. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  9720. for ( var i = 0; i < n; i ++ ) {
  9721. var info = gl.getActiveAttrib( program, i );
  9722. var name = info.name;
  9723. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  9724. attributes[ name ] = gl.getAttribLocation( program, name );
  9725. }
  9726. return attributes;
  9727. }
  9728. function filterEmptyLine( string ) {
  9729. return string !== '';
  9730. }
  9731. function replaceLightNums( string, parameters ) {
  9732. return string
  9733. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  9734. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  9735. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  9736. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  9737. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  9738. }
  9739. function parseIncludes( string ) {
  9740. var pattern = /#include +<([\w\d.]+)>/g;
  9741. function replace( match, include ) {
  9742. var replace = ShaderChunk[ include ];
  9743. if ( replace === undefined ) {
  9744. throw new Error( 'Can not resolve #include <' + include + '>' );
  9745. }
  9746. return parseIncludes( replace );
  9747. }
  9748. return string.replace( pattern, replace );
  9749. }
  9750. function unrollLoops( string ) {
  9751. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  9752. function replace( match, start, end, snippet ) {
  9753. var unroll = '';
  9754. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  9755. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  9756. }
  9757. return unroll;
  9758. }
  9759. return string.replace( pattern, replace );
  9760. }
  9761. function WebGLProgram( renderer, code, material, parameters ) {
  9762. var gl = renderer.context;
  9763. var extensions = material.extensions;
  9764. var defines = material.defines;
  9765. var vertexShader = material.__webglShader.vertexShader;
  9766. var fragmentShader = material.__webglShader.fragmentShader;
  9767. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  9768. if ( parameters.shadowMapType === PCFShadowMap ) {
  9769. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  9770. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  9771. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  9772. }
  9773. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  9774. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  9775. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  9776. if ( parameters.envMap ) {
  9777. switch ( material.envMap.mapping ) {
  9778. case CubeReflectionMapping:
  9779. case CubeRefractionMapping:
  9780. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  9781. break;
  9782. case CubeUVReflectionMapping:
  9783. case CubeUVRefractionMapping:
  9784. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  9785. break;
  9786. case EquirectangularReflectionMapping:
  9787. case EquirectangularRefractionMapping:
  9788. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  9789. break;
  9790. case SphericalReflectionMapping:
  9791. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  9792. break;
  9793. }
  9794. switch ( material.envMap.mapping ) {
  9795. case CubeRefractionMapping:
  9796. case EquirectangularRefractionMapping:
  9797. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  9798. break;
  9799. }
  9800. switch ( material.combine ) {
  9801. case MultiplyOperation:
  9802. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  9803. break;
  9804. case MixOperation:
  9805. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  9806. break;
  9807. case AddOperation:
  9808. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  9809. break;
  9810. }
  9811. }
  9812. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  9813. // console.log( 'building new program ' );
  9814. //
  9815. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  9816. var customDefines = generateDefines( defines );
  9817. //
  9818. var program = gl.createProgram();
  9819. var prefixVertex, prefixFragment;
  9820. if ( material.isRawShaderMaterial ) {
  9821. prefixVertex = [
  9822. customDefines,
  9823. '\n'
  9824. ].filter( filterEmptyLine ).join( '\n' );
  9825. prefixFragment = [
  9826. customExtensions,
  9827. customDefines,
  9828. '\n'
  9829. ].filter( filterEmptyLine ).join( '\n' );
  9830. } else {
  9831. prefixVertex = [
  9832. 'precision ' + parameters.precision + ' float;',
  9833. 'precision ' + parameters.precision + ' int;',
  9834. '#define SHADER_NAME ' + material.__webglShader.name,
  9835. customDefines,
  9836. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  9837. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  9838. '#define MAX_BONES ' + parameters.maxBones,
  9839. parameters.map ? '#define USE_MAP' : '',
  9840. parameters.envMap ? '#define USE_ENVMAP' : '',
  9841. parameters.envMap ? '#define ' + envMapModeDefine : '',
  9842. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  9843. parameters.aoMap ? '#define USE_AOMAP' : '',
  9844. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  9845. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  9846. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  9847. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  9848. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  9849. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  9850. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  9851. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  9852. parameters.vertexColors ? '#define USE_COLOR' : '',
  9853. parameters.flatShading ? '#define FLAT_SHADED' : '',
  9854. parameters.skinning ? '#define USE_SKINNING' : '',
  9855. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  9856. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  9857. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  9858. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  9859. parameters.flipSided ? '#define FLIP_SIDED' : '',
  9860. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  9861. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  9862. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  9863. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  9864. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  9865. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  9866. 'uniform mat4 modelMatrix;',
  9867. 'uniform mat4 modelViewMatrix;',
  9868. 'uniform mat4 projectionMatrix;',
  9869. 'uniform mat4 viewMatrix;',
  9870. 'uniform mat3 normalMatrix;',
  9871. 'uniform vec3 cameraPosition;',
  9872. 'attribute vec3 position;',
  9873. 'attribute vec3 normal;',
  9874. 'attribute vec2 uv;',
  9875. '#ifdef USE_COLOR',
  9876. ' attribute vec3 color;',
  9877. '#endif',
  9878. '#ifdef USE_MORPHTARGETS',
  9879. ' attribute vec3 morphTarget0;',
  9880. ' attribute vec3 morphTarget1;',
  9881. ' attribute vec3 morphTarget2;',
  9882. ' attribute vec3 morphTarget3;',
  9883. ' #ifdef USE_MORPHNORMALS',
  9884. ' attribute vec3 morphNormal0;',
  9885. ' attribute vec3 morphNormal1;',
  9886. ' attribute vec3 morphNormal2;',
  9887. ' attribute vec3 morphNormal3;',
  9888. ' #else',
  9889. ' attribute vec3 morphTarget4;',
  9890. ' attribute vec3 morphTarget5;',
  9891. ' attribute vec3 morphTarget6;',
  9892. ' attribute vec3 morphTarget7;',
  9893. ' #endif',
  9894. '#endif',
  9895. '#ifdef USE_SKINNING',
  9896. ' attribute vec4 skinIndex;',
  9897. ' attribute vec4 skinWeight;',
  9898. '#endif',
  9899. '\n'
  9900. ].filter( filterEmptyLine ).join( '\n' );
  9901. prefixFragment = [
  9902. customExtensions,
  9903. 'precision ' + parameters.precision + ' float;',
  9904. 'precision ' + parameters.precision + ' int;',
  9905. '#define SHADER_NAME ' + material.__webglShader.name,
  9906. customDefines,
  9907. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  9908. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  9909. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  9910. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  9911. parameters.map ? '#define USE_MAP' : '',
  9912. parameters.envMap ? '#define USE_ENVMAP' : '',
  9913. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  9914. parameters.envMap ? '#define ' + envMapModeDefine : '',
  9915. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  9916. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  9917. parameters.aoMap ? '#define USE_AOMAP' : '',
  9918. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  9919. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  9920. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  9921. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  9922. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  9923. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  9924. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  9925. parameters.vertexColors ? '#define USE_COLOR' : '',
  9926. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  9927. parameters.flatShading ? '#define FLAT_SHADED' : '',
  9928. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  9929. parameters.flipSided ? '#define FLIP_SIDED' : '',
  9930. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  9931. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  9932. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  9933. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  9934. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  9935. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  9936. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  9937. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  9938. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  9939. 'uniform mat4 viewMatrix;',
  9940. 'uniform vec3 cameraPosition;',
  9941. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  9942. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  9943. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  9944. ( 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
  9945. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  9946. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  9947. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  9948. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  9949. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  9950. '\n'
  9951. ].filter( filterEmptyLine ).join( '\n' );
  9952. }
  9953. vertexShader = parseIncludes( vertexShader, parameters );
  9954. vertexShader = replaceLightNums( vertexShader, parameters );
  9955. fragmentShader = parseIncludes( fragmentShader, parameters );
  9956. fragmentShader = replaceLightNums( fragmentShader, parameters );
  9957. if ( ! material.isShaderMaterial ) {
  9958. vertexShader = unrollLoops( vertexShader );
  9959. fragmentShader = unrollLoops( fragmentShader );
  9960. }
  9961. var vertexGlsl = prefixVertex + vertexShader;
  9962. var fragmentGlsl = prefixFragment + fragmentShader;
  9963. // console.log( '*VERTEX*', vertexGlsl );
  9964. // console.log( '*FRAGMENT*', fragmentGlsl );
  9965. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  9966. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  9967. gl.attachShader( program, glVertexShader );
  9968. gl.attachShader( program, glFragmentShader );
  9969. // Force a particular attribute to index 0.
  9970. if ( material.index0AttributeName !== undefined ) {
  9971. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  9972. } else if ( parameters.morphTargets === true ) {
  9973. // programs with morphTargets displace position out of attribute 0
  9974. gl.bindAttribLocation( program, 0, 'position' );
  9975. }
  9976. gl.linkProgram( program );
  9977. var programLog = gl.getProgramInfoLog( program );
  9978. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  9979. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  9980. var runnable = true;
  9981. var haveDiagnostics = true;
  9982. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  9983. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  9984. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  9985. runnable = false;
  9986. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  9987. } else if ( programLog !== '' ) {
  9988. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  9989. } else if ( vertexLog === '' || fragmentLog === '' ) {
  9990. haveDiagnostics = false;
  9991. }
  9992. if ( haveDiagnostics ) {
  9993. this.diagnostics = {
  9994. runnable: runnable,
  9995. material: material,
  9996. programLog: programLog,
  9997. vertexShader: {
  9998. log: vertexLog,
  9999. prefix: prefixVertex
  10000. },
  10001. fragmentShader: {
  10002. log: fragmentLog,
  10003. prefix: prefixFragment
  10004. }
  10005. };
  10006. }
  10007. // clean up
  10008. gl.deleteShader( glVertexShader );
  10009. gl.deleteShader( glFragmentShader );
  10010. // set up caching for uniform locations
  10011. var cachedUniforms;
  10012. this.getUniforms = function() {
  10013. if ( cachedUniforms === undefined ) {
  10014. cachedUniforms =
  10015. new WebGLUniforms( gl, program, renderer );
  10016. }
  10017. return cachedUniforms;
  10018. };
  10019. // set up caching for attribute locations
  10020. var cachedAttributes;
  10021. this.getAttributes = function() {
  10022. if ( cachedAttributes === undefined ) {
  10023. cachedAttributes = fetchAttributeLocations( gl, program );
  10024. }
  10025. return cachedAttributes;
  10026. };
  10027. // free resource
  10028. this.destroy = function() {
  10029. gl.deleteProgram( program );
  10030. this.program = undefined;
  10031. };
  10032. // DEPRECATED
  10033. Object.defineProperties( this, {
  10034. uniforms: {
  10035. get: function() {
  10036. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  10037. return this.getUniforms();
  10038. }
  10039. },
  10040. attributes: {
  10041. get: function() {
  10042. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  10043. return this.getAttributes();
  10044. }
  10045. }
  10046. } );
  10047. //
  10048. this.id = programIdCount ++;
  10049. this.code = code;
  10050. this.usedTimes = 1;
  10051. this.program = program;
  10052. this.vertexShader = glVertexShader;
  10053. this.fragmentShader = glFragmentShader;
  10054. return this;
  10055. }
  10056. /**
  10057. * @author mrdoob / http://mrdoob.com/
  10058. */
  10059. function WebGLPrograms( renderer, capabilities ) {
  10060. var programs = [];
  10061. var shaderIDs = {
  10062. MeshDepthMaterial: 'depth',
  10063. MeshNormalMaterial: 'normal',
  10064. MeshBasicMaterial: 'basic',
  10065. MeshLambertMaterial: 'lambert',
  10066. MeshPhongMaterial: 'phong',
  10067. MeshToonMaterial: 'phong',
  10068. MeshStandardMaterial: 'physical',
  10069. MeshPhysicalMaterial: 'physical',
  10070. LineBasicMaterial: 'basic',
  10071. LineDashedMaterial: 'dashed',
  10072. PointsMaterial: 'points'
  10073. };
  10074. var parameterNames = [
  10075. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  10076. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  10077. "roughnessMap", "metalnessMap", "gradientMap",
  10078. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  10079. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  10080. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  10081. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  10082. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  10083. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  10084. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking"
  10085. ];
  10086. function allocateBones( object ) {
  10087. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  10088. return 1024;
  10089. } else {
  10090. // default for when object is not specified
  10091. // ( for example when prebuilding shader to be used with multiple objects )
  10092. //
  10093. // - leave some extra space for other uniforms
  10094. // - limit here is ANGLE's 254 max uniform vectors
  10095. // (up to 54 should be safe)
  10096. var nVertexUniforms = capabilities.maxVertexUniforms;
  10097. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  10098. var maxBones = nVertexMatrices;
  10099. if ( object !== undefined && (object && object.isSkinnedMesh) ) {
  10100. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  10101. if ( maxBones < object.skeleton.bones.length ) {
  10102. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  10103. }
  10104. }
  10105. return maxBones;
  10106. }
  10107. }
  10108. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  10109. var encoding;
  10110. if ( ! map ) {
  10111. encoding = LinearEncoding;
  10112. } else if ( map.isTexture ) {
  10113. encoding = map.encoding;
  10114. } else if ( map.isWebGLRenderTarget ) {
  10115. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  10116. encoding = map.texture.encoding;
  10117. }
  10118. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  10119. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  10120. encoding = GammaEncoding;
  10121. }
  10122. return encoding;
  10123. }
  10124. this.getParameters = function ( material, lights, fog, nClipPlanes, nClipIntersection, object ) {
  10125. var shaderID = shaderIDs[ material.type ];
  10126. // heuristics to create shader parameters according to lights in the scene
  10127. // (not to blow over maxLights budget)
  10128. var maxBones = allocateBones( object );
  10129. var precision = renderer.getPrecision();
  10130. if ( material.precision !== null ) {
  10131. precision = capabilities.getMaxPrecision( material.precision );
  10132. if ( precision !== material.precision ) {
  10133. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  10134. }
  10135. }
  10136. var currentRenderTarget = renderer.getCurrentRenderTarget();
  10137. var parameters = {
  10138. shaderID: shaderID,
  10139. precision: precision,
  10140. supportsVertexTextures: capabilities.vertexTextures,
  10141. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  10142. map: !! material.map,
  10143. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  10144. envMap: !! material.envMap,
  10145. envMapMode: material.envMap && material.envMap.mapping,
  10146. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  10147. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  10148. lightMap: !! material.lightMap,
  10149. aoMap: !! material.aoMap,
  10150. emissiveMap: !! material.emissiveMap,
  10151. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  10152. bumpMap: !! material.bumpMap,
  10153. normalMap: !! material.normalMap,
  10154. displacementMap: !! material.displacementMap,
  10155. roughnessMap: !! material.roughnessMap,
  10156. metalnessMap: !! material.metalnessMap,
  10157. specularMap: !! material.specularMap,
  10158. alphaMap: !! material.alphaMap,
  10159. gradientMap: !! material.gradientMap,
  10160. combine: material.combine,
  10161. vertexColors: material.vertexColors,
  10162. fog: !! fog,
  10163. useFog: material.fog,
  10164. fogExp: (fog && fog.isFogExp2),
  10165. flatShading: material.shading === FlatShading,
  10166. sizeAttenuation: material.sizeAttenuation,
  10167. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  10168. skinning: material.skinning,
  10169. maxBones: maxBones,
  10170. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  10171. morphTargets: material.morphTargets,
  10172. morphNormals: material.morphNormals,
  10173. maxMorphTargets: renderer.maxMorphTargets,
  10174. maxMorphNormals: renderer.maxMorphNormals,
  10175. numDirLights: lights.directional.length,
  10176. numPointLights: lights.point.length,
  10177. numSpotLights: lights.spot.length,
  10178. numRectAreaLights: lights.rectArea.length,
  10179. numHemiLights: lights.hemi.length,
  10180. numClippingPlanes: nClipPlanes,
  10181. numClipIntersection: nClipIntersection,
  10182. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  10183. shadowMapType: renderer.shadowMap.type,
  10184. toneMapping: renderer.toneMapping,
  10185. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10186. premultipliedAlpha: material.premultipliedAlpha,
  10187. alphaTest: material.alphaTest,
  10188. doubleSided: material.side === DoubleSide,
  10189. flipSided: material.side === BackSide,
  10190. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  10191. };
  10192. return parameters;
  10193. };
  10194. this.getProgramCode = function ( material, parameters ) {
  10195. var array = [];
  10196. if ( parameters.shaderID ) {
  10197. array.push( parameters.shaderID );
  10198. } else {
  10199. array.push( material.fragmentShader );
  10200. array.push( material.vertexShader );
  10201. }
  10202. if ( material.defines !== undefined ) {
  10203. for ( var name in material.defines ) {
  10204. array.push( name );
  10205. array.push( material.defines[ name ] );
  10206. }
  10207. }
  10208. for ( var i = 0; i < parameterNames.length; i ++ ) {
  10209. array.push( parameters[ parameterNames[ i ] ] );
  10210. }
  10211. return array.join();
  10212. };
  10213. this.acquireProgram = function ( material, parameters, code ) {
  10214. var program;
  10215. // Check if code has been already compiled
  10216. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  10217. var programInfo = programs[ p ];
  10218. if ( programInfo.code === code ) {
  10219. program = programInfo;
  10220. ++ program.usedTimes;
  10221. break;
  10222. }
  10223. }
  10224. if ( program === undefined ) {
  10225. program = new WebGLProgram( renderer, code, material, parameters );
  10226. programs.push( program );
  10227. }
  10228. return program;
  10229. };
  10230. this.releaseProgram = function( program ) {
  10231. if ( -- program.usedTimes === 0 ) {
  10232. // Remove from unordered set
  10233. var i = programs.indexOf( program );
  10234. programs[ i ] = programs[ programs.length - 1 ];
  10235. programs.pop();
  10236. // Free WebGL resources
  10237. program.destroy();
  10238. }
  10239. };
  10240. // Exposed for resource monitoring & error feedback via renderer.info:
  10241. this.programs = programs;
  10242. }
  10243. /**
  10244. * @author mrdoob / http://mrdoob.com/
  10245. */
  10246. function WebGLGeometries( gl, properties, info ) {
  10247. var geometries = {};
  10248. function onGeometryDispose( event ) {
  10249. var geometry = event.target;
  10250. var buffergeometry = geometries[ geometry.id ];
  10251. if ( buffergeometry.index !== null ) {
  10252. deleteAttribute( buffergeometry.index );
  10253. }
  10254. deleteAttributes( buffergeometry.attributes );
  10255. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10256. delete geometries[ geometry.id ];
  10257. // TODO
  10258. var property = properties.get( geometry );
  10259. if ( property.wireframe ) {
  10260. deleteAttribute( property.wireframe );
  10261. }
  10262. properties.delete( geometry );
  10263. var bufferproperty = properties.get( buffergeometry );
  10264. if ( bufferproperty.wireframe ) {
  10265. deleteAttribute( bufferproperty.wireframe );
  10266. }
  10267. properties.delete( buffergeometry );
  10268. //
  10269. info.memory.geometries --;
  10270. }
  10271. function getAttributeBuffer( attribute ) {
  10272. if ( attribute.isInterleavedBufferAttribute ) {
  10273. return properties.get( attribute.data ).__webglBuffer;
  10274. }
  10275. return properties.get( attribute ).__webglBuffer;
  10276. }
  10277. function deleteAttribute( attribute ) {
  10278. var buffer = getAttributeBuffer( attribute );
  10279. if ( buffer !== undefined ) {
  10280. gl.deleteBuffer( buffer );
  10281. removeAttributeBuffer( attribute );
  10282. }
  10283. }
  10284. function deleteAttributes( attributes ) {
  10285. for ( var name in attributes ) {
  10286. deleteAttribute( attributes[ name ] );
  10287. }
  10288. }
  10289. function removeAttributeBuffer( attribute ) {
  10290. if ( attribute.isInterleavedBufferAttribute ) {
  10291. properties.delete( attribute.data );
  10292. } else {
  10293. properties.delete( attribute );
  10294. }
  10295. }
  10296. return {
  10297. get: function ( object ) {
  10298. var geometry = object.geometry;
  10299. if ( geometries[ geometry.id ] !== undefined ) {
  10300. return geometries[ geometry.id ];
  10301. }
  10302. geometry.addEventListener( 'dispose', onGeometryDispose );
  10303. var buffergeometry;
  10304. if ( geometry.isBufferGeometry ) {
  10305. buffergeometry = geometry;
  10306. } else if ( geometry.isGeometry ) {
  10307. if ( geometry._bufferGeometry === undefined ) {
  10308. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  10309. }
  10310. buffergeometry = geometry._bufferGeometry;
  10311. }
  10312. geometries[ geometry.id ] = buffergeometry;
  10313. info.memory.geometries ++;
  10314. return buffergeometry;
  10315. }
  10316. };
  10317. }
  10318. /**
  10319. * @author mrdoob / http://mrdoob.com/
  10320. */
  10321. function WebGLObjects( gl, properties, info ) {
  10322. var geometries = new WebGLGeometries( gl, properties, info );
  10323. //
  10324. function update( object ) {
  10325. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  10326. var geometry = geometries.get( object );
  10327. if ( object.geometry.isGeometry ) {
  10328. geometry.updateFromObject( object );
  10329. }
  10330. var index = geometry.index;
  10331. var attributes = geometry.attributes;
  10332. if ( index !== null ) {
  10333. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  10334. }
  10335. for ( var name in attributes ) {
  10336. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  10337. }
  10338. // morph targets
  10339. var morphAttributes = geometry.morphAttributes;
  10340. for ( var name in morphAttributes ) {
  10341. var array = morphAttributes[ name ];
  10342. for ( var i = 0, l = array.length; i < l; i ++ ) {
  10343. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  10344. }
  10345. }
  10346. return geometry;
  10347. }
  10348. function updateAttribute( attribute, bufferType ) {
  10349. var data = ( attribute.isInterleavedBufferAttribute ) ? attribute.data : attribute;
  10350. var attributeProperties = properties.get( data );
  10351. if ( attributeProperties.__webglBuffer === undefined ) {
  10352. createBuffer( attributeProperties, data, bufferType );
  10353. } else if ( attributeProperties.version !== data.version ) {
  10354. updateBuffer( attributeProperties, data, bufferType );
  10355. }
  10356. }
  10357. function createBuffer( attributeProperties, data, bufferType ) {
  10358. attributeProperties.__webglBuffer = gl.createBuffer();
  10359. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  10360. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  10361. gl.bufferData( bufferType, data.array, usage );
  10362. var type = gl.FLOAT;
  10363. var array = data.array;
  10364. if ( array instanceof Float32Array ) {
  10365. type = gl.FLOAT;
  10366. } else if ( array instanceof Float64Array ) {
  10367. console.warn( "Unsupported data buffer format: Float64Array" );
  10368. } else if ( array instanceof Uint16Array ) {
  10369. type = gl.UNSIGNED_SHORT;
  10370. } else if ( array instanceof Int16Array ) {
  10371. type = gl.SHORT;
  10372. } else if ( array instanceof Uint32Array ) {
  10373. type = gl.UNSIGNED_INT;
  10374. } else if ( array instanceof Int32Array ) {
  10375. type = gl.INT;
  10376. } else if ( array instanceof Int8Array ) {
  10377. type = gl.BYTE;
  10378. } else if ( array instanceof Uint8Array ) {
  10379. type = gl.UNSIGNED_BYTE;
  10380. }
  10381. attributeProperties.bytesPerElement = array.BYTES_PER_ELEMENT;
  10382. attributeProperties.type = type;
  10383. attributeProperties.version = data.version;
  10384. data.onUploadCallback();
  10385. }
  10386. function updateBuffer( attributeProperties, data, bufferType ) {
  10387. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  10388. if ( data.dynamic === false ) {
  10389. gl.bufferData( bufferType, data.array, gl.STATIC_DRAW );
  10390. } else if ( data.updateRange.count === - 1 ) {
  10391. // Not using update ranges
  10392. gl.bufferSubData( bufferType, 0, data.array );
  10393. } else if ( data.updateRange.count === 0 ) {
  10394. 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.' );
  10395. } else {
  10396. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  10397. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  10398. data.updateRange.count = 0; // reset range
  10399. }
  10400. attributeProperties.version = data.version;
  10401. }
  10402. function getAttributeBuffer( attribute ) {
  10403. if ( attribute.isInterleavedBufferAttribute ) {
  10404. return properties.get( attribute.data ).__webglBuffer;
  10405. }
  10406. return properties.get( attribute ).__webglBuffer;
  10407. }
  10408. function getAttributeProperties( attribute ) {
  10409. if ( attribute.isInterleavedBufferAttribute ) {
  10410. return properties.get( attribute.data );
  10411. }
  10412. return properties.get( attribute );
  10413. }
  10414. function getWireframeAttribute( geometry ) {
  10415. var property = properties.get( geometry );
  10416. if ( property.wireframe !== undefined ) {
  10417. return property.wireframe;
  10418. }
  10419. var indices = [];
  10420. var index = geometry.index;
  10421. var attributes = geometry.attributes;
  10422. var position = attributes.position;
  10423. // console.time( 'wireframe' );
  10424. if ( index !== null ) {
  10425. var edges = {};
  10426. var array = index.array;
  10427. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  10428. var a = array[ i + 0 ];
  10429. var b = array[ i + 1 ];
  10430. var c = array[ i + 2 ];
  10431. indices.push( a, b, b, c, c, a );
  10432. }
  10433. } else {
  10434. var array = attributes.position.array;
  10435. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10436. var a = i + 0;
  10437. var b = i + 1;
  10438. var c = i + 2;
  10439. indices.push( a, b, b, c, c, a );
  10440. }
  10441. }
  10442. // console.timeEnd( 'wireframe' );
  10443. var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array;
  10444. var attribute = new BufferAttribute( new TypeArray( indices ), 1 );
  10445. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  10446. property.wireframe = attribute;
  10447. return attribute;
  10448. }
  10449. return {
  10450. getAttributeBuffer: getAttributeBuffer,
  10451. getAttributeProperties: getAttributeProperties,
  10452. getWireframeAttribute: getWireframeAttribute,
  10453. update: update
  10454. };
  10455. }
  10456. /**
  10457. * @author mrdoob / http://mrdoob.com/
  10458. */
  10459. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) {
  10460. var _infoMemory = info.memory;
  10461. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  10462. //
  10463. function clampToMaxSize( image, maxSize ) {
  10464. if ( image.width > maxSize || image.height > maxSize ) {
  10465. // Warning: Scaling through the canvas will only work with images that use
  10466. // premultiplied alpha.
  10467. var scale = maxSize / Math.max( image.width, image.height );
  10468. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10469. canvas.width = Math.floor( image.width * scale );
  10470. canvas.height = Math.floor( image.height * scale );
  10471. var context = canvas.getContext( '2d' );
  10472. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  10473. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10474. return canvas;
  10475. }
  10476. return image;
  10477. }
  10478. function isPowerOfTwo( image ) {
  10479. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  10480. }
  10481. function makePowerOfTwo( image ) {
  10482. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  10483. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10484. canvas.width = _Math.nearestPowerOfTwo( image.width );
  10485. canvas.height = _Math.nearestPowerOfTwo( image.height );
  10486. var context = canvas.getContext( '2d' );
  10487. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  10488. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10489. return canvas;
  10490. }
  10491. return image;
  10492. }
  10493. function textureNeedsPowerOfTwo( texture ) {
  10494. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) return true;
  10495. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) return true;
  10496. return false;
  10497. }
  10498. // Fallback filters for non-power-of-2 textures
  10499. function filterFallback( f ) {
  10500. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  10501. return _gl.NEAREST;
  10502. }
  10503. return _gl.LINEAR;
  10504. }
  10505. //
  10506. function onTextureDispose( event ) {
  10507. var texture = event.target;
  10508. texture.removeEventListener( 'dispose', onTextureDispose );
  10509. deallocateTexture( texture );
  10510. _infoMemory.textures --;
  10511. }
  10512. function onRenderTargetDispose( event ) {
  10513. var renderTarget = event.target;
  10514. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10515. deallocateRenderTarget( renderTarget );
  10516. _infoMemory.textures --;
  10517. }
  10518. //
  10519. function deallocateTexture( texture ) {
  10520. var textureProperties = properties.get( texture );
  10521. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  10522. // cube texture
  10523. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  10524. } else {
  10525. // 2D texture
  10526. if ( textureProperties.__webglInit === undefined ) return;
  10527. _gl.deleteTexture( textureProperties.__webglTexture );
  10528. }
  10529. // remove all webgl properties
  10530. properties.delete( texture );
  10531. }
  10532. function deallocateRenderTarget( renderTarget ) {
  10533. var renderTargetProperties = properties.get( renderTarget );
  10534. var textureProperties = properties.get( renderTarget.texture );
  10535. if ( ! renderTarget ) return;
  10536. if ( textureProperties.__webglTexture !== undefined ) {
  10537. _gl.deleteTexture( textureProperties.__webglTexture );
  10538. }
  10539. if ( renderTarget.depthTexture ) {
  10540. renderTarget.depthTexture.dispose();
  10541. }
  10542. if ( renderTarget.isWebGLRenderTargetCube ) {
  10543. for ( var i = 0; i < 6; i ++ ) {
  10544. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  10545. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  10546. }
  10547. } else {
  10548. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  10549. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  10550. }
  10551. properties.delete( renderTarget.texture );
  10552. properties.delete( renderTarget );
  10553. }
  10554. //
  10555. function setTexture2D( texture, slot ) {
  10556. var textureProperties = properties.get( texture );
  10557. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10558. var image = texture.image;
  10559. if ( image === undefined ) {
  10560. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  10561. } else if ( image.complete === false ) {
  10562. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  10563. } else {
  10564. uploadTexture( textureProperties, texture, slot );
  10565. return;
  10566. }
  10567. }
  10568. state.activeTexture( _gl.TEXTURE0 + slot );
  10569. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10570. }
  10571. function setTextureCube( texture, slot ) {
  10572. var textureProperties = properties.get( texture );
  10573. if ( texture.image.length === 6 ) {
  10574. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10575. if ( ! textureProperties.__image__webglTextureCube ) {
  10576. texture.addEventListener( 'dispose', onTextureDispose );
  10577. textureProperties.__image__webglTextureCube = _gl.createTexture();
  10578. _infoMemory.textures ++;
  10579. }
  10580. state.activeTexture( _gl.TEXTURE0 + slot );
  10581. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10582. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10583. var isCompressed = (texture && texture.isCompressedTexture);
  10584. var isDataTexture = (texture.image[ 0 ] && texture.image[ 0 ].isDataTexture);
  10585. var cubeImage = [];
  10586. for ( var i = 0; i < 6; i ++ ) {
  10587. if ( ! isCompressed && ! isDataTexture ) {
  10588. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  10589. } else {
  10590. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  10591. }
  10592. }
  10593. var image = cubeImage[ 0 ],
  10594. isPowerOfTwoImage = isPowerOfTwo( image ),
  10595. glFormat = paramThreeToGL( texture.format ),
  10596. glType = paramThreeToGL( texture.type );
  10597. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  10598. for ( var i = 0; i < 6; i ++ ) {
  10599. if ( ! isCompressed ) {
  10600. if ( isDataTexture ) {
  10601. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  10602. } else {
  10603. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  10604. }
  10605. } else {
  10606. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  10607. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  10608. mipmap = mipmaps[ j ];
  10609. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10610. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10611. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10612. } else {
  10613. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" );
  10614. }
  10615. } else {
  10616. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10617. }
  10618. }
  10619. }
  10620. }
  10621. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  10622. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  10623. }
  10624. textureProperties.__version = texture.version;
  10625. if ( texture.onUpdate ) texture.onUpdate( texture );
  10626. } else {
  10627. state.activeTexture( _gl.TEXTURE0 + slot );
  10628. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10629. }
  10630. }
  10631. }
  10632. function setTextureCubeDynamic( texture, slot ) {
  10633. state.activeTexture( _gl.TEXTURE0 + slot );
  10634. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  10635. }
  10636. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  10637. var extension;
  10638. if ( isPowerOfTwoImage ) {
  10639. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  10640. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  10641. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  10642. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  10643. } else {
  10644. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  10645. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  10646. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  10647. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  10648. }
  10649. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  10650. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  10651. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  10652. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  10653. }
  10654. }
  10655. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  10656. if ( extension ) {
  10657. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  10658. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  10659. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  10660. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  10661. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  10662. }
  10663. }
  10664. }
  10665. function uploadTexture( textureProperties, texture, slot ) {
  10666. if ( textureProperties.__webglInit === undefined ) {
  10667. textureProperties.__webglInit = true;
  10668. texture.addEventListener( 'dispose', onTextureDispose );
  10669. textureProperties.__webglTexture = _gl.createTexture();
  10670. _infoMemory.textures ++;
  10671. }
  10672. state.activeTexture( _gl.TEXTURE0 + slot );
  10673. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10674. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10675. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  10676. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  10677. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  10678. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  10679. image = makePowerOfTwo( image );
  10680. }
  10681. var isPowerOfTwoImage = isPowerOfTwo( image ),
  10682. glFormat = paramThreeToGL( texture.format ),
  10683. glType = paramThreeToGL( texture.type );
  10684. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  10685. var mipmap, mipmaps = texture.mipmaps;
  10686. if ( texture.isDepthTexture ) {
  10687. // populate depth texture with dummy data
  10688. var internalFormat = _gl.DEPTH_COMPONENT;
  10689. if ( texture.type === FloatType ) {
  10690. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  10691. internalFormat = _gl.DEPTH_COMPONENT32F;
  10692. } else if ( _isWebGL2 ) {
  10693. // WebGL 2.0 requires signed internalformat for glTexImage2D
  10694. internalFormat = _gl.DEPTH_COMPONENT16;
  10695. }
  10696. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  10697. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  10698. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  10699. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10700. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  10701. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  10702. texture.type = UnsignedShortType;
  10703. glType = paramThreeToGL( texture.type );
  10704. }
  10705. }
  10706. // Depth stencil textures need the DEPTH_STENCIL internal format
  10707. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10708. if ( texture.format === DepthStencilFormat ) {
  10709. internalFormat = _gl.DEPTH_STENCIL;
  10710. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  10711. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  10712. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10713. if ( texture.type !== UnsignedInt248Type ) {
  10714. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  10715. texture.type = UnsignedInt248Type;
  10716. glType = paramThreeToGL( texture.type );
  10717. }
  10718. }
  10719. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  10720. } else if ( texture.isDataTexture ) {
  10721. // use manually created mipmaps if available
  10722. // if there are no manual mipmaps
  10723. // set 0 level mipmap and then use GL to generate other mipmap levels
  10724. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10725. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10726. mipmap = mipmaps[ i ];
  10727. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10728. }
  10729. texture.generateMipmaps = false;
  10730. } else {
  10731. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  10732. }
  10733. } else if ( texture.isCompressedTexture ) {
  10734. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10735. mipmap = mipmaps[ i ];
  10736. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10737. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10738. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10739. } else {
  10740. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  10741. }
  10742. } else {
  10743. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10744. }
  10745. }
  10746. } else {
  10747. // regular Texture (image, video, canvas)
  10748. // use manually created mipmaps if available
  10749. // if there are no manual mipmaps
  10750. // set 0 level mipmap and then use GL to generate other mipmap levels
  10751. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10752. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10753. mipmap = mipmaps[ i ];
  10754. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  10755. }
  10756. texture.generateMipmaps = false;
  10757. } else {
  10758. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  10759. }
  10760. }
  10761. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  10762. textureProperties.__version = texture.version;
  10763. if ( texture.onUpdate ) texture.onUpdate( texture );
  10764. }
  10765. // Render targets
  10766. // Setup storage for target texture and bind it to correct framebuffer
  10767. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  10768. var glFormat = paramThreeToGL( renderTarget.texture.format );
  10769. var glType = paramThreeToGL( renderTarget.texture.type );
  10770. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  10771. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10772. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  10773. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  10774. }
  10775. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  10776. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  10777. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  10778. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  10779. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  10780. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10781. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  10782. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  10783. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10784. } else {
  10785. // FIXME: We don't support !depth !stencil
  10786. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  10787. }
  10788. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  10789. }
  10790. // Setup resources for a Depth Texture for a FBO (needs an extension)
  10791. function setupDepthTexture( framebuffer, renderTarget ) {
  10792. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  10793. if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');
  10794. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10795. if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  10796. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  10797. }
  10798. // upload an empty depth texture with framebuffer size
  10799. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  10800. renderTarget.depthTexture.image.width !== renderTarget.width ||
  10801. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  10802. renderTarget.depthTexture.image.width = renderTarget.width;
  10803. renderTarget.depthTexture.image.height = renderTarget.height;
  10804. renderTarget.depthTexture.needsUpdate = true;
  10805. }
  10806. setTexture2D( renderTarget.depthTexture, 0 );
  10807. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  10808. if ( renderTarget.depthTexture.format === DepthFormat ) {
  10809. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  10810. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  10811. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  10812. } else {
  10813. throw new Error('Unknown depthTexture format')
  10814. }
  10815. }
  10816. // Setup GL resources for a non-texture depth buffer
  10817. function setupDepthRenderbuffer( renderTarget ) {
  10818. var renderTargetProperties = properties.get( renderTarget );
  10819. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  10820. if ( renderTarget.depthTexture ) {
  10821. if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
  10822. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  10823. } else {
  10824. if ( isCube ) {
  10825. renderTargetProperties.__webglDepthbuffer = [];
  10826. for ( var i = 0; i < 6; i ++ ) {
  10827. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  10828. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  10829. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  10830. }
  10831. } else {
  10832. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  10833. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  10834. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  10835. }
  10836. }
  10837. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  10838. }
  10839. // Set up GL resources for the render target
  10840. function setupRenderTarget( renderTarget ) {
  10841. var renderTargetProperties = properties.get( renderTarget );
  10842. var textureProperties = properties.get( renderTarget.texture );
  10843. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  10844. textureProperties.__webglTexture = _gl.createTexture();
  10845. _infoMemory.textures ++;
  10846. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  10847. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  10848. // Setup framebuffer
  10849. if ( isCube ) {
  10850. renderTargetProperties.__webglFramebuffer = [];
  10851. for ( var i = 0; i < 6; i ++ ) {
  10852. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  10853. }
  10854. } else {
  10855. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  10856. }
  10857. // Setup color buffer
  10858. if ( isCube ) {
  10859. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  10860. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  10861. for ( var i = 0; i < 6; i ++ ) {
  10862. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  10863. }
  10864. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  10865. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  10866. } else {
  10867. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10868. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  10869. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  10870. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  10871. state.bindTexture( _gl.TEXTURE_2D, null );
  10872. }
  10873. // Setup depth and stencil buffers
  10874. if ( renderTarget.depthBuffer ) {
  10875. setupDepthRenderbuffer( renderTarget );
  10876. }
  10877. }
  10878. function updateRenderTargetMipmap( renderTarget ) {
  10879. var texture = renderTarget.texture;
  10880. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  10881. texture.minFilter !== NearestFilter &&
  10882. texture.minFilter !== LinearFilter ) {
  10883. var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  10884. var webglTexture = properties.get( texture ).__webglTexture;
  10885. state.bindTexture( target, webglTexture );
  10886. _gl.generateMipmap( target );
  10887. state.bindTexture( target, null );
  10888. }
  10889. }
  10890. this.setTexture2D = setTexture2D;
  10891. this.setTextureCube = setTextureCube;
  10892. this.setTextureCubeDynamic = setTextureCubeDynamic;
  10893. this.setupRenderTarget = setupRenderTarget;
  10894. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  10895. }
  10896. /**
  10897. * @author fordacious / fordacious.github.io
  10898. */
  10899. function WebGLProperties() {
  10900. var properties = {};
  10901. return {
  10902. get: function ( object ) {
  10903. var uuid = object.uuid;
  10904. var map = properties[ uuid ];
  10905. if ( map === undefined ) {
  10906. map = {};
  10907. properties[ uuid ] = map;
  10908. }
  10909. return map;
  10910. },
  10911. delete: function ( object ) {
  10912. delete properties[ object.uuid ];
  10913. },
  10914. clear: function () {
  10915. properties = {};
  10916. }
  10917. };
  10918. }
  10919. /**
  10920. * @author mrdoob / http://mrdoob.com/
  10921. */
  10922. function WebGLState( gl, extensions, paramThreeToGL ) {
  10923. function ColorBuffer() {
  10924. var locked = false;
  10925. var color = new Vector4();
  10926. var currentColorMask = null;
  10927. var currentColorClear = new Vector4();
  10928. return {
  10929. setMask: function ( colorMask ) {
  10930. if ( currentColorMask !== colorMask && ! locked ) {
  10931. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  10932. currentColorMask = colorMask;
  10933. }
  10934. },
  10935. setLocked: function ( lock ) {
  10936. locked = lock;
  10937. },
  10938. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  10939. if ( premultipliedAlpha === true ) {
  10940. r *= a; g *= a; b *= a;
  10941. }
  10942. color.set( r, g, b, a );
  10943. if ( currentColorClear.equals( color ) === false ) {
  10944. gl.clearColor( r, g, b, a );
  10945. currentColorClear.copy( color );
  10946. }
  10947. },
  10948. reset: function () {
  10949. locked = false;
  10950. currentColorMask = null;
  10951. currentColorClear.set( 0, 0, 0, 1 );
  10952. }
  10953. };
  10954. }
  10955. function DepthBuffer() {
  10956. var locked = false;
  10957. var currentDepthMask = null;
  10958. var currentDepthFunc = null;
  10959. var currentDepthClear = null;
  10960. return {
  10961. setTest: function ( depthTest ) {
  10962. if ( depthTest ) {
  10963. enable( gl.DEPTH_TEST );
  10964. } else {
  10965. disable( gl.DEPTH_TEST );
  10966. }
  10967. },
  10968. setMask: function ( depthMask ) {
  10969. if ( currentDepthMask !== depthMask && ! locked ) {
  10970. gl.depthMask( depthMask );
  10971. currentDepthMask = depthMask;
  10972. }
  10973. },
  10974. setFunc: function ( depthFunc ) {
  10975. if ( currentDepthFunc !== depthFunc ) {
  10976. if ( depthFunc ) {
  10977. switch ( depthFunc ) {
  10978. case NeverDepth:
  10979. gl.depthFunc( gl.NEVER );
  10980. break;
  10981. case AlwaysDepth:
  10982. gl.depthFunc( gl.ALWAYS );
  10983. break;
  10984. case LessDepth:
  10985. gl.depthFunc( gl.LESS );
  10986. break;
  10987. case LessEqualDepth:
  10988. gl.depthFunc( gl.LEQUAL );
  10989. break;
  10990. case EqualDepth:
  10991. gl.depthFunc( gl.EQUAL );
  10992. break;
  10993. case GreaterEqualDepth:
  10994. gl.depthFunc( gl.GEQUAL );
  10995. break;
  10996. case GreaterDepth:
  10997. gl.depthFunc( gl.GREATER );
  10998. break;
  10999. case NotEqualDepth:
  11000. gl.depthFunc( gl.NOTEQUAL );
  11001. break;
  11002. default:
  11003. gl.depthFunc( gl.LEQUAL );
  11004. }
  11005. } else {
  11006. gl.depthFunc( gl.LEQUAL );
  11007. }
  11008. currentDepthFunc = depthFunc;
  11009. }
  11010. },
  11011. setLocked: function ( lock ) {
  11012. locked = lock;
  11013. },
  11014. setClear: function ( depth ) {
  11015. if ( currentDepthClear !== depth ) {
  11016. gl.clearDepth( depth );
  11017. currentDepthClear = depth;
  11018. }
  11019. },
  11020. reset: function () {
  11021. locked = false;
  11022. currentDepthMask = null;
  11023. currentDepthFunc = null;
  11024. currentDepthClear = null;
  11025. }
  11026. };
  11027. }
  11028. function StencilBuffer() {
  11029. var locked = false;
  11030. var currentStencilMask = null;
  11031. var currentStencilFunc = null;
  11032. var currentStencilRef = null;
  11033. var currentStencilFuncMask = null;
  11034. var currentStencilFail = null;
  11035. var currentStencilZFail = null;
  11036. var currentStencilZPass = null;
  11037. var currentStencilClear = null;
  11038. return {
  11039. setTest: function ( stencilTest ) {
  11040. if ( stencilTest ) {
  11041. enable( gl.STENCIL_TEST );
  11042. } else {
  11043. disable( gl.STENCIL_TEST );
  11044. }
  11045. },
  11046. setMask: function ( stencilMask ) {
  11047. if ( currentStencilMask !== stencilMask && ! locked ) {
  11048. gl.stencilMask( stencilMask );
  11049. currentStencilMask = stencilMask;
  11050. }
  11051. },
  11052. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  11053. if ( currentStencilFunc !== stencilFunc ||
  11054. currentStencilRef !== stencilRef ||
  11055. currentStencilFuncMask !== stencilMask ) {
  11056. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  11057. currentStencilFunc = stencilFunc;
  11058. currentStencilRef = stencilRef;
  11059. currentStencilFuncMask = stencilMask;
  11060. }
  11061. },
  11062. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  11063. if ( currentStencilFail !== stencilFail ||
  11064. currentStencilZFail !== stencilZFail ||
  11065. currentStencilZPass !== stencilZPass ) {
  11066. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  11067. currentStencilFail = stencilFail;
  11068. currentStencilZFail = stencilZFail;
  11069. currentStencilZPass = stencilZPass;
  11070. }
  11071. },
  11072. setLocked: function ( lock ) {
  11073. locked = lock;
  11074. },
  11075. setClear: function ( stencil ) {
  11076. if ( currentStencilClear !== stencil ) {
  11077. gl.clearStencil( stencil );
  11078. currentStencilClear = stencil;
  11079. }
  11080. },
  11081. reset: function () {
  11082. locked = false;
  11083. currentStencilMask = null;
  11084. currentStencilFunc = null;
  11085. currentStencilRef = null;
  11086. currentStencilFuncMask = null;
  11087. currentStencilFail = null;
  11088. currentStencilZFail = null;
  11089. currentStencilZPass = null;
  11090. currentStencilClear = null;
  11091. }
  11092. };
  11093. }
  11094. //
  11095. var colorBuffer = new ColorBuffer();
  11096. var depthBuffer = new DepthBuffer();
  11097. var stencilBuffer = new StencilBuffer();
  11098. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11099. var newAttributes = new Uint8Array( maxVertexAttributes );
  11100. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  11101. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  11102. var capabilities = {};
  11103. var compressedTextureFormats = null;
  11104. var currentBlending = null;
  11105. var currentBlendEquation = null;
  11106. var currentBlendSrc = null;
  11107. var currentBlendDst = null;
  11108. var currentBlendEquationAlpha = null;
  11109. var currentBlendSrcAlpha = null;
  11110. var currentBlendDstAlpha = null;
  11111. var currentPremultipledAlpha = false;
  11112. var currentFlipSided = null;
  11113. var currentCullFace = null;
  11114. var currentLineWidth = null;
  11115. var currentPolygonOffsetFactor = null;
  11116. var currentPolygonOffsetUnits = null;
  11117. var currentScissorTest = null;
  11118. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  11119. var currentTextureSlot = null;
  11120. var currentBoundTextures = {};
  11121. var currentScissor = new Vector4();
  11122. var currentViewport = new Vector4();
  11123. function createTexture( type, target, count ) {
  11124. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  11125. var texture = gl.createTexture();
  11126. gl.bindTexture( type, texture );
  11127. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  11128. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  11129. for ( var i = 0; i < count; i ++ ) {
  11130. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  11131. }
  11132. return texture;
  11133. }
  11134. var emptyTextures = {};
  11135. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  11136. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  11137. //
  11138. function init() {
  11139. colorBuffer.setClear( 0, 0, 0, 1 );
  11140. depthBuffer.setClear( 1 );
  11141. stencilBuffer.setClear( 0 );
  11142. enable( gl.DEPTH_TEST );
  11143. setDepthFunc( LessEqualDepth );
  11144. setFlipSided( false );
  11145. setCullFace( CullFaceBack );
  11146. enable( gl.CULL_FACE );
  11147. enable( gl.BLEND );
  11148. setBlending( NormalBlending );
  11149. }
  11150. function initAttributes() {
  11151. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  11152. newAttributes[ i ] = 0;
  11153. }
  11154. }
  11155. function enableAttribute( attribute ) {
  11156. newAttributes[ attribute ] = 1;
  11157. if ( enabledAttributes[ attribute ] === 0 ) {
  11158. gl.enableVertexAttribArray( attribute );
  11159. enabledAttributes[ attribute ] = 1;
  11160. }
  11161. if ( attributeDivisors[ attribute ] !== 0 ) {
  11162. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11163. extension.vertexAttribDivisorANGLE( attribute, 0 );
  11164. attributeDivisors[ attribute ] = 0;
  11165. }
  11166. }
  11167. function enableAttributeAndDivisor( attribute, meshPerAttribute, extension ) {
  11168. newAttributes[ attribute ] = 1;
  11169. if ( enabledAttributes[ attribute ] === 0 ) {
  11170. gl.enableVertexAttribArray( attribute );
  11171. enabledAttributes[ attribute ] = 1;
  11172. }
  11173. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  11174. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  11175. attributeDivisors[ attribute ] = meshPerAttribute;
  11176. }
  11177. }
  11178. function disableUnusedAttributes() {
  11179. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  11180. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  11181. gl.disableVertexAttribArray( i );
  11182. enabledAttributes[ i ] = 0;
  11183. }
  11184. }
  11185. }
  11186. function enable( id ) {
  11187. if ( capabilities[ id ] !== true ) {
  11188. gl.enable( id );
  11189. capabilities[ id ] = true;
  11190. }
  11191. }
  11192. function disable( id ) {
  11193. if ( capabilities[ id ] !== false ) {
  11194. gl.disable( id );
  11195. capabilities[ id ] = false;
  11196. }
  11197. }
  11198. function getCompressedTextureFormats() {
  11199. if ( compressedTextureFormats === null ) {
  11200. compressedTextureFormats = [];
  11201. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  11202. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  11203. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  11204. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  11205. for ( var i = 0; i < formats.length; i ++ ) {
  11206. compressedTextureFormats.push( formats[ i ] );
  11207. }
  11208. }
  11209. }
  11210. return compressedTextureFormats;
  11211. }
  11212. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11213. if ( blending !== NoBlending ) {
  11214. enable( gl.BLEND );
  11215. } else {
  11216. disable( gl.BLEND );
  11217. }
  11218. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  11219. if ( blending === AdditiveBlending ) {
  11220. if ( premultipliedAlpha ) {
  11221. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11222. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  11223. } else {
  11224. gl.blendEquation( gl.FUNC_ADD );
  11225. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  11226. }
  11227. } else if ( blending === SubtractiveBlending ) {
  11228. if ( premultipliedAlpha ) {
  11229. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11230. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  11231. } else {
  11232. gl.blendEquation( gl.FUNC_ADD );
  11233. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  11234. }
  11235. } else if ( blending === MultiplyBlending ) {
  11236. if ( premultipliedAlpha ) {
  11237. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11238. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  11239. } else {
  11240. gl.blendEquation( gl.FUNC_ADD );
  11241. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  11242. }
  11243. } else {
  11244. if ( premultipliedAlpha ) {
  11245. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11246. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11247. } else {
  11248. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11249. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11250. }
  11251. }
  11252. currentBlending = blending;
  11253. currentPremultipledAlpha = premultipliedAlpha;
  11254. }
  11255. if ( blending === CustomBlending ) {
  11256. blendEquationAlpha = blendEquationAlpha || blendEquation;
  11257. blendSrcAlpha = blendSrcAlpha || blendSrc;
  11258. blendDstAlpha = blendDstAlpha || blendDst;
  11259. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  11260. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  11261. currentBlendEquation = blendEquation;
  11262. currentBlendEquationAlpha = blendEquationAlpha;
  11263. }
  11264. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  11265. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  11266. currentBlendSrc = blendSrc;
  11267. currentBlendDst = blendDst;
  11268. currentBlendSrcAlpha = blendSrcAlpha;
  11269. currentBlendDstAlpha = blendDstAlpha;
  11270. }
  11271. } else {
  11272. currentBlendEquation = null;
  11273. currentBlendSrc = null;
  11274. currentBlendDst = null;
  11275. currentBlendEquationAlpha = null;
  11276. currentBlendSrcAlpha = null;
  11277. currentBlendDstAlpha = null;
  11278. }
  11279. }
  11280. // TODO Deprecate
  11281. function setColorWrite( colorWrite ) {
  11282. colorBuffer.setMask( colorWrite );
  11283. }
  11284. function setDepthTest( depthTest ) {
  11285. depthBuffer.setTest( depthTest );
  11286. }
  11287. function setDepthWrite( depthWrite ) {
  11288. depthBuffer.setMask( depthWrite );
  11289. }
  11290. function setDepthFunc( depthFunc ) {
  11291. depthBuffer.setFunc( depthFunc );
  11292. }
  11293. function setStencilTest( stencilTest ) {
  11294. stencilBuffer.setTest( stencilTest );
  11295. }
  11296. function setStencilWrite( stencilWrite ) {
  11297. stencilBuffer.setMask( stencilWrite );
  11298. }
  11299. function setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  11300. stencilBuffer.setFunc( stencilFunc, stencilRef, stencilMask );
  11301. }
  11302. function setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  11303. stencilBuffer.setOp( stencilFail, stencilZFail, stencilZPass );
  11304. }
  11305. //
  11306. function setFlipSided( flipSided ) {
  11307. if ( currentFlipSided !== flipSided ) {
  11308. if ( flipSided ) {
  11309. gl.frontFace( gl.CW );
  11310. } else {
  11311. gl.frontFace( gl.CCW );
  11312. }
  11313. currentFlipSided = flipSided;
  11314. }
  11315. }
  11316. function setCullFace( cullFace ) {
  11317. if ( cullFace !== CullFaceNone ) {
  11318. enable( gl.CULL_FACE );
  11319. if ( cullFace !== currentCullFace ) {
  11320. if ( cullFace === CullFaceBack ) {
  11321. gl.cullFace( gl.BACK );
  11322. } else if ( cullFace === CullFaceFront ) {
  11323. gl.cullFace( gl.FRONT );
  11324. } else {
  11325. gl.cullFace( gl.FRONT_AND_BACK );
  11326. }
  11327. }
  11328. } else {
  11329. disable( gl.CULL_FACE );
  11330. }
  11331. currentCullFace = cullFace;
  11332. }
  11333. function setLineWidth( width ) {
  11334. if ( width !== currentLineWidth ) {
  11335. gl.lineWidth( width );
  11336. currentLineWidth = width;
  11337. }
  11338. }
  11339. function setPolygonOffset( polygonOffset, factor, units ) {
  11340. if ( polygonOffset ) {
  11341. enable( gl.POLYGON_OFFSET_FILL );
  11342. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  11343. gl.polygonOffset( factor, units );
  11344. currentPolygonOffsetFactor = factor;
  11345. currentPolygonOffsetUnits = units;
  11346. }
  11347. } else {
  11348. disable( gl.POLYGON_OFFSET_FILL );
  11349. }
  11350. }
  11351. function getScissorTest() {
  11352. return currentScissorTest;
  11353. }
  11354. function setScissorTest( scissorTest ) {
  11355. currentScissorTest = scissorTest;
  11356. if ( scissorTest ) {
  11357. enable( gl.SCISSOR_TEST );
  11358. } else {
  11359. disable( gl.SCISSOR_TEST );
  11360. }
  11361. }
  11362. // texture
  11363. function activeTexture( webglSlot ) {
  11364. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  11365. if ( currentTextureSlot !== webglSlot ) {
  11366. gl.activeTexture( webglSlot );
  11367. currentTextureSlot = webglSlot;
  11368. }
  11369. }
  11370. function bindTexture( webglType, webglTexture ) {
  11371. if ( currentTextureSlot === null ) {
  11372. activeTexture();
  11373. }
  11374. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  11375. if ( boundTexture === undefined ) {
  11376. boundTexture = { type: undefined, texture: undefined };
  11377. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  11378. }
  11379. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  11380. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  11381. boundTexture.type = webglType;
  11382. boundTexture.texture = webglTexture;
  11383. }
  11384. }
  11385. function compressedTexImage2D() {
  11386. try {
  11387. gl.compressedTexImage2D.apply( gl, arguments );
  11388. } catch ( error ) {
  11389. console.error( error );
  11390. }
  11391. }
  11392. function texImage2D() {
  11393. try {
  11394. gl.texImage2D.apply( gl, arguments );
  11395. } catch ( error ) {
  11396. console.error( error );
  11397. }
  11398. }
  11399. //
  11400. function scissor( scissor ) {
  11401. if ( currentScissor.equals( scissor ) === false ) {
  11402. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  11403. currentScissor.copy( scissor );
  11404. }
  11405. }
  11406. function viewport( viewport ) {
  11407. if ( currentViewport.equals( viewport ) === false ) {
  11408. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  11409. currentViewport.copy( viewport );
  11410. }
  11411. }
  11412. //
  11413. function reset() {
  11414. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  11415. if ( enabledAttributes[ i ] === 1 ) {
  11416. gl.disableVertexAttribArray( i );
  11417. enabledAttributes[ i ] = 0;
  11418. }
  11419. }
  11420. capabilities = {};
  11421. compressedTextureFormats = null;
  11422. currentTextureSlot = null;
  11423. currentBoundTextures = {};
  11424. currentBlending = null;
  11425. currentFlipSided = null;
  11426. currentCullFace = null;
  11427. colorBuffer.reset();
  11428. depthBuffer.reset();
  11429. stencilBuffer.reset();
  11430. }
  11431. return {
  11432. buffers: {
  11433. color: colorBuffer,
  11434. depth: depthBuffer,
  11435. stencil: stencilBuffer
  11436. },
  11437. init: init,
  11438. initAttributes: initAttributes,
  11439. enableAttribute: enableAttribute,
  11440. enableAttributeAndDivisor: enableAttributeAndDivisor,
  11441. disableUnusedAttributes: disableUnusedAttributes,
  11442. enable: enable,
  11443. disable: disable,
  11444. getCompressedTextureFormats: getCompressedTextureFormats,
  11445. setBlending: setBlending,
  11446. setColorWrite: setColorWrite,
  11447. setDepthTest: setDepthTest,
  11448. setDepthWrite: setDepthWrite,
  11449. setDepthFunc: setDepthFunc,
  11450. setStencilTest: setStencilTest,
  11451. setStencilWrite: setStencilWrite,
  11452. setStencilFunc: setStencilFunc,
  11453. setStencilOp: setStencilOp,
  11454. setFlipSided: setFlipSided,
  11455. setCullFace: setCullFace,
  11456. setLineWidth: setLineWidth,
  11457. setPolygonOffset: setPolygonOffset,
  11458. getScissorTest: getScissorTest,
  11459. setScissorTest: setScissorTest,
  11460. activeTexture: activeTexture,
  11461. bindTexture: bindTexture,
  11462. compressedTexImage2D: compressedTexImage2D,
  11463. texImage2D: texImage2D,
  11464. scissor: scissor,
  11465. viewport: viewport,
  11466. reset: reset
  11467. };
  11468. }
  11469. /**
  11470. * @author mrdoob / http://mrdoob.com/
  11471. */
  11472. function WebGLCapabilities( gl, extensions, parameters ) {
  11473. var maxAnisotropy;
  11474. function getMaxAnisotropy() {
  11475. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  11476. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  11477. if ( extension !== null ) {
  11478. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  11479. } else {
  11480. maxAnisotropy = 0;
  11481. }
  11482. return maxAnisotropy;
  11483. }
  11484. function getMaxPrecision( precision ) {
  11485. if ( precision === 'highp' ) {
  11486. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  11487. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  11488. return 'highp';
  11489. }
  11490. precision = 'mediump';
  11491. }
  11492. if ( precision === 'mediump' ) {
  11493. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  11494. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  11495. return 'mediump';
  11496. }
  11497. }
  11498. return 'lowp';
  11499. }
  11500. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  11501. var maxPrecision = getMaxPrecision( precision );
  11502. if ( maxPrecision !== precision ) {
  11503. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  11504. precision = maxPrecision;
  11505. }
  11506. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  11507. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  11508. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11509. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  11510. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11511. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11512. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  11513. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  11514. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  11515. var vertexTextures = maxVertexTextures > 0;
  11516. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  11517. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  11518. return {
  11519. getMaxAnisotropy: getMaxAnisotropy,
  11520. getMaxPrecision: getMaxPrecision,
  11521. precision: precision,
  11522. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11523. maxTextures: maxTextures,
  11524. maxVertexTextures: maxVertexTextures,
  11525. maxTextureSize: maxTextureSize,
  11526. maxCubemapSize: maxCubemapSize,
  11527. maxAttributes: maxAttributes,
  11528. maxVertexUniforms: maxVertexUniforms,
  11529. maxVaryings: maxVaryings,
  11530. maxFragmentUniforms: maxFragmentUniforms,
  11531. vertexTextures: vertexTextures,
  11532. floatFragmentTextures: floatFragmentTextures,
  11533. floatVertexTextures: floatVertexTextures
  11534. };
  11535. }
  11536. /**
  11537. * @author mrdoob / http://mrdoob.com/
  11538. */
  11539. function WebGLExtensions( gl ) {
  11540. var extensions = {};
  11541. return {
  11542. get: function ( name ) {
  11543. if ( extensions[ name ] !== undefined ) {
  11544. return extensions[ name ];
  11545. }
  11546. var extension;
  11547. switch ( name ) {
  11548. case 'WEBGL_depth_texture':
  11549. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  11550. break;
  11551. case 'EXT_texture_filter_anisotropic':
  11552. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  11553. break;
  11554. case 'WEBGL_compressed_texture_s3tc':
  11555. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  11556. break;
  11557. case 'WEBGL_compressed_texture_pvrtc':
  11558. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  11559. break;
  11560. case 'WEBGL_compressed_texture_etc1':
  11561. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  11562. break;
  11563. default:
  11564. extension = gl.getExtension( name );
  11565. }
  11566. if ( extension === null ) {
  11567. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  11568. }
  11569. extensions[ name ] = extension;
  11570. return extension;
  11571. }
  11572. };
  11573. }
  11574. /**
  11575. * @author tschw
  11576. */
  11577. function WebGLClipping() {
  11578. var scope = this,
  11579. globalState = null,
  11580. numGlobalPlanes = 0,
  11581. localClippingEnabled = false,
  11582. renderingShadows = false,
  11583. plane = new Plane(),
  11584. viewNormalMatrix = new Matrix3(),
  11585. uniform = { value: null, needsUpdate: false };
  11586. this.uniform = uniform;
  11587. this.numPlanes = 0;
  11588. this.numIntersection = 0;
  11589. this.init = function( planes, enableLocalClipping, camera ) {
  11590. var enabled =
  11591. planes.length !== 0 ||
  11592. enableLocalClipping ||
  11593. // enable state of previous frame - the clipping code has to
  11594. // run another frame in order to reset the state:
  11595. numGlobalPlanes !== 0 ||
  11596. localClippingEnabled;
  11597. localClippingEnabled = enableLocalClipping;
  11598. globalState = projectPlanes( planes, camera, 0 );
  11599. numGlobalPlanes = planes.length;
  11600. return enabled;
  11601. };
  11602. this.beginShadows = function() {
  11603. renderingShadows = true;
  11604. projectPlanes( null );
  11605. };
  11606. this.endShadows = function() {
  11607. renderingShadows = false;
  11608. resetGlobalState();
  11609. };
  11610. this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  11611. if ( ! localClippingEnabled ||
  11612. planes === null || planes.length === 0 ||
  11613. renderingShadows && ! clipShadows ) {
  11614. // there's no local clipping
  11615. if ( renderingShadows ) {
  11616. // there's no global clipping
  11617. projectPlanes( null );
  11618. } else {
  11619. resetGlobalState();
  11620. }
  11621. } else {
  11622. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  11623. lGlobal = nGlobal * 4,
  11624. dstArray = cache.clippingState || null;
  11625. uniform.value = dstArray; // ensure unique state
  11626. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  11627. for ( var i = 0; i !== lGlobal; ++ i ) {
  11628. dstArray[ i ] = globalState[ i ];
  11629. }
  11630. cache.clippingState = dstArray;
  11631. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  11632. this.numPlanes += nGlobal;
  11633. }
  11634. };
  11635. function resetGlobalState() {
  11636. if ( uniform.value !== globalState ) {
  11637. uniform.value = globalState;
  11638. uniform.needsUpdate = numGlobalPlanes > 0;
  11639. }
  11640. scope.numPlanes = numGlobalPlanes;
  11641. scope.numIntersection = 0;
  11642. }
  11643. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  11644. var nPlanes = planes !== null ? planes.length : 0,
  11645. dstArray = null;
  11646. if ( nPlanes !== 0 ) {
  11647. dstArray = uniform.value;
  11648. if ( skipTransform !== true || dstArray === null ) {
  11649. var flatSize = dstOffset + nPlanes * 4,
  11650. viewMatrix = camera.matrixWorldInverse;
  11651. viewNormalMatrix.getNormalMatrix( viewMatrix );
  11652. if ( dstArray === null || dstArray.length < flatSize ) {
  11653. dstArray = new Float32Array( flatSize );
  11654. }
  11655. for ( var i = 0, i4 = dstOffset;
  11656. i !== nPlanes; ++ i, i4 += 4 ) {
  11657. plane.copy( planes[ i ] ).
  11658. applyMatrix4( viewMatrix, viewNormalMatrix );
  11659. plane.normal.toArray( dstArray, i4 );
  11660. dstArray[ i4 + 3 ] = plane.constant;
  11661. }
  11662. }
  11663. uniform.value = dstArray;
  11664. uniform.needsUpdate = true;
  11665. }
  11666. scope.numPlanes = nPlanes;
  11667. return dstArray;
  11668. }
  11669. }
  11670. /**
  11671. * @author supereggbert / http://www.paulbrunt.co.uk/
  11672. * @author mrdoob / http://mrdoob.com/
  11673. * @author alteredq / http://alteredqualia.com/
  11674. * @author szimek / https://github.com/szimek/
  11675. * @author tschw
  11676. */
  11677. function WebGLRenderer( parameters ) {
  11678. console.log( 'THREE.WebGLRenderer', REVISION );
  11679. parameters = parameters || {};
  11680. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  11681. _context = parameters.context !== undefined ? parameters.context : null,
  11682. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11683. _depth = parameters.depth !== undefined ? parameters.depth : true,
  11684. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11685. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11686. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11687. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  11688. var lights = [];
  11689. var opaqueObjects = [];
  11690. var opaqueObjectsLastIndex = - 1;
  11691. var transparentObjects = [];
  11692. var transparentObjectsLastIndex = - 1;
  11693. var morphInfluences = new Float32Array( 8 );
  11694. var sprites = [];
  11695. var lensFlares = [];
  11696. // public properties
  11697. this.domElement = _canvas;
  11698. this.context = null;
  11699. // clearing
  11700. this.autoClear = true;
  11701. this.autoClearColor = true;
  11702. this.autoClearDepth = true;
  11703. this.autoClearStencil = true;
  11704. // scene graph
  11705. this.sortObjects = true;
  11706. // user-defined clipping
  11707. this.clippingPlanes = [];
  11708. this.localClippingEnabled = false;
  11709. // physically based shading
  11710. this.gammaFactor = 2.0; // for backwards compatibility
  11711. this.gammaInput = false;
  11712. this.gammaOutput = false;
  11713. // physical lights
  11714. this.physicallyCorrectLights = false;
  11715. // tone mapping
  11716. this.toneMapping = LinearToneMapping;
  11717. this.toneMappingExposure = 1.0;
  11718. this.toneMappingWhitePoint = 1.0;
  11719. // morphs
  11720. this.maxMorphTargets = 8;
  11721. this.maxMorphNormals = 4;
  11722. // internal properties
  11723. var _this = this,
  11724. // internal state cache
  11725. _currentProgram = null,
  11726. _currentRenderTarget = null,
  11727. _currentFramebuffer = null,
  11728. _currentMaterialId = - 1,
  11729. _currentGeometryProgram = '',
  11730. _currentCamera = null,
  11731. _currentScissor = new Vector4(),
  11732. _currentScissorTest = null,
  11733. _currentViewport = new Vector4(),
  11734. //
  11735. _usedTextureUnits = 0,
  11736. //
  11737. _clearColor = new Color( 0x000000 ),
  11738. _clearAlpha = 0,
  11739. _width = _canvas.width,
  11740. _height = _canvas.height,
  11741. _pixelRatio = 1,
  11742. _scissor = new Vector4( 0, 0, _width, _height ),
  11743. _scissorTest = false,
  11744. _viewport = new Vector4( 0, 0, _width, _height ),
  11745. // frustum
  11746. _frustum = new Frustum(),
  11747. // clipping
  11748. _clipping = new WebGLClipping(),
  11749. _clippingEnabled = false,
  11750. _localClippingEnabled = false,
  11751. _sphere = new Sphere(),
  11752. // camera matrices cache
  11753. _projScreenMatrix = new Matrix4(),
  11754. _vector3 = new Vector3(),
  11755. _matrix4 = new Matrix4(),
  11756. _matrix42 = new Matrix4(),
  11757. // light arrays cache
  11758. _lights = {
  11759. hash: '',
  11760. ambient: [ 0, 0, 0 ],
  11761. directional: [],
  11762. directionalShadowMap: [],
  11763. directionalShadowMatrix: [],
  11764. spot: [],
  11765. spotShadowMap: [],
  11766. spotShadowMatrix: [],
  11767. rectArea: [],
  11768. point: [],
  11769. pointShadowMap: [],
  11770. pointShadowMatrix: [],
  11771. hemi: [],
  11772. shadows: []
  11773. },
  11774. // info
  11775. _infoRender = {
  11776. calls: 0,
  11777. vertices: 0,
  11778. faces: 0,
  11779. points: 0
  11780. };
  11781. this.info = {
  11782. render: _infoRender,
  11783. memory: {
  11784. geometries: 0,
  11785. textures: 0
  11786. },
  11787. programs: null
  11788. };
  11789. // initialize
  11790. var _gl;
  11791. try {
  11792. var attributes = {
  11793. alpha: _alpha,
  11794. depth: _depth,
  11795. stencil: _stencil,
  11796. antialias: _antialias,
  11797. premultipliedAlpha: _premultipliedAlpha,
  11798. preserveDrawingBuffer: _preserveDrawingBuffer
  11799. };
  11800. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  11801. if ( _gl === null ) {
  11802. if ( _canvas.getContext( 'webgl' ) !== null ) {
  11803. throw 'Error creating WebGL context with your selected attributes.';
  11804. } else {
  11805. throw 'Error creating WebGL context.';
  11806. }
  11807. }
  11808. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  11809. if ( _gl.getShaderPrecisionFormat === undefined ) {
  11810. _gl.getShaderPrecisionFormat = function () {
  11811. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  11812. };
  11813. }
  11814. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  11815. } catch ( error ) {
  11816. console.error( 'THREE.WebGLRenderer: ' + error );
  11817. }
  11818. var extensions = new WebGLExtensions( _gl );
  11819. extensions.get( 'WEBGL_depth_texture' );
  11820. extensions.get( 'OES_texture_float' );
  11821. extensions.get( 'OES_texture_float_linear' );
  11822. extensions.get( 'OES_texture_half_float' );
  11823. extensions.get( 'OES_texture_half_float_linear' );
  11824. extensions.get( 'OES_standard_derivatives' );
  11825. extensions.get( 'ANGLE_instanced_arrays' );
  11826. if ( extensions.get( 'OES_element_index_uint' ) ) {
  11827. BufferGeometry.MaxIndex = 4294967296;
  11828. }
  11829. var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  11830. var state = new WebGLState( _gl, extensions, paramThreeToGL );
  11831. var properties = new WebGLProperties();
  11832. var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info );
  11833. var objects = new WebGLObjects( _gl, properties, this.info );
  11834. var programCache = new WebGLPrograms( this, capabilities );
  11835. var lightCache = new WebGLLights();
  11836. this.info.programs = programCache.programs;
  11837. var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  11838. var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  11839. //
  11840. var backgroundCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  11841. var backgroundCamera2 = new PerspectiveCamera();
  11842. var backgroundPlaneMesh = new Mesh(
  11843. new PlaneBufferGeometry( 2, 2 ),
  11844. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  11845. );
  11846. var backgroundBoxShader = ShaderLib[ 'cube' ];
  11847. var backgroundBoxMesh = new Mesh(
  11848. new BoxBufferGeometry( 5, 5, 5 ),
  11849. new ShaderMaterial( {
  11850. uniforms: backgroundBoxShader.uniforms,
  11851. vertexShader: backgroundBoxShader.vertexShader,
  11852. fragmentShader: backgroundBoxShader.fragmentShader,
  11853. side: BackSide,
  11854. depthTest: false,
  11855. depthWrite: false,
  11856. fog: false
  11857. } )
  11858. );
  11859. //
  11860. function getTargetPixelRatio() {
  11861. return _currentRenderTarget === null ? _pixelRatio : 1;
  11862. }
  11863. function setDefaultGLState() {
  11864. state.init();
  11865. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  11866. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  11867. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  11868. }
  11869. function resetGLState() {
  11870. _currentProgram = null;
  11871. _currentCamera = null;
  11872. _currentGeometryProgram = '';
  11873. _currentMaterialId = - 1;
  11874. state.reset();
  11875. }
  11876. setDefaultGLState();
  11877. this.context = _gl;
  11878. this.capabilities = capabilities;
  11879. this.extensions = extensions;
  11880. this.properties = properties;
  11881. this.state = state;
  11882. // shadow map
  11883. var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
  11884. this.shadowMap = shadowMap;
  11885. // Plugins
  11886. var spritePlugin = new SpritePlugin( this, sprites );
  11887. var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
  11888. // API
  11889. this.getContext = function () {
  11890. return _gl;
  11891. };
  11892. this.getContextAttributes = function () {
  11893. return _gl.getContextAttributes();
  11894. };
  11895. this.forceContextLoss = function () {
  11896. extensions.get( 'WEBGL_lose_context' ).loseContext();
  11897. };
  11898. this.getMaxAnisotropy = function () {
  11899. return capabilities.getMaxAnisotropy();
  11900. };
  11901. this.getPrecision = function () {
  11902. return capabilities.precision;
  11903. };
  11904. this.getPixelRatio = function () {
  11905. return _pixelRatio;
  11906. };
  11907. this.setPixelRatio = function ( value ) {
  11908. if ( value === undefined ) return;
  11909. _pixelRatio = value;
  11910. this.setSize( _viewport.z, _viewport.w, false );
  11911. };
  11912. this.getSize = function () {
  11913. return {
  11914. width: _width,
  11915. height: _height
  11916. };
  11917. };
  11918. this.setSize = function ( width, height, updateStyle ) {
  11919. _width = width;
  11920. _height = height;
  11921. _canvas.width = width * _pixelRatio;
  11922. _canvas.height = height * _pixelRatio;
  11923. if ( updateStyle !== false ) {
  11924. _canvas.style.width = width + 'px';
  11925. _canvas.style.height = height + 'px';
  11926. }
  11927. this.setViewport( 0, 0, width, height );
  11928. };
  11929. this.setViewport = function ( x, y, width, height ) {
  11930. state.viewport( _viewport.set( x, y, width, height ) );
  11931. };
  11932. this.setScissor = function ( x, y, width, height ) {
  11933. state.scissor( _scissor.set( x, y, width, height ) );
  11934. };
  11935. this.setScissorTest = function ( boolean ) {
  11936. state.setScissorTest( _scissorTest = boolean );
  11937. };
  11938. // Clearing
  11939. this.getClearColor = function () {
  11940. return _clearColor;
  11941. };
  11942. this.setClearColor = function ( color, alpha ) {
  11943. _clearColor.set( color );
  11944. _clearAlpha = alpha !== undefined ? alpha : 1;
  11945. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  11946. };
  11947. this.getClearAlpha = function () {
  11948. return _clearAlpha;
  11949. };
  11950. this.setClearAlpha = function ( alpha ) {
  11951. _clearAlpha = alpha;
  11952. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  11953. };
  11954. this.clear = function ( color, depth, stencil ) {
  11955. var bits = 0;
  11956. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11957. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11958. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11959. _gl.clear( bits );
  11960. };
  11961. this.clearColor = function () {
  11962. this.clear( true, false, false );
  11963. };
  11964. this.clearDepth = function () {
  11965. this.clear( false, true, false );
  11966. };
  11967. this.clearStencil = function () {
  11968. this.clear( false, false, true );
  11969. };
  11970. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11971. this.setRenderTarget( renderTarget );
  11972. this.clear( color, depth, stencil );
  11973. };
  11974. // Reset
  11975. this.resetGLState = resetGLState;
  11976. this.dispose = function() {
  11977. transparentObjects = [];
  11978. transparentObjectsLastIndex = -1;
  11979. opaqueObjects = [];
  11980. opaqueObjectsLastIndex = -1;
  11981. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  11982. };
  11983. // Events
  11984. function onContextLost( event ) {
  11985. event.preventDefault();
  11986. resetGLState();
  11987. setDefaultGLState();
  11988. properties.clear();
  11989. }
  11990. function onMaterialDispose( event ) {
  11991. var material = event.target;
  11992. material.removeEventListener( 'dispose', onMaterialDispose );
  11993. deallocateMaterial( material );
  11994. }
  11995. // Buffer deallocation
  11996. function deallocateMaterial( material ) {
  11997. releaseMaterialProgramReference( material );
  11998. properties.delete( material );
  11999. }
  12000. function releaseMaterialProgramReference( material ) {
  12001. var programInfo = properties.get( material ).program;
  12002. material.program = undefined;
  12003. if ( programInfo !== undefined ) {
  12004. programCache.releaseProgram( programInfo );
  12005. }
  12006. }
  12007. // Buffer rendering
  12008. this.renderBufferImmediate = function ( object, program, material ) {
  12009. state.initAttributes();
  12010. var buffers = properties.get( object );
  12011. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  12012. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  12013. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  12014. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  12015. var attributes = program.getAttributes();
  12016. if ( object.hasPositions ) {
  12017. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  12018. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12019. state.enableAttribute( attributes.position );
  12020. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12021. }
  12022. if ( object.hasNormals ) {
  12023. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  12024. if ( ! material.isMeshPhongMaterial &&
  12025. ! material.isMeshStandardMaterial &&
  12026. material.shading === FlatShading ) {
  12027. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  12028. var array = object.normalArray;
  12029. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  12030. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  12031. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  12032. array[ i + 0 ] = nx;
  12033. array[ i + 1 ] = ny;
  12034. array[ i + 2 ] = nz;
  12035. array[ i + 3 ] = nx;
  12036. array[ i + 4 ] = ny;
  12037. array[ i + 5 ] = nz;
  12038. array[ i + 6 ] = nx;
  12039. array[ i + 7 ] = ny;
  12040. array[ i + 8 ] = nz;
  12041. }
  12042. }
  12043. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12044. state.enableAttribute( attributes.normal );
  12045. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12046. }
  12047. if ( object.hasUvs && material.map ) {
  12048. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  12049. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12050. state.enableAttribute( attributes.uv );
  12051. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12052. }
  12053. if ( object.hasColors && material.vertexColors !== NoColors ) {
  12054. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  12055. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12056. state.enableAttribute( attributes.color );
  12057. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12058. }
  12059. state.disableUnusedAttributes();
  12060. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12061. object.count = 0;
  12062. };
  12063. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  12064. setMaterial( material );
  12065. var program = setProgram( camera, fog, material, object );
  12066. var updateBuffers = false;
  12067. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  12068. if ( geometryProgram !== _currentGeometryProgram ) {
  12069. _currentGeometryProgram = geometryProgram;
  12070. updateBuffers = true;
  12071. }
  12072. // morph targets
  12073. var morphTargetInfluences = object.morphTargetInfluences;
  12074. if ( morphTargetInfluences !== undefined ) {
  12075. var activeInfluences = [];
  12076. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  12077. var influence = morphTargetInfluences[ i ];
  12078. activeInfluences.push( [ influence, i ] );
  12079. }
  12080. activeInfluences.sort( absNumericalSort );
  12081. if ( activeInfluences.length > 8 ) {
  12082. activeInfluences.length = 8;
  12083. }
  12084. var morphAttributes = geometry.morphAttributes;
  12085. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  12086. var influence = activeInfluences[ i ];
  12087. morphInfluences[ i ] = influence[ 0 ];
  12088. if ( influence[ 0 ] !== 0 ) {
  12089. var index = influence[ 1 ];
  12090. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  12091. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  12092. } else {
  12093. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  12094. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  12095. }
  12096. }
  12097. for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) {
  12098. morphInfluences[ i ] = 0.0;
  12099. }
  12100. program.getUniforms().setValue(
  12101. _gl, 'morphTargetInfluences', morphInfluences );
  12102. updateBuffers = true;
  12103. }
  12104. //
  12105. var index = geometry.index;
  12106. var position = geometry.attributes.position;
  12107. var rangeFactor = 1;
  12108. if ( material.wireframe === true ) {
  12109. index = objects.getWireframeAttribute( geometry );
  12110. rangeFactor = 2;
  12111. }
  12112. var renderer;
  12113. if ( index !== null ) {
  12114. renderer = indexedBufferRenderer;
  12115. renderer.setIndex( index );
  12116. } else {
  12117. renderer = bufferRenderer;
  12118. }
  12119. if ( updateBuffers ) {
  12120. setupVertexAttributes( material, program, geometry );
  12121. if ( index !== null ) {
  12122. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  12123. }
  12124. }
  12125. //
  12126. var dataCount = 0;
  12127. if ( index !== null ) {
  12128. dataCount = index.count;
  12129. } else if ( position !== undefined ) {
  12130. dataCount = position.count;
  12131. }
  12132. var rangeStart = geometry.drawRange.start * rangeFactor;
  12133. var rangeCount = geometry.drawRange.count * rangeFactor;
  12134. var groupStart = group !== null ? group.start * rangeFactor : 0;
  12135. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  12136. var drawStart = Math.max( rangeStart, groupStart );
  12137. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  12138. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  12139. if ( drawCount === 0 ) return;
  12140. //
  12141. if ( object.isMesh ) {
  12142. if ( material.wireframe === true ) {
  12143. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  12144. renderer.setMode( _gl.LINES );
  12145. } else {
  12146. switch ( object.drawMode ) {
  12147. case TrianglesDrawMode:
  12148. renderer.setMode( _gl.TRIANGLES );
  12149. break;
  12150. case TriangleStripDrawMode:
  12151. renderer.setMode( _gl.TRIANGLE_STRIP );
  12152. break;
  12153. case TriangleFanDrawMode:
  12154. renderer.setMode( _gl.TRIANGLE_FAN );
  12155. break;
  12156. }
  12157. }
  12158. } else if ( object.isLine ) {
  12159. var lineWidth = material.linewidth;
  12160. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  12161. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  12162. if ( object.isLineSegments ) {
  12163. renderer.setMode( _gl.LINES );
  12164. } else {
  12165. renderer.setMode( _gl.LINE_STRIP );
  12166. }
  12167. } else if ( object.isPoints ) {
  12168. renderer.setMode( _gl.POINTS );
  12169. }
  12170. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12171. if ( geometry.maxInstancedCount > 0 ) {
  12172. renderer.renderInstances( geometry, drawStart, drawCount );
  12173. }
  12174. } else {
  12175. renderer.render( drawStart, drawCount );
  12176. }
  12177. };
  12178. function setupVertexAttributes( material, program, geometry, startIndex ) {
  12179. var extension;
  12180. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12181. extension = extensions.get( 'ANGLE_instanced_arrays' );
  12182. if ( extension === null ) {
  12183. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12184. return;
  12185. }
  12186. }
  12187. if ( startIndex === undefined ) startIndex = 0;
  12188. state.initAttributes();
  12189. var geometryAttributes = geometry.attributes;
  12190. var programAttributes = program.getAttributes();
  12191. var materialDefaultAttributeValues = material.defaultAttributeValues;
  12192. for ( var name in programAttributes ) {
  12193. var programAttribute = programAttributes[ name ];
  12194. if ( programAttribute >= 0 ) {
  12195. var geometryAttribute = geometryAttributes[ name ];
  12196. if ( geometryAttribute !== undefined ) {
  12197. var normalized = geometryAttribute.normalized;
  12198. var size = geometryAttribute.itemSize;
  12199. var attributeProperties = objects.getAttributeProperties( geometryAttribute );
  12200. var buffer = attributeProperties.__webglBuffer;
  12201. var type = attributeProperties.type;
  12202. var bytesPerElement = attributeProperties.bytesPerElement;
  12203. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  12204. var data = geometryAttribute.data;
  12205. var stride = data.stride;
  12206. var offset = geometryAttribute.offset;
  12207. if ( data && data.isInstancedInterleavedBuffer ) {
  12208. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  12209. if ( geometry.maxInstancedCount === undefined ) {
  12210. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  12211. }
  12212. } else {
  12213. state.enableAttribute( programAttribute );
  12214. }
  12215. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12216. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  12217. } else {
  12218. if ( geometryAttribute.isInstancedBufferAttribute ) {
  12219. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  12220. if ( geometry.maxInstancedCount === undefined ) {
  12221. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  12222. }
  12223. } else {
  12224. state.enableAttribute( programAttribute );
  12225. }
  12226. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12227. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  12228. }
  12229. } else if ( materialDefaultAttributeValues !== undefined ) {
  12230. var value = materialDefaultAttributeValues[ name ];
  12231. if ( value !== undefined ) {
  12232. switch ( value.length ) {
  12233. case 2:
  12234. _gl.vertexAttrib2fv( programAttribute, value );
  12235. break;
  12236. case 3:
  12237. _gl.vertexAttrib3fv( programAttribute, value );
  12238. break;
  12239. case 4:
  12240. _gl.vertexAttrib4fv( programAttribute, value );
  12241. break;
  12242. default:
  12243. _gl.vertexAttrib1fv( programAttribute, value );
  12244. }
  12245. }
  12246. }
  12247. }
  12248. }
  12249. state.disableUnusedAttributes();
  12250. }
  12251. // Sorting
  12252. function absNumericalSort( a, b ) {
  12253. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  12254. }
  12255. function painterSortStable( a, b ) {
  12256. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12257. return a.object.renderOrder - b.object.renderOrder;
  12258. } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) {
  12259. return a.material.program.id - b.material.program.id;
  12260. } else if ( a.material.id !== b.material.id ) {
  12261. return a.material.id - b.material.id;
  12262. } else if ( a.z !== b.z ) {
  12263. return a.z - b.z;
  12264. } else {
  12265. return a.id - b.id;
  12266. }
  12267. }
  12268. function reversePainterSortStable( a, b ) {
  12269. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12270. return a.object.renderOrder - b.object.renderOrder;
  12271. } if ( a.z !== b.z ) {
  12272. return b.z - a.z;
  12273. } else {
  12274. return a.id - b.id;
  12275. }
  12276. }
  12277. // Rendering
  12278. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12279. if ( camera !== undefined && camera.isCamera !== true ) {
  12280. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12281. return;
  12282. }
  12283. // reset caching for this frame
  12284. _currentGeometryProgram = '';
  12285. _currentMaterialId = - 1;
  12286. _currentCamera = null;
  12287. // update scene graph
  12288. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12289. // update camera matrices and frustum
  12290. if ( camera.parent === null ) camera.updateMatrixWorld();
  12291. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12292. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12293. _frustum.setFromMatrix( _projScreenMatrix );
  12294. lights.length = 0;
  12295. opaqueObjectsLastIndex = - 1;
  12296. transparentObjectsLastIndex = - 1;
  12297. sprites.length = 0;
  12298. lensFlares.length = 0;
  12299. _localClippingEnabled = this.localClippingEnabled;
  12300. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  12301. projectObject( scene, camera );
  12302. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  12303. transparentObjects.length = transparentObjectsLastIndex + 1;
  12304. if ( _this.sortObjects === true ) {
  12305. opaqueObjects.sort( painterSortStable );
  12306. transparentObjects.sort( reversePainterSortStable );
  12307. }
  12308. //
  12309. if ( _clippingEnabled ) _clipping.beginShadows();
  12310. setupShadows( lights );
  12311. shadowMap.render( scene, camera );
  12312. setupLights( lights, camera );
  12313. if ( _clippingEnabled ) _clipping.endShadows();
  12314. //
  12315. _infoRender.calls = 0;
  12316. _infoRender.vertices = 0;
  12317. _infoRender.faces = 0;
  12318. _infoRender.points = 0;
  12319. if ( renderTarget === undefined ) {
  12320. renderTarget = null;
  12321. }
  12322. this.setRenderTarget( renderTarget );
  12323. //
  12324. var background = scene.background;
  12325. if ( background === null ) {
  12326. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  12327. } else if ( background && background.isColor ) {
  12328. state.buffers.color.setClear( background.r, background.g, background.b, 1, _premultipliedAlpha );
  12329. forceClear = true;
  12330. }
  12331. if ( this.autoClear || forceClear ) {
  12332. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12333. }
  12334. if ( background && background.isCubeTexture ) {
  12335. backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix );
  12336. backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld );
  12337. backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld );
  12338. backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
  12339. backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
  12340. objects.update( backgroundBoxMesh );
  12341. _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
  12342. } else if ( background && background.isTexture ) {
  12343. backgroundPlaneMesh.material.map = background;
  12344. objects.update( backgroundPlaneMesh );
  12345. _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
  12346. }
  12347. //
  12348. if ( scene.overrideMaterial ) {
  12349. var overrideMaterial = scene.overrideMaterial;
  12350. renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  12351. renderObjects( transparentObjects, scene, camera, overrideMaterial );
  12352. } else {
  12353. // opaque pass (front-to-back order)
  12354. state.setBlending( NoBlending );
  12355. renderObjects( opaqueObjects, scene, camera );
  12356. // transparent pass (back-to-front order)
  12357. renderObjects( transparentObjects, scene, camera );
  12358. }
  12359. // custom render plugins (post pass)
  12360. spritePlugin.render( scene, camera );
  12361. lensFlarePlugin.render( scene, camera, _currentViewport );
  12362. // Generate mipmap if we're using any kind of mipmap filtering
  12363. if ( renderTarget ) {
  12364. textures.updateRenderTargetMipmap( renderTarget );
  12365. }
  12366. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12367. state.setDepthTest( true );
  12368. state.setDepthWrite( true );
  12369. state.setColorWrite( true );
  12370. // _gl.finish();
  12371. };
  12372. function pushRenderItem( object, geometry, material, z, group ) {
  12373. var array, index;
  12374. // allocate the next position in the appropriate array
  12375. if ( material.transparent ) {
  12376. array = transparentObjects;
  12377. index = ++ transparentObjectsLastIndex;
  12378. } else {
  12379. array = opaqueObjects;
  12380. index = ++ opaqueObjectsLastIndex;
  12381. }
  12382. // recycle existing render item or grow the array
  12383. var renderItem = array[ index ];
  12384. if ( renderItem !== undefined ) {
  12385. renderItem.id = object.id;
  12386. renderItem.object = object;
  12387. renderItem.geometry = geometry;
  12388. renderItem.material = material;
  12389. renderItem.z = _vector3.z;
  12390. renderItem.group = group;
  12391. } else {
  12392. renderItem = {
  12393. id: object.id,
  12394. object: object,
  12395. geometry: geometry,
  12396. material: material,
  12397. z: _vector3.z,
  12398. group: group
  12399. };
  12400. // assert( index === array.length );
  12401. array.push( renderItem );
  12402. }
  12403. }
  12404. // TODO Duplicated code (Frustum)
  12405. function isObjectViewable( object ) {
  12406. var geometry = object.geometry;
  12407. if ( geometry.boundingSphere === null )
  12408. geometry.computeBoundingSphere();
  12409. _sphere.copy( geometry.boundingSphere ).
  12410. applyMatrix4( object.matrixWorld );
  12411. return isSphereViewable( _sphere );
  12412. }
  12413. function isSpriteViewable( sprite ) {
  12414. _sphere.center.set( 0, 0, 0 );
  12415. _sphere.radius = 0.7071067811865476;
  12416. _sphere.applyMatrix4( sprite.matrixWorld );
  12417. return isSphereViewable( _sphere );
  12418. }
  12419. function isSphereViewable( sphere ) {
  12420. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  12421. var numPlanes = _clipping.numPlanes;
  12422. if ( numPlanes === 0 ) return true;
  12423. var planes = _this.clippingPlanes,
  12424. center = sphere.center,
  12425. negRad = - sphere.radius,
  12426. i = 0;
  12427. do {
  12428. // out when deeper than radius in the negative halfspace
  12429. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  12430. } while ( ++ i !== numPlanes );
  12431. return true;
  12432. }
  12433. function projectObject( object, camera ) {
  12434. if ( object.visible === false ) return;
  12435. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  12436. if ( visible ) {
  12437. if ( object.isLight ) {
  12438. lights.push( object );
  12439. } else if ( object.isSprite ) {
  12440. if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) {
  12441. sprites.push( object );
  12442. }
  12443. } else if ( object.isLensFlare ) {
  12444. lensFlares.push( object );
  12445. } else if ( object.isImmediateRenderObject ) {
  12446. if ( _this.sortObjects === true ) {
  12447. _vector3.setFromMatrixPosition( object.matrixWorld );
  12448. _vector3.applyProjection( _projScreenMatrix );
  12449. }
  12450. pushRenderItem( object, null, object.material, _vector3.z, null );
  12451. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  12452. if ( object.isSkinnedMesh ) {
  12453. object.skeleton.update();
  12454. }
  12455. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  12456. var material = object.material;
  12457. if ( material.visible === true ) {
  12458. if ( _this.sortObjects === true ) {
  12459. _vector3.setFromMatrixPosition( object.matrixWorld );
  12460. _vector3.applyProjection( _projScreenMatrix );
  12461. }
  12462. var geometry = objects.update( object );
  12463. if ( material.isMultiMaterial ) {
  12464. var groups = geometry.groups;
  12465. var materials = material.materials;
  12466. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  12467. var group = groups[ i ];
  12468. var groupMaterial = materials[ group.materialIndex ];
  12469. if ( groupMaterial.visible === true ) {
  12470. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  12471. }
  12472. }
  12473. } else {
  12474. pushRenderItem( object, geometry, material, _vector3.z, null );
  12475. }
  12476. }
  12477. }
  12478. }
  12479. }
  12480. var children = object.children;
  12481. for ( var i = 0, l = children.length; i < l; i ++ ) {
  12482. projectObject( children[ i ], camera );
  12483. }
  12484. }
  12485. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  12486. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12487. var renderItem = renderList[ i ];
  12488. var object = renderItem.object;
  12489. var geometry = renderItem.geometry;
  12490. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  12491. var group = renderItem.group;
  12492. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  12493. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  12494. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  12495. if ( object.isImmediateRenderObject ) {
  12496. setMaterial( material );
  12497. var program = setProgram( camera, scene.fog, material, object );
  12498. _currentGeometryProgram = '';
  12499. object.render( function ( object ) {
  12500. _this.renderBufferImmediate( object, program, material );
  12501. } );
  12502. } else {
  12503. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  12504. }
  12505. object.onAfterRender( _this, scene, camera, geometry, material, group );
  12506. }
  12507. }
  12508. function initMaterial( material, fog, object ) {
  12509. var materialProperties = properties.get( material );
  12510. var parameters = programCache.getParameters(
  12511. material, _lights, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  12512. var code = programCache.getProgramCode( material, parameters );
  12513. var program = materialProperties.program;
  12514. var programChange = true;
  12515. if ( program === undefined ) {
  12516. // new material
  12517. material.addEventListener( 'dispose', onMaterialDispose );
  12518. } else if ( program.code !== code ) {
  12519. // changed glsl or parameters
  12520. releaseMaterialProgramReference( material );
  12521. } else if ( parameters.shaderID !== undefined ) {
  12522. // same glsl and uniform list
  12523. return;
  12524. } else {
  12525. // only rebuild uniform list
  12526. programChange = false;
  12527. }
  12528. if ( programChange ) {
  12529. if ( parameters.shaderID ) {
  12530. var shader = ShaderLib[ parameters.shaderID ];
  12531. materialProperties.__webglShader = {
  12532. name: material.type,
  12533. uniforms: Object.assign( {}, shader.uniforms ),
  12534. vertexShader: shader.vertexShader,
  12535. fragmentShader: shader.fragmentShader
  12536. };
  12537. } else {
  12538. materialProperties.__webglShader = {
  12539. name: material.type,
  12540. uniforms: material.uniforms,
  12541. vertexShader: material.vertexShader,
  12542. fragmentShader: material.fragmentShader
  12543. };
  12544. }
  12545. material.__webglShader = materialProperties.__webglShader;
  12546. program = programCache.acquireProgram( material, parameters, code );
  12547. materialProperties.program = program;
  12548. material.program = program;
  12549. }
  12550. var attributes = program.getAttributes();
  12551. if ( material.morphTargets ) {
  12552. material.numSupportedMorphTargets = 0;
  12553. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  12554. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  12555. material.numSupportedMorphTargets ++;
  12556. }
  12557. }
  12558. }
  12559. if ( material.morphNormals ) {
  12560. material.numSupportedMorphNormals = 0;
  12561. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  12562. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  12563. material.numSupportedMorphNormals ++;
  12564. }
  12565. }
  12566. }
  12567. var uniforms = materialProperties.__webglShader.uniforms;
  12568. if ( ! material.isShaderMaterial &&
  12569. ! material.isRawShaderMaterial ||
  12570. material.clipping === true ) {
  12571. materialProperties.numClippingPlanes = _clipping.numPlanes;
  12572. materialProperties.numIntersection = _clipping.numIntersection;
  12573. uniforms.clippingPlanes = _clipping.uniform;
  12574. }
  12575. materialProperties.fog = fog;
  12576. // store the light setup it was created for
  12577. materialProperties.lightsHash = _lights.hash;
  12578. if ( material.lights ) {
  12579. // wire up the material to this renderer's lighting state
  12580. uniforms.ambientLightColor.value = _lights.ambient;
  12581. uniforms.directionalLights.value = _lights.directional;
  12582. uniforms.spotLights.value = _lights.spot;
  12583. uniforms.rectAreaLights.value = _lights.rectArea;
  12584. uniforms.pointLights.value = _lights.point;
  12585. uniforms.hemisphereLights.value = _lights.hemi;
  12586. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  12587. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  12588. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  12589. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  12590. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  12591. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  12592. // TODO (abelnation): add area lights shadow info to uniforms
  12593. }
  12594. var progUniforms = materialProperties.program.getUniforms(),
  12595. uniformsList =
  12596. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  12597. materialProperties.uniformsList = uniformsList;
  12598. }
  12599. function setMaterial( material ) {
  12600. material.side === DoubleSide
  12601. ? state.disable( _gl.CULL_FACE )
  12602. : state.enable( _gl.CULL_FACE );
  12603. state.setFlipSided( material.side === BackSide );
  12604. material.transparent === true
  12605. ? state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  12606. : state.setBlending( NoBlending );
  12607. state.setDepthFunc( material.depthFunc );
  12608. state.setDepthTest( material.depthTest );
  12609. state.setDepthWrite( material.depthWrite );
  12610. state.setColorWrite( material.colorWrite );
  12611. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12612. }
  12613. function setProgram( camera, fog, material, object ) {
  12614. _usedTextureUnits = 0;
  12615. var materialProperties = properties.get( material );
  12616. if ( _clippingEnabled ) {
  12617. if ( _localClippingEnabled || camera !== _currentCamera ) {
  12618. var useCache =
  12619. camera === _currentCamera &&
  12620. material.id === _currentMaterialId;
  12621. // we might want to call this function with some ClippingGroup
  12622. // object instead of the material, once it becomes feasible
  12623. // (#8465, #8379)
  12624. _clipping.setState(
  12625. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  12626. camera, materialProperties, useCache );
  12627. }
  12628. }
  12629. if ( material.needsUpdate === false ) {
  12630. if ( materialProperties.program === undefined ) {
  12631. material.needsUpdate = true;
  12632. } else if ( material.fog && materialProperties.fog !== fog ) {
  12633. material.needsUpdate = true;
  12634. } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) {
  12635. material.needsUpdate = true;
  12636. } else if ( materialProperties.numClippingPlanes !== undefined &&
  12637. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  12638. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  12639. material.needsUpdate = true;
  12640. }
  12641. }
  12642. if ( material.needsUpdate ) {
  12643. initMaterial( material, fog, object );
  12644. material.needsUpdate = false;
  12645. }
  12646. var refreshProgram = false;
  12647. var refreshMaterial = false;
  12648. var refreshLights = false;
  12649. var program = materialProperties.program,
  12650. p_uniforms = program.getUniforms(),
  12651. m_uniforms = materialProperties.__webglShader.uniforms;
  12652. if ( program.id !== _currentProgram ) {
  12653. _gl.useProgram( program.program );
  12654. _currentProgram = program.id;
  12655. refreshProgram = true;
  12656. refreshMaterial = true;
  12657. refreshLights = true;
  12658. }
  12659. if ( material.id !== _currentMaterialId ) {
  12660. _currentMaterialId = material.id;
  12661. refreshMaterial = true;
  12662. }
  12663. if ( refreshProgram || camera !== _currentCamera ) {
  12664. p_uniforms.set( _gl, camera, 'projectionMatrix' );
  12665. if ( capabilities.logarithmicDepthBuffer ) {
  12666. p_uniforms.setValue( _gl, 'logDepthBufFC',
  12667. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  12668. }
  12669. if ( camera !== _currentCamera ) {
  12670. _currentCamera = camera;
  12671. // lighting uniforms depend on the camera so enforce an update
  12672. // now, in case this material supports lights - or later, when
  12673. // the next material that does gets activated:
  12674. refreshMaterial = true; // set to true on material change
  12675. refreshLights = true; // remains set until update done
  12676. }
  12677. // load material specific uniforms
  12678. // (shader material also gets them for the sake of genericity)
  12679. if ( material.isShaderMaterial ||
  12680. material.isMeshPhongMaterial ||
  12681. material.isMeshStandardMaterial ||
  12682. material.envMap ) {
  12683. var uCamPos = p_uniforms.map.cameraPosition;
  12684. if ( uCamPos !== undefined ) {
  12685. uCamPos.setValue( _gl,
  12686. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  12687. }
  12688. }
  12689. if ( material.isMeshPhongMaterial ||
  12690. material.isMeshLambertMaterial ||
  12691. material.isMeshBasicMaterial ||
  12692. material.isMeshStandardMaterial ||
  12693. material.isShaderMaterial ||
  12694. material.skinning ) {
  12695. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  12696. }
  12697. p_uniforms.set( _gl, _this, 'toneMappingExposure' );
  12698. p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
  12699. }
  12700. // skinning uniforms must be set even if material didn't change
  12701. // auto-setting of texture unit for bone texture must go before other textures
  12702. // not sure why, but otherwise weird things happen
  12703. if ( material.skinning ) {
  12704. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  12705. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  12706. var skeleton = object.skeleton;
  12707. if ( skeleton ) {
  12708. if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
  12709. p_uniforms.set( _gl, skeleton, 'boneTexture' );
  12710. p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
  12711. p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
  12712. } else {
  12713. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  12714. }
  12715. }
  12716. }
  12717. if ( refreshMaterial ) {
  12718. if ( material.lights ) {
  12719. // the current material requires lighting info
  12720. // note: all lighting uniforms are always set correctly
  12721. // they simply reference the renderer's state for their
  12722. // values
  12723. //
  12724. // use the current material's .needsUpdate flags to set
  12725. // the GL state when required
  12726. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  12727. }
  12728. // refresh uniforms common to several materials
  12729. if ( fog && material.fog ) {
  12730. refreshUniformsFog( m_uniforms, fog );
  12731. }
  12732. if ( material.isMeshBasicMaterial ||
  12733. material.isMeshLambertMaterial ||
  12734. material.isMeshPhongMaterial ||
  12735. material.isMeshStandardMaterial ||
  12736. material.isMeshDepthMaterial ) {
  12737. refreshUniformsCommon( m_uniforms, material );
  12738. }
  12739. // refresh single material specific uniforms
  12740. if ( material.isLineBasicMaterial ) {
  12741. refreshUniformsLine( m_uniforms, material );
  12742. } else if ( material.isLineDashedMaterial ) {
  12743. refreshUniformsLine( m_uniforms, material );
  12744. refreshUniformsDash( m_uniforms, material );
  12745. } else if ( material.isPointsMaterial ) {
  12746. refreshUniformsPoints( m_uniforms, material );
  12747. } else if ( material.isMeshLambertMaterial ) {
  12748. refreshUniformsLambert( m_uniforms, material );
  12749. } else if ( material.isMeshToonMaterial ) {
  12750. refreshUniformsToon( m_uniforms, material );
  12751. } else if ( material.isMeshPhongMaterial ) {
  12752. refreshUniformsPhong( m_uniforms, material );
  12753. } else if ( material.isMeshPhysicalMaterial ) {
  12754. refreshUniformsPhysical( m_uniforms, material );
  12755. } else if ( material.isMeshStandardMaterial ) {
  12756. refreshUniformsStandard( m_uniforms, material );
  12757. } else if ( material.isMeshDepthMaterial ) {
  12758. if ( material.displacementMap ) {
  12759. m_uniforms.displacementMap.value = material.displacementMap;
  12760. m_uniforms.displacementScale.value = material.displacementScale;
  12761. m_uniforms.displacementBias.value = material.displacementBias;
  12762. }
  12763. } else if ( material.isMeshNormalMaterial ) {
  12764. m_uniforms.opacity.value = material.opacity;
  12765. }
  12766. WebGLUniforms.upload(
  12767. _gl, materialProperties.uniformsList, m_uniforms, _this );
  12768. }
  12769. // common matrices
  12770. p_uniforms.set( _gl, object, 'modelViewMatrix' );
  12771. p_uniforms.set( _gl, object, 'normalMatrix' );
  12772. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  12773. return program;
  12774. }
  12775. // Uniforms (refresh uniforms objects)
  12776. function refreshUniformsCommon( uniforms, material ) {
  12777. uniforms.opacity.value = material.opacity;
  12778. uniforms.diffuse.value = material.color;
  12779. if ( material.emissive ) {
  12780. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  12781. }
  12782. uniforms.map.value = material.map;
  12783. uniforms.specularMap.value = material.specularMap;
  12784. uniforms.alphaMap.value = material.alphaMap;
  12785. if ( material.lightMap ) {
  12786. uniforms.lightMap.value = material.lightMap;
  12787. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12788. }
  12789. if ( material.aoMap ) {
  12790. uniforms.aoMap.value = material.aoMap;
  12791. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  12792. }
  12793. // uv repeat and offset setting priorities
  12794. // 1. color map
  12795. // 2. specular map
  12796. // 3. normal map
  12797. // 4. bump map
  12798. // 5. alpha map
  12799. // 6. emissive map
  12800. var uvScaleMap;
  12801. if ( material.map ) {
  12802. uvScaleMap = material.map;
  12803. } else if ( material.specularMap ) {
  12804. uvScaleMap = material.specularMap;
  12805. } else if ( material.displacementMap ) {
  12806. uvScaleMap = material.displacementMap;
  12807. } else if ( material.normalMap ) {
  12808. uvScaleMap = material.normalMap;
  12809. } else if ( material.bumpMap ) {
  12810. uvScaleMap = material.bumpMap;
  12811. } else if ( material.roughnessMap ) {
  12812. uvScaleMap = material.roughnessMap;
  12813. } else if ( material.metalnessMap ) {
  12814. uvScaleMap = material.metalnessMap;
  12815. } else if ( material.alphaMap ) {
  12816. uvScaleMap = material.alphaMap;
  12817. } else if ( material.emissiveMap ) {
  12818. uvScaleMap = material.emissiveMap;
  12819. }
  12820. if ( uvScaleMap !== undefined ) {
  12821. // backwards compatibility
  12822. if ( uvScaleMap.isWebGLRenderTarget ) {
  12823. uvScaleMap = uvScaleMap.texture;
  12824. }
  12825. var offset = uvScaleMap.offset;
  12826. var repeat = uvScaleMap.repeat;
  12827. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12828. }
  12829. uniforms.envMap.value = material.envMap;
  12830. // don't flip CubeTexture envMaps, flip everything else:
  12831. // WebGLRenderTargetCube will be flipped for backwards compatibility
  12832. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  12833. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  12834. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  12835. uniforms.reflectivity.value = material.reflectivity;
  12836. uniforms.refractionRatio.value = material.refractionRatio;
  12837. }
  12838. function refreshUniformsLine( uniforms, material ) {
  12839. uniforms.diffuse.value = material.color;
  12840. uniforms.opacity.value = material.opacity;
  12841. }
  12842. function refreshUniformsDash( uniforms, material ) {
  12843. uniforms.dashSize.value = material.dashSize;
  12844. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12845. uniforms.scale.value = material.scale;
  12846. }
  12847. function refreshUniformsPoints( uniforms, material ) {
  12848. uniforms.diffuse.value = material.color;
  12849. uniforms.opacity.value = material.opacity;
  12850. uniforms.size.value = material.size * _pixelRatio;
  12851. uniforms.scale.value = _height * 0.5;
  12852. uniforms.map.value = material.map;
  12853. if ( material.map !== null ) {
  12854. var offset = material.map.offset;
  12855. var repeat = material.map.repeat;
  12856. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12857. }
  12858. }
  12859. function refreshUniformsFog( uniforms, fog ) {
  12860. uniforms.fogColor.value = fog.color;
  12861. if ( fog.isFog ) {
  12862. uniforms.fogNear.value = fog.near;
  12863. uniforms.fogFar.value = fog.far;
  12864. } else if ( fog.isFogExp2 ) {
  12865. uniforms.fogDensity.value = fog.density;
  12866. }
  12867. }
  12868. function refreshUniformsLambert( uniforms, material ) {
  12869. if ( material.emissiveMap ) {
  12870. uniforms.emissiveMap.value = material.emissiveMap;
  12871. }
  12872. }
  12873. function refreshUniformsPhong( uniforms, material ) {
  12874. uniforms.specular.value = material.specular;
  12875. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  12876. if ( material.emissiveMap ) {
  12877. uniforms.emissiveMap.value = material.emissiveMap;
  12878. }
  12879. if ( material.bumpMap ) {
  12880. uniforms.bumpMap.value = material.bumpMap;
  12881. uniforms.bumpScale.value = material.bumpScale;
  12882. }
  12883. if ( material.normalMap ) {
  12884. uniforms.normalMap.value = material.normalMap;
  12885. uniforms.normalScale.value.copy( material.normalScale );
  12886. }
  12887. if ( material.displacementMap ) {
  12888. uniforms.displacementMap.value = material.displacementMap;
  12889. uniforms.displacementScale.value = material.displacementScale;
  12890. uniforms.displacementBias.value = material.displacementBias;
  12891. }
  12892. }
  12893. function refreshUniformsToon( uniforms, material ) {
  12894. refreshUniformsPhong( uniforms, material );
  12895. if ( material.gradientMap ) {
  12896. uniforms.gradientMap.value = material.gradientMap;
  12897. }
  12898. }
  12899. function refreshUniformsStandard( uniforms, material ) {
  12900. uniforms.roughness.value = material.roughness;
  12901. uniforms.metalness.value = material.metalness;
  12902. if ( material.roughnessMap ) {
  12903. uniforms.roughnessMap.value = material.roughnessMap;
  12904. }
  12905. if ( material.metalnessMap ) {
  12906. uniforms.metalnessMap.value = material.metalnessMap;
  12907. }
  12908. if ( material.emissiveMap ) {
  12909. uniforms.emissiveMap.value = material.emissiveMap;
  12910. }
  12911. if ( material.bumpMap ) {
  12912. uniforms.bumpMap.value = material.bumpMap;
  12913. uniforms.bumpScale.value = material.bumpScale;
  12914. }
  12915. if ( material.normalMap ) {
  12916. uniforms.normalMap.value = material.normalMap;
  12917. uniforms.normalScale.value.copy( material.normalScale );
  12918. }
  12919. if ( material.displacementMap ) {
  12920. uniforms.displacementMap.value = material.displacementMap;
  12921. uniforms.displacementScale.value = material.displacementScale;
  12922. uniforms.displacementBias.value = material.displacementBias;
  12923. }
  12924. if ( material.envMap ) {
  12925. //uniforms.envMap.value = material.envMap; // part of uniforms common
  12926. uniforms.envMapIntensity.value = material.envMapIntensity;
  12927. }
  12928. }
  12929. function refreshUniformsPhysical( uniforms, material ) {
  12930. uniforms.clearCoat.value = material.clearCoat;
  12931. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  12932. refreshUniformsStandard( uniforms, material );
  12933. }
  12934. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  12935. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  12936. uniforms.ambientLightColor.needsUpdate = value;
  12937. uniforms.directionalLights.needsUpdate = value;
  12938. uniforms.pointLights.needsUpdate = value;
  12939. uniforms.spotLights.needsUpdate = value;
  12940. uniforms.rectAreaLights.needsUpdate = value;
  12941. uniforms.hemisphereLights.needsUpdate = value;
  12942. }
  12943. // Lighting
  12944. function setupShadows( lights ) {
  12945. var lightShadowsLength = 0;
  12946. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  12947. var light = lights[ i ];
  12948. if ( light.castShadow ) {
  12949. _lights.shadows[ lightShadowsLength ++ ] = light;
  12950. }
  12951. }
  12952. _lights.shadows.length = lightShadowsLength;
  12953. }
  12954. function setupLights( lights, camera ) {
  12955. var l, ll, light,
  12956. r = 0, g = 0, b = 0,
  12957. color,
  12958. intensity,
  12959. distance,
  12960. shadowMap,
  12961. viewMatrix = camera.matrixWorldInverse,
  12962. directionalLength = 0,
  12963. pointLength = 0,
  12964. spotLength = 0,
  12965. rectAreaLength = 0,
  12966. hemiLength = 0;
  12967. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12968. light = lights[ l ];
  12969. color = light.color;
  12970. intensity = light.intensity;
  12971. distance = light.distance;
  12972. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12973. if ( light.isAmbientLight ) {
  12974. r += color.r * intensity;
  12975. g += color.g * intensity;
  12976. b += color.b * intensity;
  12977. } else if ( light.isDirectionalLight ) {
  12978. var uniforms = lightCache.get( light );
  12979. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  12980. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12981. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  12982. uniforms.direction.sub( _vector3 );
  12983. uniforms.direction.transformDirection( viewMatrix );
  12984. uniforms.shadow = light.castShadow;
  12985. if ( light.castShadow ) {
  12986. uniforms.shadowBias = light.shadow.bias;
  12987. uniforms.shadowRadius = light.shadow.radius;
  12988. uniforms.shadowMapSize = light.shadow.mapSize;
  12989. }
  12990. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  12991. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12992. _lights.directional[ directionalLength ++ ] = uniforms;
  12993. } else if ( light.isSpotLight ) {
  12994. var uniforms = lightCache.get( light );
  12995. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12996. uniforms.position.applyMatrix4( viewMatrix );
  12997. uniforms.color.copy( color ).multiplyScalar( intensity );
  12998. uniforms.distance = distance;
  12999. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13000. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13001. uniforms.direction.sub( _vector3 );
  13002. uniforms.direction.transformDirection( viewMatrix );
  13003. uniforms.coneCos = Math.cos( light.angle );
  13004. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  13005. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  13006. uniforms.shadow = light.castShadow;
  13007. if ( light.castShadow ) {
  13008. uniforms.shadowBias = light.shadow.bias;
  13009. uniforms.shadowRadius = light.shadow.radius;
  13010. uniforms.shadowMapSize = light.shadow.mapSize;
  13011. }
  13012. _lights.spotShadowMap[ spotLength ] = shadowMap;
  13013. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  13014. _lights.spot[ spotLength ++ ] = uniforms;
  13015. } else if ( light.isRectAreaLight ) {
  13016. var uniforms = lightCache.get( light );
  13017. // (a) intensity controls irradiance of entire light
  13018. uniforms.color
  13019. .copy( color )
  13020. .multiplyScalar( intensity / ( light.width * light.height ) );
  13021. // (b) intensity controls the radiance per light area
  13022. // uniforms.color.copy( color ).multiplyScalar( intensity );
  13023. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13024. uniforms.position.applyMatrix4( viewMatrix );
  13025. // extract local rotation of light to derive width/height half vectors
  13026. _matrix42.identity();
  13027. _matrix4.copy( light.matrixWorld );
  13028. _matrix4.premultiply( viewMatrix );
  13029. _matrix42.extractRotation( _matrix4 );
  13030. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13031. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13032. uniforms.halfWidth.applyMatrix4( _matrix42 );
  13033. uniforms.halfHeight.applyMatrix4( _matrix42 );
  13034. // TODO (abelnation): RectAreaLight distance?
  13035. // uniforms.distance = distance;
  13036. _lights.rectArea[ rectAreaLength ++ ] = uniforms;
  13037. } else if ( light.isPointLight ) {
  13038. var uniforms = lightCache.get( light );
  13039. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13040. uniforms.position.applyMatrix4( viewMatrix );
  13041. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13042. uniforms.distance = light.distance;
  13043. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  13044. uniforms.shadow = light.castShadow;
  13045. if ( light.castShadow ) {
  13046. uniforms.shadowBias = light.shadow.bias;
  13047. uniforms.shadowRadius = light.shadow.radius;
  13048. uniforms.shadowMapSize = light.shadow.mapSize;
  13049. }
  13050. _lights.pointShadowMap[ pointLength ] = shadowMap;
  13051. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  13052. _lights.pointShadowMatrix[ pointLength ] = new Matrix4();
  13053. }
  13054. // for point lights we set the shadow matrix to be a translation-only matrix
  13055. // equal to inverse of the light's position
  13056. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  13057. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  13058. _lights.point[ pointLength ++ ] = uniforms;
  13059. } else if ( light.isHemisphereLight ) {
  13060. var uniforms = lightCache.get( light );
  13061. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13062. uniforms.direction.transformDirection( viewMatrix );
  13063. uniforms.direction.normalize();
  13064. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  13065. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  13066. _lights.hemi[ hemiLength ++ ] = uniforms;
  13067. }
  13068. }
  13069. _lights.ambient[ 0 ] = r;
  13070. _lights.ambient[ 1 ] = g;
  13071. _lights.ambient[ 2 ] = b;
  13072. _lights.directional.length = directionalLength;
  13073. _lights.spot.length = spotLength;
  13074. _lights.rectArea.length = rectAreaLength;
  13075. _lights.point.length = pointLength;
  13076. _lights.hemi.length = hemiLength;
  13077. // TODO (sam-g-steel) why aren't we using join
  13078. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + _lights.shadows.length;
  13079. }
  13080. // GL state setting
  13081. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13082. state.setCullFace( cullFace );
  13083. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  13084. };
  13085. // Textures
  13086. function allocTextureUnit() {
  13087. var textureUnit = _usedTextureUnits;
  13088. if ( textureUnit >= capabilities.maxTextures ) {
  13089. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  13090. }
  13091. _usedTextureUnits += 1;
  13092. return textureUnit;
  13093. }
  13094. this.allocTextureUnit = allocTextureUnit;
  13095. // this.setTexture2D = setTexture2D;
  13096. this.setTexture2D = ( function() {
  13097. var warned = false;
  13098. // backwards compatibility: peel texture.texture
  13099. return function setTexture2D( texture, slot ) {
  13100. if ( texture && texture.isWebGLRenderTarget ) {
  13101. if ( ! warned ) {
  13102. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  13103. warned = true;
  13104. }
  13105. texture = texture.texture;
  13106. }
  13107. textures.setTexture2D( texture, slot );
  13108. };
  13109. }() );
  13110. this.setTexture = ( function() {
  13111. var warned = false;
  13112. return function setTexture( texture, slot ) {
  13113. if ( ! warned ) {
  13114. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  13115. warned = true;
  13116. }
  13117. textures.setTexture2D( texture, slot );
  13118. };
  13119. }() );
  13120. this.setTextureCube = ( function() {
  13121. var warned = false;
  13122. return function setTextureCube( texture, slot ) {
  13123. // backwards compatibility: peel texture.texture
  13124. if ( texture && texture.isWebGLRenderTargetCube ) {
  13125. if ( ! warned ) {
  13126. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  13127. warned = true;
  13128. }
  13129. texture = texture.texture;
  13130. }
  13131. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  13132. // TODO: unify these code paths
  13133. if ( ( texture && texture.isCubeTexture ) ||
  13134. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  13135. // CompressedTexture can have Array in image :/
  13136. // this function alone should take care of cube textures
  13137. textures.setTextureCube( texture, slot );
  13138. } else {
  13139. // assumed: texture property of THREE.WebGLRenderTargetCube
  13140. textures.setTextureCubeDynamic( texture, slot );
  13141. }
  13142. };
  13143. }() );
  13144. this.getCurrentRenderTarget = function() {
  13145. return _currentRenderTarget;
  13146. };
  13147. this.setRenderTarget = function ( renderTarget ) {
  13148. _currentRenderTarget = renderTarget;
  13149. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  13150. textures.setupRenderTarget( renderTarget );
  13151. }
  13152. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  13153. var framebuffer;
  13154. if ( renderTarget ) {
  13155. var renderTargetProperties = properties.get( renderTarget );
  13156. if ( isCube ) {
  13157. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13158. } else {
  13159. framebuffer = renderTargetProperties.__webglFramebuffer;
  13160. }
  13161. _currentScissor.copy( renderTarget.scissor );
  13162. _currentScissorTest = renderTarget.scissorTest;
  13163. _currentViewport.copy( renderTarget.viewport );
  13164. } else {
  13165. framebuffer = null;
  13166. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  13167. _currentScissorTest = _scissorTest;
  13168. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  13169. }
  13170. if ( _currentFramebuffer !== framebuffer ) {
  13171. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13172. _currentFramebuffer = framebuffer;
  13173. }
  13174. state.scissor( _currentScissor );
  13175. state.setScissorTest( _currentScissorTest );
  13176. state.viewport( _currentViewport );
  13177. if ( isCube ) {
  13178. var textureProperties = properties.get( renderTarget.texture );
  13179. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  13180. }
  13181. };
  13182. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  13183. if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
  13184. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  13185. return;
  13186. }
  13187. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  13188. if ( framebuffer ) {
  13189. var restore = false;
  13190. if ( framebuffer !== _currentFramebuffer ) {
  13191. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13192. restore = true;
  13193. }
  13194. try {
  13195. var texture = renderTarget.texture;
  13196. var textureFormat = texture.format;
  13197. var textureType = texture.type;
  13198. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  13199. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  13200. return;
  13201. }
  13202. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  13203. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  13204. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  13205. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  13206. return;
  13207. }
  13208. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13209. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  13210. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  13211. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  13212. }
  13213. } else {
  13214. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13215. }
  13216. } finally {
  13217. if ( restore ) {
  13218. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13219. }
  13220. }
  13221. }
  13222. };
  13223. // Map three.js constants to WebGL constants
  13224. function paramThreeToGL( p ) {
  13225. var extension;
  13226. if ( p === RepeatWrapping ) return _gl.REPEAT;
  13227. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13228. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13229. if ( p === NearestFilter ) return _gl.NEAREST;
  13230. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13231. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13232. if ( p === LinearFilter ) return _gl.LINEAR;
  13233. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13234. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13235. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13236. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13237. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13238. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13239. if ( p === ByteType ) return _gl.BYTE;
  13240. if ( p === ShortType ) return _gl.SHORT;
  13241. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13242. if ( p === IntType ) return _gl.INT;
  13243. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  13244. if ( p === FloatType ) return _gl.FLOAT;
  13245. if ( p === HalfFloatType ) {
  13246. extension = extensions.get( 'OES_texture_half_float' );
  13247. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  13248. }
  13249. if ( p === AlphaFormat ) return _gl.ALPHA;
  13250. if ( p === RGBFormat ) return _gl.RGB;
  13251. if ( p === RGBAFormat ) return _gl.RGBA;
  13252. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  13253. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13254. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  13255. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  13256. if ( p === AddEquation ) return _gl.FUNC_ADD;
  13257. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13258. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13259. if ( p === ZeroFactor ) return _gl.ZERO;
  13260. if ( p === OneFactor ) return _gl.ONE;
  13261. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  13262. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13263. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13264. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13265. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  13266. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13267. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  13268. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13269. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13270. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  13271. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  13272. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13273. if ( extension !== null ) {
  13274. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13275. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13276. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13277. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13278. }
  13279. }
  13280. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  13281. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  13282. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13283. if ( extension !== null ) {
  13284. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13285. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13286. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13287. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13288. }
  13289. }
  13290. if ( p === RGB_ETC1_Format ) {
  13291. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13292. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13293. }
  13294. if ( p === MinEquation || p === MaxEquation ) {
  13295. extension = extensions.get( 'EXT_blend_minmax' );
  13296. if ( extension !== null ) {
  13297. if ( p === MinEquation ) return extension.MIN_EXT;
  13298. if ( p === MaxEquation ) return extension.MAX_EXT;
  13299. }
  13300. }
  13301. if ( p === UnsignedInt248Type ) {
  13302. extension = extensions.get( 'WEBGL_depth_texture' );
  13303. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  13304. }
  13305. return 0;
  13306. }
  13307. }
  13308. /**
  13309. * @author mrdoob / http://mrdoob.com/
  13310. * @author alteredq / http://alteredqualia.com/
  13311. */
  13312. function FogExp2 ( color, density ) {
  13313. this.name = '';
  13314. this.color = new Color( color );
  13315. this.density = ( density !== undefined ) ? density : 0.00025;
  13316. }
  13317. FogExp2.prototype.isFogExp2 = true;
  13318. FogExp2.prototype.clone = function () {
  13319. return new FogExp2( this.color.getHex(), this.density );
  13320. };
  13321. FogExp2.prototype.toJSON = function ( meta ) {
  13322. return {
  13323. type: 'FogExp2',
  13324. color: this.color.getHex(),
  13325. density: this.density
  13326. };
  13327. };
  13328. /**
  13329. * @author mrdoob / http://mrdoob.com/
  13330. * @author alteredq / http://alteredqualia.com/
  13331. */
  13332. function Fog ( color, near, far ) {
  13333. this.name = '';
  13334. this.color = new Color( color );
  13335. this.near = ( near !== undefined ) ? near : 1;
  13336. this.far = ( far !== undefined ) ? far : 1000;
  13337. }
  13338. Fog.prototype.isFog = true;
  13339. Fog.prototype.clone = function () {
  13340. return new Fog( this.color.getHex(), this.near, this.far );
  13341. };
  13342. Fog.prototype.toJSON = function ( meta ) {
  13343. return {
  13344. type: 'Fog',
  13345. color: this.color.getHex(),
  13346. near: this.near,
  13347. far: this.far
  13348. };
  13349. };
  13350. /**
  13351. * @author mrdoob / http://mrdoob.com/
  13352. */
  13353. function Scene () {
  13354. Object3D.call( this );
  13355. this.type = 'Scene';
  13356. this.background = null;
  13357. this.fog = null;
  13358. this.overrideMaterial = null;
  13359. this.autoUpdate = true; // checked by the renderer
  13360. }
  13361. Scene.prototype = Object.create( Object3D.prototype );
  13362. Scene.prototype.constructor = Scene;
  13363. Scene.prototype.copy = function ( source, recursive ) {
  13364. Object3D.prototype.copy.call( this, source, recursive );
  13365. if ( source.background !== null ) this.background = source.background.clone();
  13366. if ( source.fog !== null ) this.fog = source.fog.clone();
  13367. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13368. this.autoUpdate = source.autoUpdate;
  13369. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13370. return this;
  13371. };
  13372. Scene.prototype.toJSON = function ( meta ) {
  13373. var data = Object3D.prototype.toJSON.call( this, meta );
  13374. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  13375. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13376. return data;
  13377. };
  13378. /**
  13379. * @author mikael emtinger / http://gomo.se/
  13380. * @author alteredq / http://alteredqualia.com/
  13381. */
  13382. function LensFlare( texture, size, distance, blending, color ) {
  13383. Object3D.call( this );
  13384. this.lensFlares = [];
  13385. this.positionScreen = new Vector3();
  13386. this.customUpdateCallback = undefined;
  13387. if ( texture !== undefined ) {
  13388. this.add( texture, size, distance, blending, color );
  13389. }
  13390. }
  13391. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13392. constructor: LensFlare,
  13393. isLensFlare: true,
  13394. copy: function ( source ) {
  13395. Object3D.prototype.copy.call( this, source );
  13396. this.positionScreen.copy( source.positionScreen );
  13397. this.customUpdateCallback = source.customUpdateCallback;
  13398. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13399. this.lensFlares.push( source.lensFlares[ i ] );
  13400. }
  13401. return this;
  13402. },
  13403. add: function ( texture, size, distance, blending, color, opacity ) {
  13404. if ( size === undefined ) size = - 1;
  13405. if ( distance === undefined ) distance = 0;
  13406. if ( opacity === undefined ) opacity = 1;
  13407. if ( color === undefined ) color = new Color( 0xffffff );
  13408. if ( blending === undefined ) blending = NormalBlending;
  13409. distance = Math.min( distance, Math.max( 0, distance ) );
  13410. this.lensFlares.push( {
  13411. texture: texture, // THREE.Texture
  13412. size: size, // size in pixels (-1 = use texture.width)
  13413. distance: distance, // distance (0-1) from light source (0=at light source)
  13414. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13415. scale: 1, // scale
  13416. rotation: 0, // rotation
  13417. opacity: opacity, // opacity
  13418. color: color, // color
  13419. blending: blending // blending
  13420. } );
  13421. },
  13422. /*
  13423. * Update lens flares update positions on all flares based on the screen position
  13424. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13425. */
  13426. updateLensFlares: function () {
  13427. var f, fl = this.lensFlares.length;
  13428. var flare;
  13429. var vecX = - this.positionScreen.x * 2;
  13430. var vecY = - this.positionScreen.y * 2;
  13431. for ( f = 0; f < fl; f ++ ) {
  13432. flare = this.lensFlares[ f ];
  13433. flare.x = this.positionScreen.x + vecX * flare.distance;
  13434. flare.y = this.positionScreen.y + vecY * flare.distance;
  13435. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13436. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13437. }
  13438. }
  13439. } );
  13440. /**
  13441. * @author alteredq / http://alteredqualia.com/
  13442. *
  13443. * parameters = {
  13444. * color: <hex>,
  13445. * opacity: <float>,
  13446. * map: new THREE.Texture( <Image> ),
  13447. *
  13448. * uvOffset: new THREE.Vector2(),
  13449. * uvScale: new THREE.Vector2()
  13450. * }
  13451. */
  13452. function SpriteMaterial( parameters ) {
  13453. Material.call( this );
  13454. this.type = 'SpriteMaterial';
  13455. this.color = new Color( 0xffffff );
  13456. this.map = null;
  13457. this.rotation = 0;
  13458. this.fog = false;
  13459. this.lights = false;
  13460. this.setValues( parameters );
  13461. }
  13462. SpriteMaterial.prototype = Object.create( Material.prototype );
  13463. SpriteMaterial.prototype.constructor = SpriteMaterial;
  13464. SpriteMaterial.prototype.copy = function ( source ) {
  13465. Material.prototype.copy.call( this, source );
  13466. this.color.copy( source.color );
  13467. this.map = source.map;
  13468. this.rotation = source.rotation;
  13469. return this;
  13470. };
  13471. /**
  13472. * @author mikael emtinger / http://gomo.se/
  13473. * @author alteredq / http://alteredqualia.com/
  13474. */
  13475. function Sprite( material ) {
  13476. Object3D.call( this );
  13477. this.type = 'Sprite';
  13478. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  13479. }
  13480. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13481. constructor: Sprite,
  13482. isSprite: true,
  13483. raycast: ( function () {
  13484. var matrixPosition = new Vector3();
  13485. return function raycast( raycaster, intersects ) {
  13486. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13487. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  13488. var guessSizeSq = this.scale.x * this.scale.y / 4;
  13489. if ( distanceSq > guessSizeSq ) {
  13490. return;
  13491. }
  13492. intersects.push( {
  13493. distance: Math.sqrt( distanceSq ),
  13494. point: this.position,
  13495. face: null,
  13496. object: this
  13497. } );
  13498. };
  13499. }() ),
  13500. clone: function () {
  13501. return new this.constructor( this.material ).copy( this );
  13502. }
  13503. } );
  13504. /**
  13505. * @author mikael emtinger / http://gomo.se/
  13506. * @author alteredq / http://alteredqualia.com/
  13507. * @author mrdoob / http://mrdoob.com/
  13508. */
  13509. function LOD() {
  13510. Object3D.call( this );
  13511. this.type = 'LOD';
  13512. Object.defineProperties( this, {
  13513. levels: {
  13514. enumerable: true,
  13515. value: []
  13516. }
  13517. } );
  13518. }
  13519. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13520. constructor: LOD,
  13521. copy: function ( source ) {
  13522. Object3D.prototype.copy.call( this, source, false );
  13523. var levels = source.levels;
  13524. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13525. var level = levels[ i ];
  13526. this.addLevel( level.object.clone(), level.distance );
  13527. }
  13528. return this;
  13529. },
  13530. addLevel: function ( object, distance ) {
  13531. if ( distance === undefined ) distance = 0;
  13532. distance = Math.abs( distance );
  13533. var levels = this.levels;
  13534. for ( var l = 0; l < levels.length; l ++ ) {
  13535. if ( distance < levels[ l ].distance ) {
  13536. break;
  13537. }
  13538. }
  13539. levels.splice( l, 0, { distance: distance, object: object } );
  13540. this.add( object );
  13541. },
  13542. getObjectForDistance: function ( distance ) {
  13543. var levels = this.levels;
  13544. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13545. if ( distance < levels[ i ].distance ) {
  13546. break;
  13547. }
  13548. }
  13549. return levels[ i - 1 ].object;
  13550. },
  13551. raycast: ( function () {
  13552. var matrixPosition = new Vector3();
  13553. return function raycast( raycaster, intersects ) {
  13554. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13555. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13556. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13557. };
  13558. }() ),
  13559. update: function () {
  13560. var v1 = new Vector3();
  13561. var v2 = new Vector3();
  13562. return function update( camera ) {
  13563. var levels = this.levels;
  13564. if ( levels.length > 1 ) {
  13565. v1.setFromMatrixPosition( camera.matrixWorld );
  13566. v2.setFromMatrixPosition( this.matrixWorld );
  13567. var distance = v1.distanceTo( v2 );
  13568. levels[ 0 ].object.visible = true;
  13569. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13570. if ( distance >= levels[ i ].distance ) {
  13571. levels[ i - 1 ].object.visible = false;
  13572. levels[ i ].object.visible = true;
  13573. } else {
  13574. break;
  13575. }
  13576. }
  13577. for ( ; i < l; i ++ ) {
  13578. levels[ i ].object.visible = false;
  13579. }
  13580. }
  13581. };
  13582. }(),
  13583. toJSON: function ( meta ) {
  13584. var data = Object3D.prototype.toJSON.call( this, meta );
  13585. data.object.levels = [];
  13586. var levels = this.levels;
  13587. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13588. var level = levels[ i ];
  13589. data.object.levels.push( {
  13590. object: level.object.uuid,
  13591. distance: level.distance
  13592. } );
  13593. }
  13594. return data;
  13595. }
  13596. } );
  13597. /**
  13598. * @author mikael emtinger / http://gomo.se/
  13599. * @author alteredq / http://alteredqualia.com/
  13600. * @author michael guerrero / http://realitymeltdown.com
  13601. * @author ikerr / http://verold.com
  13602. */
  13603. function Skeleton( bones, boneInverses, useVertexTexture ) {
  13604. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  13605. this.identityMatrix = new Matrix4();
  13606. // copy the bone array
  13607. bones = bones || [];
  13608. this.bones = bones.slice( 0 );
  13609. // create a bone texture or an array of floats
  13610. if ( this.useVertexTexture ) {
  13611. // layout (1 matrix = 4 pixels)
  13612. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13613. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13614. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13615. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13616. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13617. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  13618. size = _Math.nextPowerOfTwo( Math.ceil( size ) );
  13619. size = Math.max( size, 4 );
  13620. this.boneTextureWidth = size;
  13621. this.boneTextureHeight = size;
  13622. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  13623. this.boneTexture = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType );
  13624. } else {
  13625. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  13626. }
  13627. // use the supplied bone inverses or calculate the inverses
  13628. if ( boneInverses === undefined ) {
  13629. this.calculateInverses();
  13630. } else {
  13631. if ( this.bones.length === boneInverses.length ) {
  13632. this.boneInverses = boneInverses.slice( 0 );
  13633. } else {
  13634. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  13635. this.boneInverses = [];
  13636. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13637. this.boneInverses.push( new Matrix4() );
  13638. }
  13639. }
  13640. }
  13641. }
  13642. Object.assign( Skeleton.prototype, {
  13643. calculateInverses: function () {
  13644. this.boneInverses = [];
  13645. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13646. var inverse = new Matrix4();
  13647. if ( this.bones[ b ] ) {
  13648. inverse.getInverse( this.bones[ b ].matrixWorld );
  13649. }
  13650. this.boneInverses.push( inverse );
  13651. }
  13652. },
  13653. pose: function () {
  13654. var bone;
  13655. // recover the bind-time world matrices
  13656. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13657. bone = this.bones[ b ];
  13658. if ( bone ) {
  13659. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  13660. }
  13661. }
  13662. // compute the local matrices, positions, rotations and scales
  13663. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13664. bone = this.bones[ b ];
  13665. if ( bone ) {
  13666. if ( bone.parent && bone.parent.isBone ) {
  13667. bone.matrix.getInverse( bone.parent.matrixWorld );
  13668. bone.matrix.multiply( bone.matrixWorld );
  13669. } else {
  13670. bone.matrix.copy( bone.matrixWorld );
  13671. }
  13672. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  13673. }
  13674. }
  13675. },
  13676. update: ( function () {
  13677. var offsetMatrix = new Matrix4();
  13678. return function update() {
  13679. // flatten bone matrices to array
  13680. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13681. // compute the offset between the current and the original transform
  13682. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  13683. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  13684. offsetMatrix.toArray( this.boneMatrices, b * 16 );
  13685. }
  13686. if ( this.useVertexTexture ) {
  13687. this.boneTexture.needsUpdate = true;
  13688. }
  13689. };
  13690. } )(),
  13691. clone: function () {
  13692. return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  13693. }
  13694. } );
  13695. /**
  13696. * @author mikael emtinger / http://gomo.se/
  13697. * @author alteredq / http://alteredqualia.com/
  13698. * @author ikerr / http://verold.com
  13699. */
  13700. function Bone() {
  13701. Object3D.call( this );
  13702. this.type = 'Bone';
  13703. }
  13704. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13705. constructor: Bone,
  13706. isBone: true
  13707. } );
  13708. /**
  13709. * @author mikael emtinger / http://gomo.se/
  13710. * @author alteredq / http://alteredqualia.com/
  13711. * @author ikerr / http://verold.com
  13712. */
  13713. function SkinnedMesh( geometry, material, useVertexTexture ) {
  13714. Mesh.call( this, geometry, material );
  13715. this.type = 'SkinnedMesh';
  13716. this.bindMode = "attached";
  13717. this.bindMatrix = new Matrix4();
  13718. this.bindMatrixInverse = new Matrix4();
  13719. // init bones
  13720. // TODO: remove bone creation as there is no reason (other than
  13721. // convenience) for THREE.SkinnedMesh to do this.
  13722. var bones = [];
  13723. if ( this.geometry && this.geometry.bones !== undefined ) {
  13724. var bone, gbone;
  13725. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13726. gbone = this.geometry.bones[ b ];
  13727. bone = new Bone();
  13728. bones.push( bone );
  13729. bone.name = gbone.name;
  13730. bone.position.fromArray( gbone.pos );
  13731. bone.quaternion.fromArray( gbone.rotq );
  13732. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  13733. }
  13734. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13735. gbone = this.geometry.bones[ b ];
  13736. if ( gbone.parent !== - 1 && gbone.parent !== null &&
  13737. bones[ gbone.parent ] !== undefined ) {
  13738. bones[ gbone.parent ].add( bones[ b ] );
  13739. } else {
  13740. this.add( bones[ b ] );
  13741. }
  13742. }
  13743. }
  13744. this.normalizeSkinWeights();
  13745. this.updateMatrixWorld( true );
  13746. this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  13747. }
  13748. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  13749. constructor: SkinnedMesh,
  13750. isSkinnedMesh: true,
  13751. bind: function( skeleton, bindMatrix ) {
  13752. this.skeleton = skeleton;
  13753. if ( bindMatrix === undefined ) {
  13754. this.updateMatrixWorld( true );
  13755. this.skeleton.calculateInverses();
  13756. bindMatrix = this.matrixWorld;
  13757. }
  13758. this.bindMatrix.copy( bindMatrix );
  13759. this.bindMatrixInverse.getInverse( bindMatrix );
  13760. },
  13761. pose: function () {
  13762. this.skeleton.pose();
  13763. },
  13764. normalizeSkinWeights: function () {
  13765. if ( this.geometry && this.geometry.isGeometry ) {
  13766. for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  13767. var sw = this.geometry.skinWeights[ i ];
  13768. var scale = 1.0 / sw.lengthManhattan();
  13769. if ( scale !== Infinity ) {
  13770. sw.multiplyScalar( scale );
  13771. } else {
  13772. sw.set( 1, 0, 0, 0 ); // do something reasonable
  13773. }
  13774. }
  13775. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  13776. var vec = new Vector4();
  13777. var skinWeight = this.geometry.attributes.skinWeight;
  13778. for ( var i = 0; i < skinWeight.count; i ++ ) {
  13779. vec.x = skinWeight.getX( i );
  13780. vec.y = skinWeight.getY( i );
  13781. vec.z = skinWeight.getZ( i );
  13782. vec.w = skinWeight.getW( i );
  13783. var scale = 1.0 / vec.lengthManhattan();
  13784. if ( scale !== Infinity ) {
  13785. vec.multiplyScalar( scale );
  13786. } else {
  13787. vec.set( 1, 0, 0, 0 ); // do something reasonable
  13788. }
  13789. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  13790. }
  13791. }
  13792. },
  13793. updateMatrixWorld: function( force ) {
  13794. Mesh.prototype.updateMatrixWorld.call( this, true );
  13795. if ( this.bindMode === "attached" ) {
  13796. this.bindMatrixInverse.getInverse( this.matrixWorld );
  13797. } else if ( this.bindMode === "detached" ) {
  13798. this.bindMatrixInverse.getInverse( this.bindMatrix );
  13799. } else {
  13800. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  13801. }
  13802. },
  13803. clone: function() {
  13804. return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this );
  13805. }
  13806. } );
  13807. /**
  13808. * @author mrdoob / http://mrdoob.com/
  13809. * @author alteredq / http://alteredqualia.com/
  13810. *
  13811. * parameters = {
  13812. * color: <hex>,
  13813. * opacity: <float>,
  13814. *
  13815. * linewidth: <float>,
  13816. * linecap: "round",
  13817. * linejoin: "round"
  13818. * }
  13819. */
  13820. function LineBasicMaterial( parameters ) {
  13821. Material.call( this );
  13822. this.type = 'LineBasicMaterial';
  13823. this.color = new Color( 0xffffff );
  13824. this.linewidth = 1;
  13825. this.linecap = 'round';
  13826. this.linejoin = 'round';
  13827. this.lights = false;
  13828. this.setValues( parameters );
  13829. }
  13830. LineBasicMaterial.prototype = Object.create( Material.prototype );
  13831. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  13832. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  13833. LineBasicMaterial.prototype.copy = function ( source ) {
  13834. Material.prototype.copy.call( this, source );
  13835. this.color.copy( source.color );
  13836. this.linewidth = source.linewidth;
  13837. this.linecap = source.linecap;
  13838. this.linejoin = source.linejoin;
  13839. return this;
  13840. };
  13841. /**
  13842. * @author mrdoob / http://mrdoob.com/
  13843. */
  13844. function Line( geometry, material, mode ) {
  13845. if ( mode === 1 ) {
  13846. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  13847. return new LineSegments( geometry, material );
  13848. }
  13849. Object3D.call( this );
  13850. this.type = 'Line';
  13851. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13852. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  13853. }
  13854. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13855. constructor: Line,
  13856. isLine: true,
  13857. raycast: ( function () {
  13858. var inverseMatrix = new Matrix4();
  13859. var ray = new Ray();
  13860. var sphere = new Sphere();
  13861. return function raycast( raycaster, intersects ) {
  13862. var precision = raycaster.linePrecision;
  13863. var precisionSq = precision * precision;
  13864. var geometry = this.geometry;
  13865. var matrixWorld = this.matrixWorld;
  13866. // Checking boundingSphere distance to ray
  13867. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13868. sphere.copy( geometry.boundingSphere );
  13869. sphere.applyMatrix4( matrixWorld );
  13870. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13871. //
  13872. inverseMatrix.getInverse( matrixWorld );
  13873. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13874. var vStart = new Vector3();
  13875. var vEnd = new Vector3();
  13876. var interSegment = new Vector3();
  13877. var interRay = new Vector3();
  13878. var step = (this && this.isLineSegments) ? 2 : 1;
  13879. if ( geometry.isBufferGeometry ) {
  13880. var index = geometry.index;
  13881. var attributes = geometry.attributes;
  13882. var positions = attributes.position.array;
  13883. if ( index !== null ) {
  13884. var indices = index.array;
  13885. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  13886. var a = indices[ i ];
  13887. var b = indices[ i + 1 ];
  13888. vStart.fromArray( positions, a * 3 );
  13889. vEnd.fromArray( positions, b * 3 );
  13890. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13891. if ( distSq > precisionSq ) continue;
  13892. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13893. var distance = raycaster.ray.origin.distanceTo( interRay );
  13894. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13895. intersects.push( {
  13896. distance: distance,
  13897. // What do we want? intersection point on the ray or on the segment??
  13898. // point: raycaster.ray.at( distance ),
  13899. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13900. index: i,
  13901. face: null,
  13902. faceIndex: null,
  13903. object: this
  13904. } );
  13905. }
  13906. } else {
  13907. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  13908. vStart.fromArray( positions, 3 * i );
  13909. vEnd.fromArray( positions, 3 * i + 3 );
  13910. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13911. if ( distSq > precisionSq ) continue;
  13912. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13913. var distance = raycaster.ray.origin.distanceTo( interRay );
  13914. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13915. intersects.push( {
  13916. distance: distance,
  13917. // What do we want? intersection point on the ray or on the segment??
  13918. // point: raycaster.ray.at( distance ),
  13919. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13920. index: i,
  13921. face: null,
  13922. faceIndex: null,
  13923. object: this
  13924. } );
  13925. }
  13926. }
  13927. } else if ( geometry.isGeometry ) {
  13928. var vertices = geometry.vertices;
  13929. var nbVertices = vertices.length;
  13930. for ( var i = 0; i < nbVertices - 1; i += step ) {
  13931. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  13932. if ( distSq > precisionSq ) continue;
  13933. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13934. var distance = raycaster.ray.origin.distanceTo( interRay );
  13935. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13936. intersects.push( {
  13937. distance: distance,
  13938. // What do we want? intersection point on the ray or on the segment??
  13939. // point: raycaster.ray.at( distance ),
  13940. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13941. index: i,
  13942. face: null,
  13943. faceIndex: null,
  13944. object: this
  13945. } );
  13946. }
  13947. }
  13948. };
  13949. }() ),
  13950. clone: function () {
  13951. return new this.constructor( this.geometry, this.material ).copy( this );
  13952. }
  13953. } );
  13954. /**
  13955. * @author mrdoob / http://mrdoob.com/
  13956. */
  13957. function LineSegments( geometry, material ) {
  13958. Line.call( this, geometry, material );
  13959. this.type = 'LineSegments';
  13960. }
  13961. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  13962. constructor: LineSegments,
  13963. isLineSegments: true
  13964. } );
  13965. /**
  13966. * @author mrdoob / http://mrdoob.com/
  13967. * @author alteredq / http://alteredqualia.com/
  13968. *
  13969. * parameters = {
  13970. * color: <hex>,
  13971. * opacity: <float>,
  13972. * map: new THREE.Texture( <Image> ),
  13973. *
  13974. * size: <float>,
  13975. * sizeAttenuation: <bool>
  13976. * }
  13977. */
  13978. function PointsMaterial( parameters ) {
  13979. Material.call( this );
  13980. this.type = 'PointsMaterial';
  13981. this.color = new Color( 0xffffff );
  13982. this.map = null;
  13983. this.size = 1;
  13984. this.sizeAttenuation = true;
  13985. this.lights = false;
  13986. this.setValues( parameters );
  13987. }
  13988. PointsMaterial.prototype = Object.create( Material.prototype );
  13989. PointsMaterial.prototype.constructor = PointsMaterial;
  13990. PointsMaterial.prototype.isPointsMaterial = true;
  13991. PointsMaterial.prototype.copy = function ( source ) {
  13992. Material.prototype.copy.call( this, source );
  13993. this.color.copy( source.color );
  13994. this.map = source.map;
  13995. this.size = source.size;
  13996. this.sizeAttenuation = source.sizeAttenuation;
  13997. return this;
  13998. };
  13999. /**
  14000. * @author alteredq / http://alteredqualia.com/
  14001. */
  14002. function Points( geometry, material ) {
  14003. Object3D.call( this );
  14004. this.type = 'Points';
  14005. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14006. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  14007. }
  14008. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14009. constructor: Points,
  14010. isPoints: true,
  14011. raycast: ( function () {
  14012. var inverseMatrix = new Matrix4();
  14013. var ray = new Ray();
  14014. var sphere = new Sphere();
  14015. return function raycast( raycaster, intersects ) {
  14016. var object = this;
  14017. var geometry = this.geometry;
  14018. var matrixWorld = this.matrixWorld;
  14019. var threshold = raycaster.params.Points.threshold;
  14020. // Checking boundingSphere distance to ray
  14021. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14022. sphere.copy( geometry.boundingSphere );
  14023. sphere.applyMatrix4( matrixWorld );
  14024. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14025. //
  14026. inverseMatrix.getInverse( matrixWorld );
  14027. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14028. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  14029. var localThresholdSq = localThreshold * localThreshold;
  14030. var position = new Vector3();
  14031. function testPoint( point, index ) {
  14032. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  14033. if ( rayPointDistanceSq < localThresholdSq ) {
  14034. var intersectPoint = ray.closestPointToPoint( point );
  14035. intersectPoint.applyMatrix4( matrixWorld );
  14036. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  14037. if ( distance < raycaster.near || distance > raycaster.far ) return;
  14038. intersects.push( {
  14039. distance: distance,
  14040. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  14041. point: intersectPoint.clone(),
  14042. index: index,
  14043. face: null,
  14044. object: object
  14045. } );
  14046. }
  14047. }
  14048. if ( geometry.isBufferGeometry ) {
  14049. var index = geometry.index;
  14050. var attributes = geometry.attributes;
  14051. var positions = attributes.position.array;
  14052. if ( index !== null ) {
  14053. var indices = index.array;
  14054. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  14055. var a = indices[ i ];
  14056. position.fromArray( positions, a * 3 );
  14057. testPoint( position, a );
  14058. }
  14059. } else {
  14060. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  14061. position.fromArray( positions, i * 3 );
  14062. testPoint( position, i );
  14063. }
  14064. }
  14065. } else {
  14066. var vertices = geometry.vertices;
  14067. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  14068. testPoint( vertices[ i ], i );
  14069. }
  14070. }
  14071. };
  14072. }() ),
  14073. clone: function () {
  14074. return new this.constructor( this.geometry, this.material ).copy( this );
  14075. }
  14076. } );
  14077. /**
  14078. * @author mrdoob / http://mrdoob.com/
  14079. */
  14080. function Group() {
  14081. Object3D.call( this );
  14082. this.type = 'Group';
  14083. }
  14084. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14085. constructor: Group
  14086. } );
  14087. /**
  14088. * @author mrdoob / http://mrdoob.com/
  14089. */
  14090. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14091. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14092. this.generateMipmaps = false;
  14093. var scope = this;
  14094. function update() {
  14095. requestAnimationFrame( update );
  14096. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  14097. scope.needsUpdate = true;
  14098. }
  14099. }
  14100. update();
  14101. }
  14102. VideoTexture.prototype = Object.create( Texture.prototype );
  14103. VideoTexture.prototype.constructor = VideoTexture;
  14104. /**
  14105. * @author alteredq / http://alteredqualia.com/
  14106. */
  14107. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  14108. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  14109. this.image = { width: width, height: height };
  14110. this.mipmaps = mipmaps;
  14111. // no flipping for cube textures
  14112. // (also flipping doesn't work for compressed textures )
  14113. this.flipY = false;
  14114. // can't generate mipmaps for compressed textures
  14115. // mips must be embedded in DDS files
  14116. this.generateMipmaps = false;
  14117. }
  14118. CompressedTexture.prototype = Object.create( Texture.prototype );
  14119. CompressedTexture.prototype.constructor = CompressedTexture;
  14120. CompressedTexture.prototype.isCompressedTexture = true;
  14121. /**
  14122. * @author mrdoob / http://mrdoob.com/
  14123. */
  14124. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14125. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14126. this.needsUpdate = true;
  14127. }
  14128. CanvasTexture.prototype = Object.create( Texture.prototype );
  14129. CanvasTexture.prototype.constructor = CanvasTexture;
  14130. /**
  14131. * @author Matt DesLauriers / @mattdesl
  14132. * @author atix / arthursilber.de
  14133. */
  14134. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  14135. format = format !== undefined ? format : DepthFormat;
  14136. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  14137. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' )
  14138. }
  14139. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  14140. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  14141. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14142. this.image = { width: width, height: height };
  14143. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14144. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14145. this.flipY = false;
  14146. this.generateMipmaps = false;
  14147. }
  14148. DepthTexture.prototype = Object.create( Texture.prototype );
  14149. DepthTexture.prototype.constructor = DepthTexture;
  14150. DepthTexture.prototype.isDepthTexture = true;
  14151. /**
  14152. * @author mrdoob / http://mrdoob.com/
  14153. */
  14154. function WireframeGeometry( geometry ) {
  14155. BufferGeometry.call( this );
  14156. var edge = [ 0, 0 ], hash = {};
  14157. function sortFunction( a, b ) {
  14158. return a - b;
  14159. }
  14160. var keys = [ 'a', 'b', 'c' ];
  14161. if ( geometry && geometry.isGeometry ) {
  14162. var vertices = geometry.vertices;
  14163. var faces = geometry.faces;
  14164. var numEdges = 0;
  14165. // allocate maximal size
  14166. var edges = new Uint32Array( 6 * faces.length );
  14167. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  14168. var face = faces[ i ];
  14169. for ( var j = 0; j < 3; j ++ ) {
  14170. edge[ 0 ] = face[ keys[ j ] ];
  14171. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  14172. edge.sort( sortFunction );
  14173. var key = edge.toString();
  14174. if ( hash[ key ] === undefined ) {
  14175. edges[ 2 * numEdges ] = edge[ 0 ];
  14176. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  14177. hash[ key ] = true;
  14178. numEdges ++;
  14179. }
  14180. }
  14181. }
  14182. var coords = new Float32Array( numEdges * 2 * 3 );
  14183. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  14184. for ( var j = 0; j < 2; j ++ ) {
  14185. var vertex = vertices[ edges [ 2 * i + j ] ];
  14186. var index = 6 * i + 3 * j;
  14187. coords[ index + 0 ] = vertex.x;
  14188. coords[ index + 1 ] = vertex.y;
  14189. coords[ index + 2 ] = vertex.z;
  14190. }
  14191. }
  14192. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  14193. } else if ( geometry && geometry.isBufferGeometry ) {
  14194. if ( geometry.index !== null ) {
  14195. // Indexed BufferGeometry
  14196. var indices = geometry.index.array;
  14197. var vertices = geometry.attributes.position;
  14198. var groups = geometry.groups;
  14199. var numEdges = 0;
  14200. if ( groups.length === 0 ) {
  14201. geometry.addGroup( 0, indices.length );
  14202. }
  14203. // allocate maximal size
  14204. var edges = new Uint32Array( 2 * indices.length );
  14205. for ( var o = 0, ol = groups.length; o < ol; ++ o ) {
  14206. var group = groups[ o ];
  14207. var start = group.start;
  14208. var count = group.count;
  14209. for ( var i = start, il = start + count; i < il; i += 3 ) {
  14210. for ( var j = 0; j < 3; j ++ ) {
  14211. edge[ 0 ] = indices[ i + j ];
  14212. edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
  14213. edge.sort( sortFunction );
  14214. var key = edge.toString();
  14215. if ( hash[ key ] === undefined ) {
  14216. edges[ 2 * numEdges ] = edge[ 0 ];
  14217. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  14218. hash[ key ] = true;
  14219. numEdges ++;
  14220. }
  14221. }
  14222. }
  14223. }
  14224. var coords = new Float32Array( numEdges * 2 * 3 );
  14225. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  14226. for ( var j = 0; j < 2; j ++ ) {
  14227. var index = 6 * i + 3 * j;
  14228. var index2 = edges[ 2 * i + j ];
  14229. coords[ index + 0 ] = vertices.getX( index2 );
  14230. coords[ index + 1 ] = vertices.getY( index2 );
  14231. coords[ index + 2 ] = vertices.getZ( index2 );
  14232. }
  14233. }
  14234. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  14235. } else {
  14236. // non-indexed BufferGeometry
  14237. var vertices = geometry.attributes.position.array;
  14238. var numEdges = vertices.length / 3;
  14239. var numTris = numEdges / 3;
  14240. var coords = new Float32Array( numEdges * 2 * 3 );
  14241. for ( var i = 0, l = numTris; i < l; i ++ ) {
  14242. for ( var j = 0; j < 3; j ++ ) {
  14243. var index = 18 * i + 6 * j;
  14244. var index1 = 9 * i + 3 * j;
  14245. coords[ index + 0 ] = vertices[ index1 ];
  14246. coords[ index + 1 ] = vertices[ index1 + 1 ];
  14247. coords[ index + 2 ] = vertices[ index1 + 2 ];
  14248. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  14249. coords[ index + 3 ] = vertices[ index2 ];
  14250. coords[ index + 4 ] = vertices[ index2 + 1 ];
  14251. coords[ index + 5 ] = vertices[ index2 + 2 ];
  14252. }
  14253. }
  14254. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  14255. }
  14256. }
  14257. }
  14258. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  14259. WireframeGeometry.prototype.constructor = WireframeGeometry;
  14260. /**
  14261. * @author Mugen87 / https://github.com/Mugen87
  14262. *
  14263. * Parametric Surfaces Geometry
  14264. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  14265. */
  14266. function ParametricBufferGeometry( func, slices, stacks ) {
  14267. BufferGeometry.call( this );
  14268. this.type = 'ParametricBufferGeometry';
  14269. this.parameters = {
  14270. func: func,
  14271. slices: slices,
  14272. stacks: stacks
  14273. };
  14274. // generate vertices and uvs
  14275. var vertices = [];
  14276. var uvs = [];
  14277. var i, j, p;
  14278. var u, v;
  14279. var sliceCount = slices + 1;
  14280. for ( i = 0; i <= stacks; i ++ ) {
  14281. v = i / stacks;
  14282. for ( j = 0; j <= slices; j ++ ) {
  14283. u = j / slices;
  14284. p = func( u, v );
  14285. vertices.push( p.x, p.y, p.z );
  14286. uvs.push( u, v );
  14287. }
  14288. }
  14289. // generate indices
  14290. var indices = [];
  14291. var a, b, c, d;
  14292. for ( i = 0; i < stacks; i ++ ) {
  14293. for ( j = 0; j < slices; j ++ ) {
  14294. a = i * sliceCount + j;
  14295. b = i * sliceCount + j + 1;
  14296. c = ( i + 1 ) * sliceCount + j + 1;
  14297. d = ( i + 1 ) * sliceCount + j;
  14298. // faces one and two
  14299. indices.push( a, b, d );
  14300. indices.push( b, c, d );
  14301. }
  14302. }
  14303. // build geometry
  14304. this.setIndex( new ( indices.length > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  14305. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14306. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14307. // generate normals
  14308. this.computeVertexNormals();
  14309. }
  14310. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14311. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  14312. /**
  14313. * @author zz85 / https://github.com/zz85
  14314. *
  14315. * Parametric Surfaces Geometry
  14316. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  14317. */
  14318. function ParametricGeometry( func, slices, stacks ) {
  14319. Geometry.call( this );
  14320. this.type = 'ParametricGeometry';
  14321. this.parameters = {
  14322. func: func,
  14323. slices: slices,
  14324. stacks: stacks
  14325. };
  14326. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  14327. this.mergeVertices();
  14328. }
  14329. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  14330. ParametricGeometry.prototype.constructor = ParametricGeometry;
  14331. /**
  14332. * @author Mugen87 / https://github.com/Mugen87
  14333. */
  14334. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  14335. BufferGeometry.call( this );
  14336. this.type = 'PolyhedronBufferGeometry';
  14337. this.parameters = {
  14338. vertices: vertices,
  14339. indices: indices,
  14340. radius: radius,
  14341. detail: detail
  14342. };
  14343. radius = radius || 1;
  14344. detail = detail || 0;
  14345. // default buffer data
  14346. var vertexBuffer = [];
  14347. var uvBuffer = [];
  14348. // the subdivision creates the vertex buffer data
  14349. subdivide( detail );
  14350. // all vertices should lie on a conceptual sphere with a given radius
  14351. appplyRadius( radius );
  14352. // finally, create the uv data
  14353. generateUVs();
  14354. // build non-indexed geometry
  14355. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  14356. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  14357. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  14358. this.normalizeNormals();
  14359. this.boundingSphere = new Sphere( new Vector3(), radius );
  14360. // helper functions
  14361. function subdivide( detail ) {
  14362. var a = new Vector3();
  14363. var b = new Vector3();
  14364. var c = new Vector3();
  14365. // iterate over all faces and apply a subdivison with the given detail value
  14366. for ( var i = 0; i < indices.length; i += 3 ) {
  14367. // get the vertices of the face
  14368. getVertexByIndex( indices[ i + 0 ], a );
  14369. getVertexByIndex( indices[ i + 1 ], b );
  14370. getVertexByIndex( indices[ i + 2 ], c );
  14371. // perform subdivision
  14372. subdivideFace( a, b, c, detail );
  14373. }
  14374. }
  14375. function subdivideFace( a, b, c, detail ) {
  14376. var cols = Math.pow( 2, detail );
  14377. // we use this multidimensional array as a data structure for creating the subdivision
  14378. var v = [];
  14379. var i, j;
  14380. // construct all of the vertices for this subdivision
  14381. for ( i = 0 ; i <= cols; i ++ ) {
  14382. v[ i ] = [];
  14383. var aj = a.clone().lerp( c, i / cols );
  14384. var bj = b.clone().lerp( c, i / cols );
  14385. var rows = cols - i;
  14386. for ( j = 0; j <= rows; j ++ ) {
  14387. if ( j === 0 && i === cols ) {
  14388. v[ i ][ j ] = aj;
  14389. } else {
  14390. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  14391. }
  14392. }
  14393. }
  14394. // construct all of the faces
  14395. for ( i = 0; i < cols ; i ++ ) {
  14396. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  14397. var k = Math.floor( j / 2 );
  14398. if ( j % 2 === 0 ) {
  14399. pushVertex( v[ i ][ k + 1 ] );
  14400. pushVertex( v[ i + 1 ][ k ] );
  14401. pushVertex( v[ i ][ k ] );
  14402. } else {
  14403. pushVertex( v[ i ][ k + 1 ] );
  14404. pushVertex( v[ i + 1 ][ k + 1 ] );
  14405. pushVertex( v[ i + 1 ][ k ] );
  14406. }
  14407. }
  14408. }
  14409. }
  14410. function appplyRadius( radius ) {
  14411. var vertex = new Vector3();
  14412. // iterate over the entire buffer and apply the radius to each vertex
  14413. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14414. vertex.x = vertexBuffer[ i + 0 ];
  14415. vertex.y = vertexBuffer[ i + 1 ];
  14416. vertex.z = vertexBuffer[ i + 2 ];
  14417. vertex.normalize().multiplyScalar( radius );
  14418. vertexBuffer[ i + 0 ] = vertex.x;
  14419. vertexBuffer[ i + 1 ] = vertex.y;
  14420. vertexBuffer[ i + 2 ] = vertex.z;
  14421. }
  14422. }
  14423. function generateUVs() {
  14424. var vertex = new Vector3();
  14425. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14426. vertex.x = vertexBuffer[ i + 0 ];
  14427. vertex.y = vertexBuffer[ i + 1 ];
  14428. vertex.z = vertexBuffer[ i + 2 ];
  14429. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  14430. var v = inclination( vertex ) / Math.PI + 0.5;
  14431. uvBuffer.push( u, 1 - v );
  14432. }
  14433. correctUVs();
  14434. correctSeam();
  14435. }
  14436. function correctSeam() {
  14437. // handle case when face straddles the seam, see #3269
  14438. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  14439. // uv data of a single face
  14440. var x0 = uvBuffer[ i + 0 ];
  14441. var x1 = uvBuffer[ i + 2 ];
  14442. var x2 = uvBuffer[ i + 4 ];
  14443. var max = Math.max( x0, x1, x2 );
  14444. var min = Math.min( x0, x1, x2 );
  14445. // 0.9 is somewhat arbitrary
  14446. if ( max > 0.9 && min < 0.1 ) {
  14447. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  14448. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  14449. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  14450. }
  14451. }
  14452. }
  14453. function pushVertex( vertex ) {
  14454. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  14455. }
  14456. function getVertexByIndex( index, vertex ) {
  14457. var stride = index * 3;
  14458. vertex.x = vertices[ stride + 0 ];
  14459. vertex.y = vertices[ stride + 1 ];
  14460. vertex.z = vertices[ stride + 2 ];
  14461. }
  14462. function correctUVs() {
  14463. var a = new Vector3();
  14464. var b = new Vector3();
  14465. var c = new Vector3();
  14466. var centroid = new Vector3();
  14467. var uvA = new Vector2();
  14468. var uvB = new Vector2();
  14469. var uvC = new Vector2();
  14470. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  14471. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  14472. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  14473. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  14474. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  14475. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  14476. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  14477. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  14478. var azi = azimuth( centroid );
  14479. correctUV( uvA, j + 0, a, azi );
  14480. correctUV( uvB, j + 2, b, azi );
  14481. correctUV( uvC, j + 4, c, azi );
  14482. }
  14483. }
  14484. function correctUV( uv, stride, vector, azimuth ) {
  14485. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  14486. uvBuffer[ stride ] = uv.x - 1;
  14487. }
  14488. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  14489. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  14490. }
  14491. }
  14492. // Angle around the Y axis, counter-clockwise when looking from above.
  14493. function azimuth( vector ) {
  14494. return Math.atan2( vector.z, - vector.x );
  14495. }
  14496. // Angle above the XZ plane.
  14497. function inclination( vector ) {
  14498. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  14499. }
  14500. }
  14501. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14502. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  14503. /**
  14504. * @author Mugen87 / https://github.com/Mugen87
  14505. */
  14506. function TetrahedronBufferGeometry( radius, detail ) {
  14507. var vertices = [
  14508. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  14509. ];
  14510. var indices = [
  14511. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  14512. ];
  14513. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14514. this.type = 'TetrahedronBufferGeometry';
  14515. this.parameters = {
  14516. radius: radius,
  14517. detail: detail
  14518. };
  14519. }
  14520. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14521. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  14522. /**
  14523. * @author timothypratley / https://github.com/timothypratley
  14524. */
  14525. function TetrahedronGeometry( radius, detail ) {
  14526. Geometry.call( this );
  14527. this.type = 'TetrahedronGeometry';
  14528. this.parameters = {
  14529. radius: radius,
  14530. detail: detail
  14531. };
  14532. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  14533. this.mergeVertices();
  14534. }
  14535. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  14536. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  14537. /**
  14538. * @author Mugen87 / https://github.com/Mugen87
  14539. */
  14540. function OctahedronBufferGeometry( radius,detail ) {
  14541. var vertices = [
  14542. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  14543. ];
  14544. var indices = [
  14545. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  14546. ];
  14547. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14548. this.type = 'OctahedronBufferGeometry';
  14549. this.parameters = {
  14550. radius: radius,
  14551. detail: detail
  14552. };
  14553. }
  14554. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14555. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  14556. /**
  14557. * @author timothypratley / https://github.com/timothypratley
  14558. */
  14559. function OctahedronGeometry( radius, detail ) {
  14560. Geometry.call( this );
  14561. this.type = 'OctahedronGeometry';
  14562. this.parameters = {
  14563. radius: radius,
  14564. detail: detail
  14565. };
  14566. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  14567. this.mergeVertices();
  14568. }
  14569. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  14570. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  14571. /**
  14572. * @author Mugen87 / https://github.com/Mugen87
  14573. */
  14574. function IcosahedronBufferGeometry( radius, detail ) {
  14575. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  14576. var vertices = [
  14577. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  14578. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  14579. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  14580. ];
  14581. var indices = [
  14582. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  14583. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  14584. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  14585. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  14586. ];
  14587. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14588. this.type = 'IcosahedronBufferGeometry';
  14589. this.parameters = {
  14590. radius: radius,
  14591. detail: detail
  14592. };
  14593. }
  14594. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14595. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  14596. /**
  14597. * @author timothypratley / https://github.com/timothypratley
  14598. */
  14599. function IcosahedronGeometry( radius, detail ) {
  14600. Geometry.call( this );
  14601. this.type = 'IcosahedronGeometry';
  14602. this.parameters = {
  14603. radius: radius,
  14604. detail: detail
  14605. };
  14606. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  14607. this.mergeVertices();
  14608. }
  14609. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  14610. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  14611. /**
  14612. * @author Mugen87 / https://github.com/Mugen87
  14613. */
  14614. function DodecahedronBufferGeometry( radius, detail ) {
  14615. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  14616. var r = 1 / t;
  14617. var vertices = [
  14618. // (±1, ±1, ±1)
  14619. - 1, - 1, - 1, - 1, - 1, 1,
  14620. - 1, 1, - 1, - 1, 1, 1,
  14621. 1, - 1, - 1, 1, - 1, 1,
  14622. 1, 1, - 1, 1, 1, 1,
  14623. // (0, ±1/φ, ±φ)
  14624. 0, - r, - t, 0, - r, t,
  14625. 0, r, - t, 0, r, t,
  14626. // (±1/φ, ±φ, 0)
  14627. - r, - t, 0, - r, t, 0,
  14628. r, - t, 0, r, t, 0,
  14629. // (±φ, 0, ±1/φ)
  14630. - t, 0, - r, t, 0, - r,
  14631. - t, 0, r, t, 0, r
  14632. ];
  14633. var indices = [
  14634. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  14635. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  14636. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  14637. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  14638. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  14639. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  14640. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  14641. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  14642. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  14643. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  14644. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  14645. 1, 12, 14, 1, 14, 5, 1, 5, 9
  14646. ];
  14647. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14648. this.type = 'DodecahedronBufferGeometry';
  14649. this.parameters = {
  14650. radius: radius,
  14651. detail: detail
  14652. };
  14653. }
  14654. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14655. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  14656. /**
  14657. * @author Abe Pazos / https://hamoid.com
  14658. */
  14659. function DodecahedronGeometry( radius, detail ) {
  14660. Geometry.call( this );
  14661. this.type = 'DodecahedronGeometry';
  14662. this.parameters = {
  14663. radius: radius,
  14664. detail: detail
  14665. };
  14666. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  14667. this.mergeVertices();
  14668. }
  14669. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  14670. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  14671. /**
  14672. * @author clockworkgeek / https://github.com/clockworkgeek
  14673. * @author timothypratley / https://github.com/timothypratley
  14674. * @author WestLangley / http://github.com/WestLangley
  14675. */
  14676. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  14677. Geometry.call( this );
  14678. this.type = 'PolyhedronGeometry';
  14679. this.parameters = {
  14680. vertices: vertices,
  14681. indices: indices,
  14682. radius: radius,
  14683. detail: detail
  14684. };
  14685. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  14686. this.mergeVertices();
  14687. }
  14688. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  14689. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  14690. /**
  14691. * @author Mugen87 / https://github.com/Mugen87
  14692. *
  14693. * Creates a tube which extrudes along a 3d spline.
  14694. *
  14695. */
  14696. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  14697. BufferGeometry.call( this );
  14698. this.type = 'TubeBufferGeometry';
  14699. this.parameters = {
  14700. path: path,
  14701. tubularSegments: tubularSegments,
  14702. radius: radius,
  14703. radialSegments: radialSegments,
  14704. closed: closed
  14705. };
  14706. tubularSegments = tubularSegments || 64;
  14707. radius = radius || 1;
  14708. radialSegments = radialSegments || 8;
  14709. closed = closed || false;
  14710. var frames = path.computeFrenetFrames( tubularSegments, closed );
  14711. // expose internals
  14712. this.tangents = frames.tangents;
  14713. this.normals = frames.normals;
  14714. this.binormals = frames.binormals;
  14715. // helper variables
  14716. var vertex = new Vector3();
  14717. var normal = new Vector3();
  14718. var uv = new Vector2();
  14719. var i, j;
  14720. // buffer
  14721. var vertices = [];
  14722. var normals = [];
  14723. var uvs = [];
  14724. var indices = [];
  14725. // create buffer data
  14726. generateBufferData();
  14727. // build geometry
  14728. this.setIndex( new ( indices.length > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  14729. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14730. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  14731. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14732. // functions
  14733. function generateBufferData() {
  14734. for ( i = 0; i < tubularSegments; i ++ ) {
  14735. generateSegment( i );
  14736. }
  14737. // if the geometry is not closed, generate the last row of vertices and normals
  14738. // at the regular position on the given path
  14739. //
  14740. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  14741. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  14742. // uvs are generated in a separate function.
  14743. // this makes it easy compute correct values for closed geometries
  14744. generateUVs();
  14745. // finally create faces
  14746. generateIndices();
  14747. }
  14748. function generateSegment( i ) {
  14749. // we use getPointAt to sample evenly distributed points from the given path
  14750. var P = path.getPointAt( i / tubularSegments );
  14751. // retrieve corresponding normal and binormal
  14752. var N = frames.normals[ i ];
  14753. var B = frames.binormals[ i ];
  14754. // generate normals and vertices for the current segment
  14755. for ( j = 0; j <= radialSegments; j ++ ) {
  14756. var v = j / radialSegments * Math.PI * 2;
  14757. var sin = Math.sin( v );
  14758. var cos = - Math.cos( v );
  14759. // normal
  14760. normal.x = ( cos * N.x + sin * B.x );
  14761. normal.y = ( cos * N.y + sin * B.y );
  14762. normal.z = ( cos * N.z + sin * B.z );
  14763. normal.normalize();
  14764. normals.push( normal.x, normal.y, normal.z );
  14765. // vertex
  14766. vertex.x = P.x + radius * normal.x;
  14767. vertex.y = P.y + radius * normal.y;
  14768. vertex.z = P.z + radius * normal.z;
  14769. vertices.push( vertex.x, vertex.y, vertex.z );
  14770. }
  14771. }
  14772. function generateIndices() {
  14773. for ( j = 1; j <= tubularSegments; j ++ ) {
  14774. for ( i = 1; i <= radialSegments; i ++ ) {
  14775. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  14776. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  14777. var c = ( radialSegments + 1 ) * j + i;
  14778. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  14779. // faces
  14780. indices.push( a, b, d );
  14781. indices.push( b, c, d );
  14782. }
  14783. }
  14784. }
  14785. function generateUVs() {
  14786. for ( i = 0; i <= tubularSegments; i ++ ) {
  14787. for ( j = 0; j <= radialSegments; j ++ ) {
  14788. uv.x = i / tubularSegments;
  14789. uv.y = j / radialSegments;
  14790. uvs.push( uv.x, uv.y );
  14791. }
  14792. }
  14793. }
  14794. }
  14795. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14796. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  14797. /**
  14798. * @author oosmoxiecode / https://github.com/oosmoxiecode
  14799. * @author WestLangley / https://github.com/WestLangley
  14800. * @author zz85 / https://github.com/zz85
  14801. * @author miningold / https://github.com/miningold
  14802. * @author jonobr1 / https://github.com/jonobr1
  14803. *
  14804. * Creates a tube which extrudes along a 3d spline.
  14805. */
  14806. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  14807. Geometry.call( this );
  14808. this.type = 'TubeGeometry';
  14809. this.parameters = {
  14810. path: path,
  14811. tubularSegments: tubularSegments,
  14812. radius: radius,
  14813. radialSegments: radialSegments,
  14814. closed: closed
  14815. };
  14816. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  14817. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  14818. // expose internals
  14819. this.tangents = bufferGeometry.tangents;
  14820. this.normals = bufferGeometry.normals;
  14821. this.binormals = bufferGeometry.binormals;
  14822. // create geometry
  14823. this.fromBufferGeometry( bufferGeometry );
  14824. this.mergeVertices();
  14825. }
  14826. TubeGeometry.prototype = Object.create( Geometry.prototype );
  14827. TubeGeometry.prototype.constructor = TubeGeometry;
  14828. /**
  14829. * @author Mugen87 / https://github.com/Mugen87
  14830. *
  14831. * see: http://www.blackpawn.com/texts/pqtorus/
  14832. */
  14833. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  14834. BufferGeometry.call( this );
  14835. this.type = 'TorusKnotBufferGeometry';
  14836. this.parameters = {
  14837. radius: radius,
  14838. tube: tube,
  14839. tubularSegments: tubularSegments,
  14840. radialSegments: radialSegments,
  14841. p: p,
  14842. q: q
  14843. };
  14844. radius = radius || 100;
  14845. tube = tube || 40;
  14846. tubularSegments = Math.floor( tubularSegments ) || 64;
  14847. radialSegments = Math.floor( radialSegments ) || 8;
  14848. p = p || 2;
  14849. q = q || 3;
  14850. // used to calculate buffer length
  14851. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  14852. var indexCount = radialSegments * tubularSegments * 2 * 3;
  14853. // buffers
  14854. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  14855. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  14856. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  14857. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  14858. // helper variables
  14859. var i, j, index = 0, indexOffset = 0;
  14860. var vertex = new Vector3();
  14861. var normal = new Vector3();
  14862. var uv = new Vector2();
  14863. var P1 = new Vector3();
  14864. var P2 = new Vector3();
  14865. var B = new Vector3();
  14866. var T = new Vector3();
  14867. var N = new Vector3();
  14868. // generate vertices, normals and uvs
  14869. for ( i = 0; i <= tubularSegments; ++ i ) {
  14870. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  14871. var u = i / tubularSegments * p * Math.PI * 2;
  14872. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  14873. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  14874. calculatePositionOnCurve( u, p, q, radius, P1 );
  14875. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  14876. // calculate orthonormal basis
  14877. T.subVectors( P2, P1 );
  14878. N.addVectors( P2, P1 );
  14879. B.crossVectors( T, N );
  14880. N.crossVectors( B, T );
  14881. // normalize B, N. T can be ignored, we don't use it
  14882. B.normalize();
  14883. N.normalize();
  14884. for ( j = 0; j <= radialSegments; ++ j ) {
  14885. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  14886. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  14887. var v = j / radialSegments * Math.PI * 2;
  14888. var cx = - tube * Math.cos( v );
  14889. var cy = tube * Math.sin( v );
  14890. // now calculate the final vertex position.
  14891. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  14892. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  14893. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  14894. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  14895. // vertex
  14896. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  14897. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  14898. normal.subVectors( vertex, P1 ).normalize();
  14899. normals.setXYZ( index, normal.x, normal.y, normal.z );
  14900. // uv
  14901. uv.x = i / tubularSegments;
  14902. uv.y = j / radialSegments;
  14903. uvs.setXY( index, uv.x, uv.y );
  14904. // increase index
  14905. index ++;
  14906. }
  14907. }
  14908. // generate indices
  14909. for ( j = 1; j <= tubularSegments; j ++ ) {
  14910. for ( i = 1; i <= radialSegments; i ++ ) {
  14911. // indices
  14912. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  14913. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  14914. var c = ( radialSegments + 1 ) * j + i;
  14915. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  14916. // face one
  14917. indices.setX( indexOffset, a ); indexOffset++;
  14918. indices.setX( indexOffset, b ); indexOffset++;
  14919. indices.setX( indexOffset, d ); indexOffset++;
  14920. // face two
  14921. indices.setX( indexOffset, b ); indexOffset++;
  14922. indices.setX( indexOffset, c ); indexOffset++;
  14923. indices.setX( indexOffset, d ); indexOffset++;
  14924. }
  14925. }
  14926. // build geometry
  14927. this.setIndex( indices );
  14928. this.addAttribute( 'position', vertices );
  14929. this.addAttribute( 'normal', normals );
  14930. this.addAttribute( 'uv', uvs );
  14931. // this function calculates the current position on the torus curve
  14932. function calculatePositionOnCurve( u, p, q, radius, position ) {
  14933. var cu = Math.cos( u );
  14934. var su = Math.sin( u );
  14935. var quOverP = q / p * u;
  14936. var cs = Math.cos( quOverP );
  14937. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  14938. position.y = radius * ( 2 + cs ) * su * 0.5;
  14939. position.z = radius * Math.sin( quOverP ) * 0.5;
  14940. }
  14941. }
  14942. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14943. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  14944. /**
  14945. * @author oosmoxiecode
  14946. */
  14947. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  14948. Geometry.call( this );
  14949. this.type = 'TorusKnotGeometry';
  14950. this.parameters = {
  14951. radius: radius,
  14952. tube: tube,
  14953. tubularSegments: tubularSegments,
  14954. radialSegments: radialSegments,
  14955. p: p,
  14956. q: q
  14957. };
  14958. if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  14959. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  14960. this.mergeVertices();
  14961. }
  14962. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  14963. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  14964. /**
  14965. * @author Mugen87 / https://github.com/Mugen87
  14966. */
  14967. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  14968. BufferGeometry.call( this );
  14969. this.type = 'TorusBufferGeometry';
  14970. this.parameters = {
  14971. radius: radius,
  14972. tube: tube,
  14973. radialSegments: radialSegments,
  14974. tubularSegments: tubularSegments,
  14975. arc: arc
  14976. };
  14977. radius = radius || 100;
  14978. tube = tube || 40;
  14979. radialSegments = Math.floor( radialSegments ) || 8;
  14980. tubularSegments = Math.floor( tubularSegments ) || 6;
  14981. arc = arc || Math.PI * 2;
  14982. // used to calculate buffer length
  14983. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  14984. var indexCount = radialSegments * tubularSegments * 2 * 3;
  14985. // buffers
  14986. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  14987. var vertices = new Float32Array( vertexCount * 3 );
  14988. var normals = new Float32Array( vertexCount * 3 );
  14989. var uvs = new Float32Array( vertexCount * 2 );
  14990. // offset variables
  14991. var vertexBufferOffset = 0;
  14992. var uvBufferOffset = 0;
  14993. var indexBufferOffset = 0;
  14994. // helper variables
  14995. var center = new Vector3();
  14996. var vertex = new Vector3();
  14997. var normal = new Vector3();
  14998. var j, i;
  14999. // generate vertices, normals and uvs
  15000. for ( j = 0; j <= radialSegments; j ++ ) {
  15001. for ( i = 0; i <= tubularSegments; i ++ ) {
  15002. var u = i / tubularSegments * arc;
  15003. var v = j / radialSegments * Math.PI * 2;
  15004. // vertex
  15005. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  15006. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  15007. vertex.z = tube * Math.sin( v );
  15008. vertices[ vertexBufferOffset ] = vertex.x;
  15009. vertices[ vertexBufferOffset + 1 ] = vertex.y;
  15010. vertices[ vertexBufferOffset + 2 ] = vertex.z;
  15011. // this vector is used to calculate the normal
  15012. center.x = radius * Math.cos( u );
  15013. center.y = radius * Math.sin( u );
  15014. // normal
  15015. normal.subVectors( vertex, center ).normalize();
  15016. normals[ vertexBufferOffset ] = normal.x;
  15017. normals[ vertexBufferOffset + 1 ] = normal.y;
  15018. normals[ vertexBufferOffset + 2 ] = normal.z;
  15019. // uv
  15020. uvs[ uvBufferOffset ] = i / tubularSegments;
  15021. uvs[ uvBufferOffset + 1 ] = j / radialSegments;
  15022. // update offsets
  15023. vertexBufferOffset += 3;
  15024. uvBufferOffset += 2;
  15025. }
  15026. }
  15027. // generate indices
  15028. for ( j = 1; j <= radialSegments; j ++ ) {
  15029. for ( i = 1; i <= tubularSegments; i ++ ) {
  15030. // indices
  15031. var a = ( tubularSegments + 1 ) * j + i - 1;
  15032. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  15033. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  15034. var d = ( tubularSegments + 1 ) * j + i;
  15035. // face one
  15036. indices[ indexBufferOffset ] = a;
  15037. indices[ indexBufferOffset + 1 ] = b;
  15038. indices[ indexBufferOffset + 2 ] = d;
  15039. // face two
  15040. indices[ indexBufferOffset + 3 ] = b;
  15041. indices[ indexBufferOffset + 4 ] = c;
  15042. indices[ indexBufferOffset + 5 ] = d;
  15043. // update offset
  15044. indexBufferOffset += 6;
  15045. }
  15046. }
  15047. // build geometry
  15048. this.setIndex( new BufferAttribute( indices, 1 ) );
  15049. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  15050. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  15051. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  15052. }
  15053. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15054. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  15055. /**
  15056. * @author oosmoxiecode
  15057. * @author mrdoob / http://mrdoob.com/
  15058. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  15059. */
  15060. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15061. Geometry.call( this );
  15062. this.type = 'TorusGeometry';
  15063. this.parameters = {
  15064. radius: radius,
  15065. tube: tube,
  15066. radialSegments: radialSegments,
  15067. tubularSegments: tubularSegments,
  15068. arc: arc
  15069. };
  15070. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  15071. }
  15072. TorusGeometry.prototype = Object.create( Geometry.prototype );
  15073. TorusGeometry.prototype.constructor = TorusGeometry;
  15074. /**
  15075. * @author zz85 / http://www.lab4games.net/zz85/blog
  15076. */
  15077. var ShapeUtils = {
  15078. // calculate area of the contour polygon
  15079. area: function ( contour ) {
  15080. var n = contour.length;
  15081. var a = 0.0;
  15082. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  15083. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15084. }
  15085. return a * 0.5;
  15086. },
  15087. triangulate: ( function () {
  15088. /**
  15089. * This code is a quick port of code written in C++ which was submitted to
  15090. * flipcode.com by John W. Ratcliff // July 22, 2000
  15091. * See original code and more information here:
  15092. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15093. *
  15094. * ported to actionscript by Zevan Rosser
  15095. * www.actionsnippet.com
  15096. *
  15097. * ported to javascript by Joshua Koo
  15098. * http://www.lab4games.net/zz85/blog
  15099. *
  15100. */
  15101. function snip( contour, u, v, w, n, verts ) {
  15102. var p;
  15103. var ax, ay, bx, by;
  15104. var cx, cy, px, py;
  15105. ax = contour[ verts[ u ] ].x;
  15106. ay = contour[ verts[ u ] ].y;
  15107. bx = contour[ verts[ v ] ].x;
  15108. by = contour[ verts[ v ] ].y;
  15109. cx = contour[ verts[ w ] ].x;
  15110. cy = contour[ verts[ w ] ].y;
  15111. if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false;
  15112. var aX, aY, bX, bY, cX, cY;
  15113. var apx, apy, bpx, bpy, cpx, cpy;
  15114. var cCROSSap, bCROSScp, aCROSSbp;
  15115. aX = cx - bx; aY = cy - by;
  15116. bX = ax - cx; bY = ay - cy;
  15117. cX = bx - ax; cY = by - ay;
  15118. for ( p = 0; p < n; p ++ ) {
  15119. px = contour[ verts[ p ] ].x;
  15120. py = contour[ verts[ p ] ].y;
  15121. if ( ( ( px === ax ) && ( py === ay ) ) ||
  15122. ( ( px === bx ) && ( py === by ) ) ||
  15123. ( ( px === cx ) && ( py === cy ) ) ) continue;
  15124. apx = px - ax; apy = py - ay;
  15125. bpx = px - bx; bpy = py - by;
  15126. cpx = px - cx; cpy = py - cy;
  15127. // see if p is inside triangle abc
  15128. aCROSSbp = aX * bpy - aY * bpx;
  15129. cCROSSap = cX * apy - cY * apx;
  15130. bCROSScp = bX * cpy - bY * cpx;
  15131. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  15132. }
  15133. return true;
  15134. }
  15135. // takes in an contour array and returns
  15136. return function triangulate( contour, indices ) {
  15137. var n = contour.length;
  15138. if ( n < 3 ) return null;
  15139. var result = [],
  15140. verts = [],
  15141. vertIndices = [];
  15142. /* we want a counter-clockwise polygon in verts */
  15143. var u, v, w;
  15144. if ( ShapeUtils.area( contour ) > 0.0 ) {
  15145. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  15146. } else {
  15147. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  15148. }
  15149. var nv = n;
  15150. /* remove nv - 2 vertices, creating 1 triangle every time */
  15151. var count = 2 * nv; /* error detection */
  15152. for ( v = nv - 1; nv > 2; ) {
  15153. /* if we loop, it is probably a non-simple polygon */
  15154. if ( ( count -- ) <= 0 ) {
  15155. //** Triangulate: ERROR - probable bad polygon!
  15156. //throw ( "Warning, unable to triangulate polygon!" );
  15157. //return null;
  15158. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15159. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  15160. if ( indices ) return vertIndices;
  15161. return result;
  15162. }
  15163. /* three consecutive vertices in current polygon, <u,v,w> */
  15164. u = v; if ( nv <= u ) u = 0; /* previous */
  15165. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15166. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15167. if ( snip( contour, u, v, w, nv, verts ) ) {
  15168. var a, b, c, s, t;
  15169. /* true names of the vertices */
  15170. a = verts[ u ];
  15171. b = verts[ v ];
  15172. c = verts[ w ];
  15173. /* output Triangle */
  15174. result.push( [ contour[ a ],
  15175. contour[ b ],
  15176. contour[ c ] ] );
  15177. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15178. /* remove v from the remaining polygon */
  15179. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  15180. verts[ s ] = verts[ t ];
  15181. }
  15182. nv --;
  15183. /* reset error detection counter */
  15184. count = 2 * nv;
  15185. }
  15186. }
  15187. if ( indices ) return vertIndices;
  15188. return result;
  15189. }
  15190. } )(),
  15191. triangulateShape: function ( contour, holes ) {
  15192. function removeDupEndPts(points) {
  15193. var l = points.length;
  15194. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  15195. points.pop();
  15196. }
  15197. }
  15198. removeDupEndPts( contour );
  15199. holes.forEach( removeDupEndPts );
  15200. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  15201. // inOtherPt needs to be collinear to the inSegment
  15202. if ( inSegPt1.x !== inSegPt2.x ) {
  15203. if ( inSegPt1.x < inSegPt2.x ) {
  15204. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  15205. } else {
  15206. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  15207. }
  15208. } else {
  15209. if ( inSegPt1.y < inSegPt2.y ) {
  15210. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  15211. } else {
  15212. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  15213. }
  15214. }
  15215. }
  15216. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  15217. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  15218. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  15219. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  15220. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  15221. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  15222. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  15223. if ( Math.abs( limit ) > Number.EPSILON ) {
  15224. // not parallel
  15225. var perpSeg2;
  15226. if ( limit > 0 ) {
  15227. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  15228. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15229. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  15230. } else {
  15231. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  15232. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15233. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  15234. }
  15235. // i.e. to reduce rounding errors
  15236. // intersection at endpoint of segment#1?
  15237. if ( perpSeg2 === 0 ) {
  15238. if ( ( inExcludeAdjacentSegs ) &&
  15239. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15240. return [ inSeg1Pt1 ];
  15241. }
  15242. if ( perpSeg2 === limit ) {
  15243. if ( ( inExcludeAdjacentSegs ) &&
  15244. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15245. return [ inSeg1Pt2 ];
  15246. }
  15247. // intersection at endpoint of segment#2?
  15248. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  15249. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  15250. // return real intersection point
  15251. var factorSeg1 = perpSeg2 / limit;
  15252. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  15253. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  15254. } else {
  15255. // parallel or collinear
  15256. if ( ( perpSeg1 !== 0 ) ||
  15257. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  15258. // they are collinear or degenerate
  15259. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  15260. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  15261. // both segments are points
  15262. if ( seg1Pt && seg2Pt ) {
  15263. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  15264. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  15265. return [ inSeg1Pt1 ]; // they are the same point
  15266. }
  15267. // segment#1 is a single point
  15268. if ( seg1Pt ) {
  15269. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  15270. return [ inSeg1Pt1 ];
  15271. }
  15272. // segment#2 is a single point
  15273. if ( seg2Pt ) {
  15274. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  15275. return [ inSeg2Pt1 ];
  15276. }
  15277. // they are collinear segments, which might overlap
  15278. var seg1min, seg1max, seg1minVal, seg1maxVal;
  15279. var seg2min, seg2max, seg2minVal, seg2maxVal;
  15280. if ( seg1dx !== 0 ) {
  15281. // the segments are NOT on a vertical line
  15282. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  15283. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  15284. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  15285. } else {
  15286. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  15287. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  15288. }
  15289. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  15290. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  15291. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  15292. } else {
  15293. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  15294. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  15295. }
  15296. } else {
  15297. // the segments are on a vertical line
  15298. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  15299. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  15300. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  15301. } else {
  15302. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  15303. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  15304. }
  15305. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  15306. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  15307. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  15308. } else {
  15309. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  15310. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  15311. }
  15312. }
  15313. if ( seg1minVal <= seg2minVal ) {
  15314. if ( seg1maxVal < seg2minVal ) return [];
  15315. if ( seg1maxVal === seg2minVal ) {
  15316. if ( inExcludeAdjacentSegs ) return [];
  15317. return [ seg2min ];
  15318. }
  15319. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  15320. return [ seg2min, seg2max ];
  15321. } else {
  15322. if ( seg1minVal > seg2maxVal ) return [];
  15323. if ( seg1minVal === seg2maxVal ) {
  15324. if ( inExcludeAdjacentSegs ) return [];
  15325. return [ seg1min ];
  15326. }
  15327. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  15328. return [ seg1min, seg2max ];
  15329. }
  15330. }
  15331. }
  15332. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  15333. // The order of legs is important
  15334. // translation of all points, so that Vertex is at (0,0)
  15335. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  15336. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  15337. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  15338. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  15339. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  15340. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  15341. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  15342. // angle != 180 deg.
  15343. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  15344. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  15345. if ( from2toAngle > 0 ) {
  15346. // main angle < 180 deg.
  15347. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  15348. } else {
  15349. // main angle > 180 deg.
  15350. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  15351. }
  15352. } else {
  15353. // angle == 180 deg.
  15354. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  15355. return ( from2otherAngle > 0 );
  15356. }
  15357. }
  15358. function removeHoles( contour, holes ) {
  15359. var shape = contour.concat(); // work on this shape
  15360. var hole;
  15361. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  15362. // Check if hole point lies within angle around shape point
  15363. var lastShapeIdx = shape.length - 1;
  15364. var prevShapeIdx = inShapeIdx - 1;
  15365. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  15366. var nextShapeIdx = inShapeIdx + 1;
  15367. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  15368. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  15369. if ( ! insideAngle ) {
  15370. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  15371. return false;
  15372. }
  15373. // Check if shape point lies within angle around hole point
  15374. var lastHoleIdx = hole.length - 1;
  15375. var prevHoleIdx = inHoleIdx - 1;
  15376. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  15377. var nextHoleIdx = inHoleIdx + 1;
  15378. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  15379. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  15380. if ( ! insideAngle ) {
  15381. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  15382. return false;
  15383. }
  15384. return true;
  15385. }
  15386. function intersectsShapeEdge( inShapePt, inHolePt ) {
  15387. // checks for intersections with shape edges
  15388. var sIdx, nextIdx, intersection;
  15389. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  15390. nextIdx = sIdx + 1; nextIdx %= shape.length;
  15391. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  15392. if ( intersection.length > 0 ) return true;
  15393. }
  15394. return false;
  15395. }
  15396. var indepHoles = [];
  15397. function intersectsHoleEdge( inShapePt, inHolePt ) {
  15398. // checks for intersections with hole edges
  15399. var ihIdx, chkHole,
  15400. hIdx, nextIdx, intersection;
  15401. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  15402. chkHole = holes[ indepHoles[ ihIdx ]];
  15403. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  15404. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  15405. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  15406. if ( intersection.length > 0 ) return true;
  15407. }
  15408. }
  15409. return false;
  15410. }
  15411. var holeIndex, shapeIndex,
  15412. shapePt, holePt,
  15413. holeIdx, cutKey, failedCuts = [],
  15414. tmpShape1, tmpShape2,
  15415. tmpHole1, tmpHole2;
  15416. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15417. indepHoles.push( h );
  15418. }
  15419. var minShapeIndex = 0;
  15420. var counter = indepHoles.length * 2;
  15421. while ( indepHoles.length > 0 ) {
  15422. counter --;
  15423. if ( counter < 0 ) {
  15424. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  15425. break;
  15426. }
  15427. // search for shape-vertex and hole-vertex,
  15428. // which can be connected without intersections
  15429. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  15430. shapePt = shape[ shapeIndex ];
  15431. holeIndex = - 1;
  15432. // search for hole which can be reached without intersections
  15433. for ( var h = 0; h < indepHoles.length; h ++ ) {
  15434. holeIdx = indepHoles[ h ];
  15435. // prevent multiple checks
  15436. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  15437. if ( failedCuts[ cutKey ] !== undefined ) continue;
  15438. hole = holes[ holeIdx ];
  15439. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  15440. holePt = hole[ h2 ];
  15441. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  15442. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  15443. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  15444. holeIndex = h2;
  15445. indepHoles.splice( h, 1 );
  15446. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  15447. tmpShape2 = shape.slice( shapeIndex );
  15448. tmpHole1 = hole.slice( holeIndex );
  15449. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  15450. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  15451. minShapeIndex = shapeIndex;
  15452. // Debug only, to show the selected cuts
  15453. // glob_CutLines.push( [ shapePt, holePt ] );
  15454. break;
  15455. }
  15456. if ( holeIndex >= 0 ) break; // hole-vertex found
  15457. failedCuts[ cutKey ] = true; // remember failure
  15458. }
  15459. if ( holeIndex >= 0 ) break; // hole-vertex found
  15460. }
  15461. }
  15462. return shape; /* shape with no holes */
  15463. }
  15464. var i, il, f, face,
  15465. key, index,
  15466. allPointsMap = {};
  15467. // 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.
  15468. var allpoints = contour.concat();
  15469. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15470. Array.prototype.push.apply( allpoints, holes[ h ] );
  15471. }
  15472. //console.log( "allpoints",allpoints, allpoints.length );
  15473. // prepare all points map
  15474. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  15475. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  15476. if ( allPointsMap[ key ] !== undefined ) {
  15477. console.warn( "THREE.ShapeUtils: Duplicate point", key, i );
  15478. }
  15479. allPointsMap[ key ] = i;
  15480. }
  15481. // remove holes by cutting paths to holes and adding them to the shape
  15482. var shapeWithoutHoles = removeHoles( contour, holes );
  15483. var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  15484. //console.log( "triangles",triangles, triangles.length );
  15485. // check all face vertices against all points map
  15486. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  15487. face = triangles[ i ];
  15488. for ( f = 0; f < 3; f ++ ) {
  15489. key = face[ f ].x + ":" + face[ f ].y;
  15490. index = allPointsMap[ key ];
  15491. if ( index !== undefined ) {
  15492. face[ f ] = index;
  15493. }
  15494. }
  15495. }
  15496. return triangles.concat();
  15497. },
  15498. isClockWise: function ( pts ) {
  15499. return ShapeUtils.area( pts ) < 0;
  15500. },
  15501. // Bezier Curves formulas obtained from
  15502. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  15503. // Quad Bezier Functions
  15504. b2: ( function () {
  15505. function b2p0( t, p ) {
  15506. var k = 1 - t;
  15507. return k * k * p;
  15508. }
  15509. function b2p1( t, p ) {
  15510. return 2 * ( 1 - t ) * t * p;
  15511. }
  15512. function b2p2( t, p ) {
  15513. return t * t * p;
  15514. }
  15515. return function b2( t, p0, p1, p2 ) {
  15516. return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 );
  15517. };
  15518. } )(),
  15519. // Cubic Bezier Functions
  15520. b3: ( function () {
  15521. function b3p0( t, p ) {
  15522. var k = 1 - t;
  15523. return k * k * k * p;
  15524. }
  15525. function b3p1( t, p ) {
  15526. var k = 1 - t;
  15527. return 3 * k * k * t * p;
  15528. }
  15529. function b3p2( t, p ) {
  15530. var k = 1 - t;
  15531. return 3 * k * t * t * p;
  15532. }
  15533. function b3p3( t, p ) {
  15534. return t * t * t * p;
  15535. }
  15536. return function b3( t, p0, p1, p2, p3 ) {
  15537. return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 );
  15538. };
  15539. } )()
  15540. };
  15541. /**
  15542. * @author zz85 / http://www.lab4games.net/zz85/blog
  15543. *
  15544. * Creates extruded geometry from a path shape.
  15545. *
  15546. * parameters = {
  15547. *
  15548. * curveSegments: <int>, // number of points on the curves
  15549. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  15550. * amount: <int>, // Depth to extrude the shape
  15551. *
  15552. * bevelEnabled: <bool>, // turn on bevel
  15553. * bevelThickness: <float>, // how deep into the original shape bevel goes
  15554. * bevelSize: <float>, // how far from shape outline is bevel
  15555. * bevelSegments: <int>, // number of bevel layers
  15556. *
  15557. * extrudePath: <THREE.Curve> // curve to extrude shape along
  15558. * frames: <Object> // containing arrays of tangents, normals, binormals
  15559. *
  15560. * uvGenerator: <Object> // object that provides UV generator functions
  15561. *
  15562. * }
  15563. **/
  15564. function ExtrudeGeometry( shapes, options ) {
  15565. if ( typeof( shapes ) === "undefined" ) {
  15566. shapes = [];
  15567. return;
  15568. }
  15569. Geometry.call( this );
  15570. this.type = 'ExtrudeGeometry';
  15571. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  15572. this.addShapeList( shapes, options );
  15573. this.computeFaceNormals();
  15574. // can't really use automatic vertex normals
  15575. // as then front and back sides get smoothed too
  15576. // should do separate smoothing just for sides
  15577. //this.computeVertexNormals();
  15578. //console.log( "took", ( Date.now() - startTime ) );
  15579. }
  15580. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  15581. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  15582. ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  15583. var sl = shapes.length;
  15584. for ( var s = 0; s < sl; s ++ ) {
  15585. var shape = shapes[ s ];
  15586. this.addShape( shape, options );
  15587. }
  15588. };
  15589. ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  15590. var amount = options.amount !== undefined ? options.amount : 100;
  15591. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  15592. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  15593. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  15594. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  15595. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  15596. var steps = options.steps !== undefined ? options.steps : 1;
  15597. var extrudePath = options.extrudePath;
  15598. var extrudePts, extrudeByPath = false;
  15599. // Use default WorldUVGenerator if no UV generators are specified.
  15600. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  15601. var splineTube, binormal, normal, position2;
  15602. if ( extrudePath ) {
  15603. extrudePts = extrudePath.getSpacedPoints( steps );
  15604. extrudeByPath = true;
  15605. bevelEnabled = false; // bevels not supported for path extrusion
  15606. // SETUP TNB variables
  15607. // TODO1 - have a .isClosed in spline?
  15608. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  15609. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  15610. binormal = new Vector3();
  15611. normal = new Vector3();
  15612. position2 = new Vector3();
  15613. }
  15614. // Safeguards if bevels are not enabled
  15615. if ( ! bevelEnabled ) {
  15616. bevelSegments = 0;
  15617. bevelThickness = 0;
  15618. bevelSize = 0;
  15619. }
  15620. // Variables initialization
  15621. var ahole, h, hl; // looping of holes
  15622. var scope = this;
  15623. var shapesOffset = this.vertices.length;
  15624. var shapePoints = shape.extractPoints( curveSegments );
  15625. var vertices = shapePoints.shape;
  15626. var holes = shapePoints.holes;
  15627. var reverse = ! ShapeUtils.isClockWise( vertices );
  15628. if ( reverse ) {
  15629. vertices = vertices.reverse();
  15630. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  15631. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15632. ahole = holes[ h ];
  15633. if ( ShapeUtils.isClockWise( ahole ) ) {
  15634. holes[ h ] = ahole.reverse();
  15635. }
  15636. }
  15637. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  15638. }
  15639. var faces = ShapeUtils.triangulateShape( vertices, holes );
  15640. /* Vertices */
  15641. var contour = vertices; // vertices has all points but contour has only points of circumference
  15642. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15643. ahole = holes[ h ];
  15644. vertices = vertices.concat( ahole );
  15645. }
  15646. function scalePt2( pt, vec, size ) {
  15647. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  15648. return vec.clone().multiplyScalar( size ).add( pt );
  15649. }
  15650. var b, bs, t, z,
  15651. vert, vlen = vertices.length,
  15652. face, flen = faces.length;
  15653. // Find directions for point movement
  15654. function getBevelVec( inPt, inPrev, inNext ) {
  15655. // computes for inPt the corresponding point inPt' on a new contour
  15656. // shifted by 1 unit (length of normalized vector) to the left
  15657. // if we walk along contour clockwise, this new contour is outside the old one
  15658. //
  15659. // inPt' is the intersection of the two lines parallel to the two
  15660. // adjacent edges of inPt at a distance of 1 unit on the left side.
  15661. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  15662. // good reading for geometry algorithms (here: line-line intersection)
  15663. // http://geomalgorithms.com/a05-_intersect-1.html
  15664. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  15665. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  15666. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  15667. // check for collinear edges
  15668. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  15669. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  15670. // not collinear
  15671. // length of vectors for normalizing
  15672. var v_prev_len = Math.sqrt( v_prev_lensq );
  15673. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  15674. // shift adjacent points by unit vectors to the left
  15675. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  15676. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  15677. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  15678. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  15679. // scaling factor for v_prev to intersection point
  15680. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  15681. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  15682. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  15683. // vector from inPt to intersection point
  15684. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  15685. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  15686. // Don't normalize!, otherwise sharp corners become ugly
  15687. // but prevent crazy spikes
  15688. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  15689. if ( v_trans_lensq <= 2 ) {
  15690. return new Vector2( v_trans_x, v_trans_y );
  15691. } else {
  15692. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  15693. }
  15694. } else {
  15695. // handle special case of collinear edges
  15696. var direction_eq = false; // assumes: opposite
  15697. if ( v_prev_x > Number.EPSILON ) {
  15698. if ( v_next_x > Number.EPSILON ) {
  15699. direction_eq = true;
  15700. }
  15701. } else {
  15702. if ( v_prev_x < - Number.EPSILON ) {
  15703. if ( v_next_x < - Number.EPSILON ) {
  15704. direction_eq = true;
  15705. }
  15706. } else {
  15707. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  15708. direction_eq = true;
  15709. }
  15710. }
  15711. }
  15712. if ( direction_eq ) {
  15713. // console.log("Warning: lines are a straight sequence");
  15714. v_trans_x = - v_prev_y;
  15715. v_trans_y = v_prev_x;
  15716. shrink_by = Math.sqrt( v_prev_lensq );
  15717. } else {
  15718. // console.log("Warning: lines are a straight spike");
  15719. v_trans_x = v_prev_x;
  15720. v_trans_y = v_prev_y;
  15721. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  15722. }
  15723. }
  15724. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  15725. }
  15726. var contourMovements = [];
  15727. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  15728. if ( j === il ) j = 0;
  15729. if ( k === il ) k = 0;
  15730. // (j)---(i)---(k)
  15731. // console.log('i,j,k', i, j , k)
  15732. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  15733. }
  15734. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  15735. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15736. ahole = holes[ h ];
  15737. oneHoleMovements = [];
  15738. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  15739. if ( j === il ) j = 0;
  15740. if ( k === il ) k = 0;
  15741. // (j)---(i)---(k)
  15742. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  15743. }
  15744. holesMovements.push( oneHoleMovements );
  15745. verticesMovements = verticesMovements.concat( oneHoleMovements );
  15746. }
  15747. // Loop bevelSegments, 1 for the front, 1 for the back
  15748. for ( b = 0; b < bevelSegments; b ++ ) {
  15749. //for ( b = bevelSegments; b > 0; b -- ) {
  15750. t = b / bevelSegments;
  15751. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  15752. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  15753. // contract shape
  15754. for ( i = 0, il = contour.length; i < il; i ++ ) {
  15755. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  15756. v( vert.x, vert.y, - z );
  15757. }
  15758. // expand holes
  15759. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15760. ahole = holes[ h ];
  15761. oneHoleMovements = holesMovements[ h ];
  15762. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  15763. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  15764. v( vert.x, vert.y, - z );
  15765. }
  15766. }
  15767. }
  15768. bs = bevelSize;
  15769. // Back facing vertices
  15770. for ( i = 0; i < vlen; i ++ ) {
  15771. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  15772. if ( ! extrudeByPath ) {
  15773. v( vert.x, vert.y, 0 );
  15774. } else {
  15775. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  15776. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  15777. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  15778. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  15779. v( position2.x, position2.y, position2.z );
  15780. }
  15781. }
  15782. // Add stepped vertices...
  15783. // Including front facing vertices
  15784. var s;
  15785. for ( s = 1; s <= steps; s ++ ) {
  15786. for ( i = 0; i < vlen; i ++ ) {
  15787. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  15788. if ( ! extrudeByPath ) {
  15789. v( vert.x, vert.y, amount / steps * s );
  15790. } else {
  15791. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  15792. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  15793. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  15794. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  15795. v( position2.x, position2.y, position2.z );
  15796. }
  15797. }
  15798. }
  15799. // Add bevel segments planes
  15800. //for ( b = 1; b <= bevelSegments; b ++ ) {
  15801. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  15802. t = b / bevelSegments;
  15803. z = bevelThickness * Math.cos ( t * Math.PI / 2 );
  15804. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  15805. // contract shape
  15806. for ( i = 0, il = contour.length; i < il; i ++ ) {
  15807. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  15808. v( vert.x, vert.y, amount + z );
  15809. }
  15810. // expand holes
  15811. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15812. ahole = holes[ h ];
  15813. oneHoleMovements = holesMovements[ h ];
  15814. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  15815. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  15816. if ( ! extrudeByPath ) {
  15817. v( vert.x, vert.y, amount + z );
  15818. } else {
  15819. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  15820. }
  15821. }
  15822. }
  15823. }
  15824. /* Faces */
  15825. // Top and bottom faces
  15826. buildLidFaces();
  15827. // Sides faces
  15828. buildSideFaces();
  15829. ///// Internal functions
  15830. function buildLidFaces() {
  15831. if ( bevelEnabled ) {
  15832. var layer = 0; // steps + 1
  15833. var offset = vlen * layer;
  15834. // Bottom faces
  15835. for ( i = 0; i < flen; i ++ ) {
  15836. face = faces[ i ];
  15837. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  15838. }
  15839. layer = steps + bevelSegments * 2;
  15840. offset = vlen * layer;
  15841. // Top faces
  15842. for ( i = 0; i < flen; i ++ ) {
  15843. face = faces[ i ];
  15844. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  15845. }
  15846. } else {
  15847. // Bottom faces
  15848. for ( i = 0; i < flen; i ++ ) {
  15849. face = faces[ i ];
  15850. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  15851. }
  15852. // Top faces
  15853. for ( i = 0; i < flen; i ++ ) {
  15854. face = faces[ i ];
  15855. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  15856. }
  15857. }
  15858. }
  15859. // Create faces for the z-sides of the shape
  15860. function buildSideFaces() {
  15861. var layeroffset = 0;
  15862. sidewalls( contour, layeroffset );
  15863. layeroffset += contour.length;
  15864. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15865. ahole = holes[ h ];
  15866. sidewalls( ahole, layeroffset );
  15867. //, true
  15868. layeroffset += ahole.length;
  15869. }
  15870. }
  15871. function sidewalls( contour, layeroffset ) {
  15872. var j, k;
  15873. i = contour.length;
  15874. while ( -- i >= 0 ) {
  15875. j = i;
  15876. k = i - 1;
  15877. if ( k < 0 ) k = contour.length - 1;
  15878. //console.log('b', i,j, i-1, k,vertices.length);
  15879. var s = 0, sl = steps + bevelSegments * 2;
  15880. for ( s = 0; s < sl; s ++ ) {
  15881. var slen1 = vlen * s;
  15882. var slen2 = vlen * ( s + 1 );
  15883. var a = layeroffset + j + slen1,
  15884. b = layeroffset + k + slen1,
  15885. c = layeroffset + k + slen2,
  15886. d = layeroffset + j + slen2;
  15887. f4( a, b, c, d, contour, s, sl, j, k );
  15888. }
  15889. }
  15890. }
  15891. function v( x, y, z ) {
  15892. scope.vertices.push( new Vector3( x, y, z ) );
  15893. }
  15894. function f3( a, b, c ) {
  15895. a += shapesOffset;
  15896. b += shapesOffset;
  15897. c += shapesOffset;
  15898. scope.faces.push( new Face3( a, b, c, null, null, 0 ) );
  15899. var uvs = uvgen.generateTopUV( scope, a, b, c );
  15900. scope.faceVertexUvs[ 0 ].push( uvs );
  15901. }
  15902. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  15903. a += shapesOffset;
  15904. b += shapesOffset;
  15905. c += shapesOffset;
  15906. d += shapesOffset;
  15907. scope.faces.push( new Face3( a, b, d, null, null, 1 ) );
  15908. scope.faces.push( new Face3( b, c, d, null, null, 1 ) );
  15909. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  15910. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  15911. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  15912. }
  15913. };
  15914. ExtrudeGeometry.WorldUVGenerator = {
  15915. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  15916. var vertices = geometry.vertices;
  15917. var a = vertices[ indexA ];
  15918. var b = vertices[ indexB ];
  15919. var c = vertices[ indexC ];
  15920. return [
  15921. new Vector2( a.x, a.y ),
  15922. new Vector2( b.x, b.y ),
  15923. new Vector2( c.x, c.y )
  15924. ];
  15925. },
  15926. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  15927. var vertices = geometry.vertices;
  15928. var a = vertices[ indexA ];
  15929. var b = vertices[ indexB ];
  15930. var c = vertices[ indexC ];
  15931. var d = vertices[ indexD ];
  15932. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  15933. return [
  15934. new Vector2( a.x, 1 - a.z ),
  15935. new Vector2( b.x, 1 - b.z ),
  15936. new Vector2( c.x, 1 - c.z ),
  15937. new Vector2( d.x, 1 - d.z )
  15938. ];
  15939. } else {
  15940. return [
  15941. new Vector2( a.y, 1 - a.z ),
  15942. new Vector2( b.y, 1 - b.z ),
  15943. new Vector2( c.y, 1 - c.z ),
  15944. new Vector2( d.y, 1 - d.z )
  15945. ];
  15946. }
  15947. }
  15948. };
  15949. /**
  15950. * @author zz85 / http://www.lab4games.net/zz85/blog
  15951. * @author alteredq / http://alteredqualia.com/
  15952. *
  15953. * Text = 3D Text
  15954. *
  15955. * parameters = {
  15956. * font: <THREE.Font>, // font
  15957. *
  15958. * size: <float>, // size of the text
  15959. * height: <float>, // thickness to extrude text
  15960. * curveSegments: <int>, // number of points on the curves
  15961. *
  15962. * bevelEnabled: <bool>, // turn on bevel
  15963. * bevelThickness: <float>, // how deep into text bevel goes
  15964. * bevelSize: <float> // how far from text outline is bevel
  15965. * }
  15966. */
  15967. function TextGeometry( text, parameters ) {
  15968. parameters = parameters || {};
  15969. var font = parameters.font;
  15970. if ( (font && font.isFont) === false ) {
  15971. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  15972. return new Geometry();
  15973. }
  15974. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  15975. // translate parameters to ExtrudeGeometry API
  15976. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  15977. // defaults
  15978. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  15979. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  15980. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  15981. ExtrudeGeometry.call( this, shapes, parameters );
  15982. this.type = 'TextGeometry';
  15983. }
  15984. TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype );
  15985. TextGeometry.prototype.constructor = TextGeometry;
  15986. /**
  15987. * @author benaadams / https://twitter.com/ben_a_adams
  15988. * based on THREE.SphereGeometry
  15989. */
  15990. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  15991. BufferGeometry.call( this );
  15992. this.type = 'SphereBufferGeometry';
  15993. this.parameters = {
  15994. radius: radius,
  15995. widthSegments: widthSegments,
  15996. heightSegments: heightSegments,
  15997. phiStart: phiStart,
  15998. phiLength: phiLength,
  15999. thetaStart: thetaStart,
  16000. thetaLength: thetaLength
  16001. };
  16002. radius = radius || 50;
  16003. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  16004. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  16005. phiStart = phiStart !== undefined ? phiStart : 0;
  16006. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  16007. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16008. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  16009. var thetaEnd = thetaStart + thetaLength;
  16010. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  16011. var positions = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16012. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16013. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  16014. var index = 0, vertices = [], normal = new Vector3();
  16015. for ( var y = 0; y <= heightSegments; y ++ ) {
  16016. var verticesRow = [];
  16017. var v = y / heightSegments;
  16018. for ( var x = 0; x <= widthSegments; x ++ ) {
  16019. var u = x / widthSegments;
  16020. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16021. var py = radius * Math.cos( thetaStart + v * thetaLength );
  16022. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16023. normal.set( px, py, pz ).normalize();
  16024. positions.setXYZ( index, px, py, pz );
  16025. normals.setXYZ( index, normal.x, normal.y, normal.z );
  16026. uvs.setXY( index, u, 1 - v );
  16027. verticesRow.push( index );
  16028. index ++;
  16029. }
  16030. vertices.push( verticesRow );
  16031. }
  16032. var indices = [];
  16033. for ( var y = 0; y < heightSegments; y ++ ) {
  16034. for ( var x = 0; x < widthSegments; x ++ ) {
  16035. var v1 = vertices[ y ][ x + 1 ];
  16036. var v2 = vertices[ y ][ x ];
  16037. var v3 = vertices[ y + 1 ][ x ];
  16038. var v4 = vertices[ y + 1 ][ x + 1 ];
  16039. if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 );
  16040. if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 );
  16041. }
  16042. }
  16043. this.setIndex( new ( positions.count > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  16044. this.addAttribute( 'position', positions );
  16045. this.addAttribute( 'normal', normals );
  16046. this.addAttribute( 'uv', uvs );
  16047. this.boundingSphere = new Sphere( new Vector3(), radius );
  16048. }
  16049. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16050. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  16051. /**
  16052. * @author mrdoob / http://mrdoob.com/
  16053. */
  16054. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16055. Geometry.call( this );
  16056. this.type = 'SphereGeometry';
  16057. this.parameters = {
  16058. radius: radius,
  16059. widthSegments: widthSegments,
  16060. heightSegments: heightSegments,
  16061. phiStart: phiStart,
  16062. phiLength: phiLength,
  16063. thetaStart: thetaStart,
  16064. thetaLength: thetaLength
  16065. };
  16066. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  16067. }
  16068. SphereGeometry.prototype = Object.create( Geometry.prototype );
  16069. SphereGeometry.prototype.constructor = SphereGeometry;
  16070. /**
  16071. * @author Mugen87 / https://github.com/Mugen87
  16072. */
  16073. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16074. BufferGeometry.call( this );
  16075. this.type = 'RingBufferGeometry';
  16076. this.parameters = {
  16077. innerRadius: innerRadius,
  16078. outerRadius: outerRadius,
  16079. thetaSegments: thetaSegments,
  16080. phiSegments: phiSegments,
  16081. thetaStart: thetaStart,
  16082. thetaLength: thetaLength
  16083. };
  16084. innerRadius = innerRadius || 20;
  16085. outerRadius = outerRadius || 50;
  16086. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16087. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16088. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  16089. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  16090. // these are used to calculate buffer length
  16091. var vertexCount = ( thetaSegments + 1 ) * ( phiSegments + 1 );
  16092. var indexCount = thetaSegments * phiSegments * 2 * 3;
  16093. // buffers
  16094. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  16095. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16096. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16097. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  16098. // some helper variables
  16099. var index = 0, indexOffset = 0, segment;
  16100. var radius = innerRadius;
  16101. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  16102. var vertex = new Vector3();
  16103. var uv = new Vector2();
  16104. var j, i;
  16105. // generate vertices, normals and uvs
  16106. // values are generate from the inside of the ring to the outside
  16107. for ( j = 0; j <= phiSegments; j ++ ) {
  16108. for ( i = 0; i <= thetaSegments; i ++ ) {
  16109. segment = thetaStart + i / thetaSegments * thetaLength;
  16110. // vertex
  16111. vertex.x = radius * Math.cos( segment );
  16112. vertex.y = radius * Math.sin( segment );
  16113. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  16114. // normal
  16115. normals.setXYZ( index, 0, 0, 1 );
  16116. // uv
  16117. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  16118. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  16119. uvs.setXY( index, uv.x, uv.y );
  16120. // increase index
  16121. index++;
  16122. }
  16123. // increase the radius for next row of vertices
  16124. radius += radiusStep;
  16125. }
  16126. // generate indices
  16127. for ( j = 0; j < phiSegments; j ++ ) {
  16128. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  16129. for ( i = 0; i < thetaSegments; i ++ ) {
  16130. segment = i + thetaSegmentLevel;
  16131. // indices
  16132. var a = segment;
  16133. var b = segment + thetaSegments + 1;
  16134. var c = segment + thetaSegments + 2;
  16135. var d = segment + 1;
  16136. // face one
  16137. indices.setX( indexOffset, a ); indexOffset++;
  16138. indices.setX( indexOffset, b ); indexOffset++;
  16139. indices.setX( indexOffset, c ); indexOffset++;
  16140. // face two
  16141. indices.setX( indexOffset, a ); indexOffset++;
  16142. indices.setX( indexOffset, c ); indexOffset++;
  16143. indices.setX( indexOffset, d ); indexOffset++;
  16144. }
  16145. }
  16146. // build geometry
  16147. this.setIndex( indices );
  16148. this.addAttribute( 'position', vertices );
  16149. this.addAttribute( 'normal', normals );
  16150. this.addAttribute( 'uv', uvs );
  16151. }
  16152. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16153. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  16154. /**
  16155. * @author Kaleb Murphy
  16156. */
  16157. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16158. Geometry.call( this );
  16159. this.type = 'RingGeometry';
  16160. this.parameters = {
  16161. innerRadius: innerRadius,
  16162. outerRadius: outerRadius,
  16163. thetaSegments: thetaSegments,
  16164. phiSegments: phiSegments,
  16165. thetaStart: thetaStart,
  16166. thetaLength: thetaLength
  16167. };
  16168. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  16169. }
  16170. RingGeometry.prototype = Object.create( Geometry.prototype );
  16171. RingGeometry.prototype.constructor = RingGeometry;
  16172. /**
  16173. * @author mrdoob / http://mrdoob.com/
  16174. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  16175. */
  16176. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  16177. Geometry.call( this );
  16178. this.type = 'PlaneGeometry';
  16179. this.parameters = {
  16180. width: width,
  16181. height: height,
  16182. widthSegments: widthSegments,
  16183. heightSegments: heightSegments
  16184. };
  16185. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  16186. }
  16187. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  16188. PlaneGeometry.prototype.constructor = PlaneGeometry;
  16189. /**
  16190. * @author Mugen87 / https://github.com/Mugen87
  16191. */
  16192. // points - to create a closed torus, one must use a set of points
  16193. // like so: [ a, b, c, d, a ], see first is the same as last.
  16194. // segments - the number of circumference segments to create
  16195. // phiStart - the starting radian
  16196. // phiLength - the radian (0 to 2PI) range of the lathed section
  16197. // 2PI is a closed lathe, less than 2PI is a portion.
  16198. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  16199. BufferGeometry.call( this );
  16200. this.type = 'LatheBufferGeometry';
  16201. this.parameters = {
  16202. points: points,
  16203. segments: segments,
  16204. phiStart: phiStart,
  16205. phiLength: phiLength
  16206. };
  16207. segments = Math.floor( segments ) || 12;
  16208. phiStart = phiStart || 0;
  16209. phiLength = phiLength || Math.PI * 2;
  16210. // clamp phiLength so it's in range of [ 0, 2PI ]
  16211. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  16212. // these are used to calculate buffer length
  16213. var vertexCount = ( segments + 1 ) * points.length;
  16214. var indexCount = segments * points.length * 2 * 3;
  16215. // buffers
  16216. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  16217. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16218. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  16219. // helper variables
  16220. var index = 0, indexOffset = 0, base;
  16221. var inverseSegments = 1.0 / segments;
  16222. var vertex = new Vector3();
  16223. var uv = new Vector2();
  16224. var i, j;
  16225. // generate vertices and uvs
  16226. for ( i = 0; i <= segments; i ++ ) {
  16227. var phi = phiStart + i * inverseSegments * phiLength;
  16228. var sin = Math.sin( phi );
  16229. var cos = Math.cos( phi );
  16230. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  16231. // vertex
  16232. vertex.x = points[ j ].x * sin;
  16233. vertex.y = points[ j ].y;
  16234. vertex.z = points[ j ].x * cos;
  16235. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  16236. // uv
  16237. uv.x = i / segments;
  16238. uv.y = j / ( points.length - 1 );
  16239. uvs.setXY( index, uv.x, uv.y );
  16240. // increase index
  16241. index ++;
  16242. }
  16243. }
  16244. // generate indices
  16245. for ( i = 0; i < segments; i ++ ) {
  16246. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  16247. base = j + i * points.length;
  16248. // indices
  16249. var a = base;
  16250. var b = base + points.length;
  16251. var c = base + points.length + 1;
  16252. var d = base + 1;
  16253. // face one
  16254. indices.setX( indexOffset, a ); indexOffset++;
  16255. indices.setX( indexOffset, b ); indexOffset++;
  16256. indices.setX( indexOffset, d ); indexOffset++;
  16257. // face two
  16258. indices.setX( indexOffset, b ); indexOffset++;
  16259. indices.setX( indexOffset, c ); indexOffset++;
  16260. indices.setX( indexOffset, d ); indexOffset++;
  16261. }
  16262. }
  16263. // build geometry
  16264. this.setIndex( indices );
  16265. this.addAttribute( 'position', vertices );
  16266. this.addAttribute( 'uv', uvs );
  16267. // generate normals
  16268. this.computeVertexNormals();
  16269. // if the geometry is closed, we need to average the normals along the seam.
  16270. // because the corresponding vertices are identical (but still have different UVs).
  16271. if( phiLength === Math.PI * 2 ) {
  16272. var normals = this.attributes.normal.array;
  16273. var n1 = new Vector3();
  16274. var n2 = new Vector3();
  16275. var n = new Vector3();
  16276. // this is the buffer offset for the last line of vertices
  16277. base = segments * points.length * 3;
  16278. for( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  16279. // select the normal of the vertex in the first line
  16280. n1.x = normals[ j + 0 ];
  16281. n1.y = normals[ j + 1 ];
  16282. n1.z = normals[ j + 2 ];
  16283. // select the normal of the vertex in the last line
  16284. n2.x = normals[ base + j + 0 ];
  16285. n2.y = normals[ base + j + 1 ];
  16286. n2.z = normals[ base + j + 2 ];
  16287. // average normals
  16288. n.addVectors( n1, n2 ).normalize();
  16289. // assign the new values to both normals
  16290. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  16291. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  16292. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  16293. } // next row
  16294. }
  16295. }
  16296. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16297. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  16298. /**
  16299. * @author astrodud / http://astrodud.isgreat.org/
  16300. * @author zz85 / https://github.com/zz85
  16301. * @author bhouston / http://clara.io
  16302. */
  16303. // points - to create a closed torus, one must use a set of points
  16304. // like so: [ a, b, c, d, a ], see first is the same as last.
  16305. // segments - the number of circumference segments to create
  16306. // phiStart - the starting radian
  16307. // phiLength - the radian (0 to 2PI) range of the lathed section
  16308. // 2PI is a closed lathe, less than 2PI is a portion.
  16309. function LatheGeometry( points, segments, phiStart, phiLength ) {
  16310. Geometry.call( this );
  16311. this.type = 'LatheGeometry';
  16312. this.parameters = {
  16313. points: points,
  16314. segments: segments,
  16315. phiStart: phiStart,
  16316. phiLength: phiLength
  16317. };
  16318. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  16319. this.mergeVertices();
  16320. }
  16321. LatheGeometry.prototype = Object.create( Geometry.prototype );
  16322. LatheGeometry.prototype.constructor = LatheGeometry;
  16323. /**
  16324. * @author Mugen87 / https://github.com/Mugen87
  16325. *
  16326. * Creates a one-sided polygonal geometry from one or more shapes.
  16327. *
  16328. **/
  16329. function ShapeBufferGeometry( shapes, curveSegments ) {
  16330. BufferGeometry.call( this );
  16331. this.type = 'ShapeBufferGeometry';
  16332. this.parameters = {
  16333. shapes: shapes,
  16334. curveSegments: curveSegments
  16335. };
  16336. curveSegments = curveSegments || 12;
  16337. var vertices = [];
  16338. var normals = [];
  16339. var uvs = [];
  16340. var indices = [];
  16341. var groupStart = 0;
  16342. var groupCount = 0;
  16343. // allow single and array values for "shapes" parameter
  16344. if ( Array.isArray( shapes ) === false ) {
  16345. addShape( shapes );
  16346. } else {
  16347. for ( var i = 0; i < shapes.length; i++ ) {
  16348. addShape( shapes[ i ] );
  16349. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  16350. groupStart += groupCount;
  16351. groupCount = 0;
  16352. }
  16353. }
  16354. // build geometry
  16355. this.setIndex( new ( indices.length > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  16356. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16357. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16358. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16359. // helper functions
  16360. function addShape( shape ) {
  16361. var i, l, shapeHole;
  16362. var indexOffset = vertices.length / 3;
  16363. var points = shape.extractPoints( curveSegments );
  16364. var shapeVertices = points.shape;
  16365. var shapeHoles = points.holes;
  16366. // check direction of vertices
  16367. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  16368. shapeVertices = shapeVertices.reverse();
  16369. // also check if holes are in the opposite direction
  16370. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16371. shapeHole = shapeHoles[ i ];
  16372. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  16373. shapeHoles[ i ] = shapeHole.reverse();
  16374. }
  16375. }
  16376. }
  16377. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  16378. // join vertices of inner and outer paths to a single array
  16379. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16380. shapeHole = shapeHoles[ i ];
  16381. shapeVertices = shapeVertices.concat( shapeHole );
  16382. }
  16383. // vertices, normals, uvs
  16384. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  16385. var vertex = shapeVertices[ i ];
  16386. vertices.push( vertex.x, vertex.y, 0 );
  16387. normals.push( 0, 0, 1 );
  16388. uvs.push( vertex.x, vertex.y ); // world uvs
  16389. }
  16390. // incides
  16391. for ( i = 0, l = faces.length; i < l; i ++ ) {
  16392. var face = faces[ i ];
  16393. var a = face[ 0 ] + indexOffset;
  16394. var b = face[ 1 ] + indexOffset;
  16395. var c = face[ 2 ] + indexOffset;
  16396. indices.push( a, b, c );
  16397. groupCount += 3;
  16398. }
  16399. }
  16400. }
  16401. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16402. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  16403. /**
  16404. * @author jonobr1 / http://jonobr1.com
  16405. *
  16406. * Creates a one-sided polygonal geometry from a path shape.
  16407. *
  16408. **/
  16409. function ShapeGeometry( shapes, curveSegments ) {
  16410. Geometry.call( this );
  16411. this.type = 'ShapeGeometry';
  16412. if ( typeof curveSegments === 'object' ) {
  16413. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  16414. curveSegments = curveSegments.curveSegments;
  16415. }
  16416. this.parameters = {
  16417. shapes: shapes,
  16418. curveSegments: curveSegments
  16419. };
  16420. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  16421. this.mergeVertices();
  16422. }
  16423. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  16424. ShapeGeometry.prototype.constructor = ShapeGeometry;
  16425. /**
  16426. * @author WestLangley / http://github.com/WestLangley
  16427. */
  16428. function EdgesGeometry( geometry, thresholdAngle ) {
  16429. BufferGeometry.call( this );
  16430. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  16431. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  16432. var edge = [ 0, 0 ], hash = {};
  16433. function sortFunction( a, b ) {
  16434. return a - b;
  16435. }
  16436. var keys = [ 'a', 'b', 'c' ];
  16437. var geometry2;
  16438. if ( geometry.isBufferGeometry ) {
  16439. geometry2 = new Geometry();
  16440. geometry2.fromBufferGeometry( geometry );
  16441. } else {
  16442. geometry2 = geometry.clone();
  16443. }
  16444. geometry2.mergeVertices();
  16445. geometry2.computeFaceNormals();
  16446. var vertices = geometry2.vertices;
  16447. var faces = geometry2.faces;
  16448. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  16449. var face = faces[ i ];
  16450. for ( var j = 0; j < 3; j ++ ) {
  16451. edge[ 0 ] = face[ keys[ j ] ];
  16452. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  16453. edge.sort( sortFunction );
  16454. var key = edge.toString();
  16455. if ( hash[ key ] === undefined ) {
  16456. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  16457. } else {
  16458. hash[ key ].face2 = i;
  16459. }
  16460. }
  16461. }
  16462. var coords = [];
  16463. for ( var key in hash ) {
  16464. var h = hash[ key ];
  16465. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  16466. var vertex = vertices[ h.vert1 ];
  16467. coords.push( vertex.x );
  16468. coords.push( vertex.y );
  16469. coords.push( vertex.z );
  16470. vertex = vertices[ h.vert2 ];
  16471. coords.push( vertex.x );
  16472. coords.push( vertex.y );
  16473. coords.push( vertex.z );
  16474. }
  16475. }
  16476. this.addAttribute( 'position', new BufferAttribute( new Float32Array( coords ), 3 ) );
  16477. }
  16478. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  16479. EdgesGeometry.prototype.constructor = EdgesGeometry;
  16480. /**
  16481. * @author Mugen87 / https://github.com/Mugen87
  16482. */
  16483. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16484. BufferGeometry.call( this );
  16485. this.type = 'CylinderBufferGeometry';
  16486. this.parameters = {
  16487. radiusTop: radiusTop,
  16488. radiusBottom: radiusBottom,
  16489. height: height,
  16490. radialSegments: radialSegments,
  16491. heightSegments: heightSegments,
  16492. openEnded: openEnded,
  16493. thetaStart: thetaStart,
  16494. thetaLength: thetaLength
  16495. };
  16496. var scope = this;
  16497. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  16498. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  16499. height = height !== undefined ? height : 100;
  16500. radialSegments = Math.floor( radialSegments ) || 8;
  16501. heightSegments = Math.floor( heightSegments ) || 1;
  16502. openEnded = openEnded !== undefined ? openEnded : false;
  16503. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  16504. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  16505. // used to calculate buffer length
  16506. var nbCap = 0;
  16507. if ( openEnded === false ) {
  16508. if ( radiusTop > 0 ) nbCap ++;
  16509. if ( radiusBottom > 0 ) nbCap ++;
  16510. }
  16511. var vertexCount = calculateVertexCount();
  16512. var indexCount = calculateIndexCount();
  16513. // buffers
  16514. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 );
  16515. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16516. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16517. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  16518. // helper variables
  16519. var index = 0,
  16520. indexOffset = 0,
  16521. indexArray = [],
  16522. halfHeight = height / 2;
  16523. // group variables
  16524. var groupStart = 0;
  16525. // generate geometry
  16526. generateTorso();
  16527. if ( openEnded === false ) {
  16528. if ( radiusTop > 0 ) generateCap( true );
  16529. if ( radiusBottom > 0 ) generateCap( false );
  16530. }
  16531. // build geometry
  16532. this.setIndex( indices );
  16533. this.addAttribute( 'position', vertices );
  16534. this.addAttribute( 'normal', normals );
  16535. this.addAttribute( 'uv', uvs );
  16536. // helper functions
  16537. function calculateVertexCount() {
  16538. var count = ( radialSegments + 1 ) * ( heightSegments + 1 );
  16539. if ( openEnded === false ) {
  16540. count += ( ( radialSegments + 1 ) * nbCap ) + ( radialSegments * nbCap );
  16541. }
  16542. return count;
  16543. }
  16544. function calculateIndexCount() {
  16545. var count = radialSegments * heightSegments * 2 * 3;
  16546. if ( openEnded === false ) {
  16547. count += radialSegments * nbCap * 3;
  16548. }
  16549. return count;
  16550. }
  16551. function generateTorso() {
  16552. var x, y;
  16553. var normal = new Vector3();
  16554. var vertex = new Vector3();
  16555. var groupCount = 0;
  16556. // this will be used to calculate the normal
  16557. var slope = ( radiusBottom - radiusTop ) / height;
  16558. // generate vertices, normals and uvs
  16559. for ( y = 0; y <= heightSegments; y ++ ) {
  16560. var indexRow = [];
  16561. var v = y / heightSegments;
  16562. // calculate the radius of the current row
  16563. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  16564. for ( x = 0; x <= radialSegments; x ++ ) {
  16565. var u = x / radialSegments;
  16566. var theta = u * thetaLength + thetaStart;
  16567. var sinTheta = Math.sin( theta );
  16568. var cosTheta = Math.cos( theta );
  16569. // vertex
  16570. vertex.x = radius * sinTheta;
  16571. vertex.y = - v * height + halfHeight;
  16572. vertex.z = radius * cosTheta;
  16573. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  16574. // normal
  16575. normal.set( sinTheta, slope, cosTheta ).normalize();
  16576. normals.setXYZ( index, normal.x, normal.y, normal.z );
  16577. // uv
  16578. uvs.setXY( index, u, 1 - v );
  16579. // save index of vertex in respective row
  16580. indexRow.push( index );
  16581. // increase index
  16582. index ++;
  16583. }
  16584. // now save vertices of the row in our index array
  16585. indexArray.push( indexRow );
  16586. }
  16587. // generate indices
  16588. for ( x = 0; x < radialSegments; x ++ ) {
  16589. for ( y = 0; y < heightSegments; y ++ ) {
  16590. // we use the index array to access the correct indices
  16591. var i1 = indexArray[ y ][ x ];
  16592. var i2 = indexArray[ y + 1 ][ x ];
  16593. var i3 = indexArray[ y + 1 ][ x + 1 ];
  16594. var i4 = indexArray[ y ][ x + 1 ];
  16595. // face one
  16596. indices.setX( indexOffset, i1 ); indexOffset ++;
  16597. indices.setX( indexOffset, i2 ); indexOffset ++;
  16598. indices.setX( indexOffset, i4 ); indexOffset ++;
  16599. // face two
  16600. indices.setX( indexOffset, i2 ); indexOffset ++;
  16601. indices.setX( indexOffset, i3 ); indexOffset ++;
  16602. indices.setX( indexOffset, i4 ); indexOffset ++;
  16603. // update counters
  16604. groupCount += 6;
  16605. }
  16606. }
  16607. // add a group to the geometry. this will ensure multi material support
  16608. scope.addGroup( groupStart, groupCount, 0 );
  16609. // calculate new start value for groups
  16610. groupStart += groupCount;
  16611. }
  16612. function generateCap( top ) {
  16613. var x, centerIndexStart, centerIndexEnd;
  16614. var uv = new Vector2();
  16615. var vertex = new Vector3();
  16616. var groupCount = 0;
  16617. var radius = ( top === true ) ? radiusTop : radiusBottom;
  16618. var sign = ( top === true ) ? 1 : - 1;
  16619. // save the index of the first center vertex
  16620. centerIndexStart = index;
  16621. // first we generate the center vertex data of the cap.
  16622. // because the geometry needs one set of uvs per face,
  16623. // we must generate a center vertex per face/segment
  16624. for ( x = 1; x <= radialSegments; x ++ ) {
  16625. // vertex
  16626. vertices.setXYZ( index, 0, halfHeight * sign, 0 );
  16627. // normal
  16628. normals.setXYZ( index, 0, sign, 0 );
  16629. // uv
  16630. uv.x = 0.5;
  16631. uv.y = 0.5;
  16632. uvs.setXY( index, uv.x, uv.y );
  16633. // increase index
  16634. index ++;
  16635. }
  16636. // save the index of the last center vertex
  16637. centerIndexEnd = index;
  16638. // now we generate the surrounding vertices, normals and uvs
  16639. for ( x = 0; x <= radialSegments; x ++ ) {
  16640. var u = x / radialSegments;
  16641. var theta = u * thetaLength + thetaStart;
  16642. var cosTheta = Math.cos( theta );
  16643. var sinTheta = Math.sin( theta );
  16644. // vertex
  16645. vertex.x = radius * sinTheta;
  16646. vertex.y = halfHeight * sign;
  16647. vertex.z = radius * cosTheta;
  16648. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  16649. // normal
  16650. normals.setXYZ( index, 0, sign, 0 );
  16651. // uv
  16652. uv.x = ( cosTheta * 0.5 ) + 0.5;
  16653. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  16654. uvs.setXY( index, uv.x, uv.y );
  16655. // increase index
  16656. index ++;
  16657. }
  16658. // generate indices
  16659. for ( x = 0; x < radialSegments; x ++ ) {
  16660. var c = centerIndexStart + x;
  16661. var i = centerIndexEnd + x;
  16662. if ( top === true ) {
  16663. // face top
  16664. indices.setX( indexOffset, i ); indexOffset ++;
  16665. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  16666. indices.setX( indexOffset, c ); indexOffset ++;
  16667. } else {
  16668. // face bottom
  16669. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  16670. indices.setX( indexOffset, i ); indexOffset ++;
  16671. indices.setX( indexOffset, c ); indexOffset ++;
  16672. }
  16673. // update counters
  16674. groupCount += 3;
  16675. }
  16676. // add a group to the geometry. this will ensure multi material support
  16677. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  16678. // calculate new start value for groups
  16679. groupStart += groupCount;
  16680. }
  16681. }
  16682. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16683. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  16684. /**
  16685. * @author mrdoob / http://mrdoob.com/
  16686. */
  16687. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16688. Geometry.call( this );
  16689. this.type = 'CylinderGeometry';
  16690. this.parameters = {
  16691. radiusTop: radiusTop,
  16692. radiusBottom: radiusBottom,
  16693. height: height,
  16694. radialSegments: radialSegments,
  16695. heightSegments: heightSegments,
  16696. openEnded: openEnded,
  16697. thetaStart: thetaStart,
  16698. thetaLength: thetaLength
  16699. };
  16700. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  16701. this.mergeVertices();
  16702. }
  16703. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  16704. CylinderGeometry.prototype.constructor = CylinderGeometry;
  16705. /**
  16706. * @author abelnation / http://github.com/abelnation
  16707. */
  16708. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16709. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  16710. this.type = 'ConeGeometry';
  16711. this.parameters = {
  16712. radius: radius,
  16713. height: height,
  16714. radialSegments: radialSegments,
  16715. heightSegments: heightSegments,
  16716. openEnded: openEnded,
  16717. thetaStart: thetaStart,
  16718. thetaLength: thetaLength
  16719. };
  16720. }
  16721. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  16722. ConeGeometry.prototype.constructor = ConeGeometry;
  16723. /**
  16724. * @author: abelnation / http://github.com/abelnation
  16725. */
  16726. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16727. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  16728. this.type = 'ConeBufferGeometry';
  16729. this.parameters = {
  16730. radius: radius,
  16731. height: height,
  16732. radialSegments: radialSegments,
  16733. heightSegments: heightSegments,
  16734. openEnded: openEnded,
  16735. thetaStart: thetaStart,
  16736. thetaLength: thetaLength
  16737. };
  16738. }
  16739. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  16740. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  16741. /**
  16742. * @author benaadams / https://twitter.com/ben_a_adams
  16743. */
  16744. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  16745. BufferGeometry.call( this );
  16746. this.type = 'CircleBufferGeometry';
  16747. this.parameters = {
  16748. radius: radius,
  16749. segments: segments,
  16750. thetaStart: thetaStart,
  16751. thetaLength: thetaLength
  16752. };
  16753. radius = radius || 50;
  16754. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  16755. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16756. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16757. var vertices = segments + 2;
  16758. var positions = new Float32Array( vertices * 3 );
  16759. var normals = new Float32Array( vertices * 3 );
  16760. var uvs = new Float32Array( vertices * 2 );
  16761. // center data is already zero, but need to set a few extras
  16762. normals[ 2 ] = 1.0;
  16763. uvs[ 0 ] = 0.5;
  16764. uvs[ 1 ] = 0.5;
  16765. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) {
  16766. var segment = thetaStart + s / segments * thetaLength;
  16767. positions[ i ] = radius * Math.cos( segment );
  16768. positions[ i + 1 ] = radius * Math.sin( segment );
  16769. normals[ i + 2 ] = 1; // normal z
  16770. uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2;
  16771. uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2;
  16772. }
  16773. var indices = [];
  16774. for ( var i = 1; i <= segments; i ++ ) {
  16775. indices.push( i, i + 1, 0 );
  16776. }
  16777. this.setIndex( new BufferAttribute( new Uint16Array( indices ), 1 ) );
  16778. this.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  16779. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  16780. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  16781. this.boundingSphere = new Sphere( new Vector3(), radius );
  16782. }
  16783. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16784. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  16785. /**
  16786. * @author hughes
  16787. */
  16788. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  16789. Geometry.call( this );
  16790. this.type = 'CircleGeometry';
  16791. this.parameters = {
  16792. radius: radius,
  16793. segments: segments,
  16794. thetaStart: thetaStart,
  16795. thetaLength: thetaLength
  16796. };
  16797. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  16798. }
  16799. CircleGeometry.prototype = Object.create( Geometry.prototype );
  16800. CircleGeometry.prototype.constructor = CircleGeometry;
  16801. /**
  16802. * @author mrdoob / http://mrdoob.com/
  16803. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  16804. */
  16805. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  16806. Geometry.call( this );
  16807. this.type = 'BoxGeometry';
  16808. this.parameters = {
  16809. width: width,
  16810. height: height,
  16811. depth: depth,
  16812. widthSegments: widthSegments,
  16813. heightSegments: heightSegments,
  16814. depthSegments: depthSegments
  16815. };
  16816. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  16817. this.mergeVertices();
  16818. }
  16819. BoxGeometry.prototype = Object.create( Geometry.prototype );
  16820. BoxGeometry.prototype.constructor = BoxGeometry;
  16821. var Geometries = Object.freeze({
  16822. WireframeGeometry: WireframeGeometry,
  16823. ParametricGeometry: ParametricGeometry,
  16824. ParametricBufferGeometry: ParametricBufferGeometry,
  16825. TetrahedronGeometry: TetrahedronGeometry,
  16826. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  16827. OctahedronGeometry: OctahedronGeometry,
  16828. OctahedronBufferGeometry: OctahedronBufferGeometry,
  16829. IcosahedronGeometry: IcosahedronGeometry,
  16830. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  16831. DodecahedronGeometry: DodecahedronGeometry,
  16832. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  16833. PolyhedronGeometry: PolyhedronGeometry,
  16834. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  16835. TubeGeometry: TubeGeometry,
  16836. TubeBufferGeometry: TubeBufferGeometry,
  16837. TorusKnotGeometry: TorusKnotGeometry,
  16838. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  16839. TorusGeometry: TorusGeometry,
  16840. TorusBufferGeometry: TorusBufferGeometry,
  16841. TextGeometry: TextGeometry,
  16842. SphereBufferGeometry: SphereBufferGeometry,
  16843. SphereGeometry: SphereGeometry,
  16844. RingGeometry: RingGeometry,
  16845. RingBufferGeometry: RingBufferGeometry,
  16846. PlaneBufferGeometry: PlaneBufferGeometry,
  16847. PlaneGeometry: PlaneGeometry,
  16848. LatheGeometry: LatheGeometry,
  16849. LatheBufferGeometry: LatheBufferGeometry,
  16850. ShapeGeometry: ShapeGeometry,
  16851. ShapeBufferGeometry: ShapeBufferGeometry,
  16852. ExtrudeGeometry: ExtrudeGeometry,
  16853. EdgesGeometry: EdgesGeometry,
  16854. ConeGeometry: ConeGeometry,
  16855. ConeBufferGeometry: ConeBufferGeometry,
  16856. CylinderGeometry: CylinderGeometry,
  16857. CylinderBufferGeometry: CylinderBufferGeometry,
  16858. CircleBufferGeometry: CircleBufferGeometry,
  16859. CircleGeometry: CircleGeometry,
  16860. BoxBufferGeometry: BoxBufferGeometry,
  16861. BoxGeometry: BoxGeometry
  16862. });
  16863. /**
  16864. * @author mrdoob / http://mrdoob.com/
  16865. */
  16866. function ShadowMaterial() {
  16867. ShaderMaterial.call( this, {
  16868. uniforms: Object.assign( {},
  16869. UniformsLib.lights,
  16870. {
  16871. opacity: { value: 1.0 }
  16872. }
  16873. ),
  16874. vertexShader: ShaderChunk[ 'shadow_vert' ],
  16875. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  16876. } );
  16877. this.lights = true;
  16878. this.transparent = true;
  16879. Object.defineProperties( this, {
  16880. opacity: {
  16881. enumerable: true,
  16882. get: function () {
  16883. return this.uniforms.opacity.value;
  16884. },
  16885. set: function ( value ) {
  16886. this.uniforms.opacity.value = value;
  16887. }
  16888. }
  16889. } );
  16890. }
  16891. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  16892. ShadowMaterial.prototype.constructor = ShadowMaterial;
  16893. ShadowMaterial.prototype.isShadowMaterial = true;
  16894. /**
  16895. * @author mrdoob / http://mrdoob.com/
  16896. */
  16897. function RawShaderMaterial( parameters ) {
  16898. ShaderMaterial.call( this, parameters );
  16899. this.type = 'RawShaderMaterial';
  16900. }
  16901. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  16902. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  16903. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  16904. /**
  16905. * @author mrdoob / http://mrdoob.com/
  16906. */
  16907. function MultiMaterial( materials ) {
  16908. this.uuid = _Math.generateUUID();
  16909. this.type = 'MultiMaterial';
  16910. this.materials = Array.isArray( materials ) ? materials : [];
  16911. this.visible = true;
  16912. }
  16913. MultiMaterial.prototype = {
  16914. constructor: MultiMaterial,
  16915. isMultiMaterial: true,
  16916. toJSON: function ( meta ) {
  16917. var output = {
  16918. metadata: {
  16919. version: 4.2,
  16920. type: 'material',
  16921. generator: 'MaterialExporter'
  16922. },
  16923. uuid: this.uuid,
  16924. type: this.type,
  16925. materials: []
  16926. };
  16927. var materials = this.materials;
  16928. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16929. var material = materials[ i ].toJSON( meta );
  16930. delete material.metadata;
  16931. output.materials.push( material );
  16932. }
  16933. output.visible = this.visible;
  16934. return output;
  16935. },
  16936. clone: function () {
  16937. var material = new this.constructor();
  16938. for ( var i = 0; i < this.materials.length; i ++ ) {
  16939. material.materials.push( this.materials[ i ].clone() );
  16940. }
  16941. material.visible = this.visible;
  16942. return material;
  16943. }
  16944. };
  16945. /**
  16946. * @author WestLangley / http://github.com/WestLangley
  16947. *
  16948. * parameters = {
  16949. * color: <hex>,
  16950. * roughness: <float>,
  16951. * metalness: <float>,
  16952. * opacity: <float>,
  16953. *
  16954. * map: new THREE.Texture( <Image> ),
  16955. *
  16956. * lightMap: new THREE.Texture( <Image> ),
  16957. * lightMapIntensity: <float>
  16958. *
  16959. * aoMap: new THREE.Texture( <Image> ),
  16960. * aoMapIntensity: <float>
  16961. *
  16962. * emissive: <hex>,
  16963. * emissiveIntensity: <float>
  16964. * emissiveMap: new THREE.Texture( <Image> ),
  16965. *
  16966. * bumpMap: new THREE.Texture( <Image> ),
  16967. * bumpScale: <float>,
  16968. *
  16969. * normalMap: new THREE.Texture( <Image> ),
  16970. * normalScale: <Vector2>,
  16971. *
  16972. * displacementMap: new THREE.Texture( <Image> ),
  16973. * displacementScale: <float>,
  16974. * displacementBias: <float>,
  16975. *
  16976. * roughnessMap: new THREE.Texture( <Image> ),
  16977. *
  16978. * metalnessMap: new THREE.Texture( <Image> ),
  16979. *
  16980. * alphaMap: new THREE.Texture( <Image> ),
  16981. *
  16982. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  16983. * envMapIntensity: <float>
  16984. *
  16985. * refractionRatio: <float>,
  16986. *
  16987. * wireframe: <boolean>,
  16988. * wireframeLinewidth: <float>,
  16989. *
  16990. * skinning: <bool>,
  16991. * morphTargets: <bool>,
  16992. * morphNormals: <bool>
  16993. * }
  16994. */
  16995. function MeshStandardMaterial( parameters ) {
  16996. Material.call( this );
  16997. this.defines = { 'STANDARD': '' };
  16998. this.type = 'MeshStandardMaterial';
  16999. this.color = new Color( 0xffffff ); // diffuse
  17000. this.roughness = 0.5;
  17001. this.metalness = 0.5;
  17002. this.map = null;
  17003. this.lightMap = null;
  17004. this.lightMapIntensity = 1.0;
  17005. this.aoMap = null;
  17006. this.aoMapIntensity = 1.0;
  17007. this.emissive = new Color( 0x000000 );
  17008. this.emissiveIntensity = 1.0;
  17009. this.emissiveMap = null;
  17010. this.bumpMap = null;
  17011. this.bumpScale = 1;
  17012. this.normalMap = null;
  17013. this.normalScale = new Vector2( 1, 1 );
  17014. this.displacementMap = null;
  17015. this.displacementScale = 1;
  17016. this.displacementBias = 0;
  17017. this.roughnessMap = null;
  17018. this.metalnessMap = null;
  17019. this.alphaMap = null;
  17020. this.envMap = null;
  17021. this.envMapIntensity = 1.0;
  17022. this.refractionRatio = 0.98;
  17023. this.wireframe = false;
  17024. this.wireframeLinewidth = 1;
  17025. this.wireframeLinecap = 'round';
  17026. this.wireframeLinejoin = 'round';
  17027. this.skinning = false;
  17028. this.morphTargets = false;
  17029. this.morphNormals = false;
  17030. this.setValues( parameters );
  17031. }
  17032. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  17033. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  17034. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  17035. MeshStandardMaterial.prototype.copy = function ( source ) {
  17036. Material.prototype.copy.call( this, source );
  17037. this.defines = { 'STANDARD': '' };
  17038. this.color.copy( source.color );
  17039. this.roughness = source.roughness;
  17040. this.metalness = source.metalness;
  17041. this.map = source.map;
  17042. this.lightMap = source.lightMap;
  17043. this.lightMapIntensity = source.lightMapIntensity;
  17044. this.aoMap = source.aoMap;
  17045. this.aoMapIntensity = source.aoMapIntensity;
  17046. this.emissive.copy( source.emissive );
  17047. this.emissiveMap = source.emissiveMap;
  17048. this.emissiveIntensity = source.emissiveIntensity;
  17049. this.bumpMap = source.bumpMap;
  17050. this.bumpScale = source.bumpScale;
  17051. this.normalMap = source.normalMap;
  17052. this.normalScale.copy( source.normalScale );
  17053. this.displacementMap = source.displacementMap;
  17054. this.displacementScale = source.displacementScale;
  17055. this.displacementBias = source.displacementBias;
  17056. this.roughnessMap = source.roughnessMap;
  17057. this.metalnessMap = source.metalnessMap;
  17058. this.alphaMap = source.alphaMap;
  17059. this.envMap = source.envMap;
  17060. this.envMapIntensity = source.envMapIntensity;
  17061. this.refractionRatio = source.refractionRatio;
  17062. this.wireframe = source.wireframe;
  17063. this.wireframeLinewidth = source.wireframeLinewidth;
  17064. this.wireframeLinecap = source.wireframeLinecap;
  17065. this.wireframeLinejoin = source.wireframeLinejoin;
  17066. this.skinning = source.skinning;
  17067. this.morphTargets = source.morphTargets;
  17068. this.morphNormals = source.morphNormals;
  17069. return this;
  17070. };
  17071. /**
  17072. * @author WestLangley / http://github.com/WestLangley
  17073. *
  17074. * parameters = {
  17075. * reflectivity: <float>
  17076. * }
  17077. */
  17078. function MeshPhysicalMaterial( parameters ) {
  17079. MeshStandardMaterial.call( this );
  17080. this.defines = { 'PHYSICAL': '' };
  17081. this.type = 'MeshPhysicalMaterial';
  17082. this.reflectivity = 0.5; // maps to F0 = 0.04
  17083. this.clearCoat = 0.0;
  17084. this.clearCoatRoughness = 0.0;
  17085. this.setValues( parameters );
  17086. }
  17087. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  17088. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  17089. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  17090. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  17091. MeshStandardMaterial.prototype.copy.call( this, source );
  17092. this.defines = { 'PHYSICAL': '' };
  17093. this.reflectivity = source.reflectivity;
  17094. this.clearCoat = source.clearCoat;
  17095. this.clearCoatRoughness = source.clearCoatRoughness;
  17096. return this;
  17097. };
  17098. /**
  17099. * @author mrdoob / http://mrdoob.com/
  17100. * @author alteredq / http://alteredqualia.com/
  17101. *
  17102. * parameters = {
  17103. * color: <hex>,
  17104. * specular: <hex>,
  17105. * shininess: <float>,
  17106. * opacity: <float>,
  17107. *
  17108. * map: new THREE.Texture( <Image> ),
  17109. *
  17110. * lightMap: new THREE.Texture( <Image> ),
  17111. * lightMapIntensity: <float>
  17112. *
  17113. * aoMap: new THREE.Texture( <Image> ),
  17114. * aoMapIntensity: <float>
  17115. *
  17116. * emissive: <hex>,
  17117. * emissiveIntensity: <float>
  17118. * emissiveMap: new THREE.Texture( <Image> ),
  17119. *
  17120. * bumpMap: new THREE.Texture( <Image> ),
  17121. * bumpScale: <float>,
  17122. *
  17123. * normalMap: new THREE.Texture( <Image> ),
  17124. * normalScale: <Vector2>,
  17125. *
  17126. * displacementMap: new THREE.Texture( <Image> ),
  17127. * displacementScale: <float>,
  17128. * displacementBias: <float>,
  17129. *
  17130. * specularMap: new THREE.Texture( <Image> ),
  17131. *
  17132. * alphaMap: new THREE.Texture( <Image> ),
  17133. *
  17134. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17135. * combine: THREE.Multiply,
  17136. * reflectivity: <float>,
  17137. * refractionRatio: <float>,
  17138. *
  17139. * wireframe: <boolean>,
  17140. * wireframeLinewidth: <float>,
  17141. *
  17142. * skinning: <bool>,
  17143. * morphTargets: <bool>,
  17144. * morphNormals: <bool>
  17145. * }
  17146. */
  17147. function MeshPhongMaterial( parameters ) {
  17148. Material.call( this );
  17149. this.type = 'MeshPhongMaterial';
  17150. this.color = new Color( 0xffffff ); // diffuse
  17151. this.specular = new Color( 0x111111 );
  17152. this.shininess = 30;
  17153. this.map = null;
  17154. this.lightMap = null;
  17155. this.lightMapIntensity = 1.0;
  17156. this.aoMap = null;
  17157. this.aoMapIntensity = 1.0;
  17158. this.emissive = new Color( 0x000000 );
  17159. this.emissiveIntensity = 1.0;
  17160. this.emissiveMap = null;
  17161. this.bumpMap = null;
  17162. this.bumpScale = 1;
  17163. this.normalMap = null;
  17164. this.normalScale = new Vector2( 1, 1 );
  17165. this.displacementMap = null;
  17166. this.displacementScale = 1;
  17167. this.displacementBias = 0;
  17168. this.specularMap = null;
  17169. this.alphaMap = null;
  17170. this.envMap = null;
  17171. this.combine = MultiplyOperation;
  17172. this.reflectivity = 1;
  17173. this.refractionRatio = 0.98;
  17174. this.wireframe = false;
  17175. this.wireframeLinewidth = 1;
  17176. this.wireframeLinecap = 'round';
  17177. this.wireframeLinejoin = 'round';
  17178. this.skinning = false;
  17179. this.morphTargets = false;
  17180. this.morphNormals = false;
  17181. this.setValues( parameters );
  17182. }
  17183. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  17184. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  17185. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  17186. MeshPhongMaterial.prototype.copy = function ( source ) {
  17187. Material.prototype.copy.call( this, source );
  17188. this.color.copy( source.color );
  17189. this.specular.copy( source.specular );
  17190. this.shininess = source.shininess;
  17191. this.map = source.map;
  17192. this.lightMap = source.lightMap;
  17193. this.lightMapIntensity = source.lightMapIntensity;
  17194. this.aoMap = source.aoMap;
  17195. this.aoMapIntensity = source.aoMapIntensity;
  17196. this.emissive.copy( source.emissive );
  17197. this.emissiveMap = source.emissiveMap;
  17198. this.emissiveIntensity = source.emissiveIntensity;
  17199. this.bumpMap = source.bumpMap;
  17200. this.bumpScale = source.bumpScale;
  17201. this.normalMap = source.normalMap;
  17202. this.normalScale.copy( source.normalScale );
  17203. this.displacementMap = source.displacementMap;
  17204. this.displacementScale = source.displacementScale;
  17205. this.displacementBias = source.displacementBias;
  17206. this.specularMap = source.specularMap;
  17207. this.alphaMap = source.alphaMap;
  17208. this.envMap = source.envMap;
  17209. this.combine = source.combine;
  17210. this.reflectivity = source.reflectivity;
  17211. this.refractionRatio = source.refractionRatio;
  17212. this.wireframe = source.wireframe;
  17213. this.wireframeLinewidth = source.wireframeLinewidth;
  17214. this.wireframeLinecap = source.wireframeLinecap;
  17215. this.wireframeLinejoin = source.wireframeLinejoin;
  17216. this.skinning = source.skinning;
  17217. this.morphTargets = source.morphTargets;
  17218. this.morphNormals = source.morphNormals;
  17219. return this;
  17220. };
  17221. /**
  17222. * @author takahirox / http://github.com/takahirox
  17223. *
  17224. * parameters = {
  17225. * gradientMap: new THREE.Texture( <Image> )
  17226. * }
  17227. */
  17228. function MeshToonMaterial( parameters ) {
  17229. MeshPhongMaterial.call( this );
  17230. this.defines = { 'TOON': '' };
  17231. this.type = 'MeshToonMaterial';
  17232. this.gradientMap = null;
  17233. this.setValues( parameters );
  17234. }
  17235. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  17236. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  17237. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  17238. MeshToonMaterial.prototype.copy = function ( source ) {
  17239. MeshPhongMaterial.prototype.copy.call( this, source );
  17240. this.gradientMap = source.gradientMap;
  17241. return this;
  17242. };
  17243. /**
  17244. * @author mrdoob / http://mrdoob.com/
  17245. *
  17246. * parameters = {
  17247. * opacity: <float>,
  17248. *
  17249. * wireframe: <boolean>,
  17250. * wireframeLinewidth: <float>
  17251. * }
  17252. */
  17253. function MeshNormalMaterial( parameters ) {
  17254. Material.call( this, parameters );
  17255. this.type = 'MeshNormalMaterial';
  17256. this.wireframe = false;
  17257. this.wireframeLinewidth = 1;
  17258. this.fog = false;
  17259. this.lights = false;
  17260. this.morphTargets = false;
  17261. this.setValues( parameters );
  17262. }
  17263. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  17264. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  17265. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  17266. MeshNormalMaterial.prototype.copy = function ( source ) {
  17267. Material.prototype.copy.call( this, source );
  17268. this.wireframe = source.wireframe;
  17269. this.wireframeLinewidth = source.wireframeLinewidth;
  17270. return this;
  17271. };
  17272. /**
  17273. * @author mrdoob / http://mrdoob.com/
  17274. * @author alteredq / http://alteredqualia.com/
  17275. *
  17276. * parameters = {
  17277. * color: <hex>,
  17278. * opacity: <float>,
  17279. *
  17280. * map: new THREE.Texture( <Image> ),
  17281. *
  17282. * lightMap: new THREE.Texture( <Image> ),
  17283. * lightMapIntensity: <float>
  17284. *
  17285. * aoMap: new THREE.Texture( <Image> ),
  17286. * aoMapIntensity: <float>
  17287. *
  17288. * emissive: <hex>,
  17289. * emissiveIntensity: <float>
  17290. * emissiveMap: new THREE.Texture( <Image> ),
  17291. *
  17292. * specularMap: new THREE.Texture( <Image> ),
  17293. *
  17294. * alphaMap: new THREE.Texture( <Image> ),
  17295. *
  17296. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17297. * combine: THREE.Multiply,
  17298. * reflectivity: <float>,
  17299. * refractionRatio: <float>,
  17300. *
  17301. * wireframe: <boolean>,
  17302. * wireframeLinewidth: <float>,
  17303. *
  17304. * skinning: <bool>,
  17305. * morphTargets: <bool>,
  17306. * morphNormals: <bool>
  17307. * }
  17308. */
  17309. function MeshLambertMaterial( parameters ) {
  17310. Material.call( this );
  17311. this.type = 'MeshLambertMaterial';
  17312. this.color = new Color( 0xffffff ); // diffuse
  17313. this.map = null;
  17314. this.lightMap = null;
  17315. this.lightMapIntensity = 1.0;
  17316. this.aoMap = null;
  17317. this.aoMapIntensity = 1.0;
  17318. this.emissive = new Color( 0x000000 );
  17319. this.emissiveIntensity = 1.0;
  17320. this.emissiveMap = null;
  17321. this.specularMap = null;
  17322. this.alphaMap = null;
  17323. this.envMap = null;
  17324. this.combine = MultiplyOperation;
  17325. this.reflectivity = 1;
  17326. this.refractionRatio = 0.98;
  17327. this.wireframe = false;
  17328. this.wireframeLinewidth = 1;
  17329. this.wireframeLinecap = 'round';
  17330. this.wireframeLinejoin = 'round';
  17331. this.skinning = false;
  17332. this.morphTargets = false;
  17333. this.morphNormals = false;
  17334. this.setValues( parameters );
  17335. }
  17336. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  17337. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  17338. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  17339. MeshLambertMaterial.prototype.copy = function ( source ) {
  17340. Material.prototype.copy.call( this, source );
  17341. this.color.copy( source.color );
  17342. this.map = source.map;
  17343. this.lightMap = source.lightMap;
  17344. this.lightMapIntensity = source.lightMapIntensity;
  17345. this.aoMap = source.aoMap;
  17346. this.aoMapIntensity = source.aoMapIntensity;
  17347. this.emissive.copy( source.emissive );
  17348. this.emissiveMap = source.emissiveMap;
  17349. this.emissiveIntensity = source.emissiveIntensity;
  17350. this.specularMap = source.specularMap;
  17351. this.alphaMap = source.alphaMap;
  17352. this.envMap = source.envMap;
  17353. this.combine = source.combine;
  17354. this.reflectivity = source.reflectivity;
  17355. this.refractionRatio = source.refractionRatio;
  17356. this.wireframe = source.wireframe;
  17357. this.wireframeLinewidth = source.wireframeLinewidth;
  17358. this.wireframeLinecap = source.wireframeLinecap;
  17359. this.wireframeLinejoin = source.wireframeLinejoin;
  17360. this.skinning = source.skinning;
  17361. this.morphTargets = source.morphTargets;
  17362. this.morphNormals = source.morphNormals;
  17363. return this;
  17364. };
  17365. /**
  17366. * @author alteredq / http://alteredqualia.com/
  17367. *
  17368. * parameters = {
  17369. * color: <hex>,
  17370. * opacity: <float>,
  17371. *
  17372. * linewidth: <float>,
  17373. *
  17374. * scale: <float>,
  17375. * dashSize: <float>,
  17376. * gapSize: <float>
  17377. * }
  17378. */
  17379. function LineDashedMaterial( parameters ) {
  17380. Material.call( this );
  17381. this.type = 'LineDashedMaterial';
  17382. this.color = new Color( 0xffffff );
  17383. this.linewidth = 1;
  17384. this.scale = 1;
  17385. this.dashSize = 3;
  17386. this.gapSize = 1;
  17387. this.lights = false;
  17388. this.setValues( parameters );
  17389. }
  17390. LineDashedMaterial.prototype = Object.create( Material.prototype );
  17391. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  17392. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  17393. LineDashedMaterial.prototype.copy = function ( source ) {
  17394. Material.prototype.copy.call( this, source );
  17395. this.color.copy( source.color );
  17396. this.linewidth = source.linewidth;
  17397. this.scale = source.scale;
  17398. this.dashSize = source.dashSize;
  17399. this.gapSize = source.gapSize;
  17400. return this;
  17401. };
  17402. var Materials = Object.freeze({
  17403. ShadowMaterial: ShadowMaterial,
  17404. SpriteMaterial: SpriteMaterial,
  17405. RawShaderMaterial: RawShaderMaterial,
  17406. ShaderMaterial: ShaderMaterial,
  17407. PointsMaterial: PointsMaterial,
  17408. MultiMaterial: MultiMaterial,
  17409. MeshPhysicalMaterial: MeshPhysicalMaterial,
  17410. MeshStandardMaterial: MeshStandardMaterial,
  17411. MeshPhongMaterial: MeshPhongMaterial,
  17412. MeshToonMaterial: MeshToonMaterial,
  17413. MeshNormalMaterial: MeshNormalMaterial,
  17414. MeshLambertMaterial: MeshLambertMaterial,
  17415. MeshDepthMaterial: MeshDepthMaterial,
  17416. MeshBasicMaterial: MeshBasicMaterial,
  17417. LineDashedMaterial: LineDashedMaterial,
  17418. LineBasicMaterial: LineBasicMaterial,
  17419. Material: Material
  17420. });
  17421. /**
  17422. * @author mrdoob / http://mrdoob.com/
  17423. */
  17424. var Cache = {
  17425. enabled: false,
  17426. files: {},
  17427. add: function ( key, file ) {
  17428. if ( this.enabled === false ) return;
  17429. // console.log( 'THREE.Cache', 'Adding key:', key );
  17430. this.files[ key ] = file;
  17431. },
  17432. get: function ( key ) {
  17433. if ( this.enabled === false ) return;
  17434. // console.log( 'THREE.Cache', 'Checking key:', key );
  17435. return this.files[ key ];
  17436. },
  17437. remove: function ( key ) {
  17438. delete this.files[ key ];
  17439. },
  17440. clear: function () {
  17441. this.files = {};
  17442. }
  17443. };
  17444. /**
  17445. * @author mrdoob / http://mrdoob.com/
  17446. */
  17447. function LoadingManager( onLoad, onProgress, onError ) {
  17448. var scope = this;
  17449. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  17450. this.onStart = undefined;
  17451. this.onLoad = onLoad;
  17452. this.onProgress = onProgress;
  17453. this.onError = onError;
  17454. this.itemStart = function ( url ) {
  17455. itemsTotal ++;
  17456. if ( isLoading === false ) {
  17457. if ( scope.onStart !== undefined ) {
  17458. scope.onStart( url, itemsLoaded, itemsTotal );
  17459. }
  17460. }
  17461. isLoading = true;
  17462. };
  17463. this.itemEnd = function ( url ) {
  17464. itemsLoaded ++;
  17465. if ( scope.onProgress !== undefined ) {
  17466. scope.onProgress( url, itemsLoaded, itemsTotal );
  17467. }
  17468. if ( itemsLoaded === itemsTotal ) {
  17469. isLoading = false;
  17470. if ( scope.onLoad !== undefined ) {
  17471. scope.onLoad();
  17472. }
  17473. }
  17474. };
  17475. this.itemError = function ( url ) {
  17476. if ( scope.onError !== undefined ) {
  17477. scope.onError( url );
  17478. }
  17479. };
  17480. }
  17481. var DefaultLoadingManager = new LoadingManager();
  17482. /**
  17483. * @author mrdoob / http://mrdoob.com/
  17484. */
  17485. function FileLoader( manager ) {
  17486. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17487. }
  17488. Object.assign( FileLoader.prototype, {
  17489. load: function ( url, onLoad, onProgress, onError ) {
  17490. if ( url === undefined ) url = '';
  17491. if ( this.path !== undefined ) url = this.path + url;
  17492. var scope = this;
  17493. var cached = Cache.get( url );
  17494. if ( cached !== undefined ) {
  17495. scope.manager.itemStart( url );
  17496. setTimeout( function () {
  17497. if ( onLoad ) onLoad( cached );
  17498. scope.manager.itemEnd( url );
  17499. }, 0 );
  17500. return cached;
  17501. }
  17502. // Check for data: URI
  17503. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  17504. var dataUriRegexResult = url.match( dataUriRegex );
  17505. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  17506. if ( dataUriRegexResult ) {
  17507. var mimeType = dataUriRegexResult[ 1 ];
  17508. var isBase64 = !! dataUriRegexResult[ 2 ];
  17509. var data = dataUriRegexResult[ 3 ];
  17510. data = window.decodeURIComponent( data );
  17511. if ( isBase64 ) data = window.atob( data );
  17512. try {
  17513. var response;
  17514. var responseType = ( this.responseType || '' ).toLowerCase();
  17515. switch ( responseType ) {
  17516. case 'arraybuffer':
  17517. case 'blob':
  17518. response = new ArrayBuffer( data.length );
  17519. var view = new Uint8Array( response );
  17520. for ( var i = 0; i < data.length; i ++ ) {
  17521. view[ i ] = data.charCodeAt( i );
  17522. }
  17523. if ( responseType === 'blob' ) {
  17524. response = new Blob( [ response ], { type: mimeType } );
  17525. }
  17526. break;
  17527. case 'document':
  17528. var parser = new DOMParser();
  17529. response = parser.parseFromString( data, mimeType );
  17530. break;
  17531. case 'json':
  17532. response = JSON.parse( data );
  17533. break;
  17534. default: // 'text' or other
  17535. response = data;
  17536. break;
  17537. }
  17538. // Wait for next browser tick
  17539. window.setTimeout( function () {
  17540. if ( onLoad ) onLoad( response );
  17541. scope.manager.itemEnd( url );
  17542. }, 0 );
  17543. } catch ( error ) {
  17544. // Wait for next browser tick
  17545. window.setTimeout( function () {
  17546. if ( onError ) onError( error );
  17547. scope.manager.itemError( url );
  17548. }, 0 );
  17549. }
  17550. } else {
  17551. var request = new XMLHttpRequest();
  17552. request.open( 'GET', url, true );
  17553. request.addEventListener( 'load', function ( event ) {
  17554. var response = event.target.response;
  17555. Cache.add( url, response );
  17556. if ( this.status === 200 ) {
  17557. if ( onLoad ) onLoad( response );
  17558. scope.manager.itemEnd( url );
  17559. } else if ( this.status === 0 ) {
  17560. // Some browsers return HTTP Status 0 when using non-http protocol
  17561. // e.g. 'file://' or 'data://'. Handle as success.
  17562. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  17563. if ( onLoad ) onLoad( response );
  17564. scope.manager.itemEnd( url );
  17565. } else {
  17566. if ( onError ) onError( event );
  17567. scope.manager.itemError( url );
  17568. }
  17569. }, false );
  17570. if ( onProgress !== undefined ) {
  17571. request.addEventListener( 'progress', function ( event ) {
  17572. onProgress( event );
  17573. }, false );
  17574. }
  17575. request.addEventListener( 'error', function ( event ) {
  17576. if ( onError ) onError( event );
  17577. scope.manager.itemError( url );
  17578. }, false );
  17579. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  17580. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  17581. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  17582. request.send( null );
  17583. }
  17584. scope.manager.itemStart( url );
  17585. return request;
  17586. },
  17587. setPath: function ( value ) {
  17588. this.path = value;
  17589. return this;
  17590. },
  17591. setResponseType: function ( value ) {
  17592. this.responseType = value;
  17593. return this;
  17594. },
  17595. setWithCredentials: function ( value ) {
  17596. this.withCredentials = value;
  17597. return this;
  17598. },
  17599. setMimeType: function ( value ) {
  17600. this.mimeType = value;
  17601. return this;
  17602. }
  17603. } );
  17604. /**
  17605. * @author mrdoob / http://mrdoob.com/
  17606. *
  17607. * Abstract Base class to block based textures loader (dds, pvr, ...)
  17608. */
  17609. function CompressedTextureLoader( manager ) {
  17610. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17611. // override in sub classes
  17612. this._parser = null;
  17613. }
  17614. Object.assign( CompressedTextureLoader.prototype, {
  17615. load: function ( url, onLoad, onProgress, onError ) {
  17616. var scope = this;
  17617. var images = [];
  17618. var texture = new CompressedTexture();
  17619. texture.image = images;
  17620. var loader = new FileLoader( this.manager );
  17621. loader.setPath( this.path );
  17622. loader.setResponseType( 'arraybuffer' );
  17623. function loadTexture( i ) {
  17624. loader.load( url[ i ], function ( buffer ) {
  17625. var texDatas = scope._parser( buffer, true );
  17626. images[ i ] = {
  17627. width: texDatas.width,
  17628. height: texDatas.height,
  17629. format: texDatas.format,
  17630. mipmaps: texDatas.mipmaps
  17631. };
  17632. loaded += 1;
  17633. if ( loaded === 6 ) {
  17634. if ( texDatas.mipmapCount === 1 )
  17635. texture.minFilter = LinearFilter;
  17636. texture.format = texDatas.format;
  17637. texture.needsUpdate = true;
  17638. if ( onLoad ) onLoad( texture );
  17639. }
  17640. }, onProgress, onError );
  17641. }
  17642. if ( Array.isArray( url ) ) {
  17643. var loaded = 0;
  17644. for ( var i = 0, il = url.length; i < il; ++ i ) {
  17645. loadTexture( i );
  17646. }
  17647. } else {
  17648. // compressed cubemap texture stored in a single DDS file
  17649. loader.load( url, function ( buffer ) {
  17650. var texDatas = scope._parser( buffer, true );
  17651. if ( texDatas.isCubemap ) {
  17652. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  17653. for ( var f = 0; f < faces; f ++ ) {
  17654. images[ f ] = { mipmaps : [] };
  17655. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  17656. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  17657. images[ f ].format = texDatas.format;
  17658. images[ f ].width = texDatas.width;
  17659. images[ f ].height = texDatas.height;
  17660. }
  17661. }
  17662. } else {
  17663. texture.image.width = texDatas.width;
  17664. texture.image.height = texDatas.height;
  17665. texture.mipmaps = texDatas.mipmaps;
  17666. }
  17667. if ( texDatas.mipmapCount === 1 ) {
  17668. texture.minFilter = LinearFilter;
  17669. }
  17670. texture.format = texDatas.format;
  17671. texture.needsUpdate = true;
  17672. if ( onLoad ) onLoad( texture );
  17673. }, onProgress, onError );
  17674. }
  17675. return texture;
  17676. },
  17677. setPath: function ( value ) {
  17678. this.path = value;
  17679. return this;
  17680. }
  17681. } );
  17682. /**
  17683. * @author Nikos M. / https://github.com/foo123/
  17684. *
  17685. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  17686. */
  17687. var DataTextureLoader = BinaryTextureLoader;
  17688. function BinaryTextureLoader( manager ) {
  17689. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17690. // override in sub classes
  17691. this._parser = null;
  17692. }
  17693. Object.assign( BinaryTextureLoader.prototype, {
  17694. load: function ( url, onLoad, onProgress, onError ) {
  17695. var scope = this;
  17696. var texture = new DataTexture();
  17697. var loader = new FileLoader( this.manager );
  17698. loader.setResponseType( 'arraybuffer' );
  17699. loader.load( url, function ( buffer ) {
  17700. var texData = scope._parser( buffer );
  17701. if ( ! texData ) return;
  17702. if ( undefined !== texData.image ) {
  17703. texture.image = texData.image;
  17704. } else if ( undefined !== texData.data ) {
  17705. texture.image.width = texData.width;
  17706. texture.image.height = texData.height;
  17707. texture.image.data = texData.data;
  17708. }
  17709. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  17710. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  17711. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  17712. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  17713. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  17714. if ( undefined !== texData.format ) {
  17715. texture.format = texData.format;
  17716. }
  17717. if ( undefined !== texData.type ) {
  17718. texture.type = texData.type;
  17719. }
  17720. if ( undefined !== texData.mipmaps ) {
  17721. texture.mipmaps = texData.mipmaps;
  17722. }
  17723. if ( 1 === texData.mipmapCount ) {
  17724. texture.minFilter = LinearFilter;
  17725. }
  17726. texture.needsUpdate = true;
  17727. if ( onLoad ) onLoad( texture, texData );
  17728. }, onProgress, onError );
  17729. return texture;
  17730. }
  17731. } );
  17732. /**
  17733. * @author mrdoob / http://mrdoob.com/
  17734. */
  17735. function ImageLoader( manager ) {
  17736. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17737. }
  17738. Object.assign( ImageLoader.prototype, {
  17739. load: function ( url, onLoad, onProgress, onError ) {
  17740. var scope = this;
  17741. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  17742. image.onload = function () {
  17743. image.onload = null;
  17744. URL.revokeObjectURL( image.src );
  17745. if ( onLoad ) onLoad( image );
  17746. scope.manager.itemEnd( url );
  17747. };
  17748. image.onerror = onError;
  17749. if ( url.indexOf( 'data:' ) === 0 ) {
  17750. image.src = url;
  17751. } else if ( this.crossOrigin !== undefined ) {
  17752. // crossOrigin doesn't work with URL.createObjectURL()?
  17753. image.crossOrigin = this.crossOrigin;
  17754. image.src = url;
  17755. } else {
  17756. var loader = new FileLoader();
  17757. loader.setPath( this.path );
  17758. loader.setResponseType( 'blob' );
  17759. loader.setWithCredentials( this.withCredentials );
  17760. loader.load( url, function ( blob ) {
  17761. image.src = URL.createObjectURL( blob );
  17762. }, onProgress, onError );
  17763. }
  17764. scope.manager.itemStart( url );
  17765. return image;
  17766. },
  17767. setCrossOrigin: function ( value ) {
  17768. this.crossOrigin = value;
  17769. return this;
  17770. },
  17771. setWithCredentials: function ( value ) {
  17772. this.withCredentials = value;
  17773. return this;
  17774. },
  17775. setPath: function ( value ) {
  17776. this.path = value;
  17777. return this;
  17778. }
  17779. } );
  17780. /**
  17781. * @author mrdoob / http://mrdoob.com/
  17782. */
  17783. function CubeTextureLoader( manager ) {
  17784. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17785. }
  17786. Object.assign( CubeTextureLoader.prototype, {
  17787. load: function ( urls, onLoad, onProgress, onError ) {
  17788. var texture = new CubeTexture();
  17789. var loader = new ImageLoader( this.manager );
  17790. loader.setCrossOrigin( this.crossOrigin );
  17791. loader.setPath( this.path );
  17792. var loaded = 0;
  17793. function loadTexture( i ) {
  17794. loader.load( urls[ i ], function ( image ) {
  17795. texture.images[ i ] = image;
  17796. loaded ++;
  17797. if ( loaded === 6 ) {
  17798. texture.needsUpdate = true;
  17799. if ( onLoad ) onLoad( texture );
  17800. }
  17801. }, undefined, onError );
  17802. }
  17803. for ( var i = 0; i < urls.length; ++ i ) {
  17804. loadTexture( i );
  17805. }
  17806. return texture;
  17807. },
  17808. setCrossOrigin: function ( value ) {
  17809. this.crossOrigin = value;
  17810. return this;
  17811. },
  17812. setPath: function ( value ) {
  17813. this.path = value;
  17814. return this;
  17815. }
  17816. } );
  17817. /**
  17818. * @author mrdoob / http://mrdoob.com/
  17819. */
  17820. function TextureLoader( manager ) {
  17821. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17822. }
  17823. Object.assign( TextureLoader.prototype, {
  17824. load: function ( url, onLoad, onProgress, onError ) {
  17825. var texture = new Texture();
  17826. var loader = new ImageLoader( this.manager );
  17827. loader.setCrossOrigin( this.crossOrigin );
  17828. loader.setWithCredentials( this.withCredentials );
  17829. loader.setPath( this.path );
  17830. loader.load( url, function ( image ) {
  17831. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  17832. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  17833. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  17834. texture.image = image;
  17835. texture.needsUpdate = true;
  17836. if ( onLoad !== undefined ) {
  17837. onLoad( texture );
  17838. }
  17839. }, onProgress, onError );
  17840. return texture;
  17841. },
  17842. setCrossOrigin: function ( value ) {
  17843. this.crossOrigin = value;
  17844. return this;
  17845. },
  17846. setWithCredentials: function ( value ) {
  17847. this.withCredentials = value;
  17848. return this;
  17849. },
  17850. setPath: function ( value ) {
  17851. this.path = value;
  17852. return this;
  17853. }
  17854. } );
  17855. /**
  17856. * @author mrdoob / http://mrdoob.com/
  17857. * @author alteredq / http://alteredqualia.com/
  17858. */
  17859. function Light( color, intensity ) {
  17860. Object3D.call( this );
  17861. this.type = 'Light';
  17862. this.color = new Color( color );
  17863. this.intensity = intensity !== undefined ? intensity : 1;
  17864. this.receiveShadow = undefined;
  17865. }
  17866. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  17867. constructor: Light,
  17868. isLight: true,
  17869. copy: function ( source ) {
  17870. Object3D.prototype.copy.call( this, source );
  17871. this.color.copy( source.color );
  17872. this.intensity = source.intensity;
  17873. return this;
  17874. },
  17875. toJSON: function ( meta ) {
  17876. var data = Object3D.prototype.toJSON.call( this, meta );
  17877. data.object.color = this.color.getHex();
  17878. data.object.intensity = this.intensity;
  17879. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  17880. if ( this.distance !== undefined ) data.object.distance = this.distance;
  17881. if ( this.angle !== undefined ) data.object.angle = this.angle;
  17882. if ( this.decay !== undefined ) data.object.decay = this.decay;
  17883. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  17884. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  17885. return data;
  17886. }
  17887. } );
  17888. /**
  17889. * @author alteredq / http://alteredqualia.com/
  17890. */
  17891. function HemisphereLight( skyColor, groundColor, intensity ) {
  17892. Light.call( this, skyColor, intensity );
  17893. this.type = 'HemisphereLight';
  17894. this.castShadow = undefined;
  17895. this.position.copy( Object3D.DefaultUp );
  17896. this.updateMatrix();
  17897. this.groundColor = new Color( groundColor );
  17898. }
  17899. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  17900. constructor: HemisphereLight,
  17901. isHemisphereLight: true,
  17902. copy: function ( source ) {
  17903. Light.prototype.copy.call( this, source );
  17904. this.groundColor.copy( source.groundColor );
  17905. return this;
  17906. }
  17907. } );
  17908. /**
  17909. * @author mrdoob / http://mrdoob.com/
  17910. */
  17911. function LightShadow( camera ) {
  17912. this.camera = camera;
  17913. this.bias = 0;
  17914. this.radius = 1;
  17915. this.mapSize = new Vector2( 512, 512 );
  17916. this.map = null;
  17917. this.matrix = new Matrix4();
  17918. }
  17919. Object.assign( LightShadow.prototype, {
  17920. copy: function ( source ) {
  17921. this.camera = source.camera.clone();
  17922. this.bias = source.bias;
  17923. this.radius = source.radius;
  17924. this.mapSize.copy( source.mapSize );
  17925. return this;
  17926. },
  17927. clone: function () {
  17928. return new this.constructor().copy( this );
  17929. },
  17930. toJSON: function () {
  17931. var object = {};
  17932. if ( this.bias !== 0 ) object.bias = this.bias;
  17933. if ( this.radius !== 1 ) object.radius = this.radius;
  17934. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  17935. object.camera = this.camera.toJSON( false ).object;
  17936. delete object.camera.matrix;
  17937. return object;
  17938. }
  17939. } );
  17940. /**
  17941. * @author mrdoob / http://mrdoob.com/
  17942. */
  17943. function SpotLightShadow() {
  17944. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  17945. }
  17946. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  17947. constructor: SpotLightShadow,
  17948. isSpotLightShadow: true,
  17949. update: function ( light ) {
  17950. var fov = _Math.RAD2DEG * 2 * light.angle;
  17951. var aspect = this.mapSize.width / this.mapSize.height;
  17952. var far = light.distance || 500;
  17953. var camera = this.camera;
  17954. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  17955. camera.fov = fov;
  17956. camera.aspect = aspect;
  17957. camera.far = far;
  17958. camera.updateProjectionMatrix();
  17959. }
  17960. }
  17961. } );
  17962. /**
  17963. * @author alteredq / http://alteredqualia.com/
  17964. */
  17965. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  17966. Light.call( this, color, intensity );
  17967. this.type = 'SpotLight';
  17968. this.position.copy( Object3D.DefaultUp );
  17969. this.updateMatrix();
  17970. this.target = new Object3D();
  17971. Object.defineProperty( this, 'power', {
  17972. get: function () {
  17973. // intensity = power per solid angle.
  17974. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  17975. return this.intensity * Math.PI;
  17976. },
  17977. set: function ( power ) {
  17978. // intensity = power per solid angle.
  17979. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  17980. this.intensity = power / Math.PI;
  17981. }
  17982. } );
  17983. this.distance = ( distance !== undefined ) ? distance : 0;
  17984. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  17985. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  17986. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  17987. this.shadow = new SpotLightShadow();
  17988. }
  17989. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  17990. constructor: SpotLight,
  17991. isSpotLight: true,
  17992. copy: function ( source ) {
  17993. Light.prototype.copy.call( this, source );
  17994. this.distance = source.distance;
  17995. this.angle = source.angle;
  17996. this.penumbra = source.penumbra;
  17997. this.decay = source.decay;
  17998. this.target = source.target.clone();
  17999. this.shadow = source.shadow.clone();
  18000. return this;
  18001. }
  18002. } );
  18003. /**
  18004. * @author mrdoob / http://mrdoob.com/
  18005. */
  18006. function PointLight( color, intensity, distance, decay ) {
  18007. Light.call( this, color, intensity );
  18008. this.type = 'PointLight';
  18009. Object.defineProperty( this, 'power', {
  18010. get: function () {
  18011. // intensity = power per solid angle.
  18012. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18013. return this.intensity * 4 * Math.PI;
  18014. },
  18015. set: function ( power ) {
  18016. // intensity = power per solid angle.
  18017. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18018. this.intensity = power / ( 4 * Math.PI );
  18019. }
  18020. } );
  18021. this.distance = ( distance !== undefined ) ? distance : 0;
  18022. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18023. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  18024. }
  18025. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18026. constructor: PointLight,
  18027. isPointLight: true,
  18028. copy: function ( source ) {
  18029. Light.prototype.copy.call( this, source );
  18030. this.distance = source.distance;
  18031. this.decay = source.decay;
  18032. this.shadow = source.shadow.clone();
  18033. return this;
  18034. }
  18035. } );
  18036. /**
  18037. * @author mrdoob / http://mrdoob.com/
  18038. */
  18039. function DirectionalLightShadow( light ) {
  18040. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  18041. }
  18042. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18043. constructor: DirectionalLightShadow
  18044. } );
  18045. /**
  18046. * @author mrdoob / http://mrdoob.com/
  18047. * @author alteredq / http://alteredqualia.com/
  18048. */
  18049. function DirectionalLight( color, intensity ) {
  18050. Light.call( this, color, intensity );
  18051. this.type = 'DirectionalLight';
  18052. this.position.copy( Object3D.DefaultUp );
  18053. this.updateMatrix();
  18054. this.target = new Object3D();
  18055. this.shadow = new DirectionalLightShadow();
  18056. }
  18057. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18058. constructor: DirectionalLight,
  18059. isDirectionalLight: true,
  18060. copy: function ( source ) {
  18061. Light.prototype.copy.call( this, source );
  18062. this.target = source.target.clone();
  18063. this.shadow = source.shadow.clone();
  18064. return this;
  18065. }
  18066. } );
  18067. /**
  18068. * @author mrdoob / http://mrdoob.com/
  18069. */
  18070. function AmbientLight( color, intensity ) {
  18071. Light.call( this, color, intensity );
  18072. this.type = 'AmbientLight';
  18073. this.castShadow = undefined;
  18074. }
  18075. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18076. constructor: AmbientLight,
  18077. isAmbientLight: true,
  18078. } );
  18079. /**
  18080. * @author tschw
  18081. * @author Ben Houston / http://clara.io/
  18082. * @author David Sarno / http://lighthaus.us/
  18083. */
  18084. var AnimationUtils = {
  18085. // same as Array.prototype.slice, but also works on typed arrays
  18086. arraySlice: function( array, from, to ) {
  18087. if ( AnimationUtils.isTypedArray( array ) ) {
  18088. return new array.constructor( array.subarray( from, to ) );
  18089. }
  18090. return array.slice( from, to );
  18091. },
  18092. // converts an array to a specific type
  18093. convertArray: function( array, type, forceClone ) {
  18094. if ( ! array || // let 'undefined' and 'null' pass
  18095. ! forceClone && array.constructor === type ) return array;
  18096. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  18097. return new type( array ); // create typed array
  18098. }
  18099. return Array.prototype.slice.call( array ); // create Array
  18100. },
  18101. isTypedArray: function( object ) {
  18102. return ArrayBuffer.isView( object ) &&
  18103. ! ( object instanceof DataView );
  18104. },
  18105. // returns an array by which times and values can be sorted
  18106. getKeyframeOrder: function( times ) {
  18107. function compareTime( i, j ) {
  18108. return times[ i ] - times[ j ];
  18109. }
  18110. var n = times.length;
  18111. var result = new Array( n );
  18112. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  18113. result.sort( compareTime );
  18114. return result;
  18115. },
  18116. // uses the array previously returned by 'getKeyframeOrder' to sort data
  18117. sortedArray: function( values, stride, order ) {
  18118. var nValues = values.length;
  18119. var result = new values.constructor( nValues );
  18120. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  18121. var srcOffset = order[ i ] * stride;
  18122. for ( var j = 0; j !== stride; ++ j ) {
  18123. result[ dstOffset ++ ] = values[ srcOffset + j ];
  18124. }
  18125. }
  18126. return result;
  18127. },
  18128. // function for parsing AOS keyframe formats
  18129. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  18130. var i = 1, key = jsonKeys[ 0 ];
  18131. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  18132. key = jsonKeys[ i ++ ];
  18133. }
  18134. if ( key === undefined ) return; // no data
  18135. var value = key[ valuePropertyName ];
  18136. if ( value === undefined ) return; // no data
  18137. if ( Array.isArray( value ) ) {
  18138. do {
  18139. value = key[ valuePropertyName ];
  18140. if ( value !== undefined ) {
  18141. times.push( key.time );
  18142. values.push.apply( values, value ); // push all elements
  18143. }
  18144. key = jsonKeys[ i ++ ];
  18145. } while ( key !== undefined );
  18146. } else if ( value.toArray !== undefined ) {
  18147. // ...assume THREE.Math-ish
  18148. do {
  18149. value = key[ valuePropertyName ];
  18150. if ( value !== undefined ) {
  18151. times.push( key.time );
  18152. value.toArray( values, values.length );
  18153. }
  18154. key = jsonKeys[ i ++ ];
  18155. } while ( key !== undefined );
  18156. } else {
  18157. // otherwise push as-is
  18158. do {
  18159. value = key[ valuePropertyName ];
  18160. if ( value !== undefined ) {
  18161. times.push( key.time );
  18162. values.push( value );
  18163. }
  18164. key = jsonKeys[ i ++ ];
  18165. } while ( key !== undefined );
  18166. }
  18167. }
  18168. };
  18169. /**
  18170. * Abstract base class of interpolants over parametric samples.
  18171. *
  18172. * The parameter domain is one dimensional, typically the time or a path
  18173. * along a curve defined by the data.
  18174. *
  18175. * The sample values can have any dimensionality and derived classes may
  18176. * apply special interpretations to the data.
  18177. *
  18178. * This class provides the interval seek in a Template Method, deferring
  18179. * the actual interpolation to derived classes.
  18180. *
  18181. * Time complexity is O(1) for linear access crossing at most two points
  18182. * and O(log N) for random access, where N is the number of positions.
  18183. *
  18184. * References:
  18185. *
  18186. * http://www.oodesign.com/template-method-pattern.html
  18187. *
  18188. * @author tschw
  18189. */
  18190. function Interpolant(
  18191. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18192. this.parameterPositions = parameterPositions;
  18193. this._cachedIndex = 0;
  18194. this.resultBuffer = resultBuffer !== undefined ?
  18195. resultBuffer : new sampleValues.constructor( sampleSize );
  18196. this.sampleValues = sampleValues;
  18197. this.valueSize = sampleSize;
  18198. }
  18199. Interpolant.prototype = {
  18200. constructor: Interpolant,
  18201. evaluate: function( t ) {
  18202. var pp = this.parameterPositions,
  18203. i1 = this._cachedIndex,
  18204. t1 = pp[ i1 ],
  18205. t0 = pp[ i1 - 1 ];
  18206. validate_interval: {
  18207. seek: {
  18208. var right;
  18209. linear_scan: {
  18210. //- See http://jsperf.com/comparison-to-undefined/3
  18211. //- slower code:
  18212. //-
  18213. //- if ( t >= t1 || t1 === undefined ) {
  18214. forward_scan: if ( ! ( t < t1 ) ) {
  18215. for ( var giveUpAt = i1 + 2; ;) {
  18216. if ( t1 === undefined ) {
  18217. if ( t < t0 ) break forward_scan;
  18218. // after end
  18219. i1 = pp.length;
  18220. this._cachedIndex = i1;
  18221. return this.afterEnd_( i1 - 1, t, t0 );
  18222. }
  18223. if ( i1 === giveUpAt ) break; // this loop
  18224. t0 = t1;
  18225. t1 = pp[ ++ i1 ];
  18226. if ( t < t1 ) {
  18227. // we have arrived at the sought interval
  18228. break seek;
  18229. }
  18230. }
  18231. // prepare binary search on the right side of the index
  18232. right = pp.length;
  18233. break linear_scan;
  18234. }
  18235. //- slower code:
  18236. //- if ( t < t0 || t0 === undefined ) {
  18237. if ( ! ( t >= t0 ) ) {
  18238. // looping?
  18239. var t1global = pp[ 1 ];
  18240. if ( t < t1global ) {
  18241. i1 = 2; // + 1, using the scan for the details
  18242. t0 = t1global;
  18243. }
  18244. // linear reverse scan
  18245. for ( var giveUpAt = i1 - 2; ;) {
  18246. if ( t0 === undefined ) {
  18247. // before start
  18248. this._cachedIndex = 0;
  18249. return this.beforeStart_( 0, t, t1 );
  18250. }
  18251. if ( i1 === giveUpAt ) break; // this loop
  18252. t1 = t0;
  18253. t0 = pp[ -- i1 - 1 ];
  18254. if ( t >= t0 ) {
  18255. // we have arrived at the sought interval
  18256. break seek;
  18257. }
  18258. }
  18259. // prepare binary search on the left side of the index
  18260. right = i1;
  18261. i1 = 0;
  18262. break linear_scan;
  18263. }
  18264. // the interval is valid
  18265. break validate_interval;
  18266. } // linear scan
  18267. // binary search
  18268. while ( i1 < right ) {
  18269. var mid = ( i1 + right ) >>> 1;
  18270. if ( t < pp[ mid ] ) {
  18271. right = mid;
  18272. } else {
  18273. i1 = mid + 1;
  18274. }
  18275. }
  18276. t1 = pp[ i1 ];
  18277. t0 = pp[ i1 - 1 ];
  18278. // check boundary cases, again
  18279. if ( t0 === undefined ) {
  18280. this._cachedIndex = 0;
  18281. return this.beforeStart_( 0, t, t1 );
  18282. }
  18283. if ( t1 === undefined ) {
  18284. i1 = pp.length;
  18285. this._cachedIndex = i1;
  18286. return this.afterEnd_( i1 - 1, t0, t );
  18287. }
  18288. } // seek
  18289. this._cachedIndex = i1;
  18290. this.intervalChanged_( i1, t0, t1 );
  18291. } // validate_interval
  18292. return this.interpolate_( i1, t0, t, t1 );
  18293. },
  18294. settings: null, // optional, subclass-specific settings structure
  18295. // Note: The indirection allows central control of many interpolants.
  18296. // --- Protected interface
  18297. DefaultSettings_: {},
  18298. getSettings_: function() {
  18299. return this.settings || this.DefaultSettings_;
  18300. },
  18301. copySampleValue_: function( index ) {
  18302. // copies a sample value to the result buffer
  18303. var result = this.resultBuffer,
  18304. values = this.sampleValues,
  18305. stride = this.valueSize,
  18306. offset = index * stride;
  18307. for ( var i = 0; i !== stride; ++ i ) {
  18308. result[ i ] = values[ offset + i ];
  18309. }
  18310. return result;
  18311. },
  18312. // Template methods for derived classes:
  18313. interpolate_: function( i1, t0, t, t1 ) {
  18314. throw new Error( "call to abstract method" );
  18315. // implementations shall return this.resultBuffer
  18316. },
  18317. intervalChanged_: function( i1, t0, t1 ) {
  18318. // empty
  18319. }
  18320. };
  18321. Object.assign( Interpolant.prototype, {
  18322. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  18323. Interpolant.prototype.copySampleValue_,
  18324. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  18325. Interpolant.prototype.copySampleValue_
  18326. } );
  18327. /**
  18328. * Fast and simple cubic spline interpolant.
  18329. *
  18330. * It was derived from a Hermitian construction setting the first derivative
  18331. * at each sample position to the linear slope between neighboring positions
  18332. * over their parameter interval.
  18333. *
  18334. * @author tschw
  18335. */
  18336. function CubicInterpolant(
  18337. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18338. Interpolant.call(
  18339. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18340. this._weightPrev = -0;
  18341. this._offsetPrev = -0;
  18342. this._weightNext = -0;
  18343. this._offsetNext = -0;
  18344. }
  18345. CubicInterpolant.prototype =
  18346. Object.assign( Object.create( Interpolant.prototype ), {
  18347. constructor: CubicInterpolant,
  18348. DefaultSettings_: {
  18349. endingStart: ZeroCurvatureEnding,
  18350. endingEnd: ZeroCurvatureEnding
  18351. },
  18352. intervalChanged_: function( i1, t0, t1 ) {
  18353. var pp = this.parameterPositions,
  18354. iPrev = i1 - 2,
  18355. iNext = i1 + 1,
  18356. tPrev = pp[ iPrev ],
  18357. tNext = pp[ iNext ];
  18358. if ( tPrev === undefined ) {
  18359. switch ( this.getSettings_().endingStart ) {
  18360. case ZeroSlopeEnding:
  18361. // f'(t0) = 0
  18362. iPrev = i1;
  18363. tPrev = 2 * t0 - t1;
  18364. break;
  18365. case WrapAroundEnding:
  18366. // use the other end of the curve
  18367. iPrev = pp.length - 2;
  18368. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  18369. break;
  18370. default: // ZeroCurvatureEnding
  18371. // f''(t0) = 0 a.k.a. Natural Spline
  18372. iPrev = i1;
  18373. tPrev = t1;
  18374. }
  18375. }
  18376. if ( tNext === undefined ) {
  18377. switch ( this.getSettings_().endingEnd ) {
  18378. case ZeroSlopeEnding:
  18379. // f'(tN) = 0
  18380. iNext = i1;
  18381. tNext = 2 * t1 - t0;
  18382. break;
  18383. case WrapAroundEnding:
  18384. // use the other end of the curve
  18385. iNext = 1;
  18386. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  18387. break;
  18388. default: // ZeroCurvatureEnding
  18389. // f''(tN) = 0, a.k.a. Natural Spline
  18390. iNext = i1 - 1;
  18391. tNext = t0;
  18392. }
  18393. }
  18394. var halfDt = ( t1 - t0 ) * 0.5,
  18395. stride = this.valueSize;
  18396. this._weightPrev = halfDt / ( t0 - tPrev );
  18397. this._weightNext = halfDt / ( tNext - t1 );
  18398. this._offsetPrev = iPrev * stride;
  18399. this._offsetNext = iNext * stride;
  18400. },
  18401. interpolate_: function( i1, t0, t, t1 ) {
  18402. var result = this.resultBuffer,
  18403. values = this.sampleValues,
  18404. stride = this.valueSize,
  18405. o1 = i1 * stride, o0 = o1 - stride,
  18406. oP = this._offsetPrev, oN = this._offsetNext,
  18407. wP = this._weightPrev, wN = this._weightNext,
  18408. p = ( t - t0 ) / ( t1 - t0 ),
  18409. pp = p * p,
  18410. ppp = pp * p;
  18411. // evaluate polynomials
  18412. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  18413. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  18414. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  18415. var sN = wN * ppp - wN * pp;
  18416. // combine data linearly
  18417. for ( var i = 0; i !== stride; ++ i ) {
  18418. result[ i ] =
  18419. sP * values[ oP + i ] +
  18420. s0 * values[ o0 + i ] +
  18421. s1 * values[ o1 + i ] +
  18422. sN * values[ oN + i ];
  18423. }
  18424. return result;
  18425. }
  18426. } );
  18427. /**
  18428. * @author tschw
  18429. */
  18430. function LinearInterpolant(
  18431. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18432. Interpolant.call(
  18433. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18434. }
  18435. LinearInterpolant.prototype =
  18436. Object.assign( Object.create( Interpolant.prototype ), {
  18437. constructor: LinearInterpolant,
  18438. interpolate_: function( i1, t0, t, t1 ) {
  18439. var result = this.resultBuffer,
  18440. values = this.sampleValues,
  18441. stride = this.valueSize,
  18442. offset1 = i1 * stride,
  18443. offset0 = offset1 - stride,
  18444. weight1 = ( t - t0 ) / ( t1 - t0 ),
  18445. weight0 = 1 - weight1;
  18446. for ( var i = 0; i !== stride; ++ i ) {
  18447. result[ i ] =
  18448. values[ offset0 + i ] * weight0 +
  18449. values[ offset1 + i ] * weight1;
  18450. }
  18451. return result;
  18452. }
  18453. } );
  18454. /**
  18455. *
  18456. * Interpolant that evaluates to the sample value at the position preceeding
  18457. * the parameter.
  18458. *
  18459. * @author tschw
  18460. */
  18461. function DiscreteInterpolant(
  18462. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18463. Interpolant.call(
  18464. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18465. }
  18466. DiscreteInterpolant.prototype =
  18467. Object.assign( Object.create( Interpolant.prototype ), {
  18468. constructor: DiscreteInterpolant,
  18469. interpolate_: function( i1, t0, t, t1 ) {
  18470. return this.copySampleValue_( i1 - 1 );
  18471. }
  18472. } );
  18473. var KeyframeTrackPrototype;
  18474. KeyframeTrackPrototype = {
  18475. TimeBufferType: Float32Array,
  18476. ValueBufferType: Float32Array,
  18477. DefaultInterpolation: InterpolateLinear,
  18478. InterpolantFactoryMethodDiscrete: function( result ) {
  18479. return new DiscreteInterpolant(
  18480. this.times, this.values, this.getValueSize(), result );
  18481. },
  18482. InterpolantFactoryMethodLinear: function( result ) {
  18483. return new LinearInterpolant(
  18484. this.times, this.values, this.getValueSize(), result );
  18485. },
  18486. InterpolantFactoryMethodSmooth: function( result ) {
  18487. return new CubicInterpolant(
  18488. this.times, this.values, this.getValueSize(), result );
  18489. },
  18490. setInterpolation: function( interpolation ) {
  18491. var factoryMethod;
  18492. switch ( interpolation ) {
  18493. case InterpolateDiscrete:
  18494. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  18495. break;
  18496. case InterpolateLinear:
  18497. factoryMethod = this.InterpolantFactoryMethodLinear;
  18498. break;
  18499. case InterpolateSmooth:
  18500. factoryMethod = this.InterpolantFactoryMethodSmooth;
  18501. break;
  18502. }
  18503. if ( factoryMethod === undefined ) {
  18504. var message = "unsupported interpolation for " +
  18505. this.ValueTypeName + " keyframe track named " + this.name;
  18506. if ( this.createInterpolant === undefined ) {
  18507. // fall back to default, unless the default itself is messed up
  18508. if ( interpolation !== this.DefaultInterpolation ) {
  18509. this.setInterpolation( this.DefaultInterpolation );
  18510. } else {
  18511. throw new Error( message ); // fatal, in this case
  18512. }
  18513. }
  18514. console.warn( message );
  18515. return;
  18516. }
  18517. this.createInterpolant = factoryMethod;
  18518. },
  18519. getInterpolation: function() {
  18520. switch ( this.createInterpolant ) {
  18521. case this.InterpolantFactoryMethodDiscrete:
  18522. return InterpolateDiscrete;
  18523. case this.InterpolantFactoryMethodLinear:
  18524. return InterpolateLinear;
  18525. case this.InterpolantFactoryMethodSmooth:
  18526. return InterpolateSmooth;
  18527. }
  18528. },
  18529. getValueSize: function() {
  18530. return this.values.length / this.times.length;
  18531. },
  18532. // move all keyframes either forwards or backwards in time
  18533. shift: function( timeOffset ) {
  18534. if( timeOffset !== 0.0 ) {
  18535. var times = this.times;
  18536. for( var i = 0, n = times.length; i !== n; ++ i ) {
  18537. times[ i ] += timeOffset;
  18538. }
  18539. }
  18540. return this;
  18541. },
  18542. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  18543. scale: function( timeScale ) {
  18544. if( timeScale !== 1.0 ) {
  18545. var times = this.times;
  18546. for( var i = 0, n = times.length; i !== n; ++ i ) {
  18547. times[ i ] *= timeScale;
  18548. }
  18549. }
  18550. return this;
  18551. },
  18552. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  18553. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  18554. trim: function( startTime, endTime ) {
  18555. var times = this.times,
  18556. nKeys = times.length,
  18557. from = 0,
  18558. to = nKeys - 1;
  18559. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  18560. while ( to !== -1 && times[ to ] > endTime ) -- to;
  18561. ++ to; // inclusive -> exclusive bound
  18562. if( from !== 0 || to !== nKeys ) {
  18563. // empty tracks are forbidden, so keep at least one keyframe
  18564. if ( from >= to ) to = Math.max( to , 1 ), from = to - 1;
  18565. var stride = this.getValueSize();
  18566. this.times = AnimationUtils.arraySlice( times, from, to );
  18567. this.values = AnimationUtils.
  18568. arraySlice( this.values, from * stride, to * stride );
  18569. }
  18570. return this;
  18571. },
  18572. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  18573. validate: function() {
  18574. var valid = true;
  18575. var valueSize = this.getValueSize();
  18576. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  18577. console.error( "invalid value size in track", this );
  18578. valid = false;
  18579. }
  18580. var times = this.times,
  18581. values = this.values,
  18582. nKeys = times.length;
  18583. if( nKeys === 0 ) {
  18584. console.error( "track is empty", this );
  18585. valid = false;
  18586. }
  18587. var prevTime = null;
  18588. for( var i = 0; i !== nKeys; i ++ ) {
  18589. var currTime = times[ i ];
  18590. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  18591. console.error( "time is not a valid number", this, i, currTime );
  18592. valid = false;
  18593. break;
  18594. }
  18595. if( prevTime !== null && prevTime > currTime ) {
  18596. console.error( "out of order keys", this, i, currTime, prevTime );
  18597. valid = false;
  18598. break;
  18599. }
  18600. prevTime = currTime;
  18601. }
  18602. if ( values !== undefined ) {
  18603. if ( AnimationUtils.isTypedArray( values ) ) {
  18604. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  18605. var value = values[ i ];
  18606. if ( isNaN( value ) ) {
  18607. console.error( "value is not a valid number", this, i, value );
  18608. valid = false;
  18609. break;
  18610. }
  18611. }
  18612. }
  18613. }
  18614. return valid;
  18615. },
  18616. // removes equivalent sequential keys as common in morph target sequences
  18617. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  18618. optimize: function() {
  18619. var times = this.times,
  18620. values = this.values,
  18621. stride = this.getValueSize(),
  18622. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  18623. writeIndex = 1,
  18624. lastIndex = times.length - 1;
  18625. for( var i = 1; i < lastIndex; ++ i ) {
  18626. var keep = false;
  18627. var time = times[ i ];
  18628. var timeNext = times[ i + 1 ];
  18629. // remove adjacent keyframes scheduled at the same time
  18630. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  18631. if ( ! smoothInterpolation ) {
  18632. // remove unnecessary keyframes same as their neighbors
  18633. var offset = i * stride,
  18634. offsetP = offset - stride,
  18635. offsetN = offset + stride;
  18636. for ( var j = 0; j !== stride; ++ j ) {
  18637. var value = values[ offset + j ];
  18638. if ( value !== values[ offsetP + j ] ||
  18639. value !== values[ offsetN + j ] ) {
  18640. keep = true;
  18641. break;
  18642. }
  18643. }
  18644. } else keep = true;
  18645. }
  18646. // in-place compaction
  18647. if ( keep ) {
  18648. if ( i !== writeIndex ) {
  18649. times[ writeIndex ] = times[ i ];
  18650. var readOffset = i * stride,
  18651. writeOffset = writeIndex * stride;
  18652. for ( var j = 0; j !== stride; ++ j )
  18653. values[ writeOffset + j ] = values[ readOffset + j ];
  18654. }
  18655. ++ writeIndex;
  18656. }
  18657. }
  18658. // flush last keyframe (compaction looks ahead)
  18659. if ( lastIndex > 0 ) {
  18660. times[ writeIndex ] = times[ lastIndex ];
  18661. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j )
  18662. values[ writeOffset + j ] = values[ readOffset + j ];
  18663. ++ writeIndex;
  18664. }
  18665. if ( writeIndex !== times.length ) {
  18666. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  18667. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  18668. }
  18669. return this;
  18670. }
  18671. };
  18672. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  18673. if( name === undefined ) throw new Error( "track name is undefined" );
  18674. if( times === undefined || times.length === 0 ) {
  18675. throw new Error( "no keyframes in track named " + name );
  18676. }
  18677. this.name = name;
  18678. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  18679. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  18680. this.setInterpolation( interpolation || this.DefaultInterpolation );
  18681. this.validate();
  18682. this.optimize();
  18683. }
  18684. /**
  18685. *
  18686. * A Track of vectored keyframe values.
  18687. *
  18688. *
  18689. * @author Ben Houston / http://clara.io/
  18690. * @author David Sarno / http://lighthaus.us/
  18691. * @author tschw
  18692. */
  18693. function VectorKeyframeTrack( name, times, values, interpolation ) {
  18694. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18695. }
  18696. VectorKeyframeTrack.prototype =
  18697. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18698. constructor: VectorKeyframeTrack,
  18699. ValueTypeName: 'vector'
  18700. // ValueBufferType is inherited
  18701. // DefaultInterpolation is inherited
  18702. } );
  18703. /**
  18704. * Spherical linear unit quaternion interpolant.
  18705. *
  18706. * @author tschw
  18707. */
  18708. function QuaternionLinearInterpolant(
  18709. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18710. Interpolant.call(
  18711. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18712. }
  18713. QuaternionLinearInterpolant.prototype =
  18714. Object.assign( Object.create( Interpolant.prototype ), {
  18715. constructor: QuaternionLinearInterpolant,
  18716. interpolate_: function( i1, t0, t, t1 ) {
  18717. var result = this.resultBuffer,
  18718. values = this.sampleValues,
  18719. stride = this.valueSize,
  18720. offset = i1 * stride,
  18721. alpha = ( t - t0 ) / ( t1 - t0 );
  18722. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  18723. Quaternion.slerpFlat( result, 0,
  18724. values, offset - stride, values, offset, alpha );
  18725. }
  18726. return result;
  18727. }
  18728. } );
  18729. /**
  18730. *
  18731. * A Track of quaternion keyframe values.
  18732. *
  18733. * @author Ben Houston / http://clara.io/
  18734. * @author David Sarno / http://lighthaus.us/
  18735. * @author tschw
  18736. */
  18737. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  18738. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18739. }
  18740. QuaternionKeyframeTrack.prototype =
  18741. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18742. constructor: QuaternionKeyframeTrack,
  18743. ValueTypeName: 'quaternion',
  18744. // ValueBufferType is inherited
  18745. DefaultInterpolation: InterpolateLinear,
  18746. InterpolantFactoryMethodLinear: function( result ) {
  18747. return new QuaternionLinearInterpolant(
  18748. this.times, this.values, this.getValueSize(), result );
  18749. },
  18750. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  18751. } );
  18752. /**
  18753. *
  18754. * A Track of numeric keyframe values.
  18755. *
  18756. * @author Ben Houston / http://clara.io/
  18757. * @author David Sarno / http://lighthaus.us/
  18758. * @author tschw
  18759. */
  18760. function NumberKeyframeTrack( name, times, values, interpolation ) {
  18761. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18762. }
  18763. NumberKeyframeTrack.prototype =
  18764. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18765. constructor: NumberKeyframeTrack,
  18766. ValueTypeName: 'number',
  18767. // ValueBufferType is inherited
  18768. // DefaultInterpolation is inherited
  18769. } );
  18770. /**
  18771. *
  18772. * A Track that interpolates Strings
  18773. *
  18774. *
  18775. * @author Ben Houston / http://clara.io/
  18776. * @author David Sarno / http://lighthaus.us/
  18777. * @author tschw
  18778. */
  18779. function StringKeyframeTrack( name, times, values, interpolation ) {
  18780. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18781. }
  18782. StringKeyframeTrack.prototype =
  18783. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18784. constructor: StringKeyframeTrack,
  18785. ValueTypeName: 'string',
  18786. ValueBufferType: Array,
  18787. DefaultInterpolation: InterpolateDiscrete,
  18788. InterpolantFactoryMethodLinear: undefined,
  18789. InterpolantFactoryMethodSmooth: undefined
  18790. } );
  18791. /**
  18792. *
  18793. * A Track of Boolean keyframe values.
  18794. *
  18795. *
  18796. * @author Ben Houston / http://clara.io/
  18797. * @author David Sarno / http://lighthaus.us/
  18798. * @author tschw
  18799. */
  18800. function BooleanKeyframeTrack( name, times, values ) {
  18801. KeyframeTrackConstructor.call( this, name, times, values );
  18802. }
  18803. BooleanKeyframeTrack.prototype =
  18804. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18805. constructor: BooleanKeyframeTrack,
  18806. ValueTypeName: 'bool',
  18807. ValueBufferType: Array,
  18808. DefaultInterpolation: InterpolateDiscrete,
  18809. InterpolantFactoryMethodLinear: undefined,
  18810. InterpolantFactoryMethodSmooth: undefined
  18811. // Note: Actually this track could have a optimized / compressed
  18812. // representation of a single value and a custom interpolant that
  18813. // computes "firstValue ^ isOdd( index )".
  18814. } );
  18815. /**
  18816. *
  18817. * A Track of keyframe values that represent color.
  18818. *
  18819. *
  18820. * @author Ben Houston / http://clara.io/
  18821. * @author David Sarno / http://lighthaus.us/
  18822. * @author tschw
  18823. */
  18824. function ColorKeyframeTrack( name, times, values, interpolation ) {
  18825. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18826. }
  18827. ColorKeyframeTrack.prototype =
  18828. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18829. constructor: ColorKeyframeTrack,
  18830. ValueTypeName: 'color'
  18831. // ValueBufferType is inherited
  18832. // DefaultInterpolation is inherited
  18833. // Note: Very basic implementation and nothing special yet.
  18834. // However, this is the place for color space parameterization.
  18835. } );
  18836. /**
  18837. *
  18838. * A timed sequence of keyframes for a specific property.
  18839. *
  18840. *
  18841. * @author Ben Houston / http://clara.io/
  18842. * @author David Sarno / http://lighthaus.us/
  18843. * @author tschw
  18844. */
  18845. function KeyframeTrack( name, times, values, interpolation ) {
  18846. KeyframeTrackConstructor.apply( this, arguments );
  18847. }
  18848. KeyframeTrack.prototype = KeyframeTrackPrototype;
  18849. KeyframeTrackPrototype.constructor = KeyframeTrack;
  18850. // Static methods:
  18851. Object.assign( KeyframeTrack, {
  18852. // Serialization (in static context, because of constructor invocation
  18853. // and automatic invocation of .toJSON):
  18854. parse: function( json ) {
  18855. if( json.type === undefined ) {
  18856. throw new Error( "track type undefined, can not parse" );
  18857. }
  18858. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  18859. if ( json.times === undefined ) {
  18860. var times = [], values = [];
  18861. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  18862. json.times = times;
  18863. json.values = values;
  18864. }
  18865. // derived classes can define a static parse method
  18866. if ( trackType.parse !== undefined ) {
  18867. return trackType.parse( json );
  18868. } else {
  18869. // by default, we asssume a constructor compatible with the base
  18870. return new trackType(
  18871. json.name, json.times, json.values, json.interpolation );
  18872. }
  18873. },
  18874. toJSON: function( track ) {
  18875. var trackType = track.constructor;
  18876. var json;
  18877. // derived classes can define a static toJSON method
  18878. if ( trackType.toJSON !== undefined ) {
  18879. json = trackType.toJSON( track );
  18880. } else {
  18881. // by default, we assume the data can be serialized as-is
  18882. json = {
  18883. 'name': track.name,
  18884. 'times': AnimationUtils.convertArray( track.times, Array ),
  18885. 'values': AnimationUtils.convertArray( track.values, Array )
  18886. };
  18887. var interpolation = track.getInterpolation();
  18888. if ( interpolation !== track.DefaultInterpolation ) {
  18889. json.interpolation = interpolation;
  18890. }
  18891. }
  18892. json.type = track.ValueTypeName; // mandatory
  18893. return json;
  18894. },
  18895. _getTrackTypeForValueTypeName: function( typeName ) {
  18896. switch( typeName.toLowerCase() ) {
  18897. case "scalar":
  18898. case "double":
  18899. case "float":
  18900. case "number":
  18901. case "integer":
  18902. return NumberKeyframeTrack;
  18903. case "vector":
  18904. case "vector2":
  18905. case "vector3":
  18906. case "vector4":
  18907. return VectorKeyframeTrack;
  18908. case "color":
  18909. return ColorKeyframeTrack;
  18910. case "quaternion":
  18911. return QuaternionKeyframeTrack;
  18912. case "bool":
  18913. case "boolean":
  18914. return BooleanKeyframeTrack;
  18915. case "string":
  18916. return StringKeyframeTrack;
  18917. }
  18918. throw new Error( "Unsupported typeName: " + typeName );
  18919. }
  18920. } );
  18921. /**
  18922. *
  18923. * Reusable set of Tracks that represent an animation.
  18924. *
  18925. * @author Ben Houston / http://clara.io/
  18926. * @author David Sarno / http://lighthaus.us/
  18927. */
  18928. function AnimationClip( name, duration, tracks ) {
  18929. this.name = name;
  18930. this.tracks = tracks;
  18931. this.duration = ( duration !== undefined ) ? duration : -1;
  18932. this.uuid = _Math.generateUUID();
  18933. // this means it should figure out its duration by scanning the tracks
  18934. if ( this.duration < 0 ) {
  18935. this.resetDuration();
  18936. }
  18937. this.optimize();
  18938. }
  18939. AnimationClip.prototype = {
  18940. constructor: AnimationClip,
  18941. resetDuration: function() {
  18942. var tracks = this.tracks,
  18943. duration = 0;
  18944. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  18945. var track = this.tracks[ i ];
  18946. duration = Math.max(
  18947. duration, track.times[ track.times.length - 1 ] );
  18948. }
  18949. this.duration = duration;
  18950. },
  18951. trim: function() {
  18952. for ( var i = 0; i < this.tracks.length; i ++ ) {
  18953. this.tracks[ i ].trim( 0, this.duration );
  18954. }
  18955. return this;
  18956. },
  18957. optimize: function() {
  18958. for ( var i = 0; i < this.tracks.length; i ++ ) {
  18959. this.tracks[ i ].optimize();
  18960. }
  18961. return this;
  18962. }
  18963. };
  18964. // Static methods:
  18965. Object.assign( AnimationClip, {
  18966. parse: function( json ) {
  18967. var tracks = [],
  18968. jsonTracks = json.tracks,
  18969. frameTime = 1.0 / ( json.fps || 1.0 );
  18970. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  18971. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  18972. }
  18973. return new AnimationClip( json.name, json.duration, tracks );
  18974. },
  18975. toJSON: function( clip ) {
  18976. var tracks = [],
  18977. clipTracks = clip.tracks;
  18978. var json = {
  18979. 'name': clip.name,
  18980. 'duration': clip.duration,
  18981. 'tracks': tracks
  18982. };
  18983. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  18984. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  18985. }
  18986. return json;
  18987. },
  18988. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) {
  18989. var numMorphTargets = morphTargetSequence.length;
  18990. var tracks = [];
  18991. for ( var i = 0; i < numMorphTargets; i ++ ) {
  18992. var times = [];
  18993. var values = [];
  18994. times.push(
  18995. ( i + numMorphTargets - 1 ) % numMorphTargets,
  18996. i,
  18997. ( i + 1 ) % numMorphTargets );
  18998. values.push( 0, 1, 0 );
  18999. var order = AnimationUtils.getKeyframeOrder( times );
  19000. times = AnimationUtils.sortedArray( times, 1, order );
  19001. values = AnimationUtils.sortedArray( values, 1, order );
  19002. // if there is a key at the first frame, duplicate it as the
  19003. // last frame as well for perfect loop.
  19004. if ( ! noLoop && times[ 0 ] === 0 ) {
  19005. times.push( numMorphTargets );
  19006. values.push( values[ 0 ] );
  19007. }
  19008. tracks.push(
  19009. new NumberKeyframeTrack(
  19010. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  19011. times, values
  19012. ).scale( 1.0 / fps ) );
  19013. }
  19014. return new AnimationClip( name, -1, tracks );
  19015. },
  19016. findByName: function( objectOrClipArray, name ) {
  19017. var clipArray = objectOrClipArray;
  19018. if ( ! Array.isArray( objectOrClipArray ) ) {
  19019. var o = objectOrClipArray;
  19020. clipArray = o.geometry && o.geometry.animations || o.animations;
  19021. }
  19022. for ( var i = 0; i < clipArray.length; i ++ ) {
  19023. if ( clipArray[ i ].name === name ) {
  19024. return clipArray[ i ];
  19025. }
  19026. }
  19027. return null;
  19028. },
  19029. CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) {
  19030. var animationToMorphTargets = {};
  19031. // tested with https://regex101.com/ on trick sequences
  19032. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  19033. var pattern = /^([\w-]*?)([\d]+)$/;
  19034. // sort morph target names into animation groups based
  19035. // patterns like Walk_001, Walk_002, Run_001, Run_002
  19036. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  19037. var morphTarget = morphTargets[ i ];
  19038. var parts = morphTarget.name.match( pattern );
  19039. if ( parts && parts.length > 1 ) {
  19040. var name = parts[ 1 ];
  19041. var animationMorphTargets = animationToMorphTargets[ name ];
  19042. if ( ! animationMorphTargets ) {
  19043. animationToMorphTargets[ name ] = animationMorphTargets = [];
  19044. }
  19045. animationMorphTargets.push( morphTarget );
  19046. }
  19047. }
  19048. var clips = [];
  19049. for ( var name in animationToMorphTargets ) {
  19050. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  19051. }
  19052. return clips;
  19053. },
  19054. // parse the animation.hierarchy format
  19055. parseAnimation: function( animation, bones ) {
  19056. if ( ! animation ) {
  19057. console.error( " no animation in JSONLoader data" );
  19058. return null;
  19059. }
  19060. var addNonemptyTrack = function(
  19061. trackType, trackName, animationKeys, propertyName, destTracks ) {
  19062. // only return track if there are actually keys.
  19063. if ( animationKeys.length !== 0 ) {
  19064. var times = [];
  19065. var values = [];
  19066. AnimationUtils.flattenJSON(
  19067. animationKeys, times, values, propertyName );
  19068. // empty keys are filtered out, so check again
  19069. if ( times.length !== 0 ) {
  19070. destTracks.push( new trackType( trackName, times, values ) );
  19071. }
  19072. }
  19073. };
  19074. var tracks = [];
  19075. var clipName = animation.name || 'default';
  19076. // automatic length determination in AnimationClip.
  19077. var duration = animation.length || -1;
  19078. var fps = animation.fps || 30;
  19079. var hierarchyTracks = animation.hierarchy || [];
  19080. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  19081. var animationKeys = hierarchyTracks[ h ].keys;
  19082. // skip empty tracks
  19083. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  19084. // process morph targets in a way exactly compatible
  19085. // with AnimationHandler.init( animation )
  19086. if ( animationKeys[0].morphTargets ) {
  19087. // figure out all morph targets used in this track
  19088. var morphTargetNames = {};
  19089. for ( var k = 0; k < animationKeys.length; k ++ ) {
  19090. if ( animationKeys[k].morphTargets ) {
  19091. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  19092. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  19093. }
  19094. }
  19095. }
  19096. // create a track for each morph target with all zero
  19097. // morphTargetInfluences except for the keys in which
  19098. // the morphTarget is named.
  19099. for ( var morphTargetName in morphTargetNames ) {
  19100. var times = [];
  19101. var values = [];
  19102. for ( var m = 0;
  19103. m !== animationKeys[k].morphTargets.length; ++ m ) {
  19104. var animationKey = animationKeys[k];
  19105. times.push( animationKey.time );
  19106. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  19107. }
  19108. tracks.push( new NumberKeyframeTrack(
  19109. '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  19110. }
  19111. duration = morphTargetNames.length * ( fps || 1.0 );
  19112. } else {
  19113. // ...assume skeletal animation
  19114. var boneName = '.bones[' + bones[ h ].name + ']';
  19115. addNonemptyTrack(
  19116. VectorKeyframeTrack, boneName + '.position',
  19117. animationKeys, 'pos', tracks );
  19118. addNonemptyTrack(
  19119. QuaternionKeyframeTrack, boneName + '.quaternion',
  19120. animationKeys, 'rot', tracks );
  19121. addNonemptyTrack(
  19122. VectorKeyframeTrack, boneName + '.scale',
  19123. animationKeys, 'scl', tracks );
  19124. }
  19125. }
  19126. if ( tracks.length === 0 ) {
  19127. return null;
  19128. }
  19129. var clip = new AnimationClip( clipName, duration, tracks );
  19130. return clip;
  19131. }
  19132. } );
  19133. /**
  19134. * @author mrdoob / http://mrdoob.com/
  19135. */
  19136. function MaterialLoader( manager ) {
  19137. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19138. this.textures = {};
  19139. }
  19140. Object.assign( MaterialLoader.prototype, {
  19141. load: function ( url, onLoad, onProgress, onError ) {
  19142. var scope = this;
  19143. var loader = new FileLoader( scope.manager );
  19144. loader.load( url, function ( text ) {
  19145. onLoad( scope.parse( JSON.parse( text ) ) );
  19146. }, onProgress, onError );
  19147. },
  19148. setTextures: function ( value ) {
  19149. this.textures = value;
  19150. },
  19151. parse: function ( json ) {
  19152. var textures = this.textures;
  19153. function getTexture( name ) {
  19154. if ( textures[ name ] === undefined ) {
  19155. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  19156. }
  19157. return textures[ name ];
  19158. }
  19159. var material = new Materials[ json.type ]();
  19160. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  19161. if ( json.name !== undefined ) material.name = json.name;
  19162. if ( json.color !== undefined ) material.color.setHex( json.color );
  19163. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  19164. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  19165. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  19166. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  19167. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  19168. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  19169. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  19170. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  19171. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  19172. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  19173. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  19174. if ( json.fog !== undefined ) material.fog = json.fog;
  19175. if ( json.shading !== undefined ) material.shading = json.shading;
  19176. if ( json.blending !== undefined ) material.blending = json.blending;
  19177. if ( json.side !== undefined ) material.side = json.side;
  19178. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  19179. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  19180. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  19181. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  19182. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  19183. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  19184. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  19185. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  19186. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  19187. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  19188. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  19189. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  19190. // for PointsMaterial
  19191. if ( json.size !== undefined ) material.size = json.size;
  19192. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  19193. // maps
  19194. if ( json.map !== undefined ) material.map = getTexture( json.map );
  19195. if ( json.alphaMap !== undefined ) {
  19196. material.alphaMap = getTexture( json.alphaMap );
  19197. material.transparent = true;
  19198. }
  19199. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  19200. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  19201. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  19202. if ( json.normalScale !== undefined ) {
  19203. var normalScale = json.normalScale;
  19204. if ( Array.isArray( normalScale ) === false ) {
  19205. // Blender exporter used to export a scalar. See #7459
  19206. normalScale = [ normalScale, normalScale ];
  19207. }
  19208. material.normalScale = new Vector2().fromArray( normalScale );
  19209. }
  19210. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  19211. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  19212. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  19213. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  19214. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  19215. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  19216. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  19217. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  19218. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  19219. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  19220. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  19221. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  19222. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  19223. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  19224. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  19225. // MultiMaterial
  19226. if ( json.materials !== undefined ) {
  19227. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  19228. material.materials.push( this.parse( json.materials[ i ] ) );
  19229. }
  19230. }
  19231. return material;
  19232. }
  19233. } );
  19234. /**
  19235. * @author mrdoob / http://mrdoob.com/
  19236. */
  19237. function BufferGeometryLoader( manager ) {
  19238. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19239. }
  19240. Object.assign( BufferGeometryLoader.prototype, {
  19241. load: function ( url, onLoad, onProgress, onError ) {
  19242. var scope = this;
  19243. var loader = new FileLoader( scope.manager );
  19244. loader.load( url, function ( text ) {
  19245. onLoad( scope.parse( JSON.parse( text ) ) );
  19246. }, onProgress, onError );
  19247. },
  19248. parse: function ( json ) {
  19249. var geometry = new BufferGeometry();
  19250. var index = json.data.index;
  19251. var TYPED_ARRAYS = {
  19252. 'Int8Array': Int8Array,
  19253. 'Uint8Array': Uint8Array,
  19254. 'Uint8ClampedArray': Uint8ClampedArray,
  19255. 'Int16Array': Int16Array,
  19256. 'Uint16Array': Uint16Array,
  19257. 'Int32Array': Int32Array,
  19258. 'Uint32Array': Uint32Array,
  19259. 'Float32Array': Float32Array,
  19260. 'Float64Array': Float64Array
  19261. };
  19262. if ( index !== undefined ) {
  19263. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  19264. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  19265. }
  19266. var attributes = json.data.attributes;
  19267. for ( var key in attributes ) {
  19268. var attribute = attributes[ key ];
  19269. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  19270. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  19271. }
  19272. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  19273. if ( groups !== undefined ) {
  19274. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  19275. var group = groups[ i ];
  19276. geometry.addGroup( group.start, group.count, group.materialIndex );
  19277. }
  19278. }
  19279. var boundingSphere = json.data.boundingSphere;
  19280. if ( boundingSphere !== undefined ) {
  19281. var center = new Vector3();
  19282. if ( boundingSphere.center !== undefined ) {
  19283. center.fromArray( boundingSphere.center );
  19284. }
  19285. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  19286. }
  19287. return geometry;
  19288. }
  19289. } );
  19290. /**
  19291. * @author alteredq / http://alteredqualia.com/
  19292. */
  19293. function Loader() {
  19294. this.onLoadStart = function () {};
  19295. this.onLoadProgress = function () {};
  19296. this.onLoadComplete = function () {};
  19297. }
  19298. Loader.prototype = {
  19299. constructor: Loader,
  19300. crossOrigin: undefined,
  19301. extractUrlBase: function ( url ) {
  19302. var parts = url.split( '/' );
  19303. if ( parts.length === 1 ) return './';
  19304. parts.pop();
  19305. return parts.join( '/' ) + '/';
  19306. },
  19307. initMaterials: function ( materials, texturePath, crossOrigin ) {
  19308. var array = [];
  19309. for ( var i = 0; i < materials.length; ++ i ) {
  19310. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  19311. }
  19312. return array;
  19313. },
  19314. createMaterial: ( function () {
  19315. var color, textureLoader, materialLoader;
  19316. return function createMaterial( m, texturePath, crossOrigin ) {
  19317. if ( color === undefined ) color = new Color();
  19318. if ( textureLoader === undefined ) textureLoader = new TextureLoader();
  19319. if ( materialLoader === undefined ) materialLoader = new MaterialLoader();
  19320. // convert from old material format
  19321. var textures = {};
  19322. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  19323. var fullPath = texturePath + path;
  19324. var loader = Loader.Handlers.get( fullPath );
  19325. var texture;
  19326. if ( loader !== null ) {
  19327. texture = loader.load( fullPath );
  19328. } else {
  19329. textureLoader.setCrossOrigin( crossOrigin );
  19330. texture = textureLoader.load( fullPath );
  19331. }
  19332. if ( repeat !== undefined ) {
  19333. texture.repeat.fromArray( repeat );
  19334. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  19335. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  19336. }
  19337. if ( offset !== undefined ) {
  19338. texture.offset.fromArray( offset );
  19339. }
  19340. if ( wrap !== undefined ) {
  19341. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  19342. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  19343. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  19344. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  19345. }
  19346. if ( anisotropy !== undefined ) {
  19347. texture.anisotropy = anisotropy;
  19348. }
  19349. var uuid = _Math.generateUUID();
  19350. textures[ uuid ] = texture;
  19351. return uuid;
  19352. }
  19353. //
  19354. var json = {
  19355. uuid: _Math.generateUUID(),
  19356. type: 'MeshLambertMaterial'
  19357. };
  19358. for ( var name in m ) {
  19359. var value = m[ name ];
  19360. switch ( name ) {
  19361. case 'DbgColor':
  19362. case 'DbgIndex':
  19363. case 'opticalDensity':
  19364. case 'illumination':
  19365. break;
  19366. case 'DbgName':
  19367. json.name = value;
  19368. break;
  19369. case 'blending':
  19370. json.blending = BlendingMode[ value ];
  19371. break;
  19372. case 'colorAmbient':
  19373. case 'mapAmbient':
  19374. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  19375. break;
  19376. case 'colorDiffuse':
  19377. json.color = color.fromArray( value ).getHex();
  19378. break;
  19379. case 'colorSpecular':
  19380. json.specular = color.fromArray( value ).getHex();
  19381. break;
  19382. case 'colorEmissive':
  19383. json.emissive = color.fromArray( value ).getHex();
  19384. break;
  19385. case 'specularCoef':
  19386. json.shininess = value;
  19387. break;
  19388. case 'shading':
  19389. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  19390. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  19391. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  19392. break;
  19393. case 'mapDiffuse':
  19394. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  19395. break;
  19396. case 'mapDiffuseRepeat':
  19397. case 'mapDiffuseOffset':
  19398. case 'mapDiffuseWrap':
  19399. case 'mapDiffuseAnisotropy':
  19400. break;
  19401. case 'mapEmissive':
  19402. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  19403. break;
  19404. case 'mapEmissiveRepeat':
  19405. case 'mapEmissiveOffset':
  19406. case 'mapEmissiveWrap':
  19407. case 'mapEmissiveAnisotropy':
  19408. break;
  19409. case 'mapLight':
  19410. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  19411. break;
  19412. case 'mapLightRepeat':
  19413. case 'mapLightOffset':
  19414. case 'mapLightWrap':
  19415. case 'mapLightAnisotropy':
  19416. break;
  19417. case 'mapAO':
  19418. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  19419. break;
  19420. case 'mapAORepeat':
  19421. case 'mapAOOffset':
  19422. case 'mapAOWrap':
  19423. case 'mapAOAnisotropy':
  19424. break;
  19425. case 'mapBump':
  19426. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  19427. break;
  19428. case 'mapBumpScale':
  19429. json.bumpScale = value;
  19430. break;
  19431. case 'mapBumpRepeat':
  19432. case 'mapBumpOffset':
  19433. case 'mapBumpWrap':
  19434. case 'mapBumpAnisotropy':
  19435. break;
  19436. case 'mapNormal':
  19437. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  19438. break;
  19439. case 'mapNormalFactor':
  19440. json.normalScale = [ value, value ];
  19441. break;
  19442. case 'mapNormalRepeat':
  19443. case 'mapNormalOffset':
  19444. case 'mapNormalWrap':
  19445. case 'mapNormalAnisotropy':
  19446. break;
  19447. case 'mapSpecular':
  19448. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  19449. break;
  19450. case 'mapSpecularRepeat':
  19451. case 'mapSpecularOffset':
  19452. case 'mapSpecularWrap':
  19453. case 'mapSpecularAnisotropy':
  19454. break;
  19455. case 'mapMetalness':
  19456. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  19457. break;
  19458. case 'mapMetalnessRepeat':
  19459. case 'mapMetalnessOffset':
  19460. case 'mapMetalnessWrap':
  19461. case 'mapMetalnessAnisotropy':
  19462. break;
  19463. case 'mapRoughness':
  19464. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  19465. break;
  19466. case 'mapRoughnessRepeat':
  19467. case 'mapRoughnessOffset':
  19468. case 'mapRoughnessWrap':
  19469. case 'mapRoughnessAnisotropy':
  19470. break;
  19471. case 'mapAlpha':
  19472. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  19473. break;
  19474. case 'mapAlphaRepeat':
  19475. case 'mapAlphaOffset':
  19476. case 'mapAlphaWrap':
  19477. case 'mapAlphaAnisotropy':
  19478. break;
  19479. case 'flipSided':
  19480. json.side = BackSide;
  19481. break;
  19482. case 'doubleSided':
  19483. json.side = DoubleSide;
  19484. break;
  19485. case 'transparency':
  19486. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  19487. json.opacity = value;
  19488. break;
  19489. case 'depthTest':
  19490. case 'depthWrite':
  19491. case 'colorWrite':
  19492. case 'opacity':
  19493. case 'reflectivity':
  19494. case 'transparent':
  19495. case 'visible':
  19496. case 'wireframe':
  19497. json[ name ] = value;
  19498. break;
  19499. case 'vertexColors':
  19500. if ( value === true ) json.vertexColors = VertexColors;
  19501. if ( value === 'face' ) json.vertexColors = FaceColors;
  19502. break;
  19503. default:
  19504. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  19505. break;
  19506. }
  19507. }
  19508. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  19509. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  19510. if ( json.opacity < 1 ) json.transparent = true;
  19511. materialLoader.setTextures( textures );
  19512. return materialLoader.parse( json );
  19513. };
  19514. } )()
  19515. };
  19516. Loader.Handlers = {
  19517. handlers: [],
  19518. add: function ( regex, loader ) {
  19519. this.handlers.push( regex, loader );
  19520. },
  19521. get: function ( file ) {
  19522. var handlers = this.handlers;
  19523. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  19524. var regex = handlers[ i ];
  19525. var loader = handlers[ i + 1 ];
  19526. if ( regex.test( file ) ) {
  19527. return loader;
  19528. }
  19529. }
  19530. return null;
  19531. }
  19532. };
  19533. /**
  19534. * @author mrdoob / http://mrdoob.com/
  19535. * @author alteredq / http://alteredqualia.com/
  19536. */
  19537. function JSONLoader( manager ) {
  19538. if ( typeof manager === 'boolean' ) {
  19539. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  19540. manager = undefined;
  19541. }
  19542. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19543. this.withCredentials = false;
  19544. }
  19545. Object.assign( JSONLoader.prototype, {
  19546. load: function( url, onLoad, onProgress, onError ) {
  19547. var scope = this;
  19548. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  19549. var loader = new FileLoader( this.manager );
  19550. loader.setWithCredentials( this.withCredentials );
  19551. loader.load( url, function ( text ) {
  19552. var json = JSON.parse( text );
  19553. var metadata = json.metadata;
  19554. if ( metadata !== undefined ) {
  19555. var type = metadata.type;
  19556. if ( type !== undefined ) {
  19557. if ( type.toLowerCase() === 'object' ) {
  19558. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  19559. return;
  19560. }
  19561. if ( type.toLowerCase() === 'scene' ) {
  19562. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  19563. return;
  19564. }
  19565. }
  19566. }
  19567. var object = scope.parse( json, texturePath );
  19568. onLoad( object.geometry, object.materials );
  19569. }, onProgress, onError );
  19570. },
  19571. setTexturePath: function ( value ) {
  19572. this.texturePath = value;
  19573. },
  19574. parse: function ( json, texturePath ) {
  19575. var geometry = new Geometry(),
  19576. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  19577. parseModel( scale );
  19578. parseSkin();
  19579. parseMorphing( scale );
  19580. parseAnimations();
  19581. geometry.computeFaceNormals();
  19582. geometry.computeBoundingSphere();
  19583. function parseModel( scale ) {
  19584. function isBitSet( value, position ) {
  19585. return value & ( 1 << position );
  19586. }
  19587. var i, j, fi,
  19588. offset, zLength,
  19589. colorIndex, normalIndex, uvIndex, materialIndex,
  19590. type,
  19591. isQuad,
  19592. hasMaterial,
  19593. hasFaceVertexUv,
  19594. hasFaceNormal, hasFaceVertexNormal,
  19595. hasFaceColor, hasFaceVertexColor,
  19596. vertex, face, faceA, faceB, hex, normal,
  19597. uvLayer, uv, u, v,
  19598. faces = json.faces,
  19599. vertices = json.vertices,
  19600. normals = json.normals,
  19601. colors = json.colors,
  19602. nUvLayers = 0;
  19603. if ( json.uvs !== undefined ) {
  19604. // disregard empty arrays
  19605. for ( i = 0; i < json.uvs.length; i ++ ) {
  19606. if ( json.uvs[ i ].length ) nUvLayers ++;
  19607. }
  19608. for ( i = 0; i < nUvLayers; i ++ ) {
  19609. geometry.faceVertexUvs[ i ] = [];
  19610. }
  19611. }
  19612. offset = 0;
  19613. zLength = vertices.length;
  19614. while ( offset < zLength ) {
  19615. vertex = new Vector3();
  19616. vertex.x = vertices[ offset ++ ] * scale;
  19617. vertex.y = vertices[ offset ++ ] * scale;
  19618. vertex.z = vertices[ offset ++ ] * scale;
  19619. geometry.vertices.push( vertex );
  19620. }
  19621. offset = 0;
  19622. zLength = faces.length;
  19623. while ( offset < zLength ) {
  19624. type = faces[ offset ++ ];
  19625. isQuad = isBitSet( type, 0 );
  19626. hasMaterial = isBitSet( type, 1 );
  19627. hasFaceVertexUv = isBitSet( type, 3 );
  19628. hasFaceNormal = isBitSet( type, 4 );
  19629. hasFaceVertexNormal = isBitSet( type, 5 );
  19630. hasFaceColor = isBitSet( type, 6 );
  19631. hasFaceVertexColor = isBitSet( type, 7 );
  19632. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  19633. if ( isQuad ) {
  19634. faceA = new Face3();
  19635. faceA.a = faces[ offset ];
  19636. faceA.b = faces[ offset + 1 ];
  19637. faceA.c = faces[ offset + 3 ];
  19638. faceB = new Face3();
  19639. faceB.a = faces[ offset + 1 ];
  19640. faceB.b = faces[ offset + 2 ];
  19641. faceB.c = faces[ offset + 3 ];
  19642. offset += 4;
  19643. if ( hasMaterial ) {
  19644. materialIndex = faces[ offset ++ ];
  19645. faceA.materialIndex = materialIndex;
  19646. faceB.materialIndex = materialIndex;
  19647. }
  19648. // to get face <=> uv index correspondence
  19649. fi = geometry.faces.length;
  19650. if ( hasFaceVertexUv ) {
  19651. for ( i = 0; i < nUvLayers; i ++ ) {
  19652. uvLayer = json.uvs[ i ];
  19653. geometry.faceVertexUvs[ i ][ fi ] = [];
  19654. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  19655. for ( j = 0; j < 4; j ++ ) {
  19656. uvIndex = faces[ offset ++ ];
  19657. u = uvLayer[ uvIndex * 2 ];
  19658. v = uvLayer[ uvIndex * 2 + 1 ];
  19659. uv = new Vector2( u, v );
  19660. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  19661. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  19662. }
  19663. }
  19664. }
  19665. if ( hasFaceNormal ) {
  19666. normalIndex = faces[ offset ++ ] * 3;
  19667. faceA.normal.set(
  19668. normals[ normalIndex ++ ],
  19669. normals[ normalIndex ++ ],
  19670. normals[ normalIndex ]
  19671. );
  19672. faceB.normal.copy( faceA.normal );
  19673. }
  19674. if ( hasFaceVertexNormal ) {
  19675. for ( i = 0; i < 4; i ++ ) {
  19676. normalIndex = faces[ offset ++ ] * 3;
  19677. normal = new Vector3(
  19678. normals[ normalIndex ++ ],
  19679. normals[ normalIndex ++ ],
  19680. normals[ normalIndex ]
  19681. );
  19682. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  19683. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  19684. }
  19685. }
  19686. if ( hasFaceColor ) {
  19687. colorIndex = faces[ offset ++ ];
  19688. hex = colors[ colorIndex ];
  19689. faceA.color.setHex( hex );
  19690. faceB.color.setHex( hex );
  19691. }
  19692. if ( hasFaceVertexColor ) {
  19693. for ( i = 0; i < 4; i ++ ) {
  19694. colorIndex = faces[ offset ++ ];
  19695. hex = colors[ colorIndex ];
  19696. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  19697. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  19698. }
  19699. }
  19700. geometry.faces.push( faceA );
  19701. geometry.faces.push( faceB );
  19702. } else {
  19703. face = new Face3();
  19704. face.a = faces[ offset ++ ];
  19705. face.b = faces[ offset ++ ];
  19706. face.c = faces[ offset ++ ];
  19707. if ( hasMaterial ) {
  19708. materialIndex = faces[ offset ++ ];
  19709. face.materialIndex = materialIndex;
  19710. }
  19711. // to get face <=> uv index correspondence
  19712. fi = geometry.faces.length;
  19713. if ( hasFaceVertexUv ) {
  19714. for ( i = 0; i < nUvLayers; i ++ ) {
  19715. uvLayer = json.uvs[ i ];
  19716. geometry.faceVertexUvs[ i ][ fi ] = [];
  19717. for ( j = 0; j < 3; j ++ ) {
  19718. uvIndex = faces[ offset ++ ];
  19719. u = uvLayer[ uvIndex * 2 ];
  19720. v = uvLayer[ uvIndex * 2 + 1 ];
  19721. uv = new Vector2( u, v );
  19722. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  19723. }
  19724. }
  19725. }
  19726. if ( hasFaceNormal ) {
  19727. normalIndex = faces[ offset ++ ] * 3;
  19728. face.normal.set(
  19729. normals[ normalIndex ++ ],
  19730. normals[ normalIndex ++ ],
  19731. normals[ normalIndex ]
  19732. );
  19733. }
  19734. if ( hasFaceVertexNormal ) {
  19735. for ( i = 0; i < 3; i ++ ) {
  19736. normalIndex = faces[ offset ++ ] * 3;
  19737. normal = new Vector3(
  19738. normals[ normalIndex ++ ],
  19739. normals[ normalIndex ++ ],
  19740. normals[ normalIndex ]
  19741. );
  19742. face.vertexNormals.push( normal );
  19743. }
  19744. }
  19745. if ( hasFaceColor ) {
  19746. colorIndex = faces[ offset ++ ];
  19747. face.color.setHex( colors[ colorIndex ] );
  19748. }
  19749. if ( hasFaceVertexColor ) {
  19750. for ( i = 0; i < 3; i ++ ) {
  19751. colorIndex = faces[ offset ++ ];
  19752. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  19753. }
  19754. }
  19755. geometry.faces.push( face );
  19756. }
  19757. }
  19758. }
  19759. function parseSkin() {
  19760. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  19761. if ( json.skinWeights ) {
  19762. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  19763. var x = json.skinWeights[ i ];
  19764. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  19765. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  19766. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  19767. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  19768. }
  19769. }
  19770. if ( json.skinIndices ) {
  19771. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  19772. var a = json.skinIndices[ i ];
  19773. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  19774. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  19775. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  19776. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  19777. }
  19778. }
  19779. geometry.bones = json.bones;
  19780. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  19781. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  19782. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  19783. }
  19784. }
  19785. function parseMorphing( scale ) {
  19786. if ( json.morphTargets !== undefined ) {
  19787. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  19788. geometry.morphTargets[ i ] = {};
  19789. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  19790. geometry.morphTargets[ i ].vertices = [];
  19791. var dstVertices = geometry.morphTargets[ i ].vertices;
  19792. var srcVertices = json.morphTargets[ i ].vertices;
  19793. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  19794. var vertex = new Vector3();
  19795. vertex.x = srcVertices[ v ] * scale;
  19796. vertex.y = srcVertices[ v + 1 ] * scale;
  19797. vertex.z = srcVertices[ v + 2 ] * scale;
  19798. dstVertices.push( vertex );
  19799. }
  19800. }
  19801. }
  19802. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  19803. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  19804. var faces = geometry.faces;
  19805. var morphColors = json.morphColors[ 0 ].colors;
  19806. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19807. faces[ i ].color.fromArray( morphColors, i * 3 );
  19808. }
  19809. }
  19810. }
  19811. function parseAnimations() {
  19812. var outputAnimations = [];
  19813. // parse old style Bone/Hierarchy animations
  19814. var animations = [];
  19815. if ( json.animation !== undefined ) {
  19816. animations.push( json.animation );
  19817. }
  19818. if ( json.animations !== undefined ) {
  19819. if ( json.animations.length ) {
  19820. animations = animations.concat( json.animations );
  19821. } else {
  19822. animations.push( json.animations );
  19823. }
  19824. }
  19825. for ( var i = 0; i < animations.length; i ++ ) {
  19826. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  19827. if ( clip ) outputAnimations.push( clip );
  19828. }
  19829. // parse implicit morph animations
  19830. if ( geometry.morphTargets ) {
  19831. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  19832. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  19833. outputAnimations = outputAnimations.concat( morphAnimationClips );
  19834. }
  19835. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  19836. }
  19837. if ( json.materials === undefined || json.materials.length === 0 ) {
  19838. return { geometry: geometry };
  19839. } else {
  19840. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  19841. return { geometry: geometry, materials: materials };
  19842. }
  19843. }
  19844. } );
  19845. /**
  19846. * @author mrdoob / http://mrdoob.com/
  19847. */
  19848. function ObjectLoader( manager ) {
  19849. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19850. this.texturePath = '';
  19851. }
  19852. Object.assign( ObjectLoader.prototype, {
  19853. load: function ( url, onLoad, onProgress, onError ) {
  19854. if ( this.texturePath === '' ) {
  19855. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  19856. }
  19857. var scope = this;
  19858. var loader = new FileLoader( scope.manager );
  19859. loader.load( url, function ( text ) {
  19860. var json = null;
  19861. try {
  19862. json = JSON.parse( text );
  19863. } catch ( error ) {
  19864. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  19865. return;
  19866. }
  19867. var metadata = json.metadata;
  19868. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  19869. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  19870. return;
  19871. }
  19872. scope.parse( json, onLoad );
  19873. }, onProgress, onError );
  19874. },
  19875. setTexturePath: function ( value ) {
  19876. this.texturePath = value;
  19877. },
  19878. setCrossOrigin: function ( value ) {
  19879. this.crossOrigin = value;
  19880. },
  19881. parse: function ( json, onLoad ) {
  19882. var geometries = this.parseGeometries( json.geometries );
  19883. var images = this.parseImages( json.images, function () {
  19884. if ( onLoad !== undefined ) onLoad( object );
  19885. } );
  19886. var textures = this.parseTextures( json.textures, images );
  19887. var materials = this.parseMaterials( json.materials, textures );
  19888. var object = this.parseObject( json.object, geometries, materials );
  19889. if ( json.animations ) {
  19890. object.animations = this.parseAnimations( json.animations );
  19891. }
  19892. if ( json.images === undefined || json.images.length === 0 ) {
  19893. if ( onLoad !== undefined ) onLoad( object );
  19894. }
  19895. return object;
  19896. },
  19897. parseGeometries: function ( json ) {
  19898. var geometries = {};
  19899. if ( json !== undefined ) {
  19900. var geometryLoader = new JSONLoader();
  19901. var bufferGeometryLoader = new BufferGeometryLoader();
  19902. for ( var i = 0, l = json.length; i < l; i ++ ) {
  19903. var geometry;
  19904. var data = json[ i ];
  19905. switch ( data.type ) {
  19906. case 'PlaneGeometry':
  19907. case 'PlaneBufferGeometry':
  19908. geometry = new Geometries[ data.type ](
  19909. data.width,
  19910. data.height,
  19911. data.widthSegments,
  19912. data.heightSegments
  19913. );
  19914. break;
  19915. case 'BoxGeometry':
  19916. case 'BoxBufferGeometry':
  19917. case 'CubeGeometry': // backwards compatible
  19918. geometry = new Geometries[ data.type ](
  19919. data.width,
  19920. data.height,
  19921. data.depth,
  19922. data.widthSegments,
  19923. data.heightSegments,
  19924. data.depthSegments
  19925. );
  19926. break;
  19927. case 'CircleGeometry':
  19928. case 'CircleBufferGeometry':
  19929. geometry = new Geometries[ data.type ](
  19930. data.radius,
  19931. data.segments,
  19932. data.thetaStart,
  19933. data.thetaLength
  19934. );
  19935. break;
  19936. case 'CylinderGeometry':
  19937. case 'CylinderBufferGeometry':
  19938. geometry = new Geometries[ data.type ](
  19939. data.radiusTop,
  19940. data.radiusBottom,
  19941. data.height,
  19942. data.radialSegments,
  19943. data.heightSegments,
  19944. data.openEnded,
  19945. data.thetaStart,
  19946. data.thetaLength
  19947. );
  19948. break;
  19949. case 'ConeGeometry':
  19950. case 'ConeBufferGeometry':
  19951. geometry = new Geometries[ data.type ](
  19952. data.radius,
  19953. data.height,
  19954. data.radialSegments,
  19955. data.heightSegments,
  19956. data.openEnded,
  19957. data.thetaStart,
  19958. data.thetaLength
  19959. );
  19960. break;
  19961. case 'SphereGeometry':
  19962. case 'SphereBufferGeometry':
  19963. geometry = new Geometries[ data.type ](
  19964. data.radius,
  19965. data.widthSegments,
  19966. data.heightSegments,
  19967. data.phiStart,
  19968. data.phiLength,
  19969. data.thetaStart,
  19970. data.thetaLength
  19971. );
  19972. break;
  19973. case 'DodecahedronGeometry':
  19974. case 'IcosahedronGeometry':
  19975. case 'OctahedronGeometry':
  19976. case 'TetrahedronGeometry':
  19977. geometry = new Geometries[ data.type ](
  19978. data.radius,
  19979. data.detail
  19980. );
  19981. break;
  19982. case 'RingGeometry':
  19983. case 'RingBufferGeometry':
  19984. geometry = new Geometries[ data.type ](
  19985. data.innerRadius,
  19986. data.outerRadius,
  19987. data.thetaSegments,
  19988. data.phiSegments,
  19989. data.thetaStart,
  19990. data.thetaLength
  19991. );
  19992. break;
  19993. case 'TorusGeometry':
  19994. case 'TorusBufferGeometry':
  19995. geometry = new Geometries[ data.type ](
  19996. data.radius,
  19997. data.tube,
  19998. data.radialSegments,
  19999. data.tubularSegments,
  20000. data.arc
  20001. );
  20002. break;
  20003. case 'TorusKnotGeometry':
  20004. case 'TorusKnotBufferGeometry':
  20005. geometry = new Geometries[ data.type ](
  20006. data.radius,
  20007. data.tube,
  20008. data.tubularSegments,
  20009. data.radialSegments,
  20010. data.p,
  20011. data.q
  20012. );
  20013. break;
  20014. case 'LatheGeometry':
  20015. case 'LatheBufferGeometry':
  20016. geometry = new Geometries[ data.type ](
  20017. data.points,
  20018. data.segments,
  20019. data.phiStart,
  20020. data.phiLength
  20021. );
  20022. break;
  20023. case 'BufferGeometry':
  20024. geometry = bufferGeometryLoader.parse( data );
  20025. break;
  20026. case 'Geometry':
  20027. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  20028. break;
  20029. default:
  20030. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  20031. continue;
  20032. }
  20033. geometry.uuid = data.uuid;
  20034. if ( data.name !== undefined ) geometry.name = data.name;
  20035. geometries[ data.uuid ] = geometry;
  20036. }
  20037. }
  20038. return geometries;
  20039. },
  20040. parseMaterials: function ( json, textures ) {
  20041. var materials = {};
  20042. if ( json !== undefined ) {
  20043. var loader = new MaterialLoader();
  20044. loader.setTextures( textures );
  20045. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20046. var material = loader.parse( json[ i ] );
  20047. materials[ material.uuid ] = material;
  20048. }
  20049. }
  20050. return materials;
  20051. },
  20052. parseAnimations: function ( json ) {
  20053. var animations = [];
  20054. for ( var i = 0; i < json.length; i ++ ) {
  20055. var clip = AnimationClip.parse( json[ i ] );
  20056. animations.push( clip );
  20057. }
  20058. return animations;
  20059. },
  20060. parseImages: function ( json, onLoad ) {
  20061. var scope = this;
  20062. var images = {};
  20063. function loadImage( url ) {
  20064. scope.manager.itemStart( url );
  20065. return loader.load( url, function () {
  20066. scope.manager.itemEnd( url );
  20067. }, undefined, function () {
  20068. scope.manager.itemError( url );
  20069. } );
  20070. }
  20071. if ( json !== undefined && json.length > 0 ) {
  20072. var manager = new LoadingManager( onLoad );
  20073. var loader = new ImageLoader( manager );
  20074. loader.setCrossOrigin( this.crossOrigin );
  20075. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20076. var image = json[ i ];
  20077. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  20078. images[ image.uuid ] = loadImage( path );
  20079. }
  20080. }
  20081. return images;
  20082. },
  20083. parseTextures: function ( json, images ) {
  20084. function parseConstant( value, type ) {
  20085. if ( typeof( value ) === 'number' ) return value;
  20086. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  20087. return type[ value ];
  20088. }
  20089. var textures = {};
  20090. if ( json !== undefined ) {
  20091. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20092. var data = json[ i ];
  20093. if ( data.image === undefined ) {
  20094. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  20095. }
  20096. if ( images[ data.image ] === undefined ) {
  20097. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  20098. }
  20099. var texture = new Texture( images[ data.image ] );
  20100. texture.needsUpdate = true;
  20101. texture.uuid = data.uuid;
  20102. if ( data.name !== undefined ) texture.name = data.name;
  20103. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TextureMapping );
  20104. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  20105. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  20106. if ( data.wrap !== undefined ) {
  20107. texture.wrapS = parseConstant( data.wrap[ 0 ], TextureWrapping );
  20108. texture.wrapT = parseConstant( data.wrap[ 1 ], TextureWrapping );
  20109. }
  20110. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TextureFilter );
  20111. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TextureFilter );
  20112. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  20113. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  20114. textures[ data.uuid ] = texture;
  20115. }
  20116. }
  20117. return textures;
  20118. },
  20119. parseObject: function () {
  20120. var matrix = new Matrix4();
  20121. return function parseObject( data, geometries, materials ) {
  20122. var object;
  20123. function getGeometry( name ) {
  20124. if ( geometries[ name ] === undefined ) {
  20125. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  20126. }
  20127. return geometries[ name ];
  20128. }
  20129. function getMaterial( name ) {
  20130. if ( name === undefined ) return undefined;
  20131. if ( materials[ name ] === undefined ) {
  20132. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  20133. }
  20134. return materials[ name ];
  20135. }
  20136. switch ( data.type ) {
  20137. case 'Scene':
  20138. object = new Scene();
  20139. if ( data.background !== undefined ) {
  20140. if ( Number.isInteger( data.background ) ) {
  20141. object.background = new Color( data.background );
  20142. }
  20143. }
  20144. if ( data.fog !== undefined ) {
  20145. if ( data.fog.type === 'Fog' ) {
  20146. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  20147. } else if ( data.fog.type === 'FogExp2' ) {
  20148. object.fog = new FogExp2( data.fog.color, data.fog.density );
  20149. }
  20150. }
  20151. break;
  20152. case 'PerspectiveCamera':
  20153. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  20154. if ( data.focus !== undefined ) object.focus = data.focus;
  20155. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  20156. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  20157. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  20158. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  20159. break;
  20160. case 'OrthographicCamera':
  20161. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  20162. break;
  20163. case 'AmbientLight':
  20164. object = new AmbientLight( data.color, data.intensity );
  20165. break;
  20166. case 'DirectionalLight':
  20167. object = new DirectionalLight( data.color, data.intensity );
  20168. break;
  20169. case 'PointLight':
  20170. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  20171. break;
  20172. case 'SpotLight':
  20173. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  20174. break;
  20175. case 'HemisphereLight':
  20176. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  20177. break;
  20178. case 'Mesh':
  20179. var geometry = getGeometry( data.geometry );
  20180. var material = getMaterial( data.material );
  20181. if ( geometry.bones && geometry.bones.length > 0 ) {
  20182. object = new SkinnedMesh( geometry, material );
  20183. } else {
  20184. object = new Mesh( geometry, material );
  20185. }
  20186. break;
  20187. case 'LOD':
  20188. object = new LOD();
  20189. break;
  20190. case 'Line':
  20191. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  20192. break;
  20193. case 'LineSegments':
  20194. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  20195. break;
  20196. case 'PointCloud':
  20197. case 'Points':
  20198. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  20199. break;
  20200. case 'Sprite':
  20201. object = new Sprite( getMaterial( data.material ) );
  20202. break;
  20203. case 'Group':
  20204. object = new Group();
  20205. break;
  20206. default:
  20207. object = new Object3D();
  20208. }
  20209. object.uuid = data.uuid;
  20210. if ( data.name !== undefined ) object.name = data.name;
  20211. if ( data.matrix !== undefined ) {
  20212. matrix.fromArray( data.matrix );
  20213. matrix.decompose( object.position, object.quaternion, object.scale );
  20214. } else {
  20215. if ( data.position !== undefined ) object.position.fromArray( data.position );
  20216. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  20217. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  20218. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  20219. }
  20220. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  20221. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  20222. if ( data.shadow ) {
  20223. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  20224. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  20225. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  20226. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  20227. }
  20228. if ( data.visible !== undefined ) object.visible = data.visible;
  20229. if ( data.userData !== undefined ) object.userData = data.userData;
  20230. if ( data.children !== undefined ) {
  20231. for ( var child in data.children ) {
  20232. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  20233. }
  20234. }
  20235. if ( data.type === 'LOD' ) {
  20236. var levels = data.levels;
  20237. for ( var l = 0; l < levels.length; l ++ ) {
  20238. var level = levels[ l ];
  20239. var child = object.getObjectByProperty( 'uuid', level.object );
  20240. if ( child !== undefined ) {
  20241. object.addLevel( child, level.distance );
  20242. }
  20243. }
  20244. }
  20245. return object;
  20246. };
  20247. }()
  20248. } );
  20249. /**
  20250. * @author zz85 / http://www.lab4games.net/zz85/blog
  20251. * Extensible curve object
  20252. *
  20253. * Some common of Curve methods
  20254. * .getPoint(t), getTangent(t)
  20255. * .getPointAt(u), getTangentAt(u)
  20256. * .getPoints(), .getSpacedPoints()
  20257. * .getLength()
  20258. * .updateArcLengths()
  20259. *
  20260. * This following classes subclasses THREE.Curve:
  20261. *
  20262. * -- 2d classes --
  20263. * THREE.LineCurve
  20264. * THREE.QuadraticBezierCurve
  20265. * THREE.CubicBezierCurve
  20266. * THREE.SplineCurve
  20267. * THREE.ArcCurve
  20268. * THREE.EllipseCurve
  20269. *
  20270. * -- 3d classes --
  20271. * THREE.LineCurve3
  20272. * THREE.QuadraticBezierCurve3
  20273. * THREE.CubicBezierCurve3
  20274. * THREE.SplineCurve3
  20275. *
  20276. * A series of curves can be represented as a THREE.CurvePath
  20277. *
  20278. **/
  20279. /**************************************************************
  20280. * Abstract Curve base class
  20281. **************************************************************/
  20282. function Curve() {}
  20283. Curve.prototype = {
  20284. constructor: Curve,
  20285. // Virtual base class method to overwrite and implement in subclasses
  20286. // - t [0 .. 1]
  20287. getPoint: function ( t ) {
  20288. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  20289. return null;
  20290. },
  20291. // Get point at relative position in curve according to arc length
  20292. // - u [0 .. 1]
  20293. getPointAt: function ( u ) {
  20294. var t = this.getUtoTmapping( u );
  20295. return this.getPoint( t );
  20296. },
  20297. // Get sequence of points using getPoint( t )
  20298. getPoints: function ( divisions ) {
  20299. if ( ! divisions ) divisions = 5;
  20300. var points = [];
  20301. for ( var d = 0; d <= divisions; d ++ ) {
  20302. points.push( this.getPoint( d / divisions ) );
  20303. }
  20304. return points;
  20305. },
  20306. // Get sequence of points using getPointAt( u )
  20307. getSpacedPoints: function ( divisions ) {
  20308. if ( ! divisions ) divisions = 5;
  20309. var points = [];
  20310. for ( var d = 0; d <= divisions; d ++ ) {
  20311. points.push( this.getPointAt( d / divisions ) );
  20312. }
  20313. return points;
  20314. },
  20315. // Get total curve arc length
  20316. getLength: function () {
  20317. var lengths = this.getLengths();
  20318. return lengths[ lengths.length - 1 ];
  20319. },
  20320. // Get list of cumulative segment lengths
  20321. getLengths: function ( divisions ) {
  20322. if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  20323. if ( this.cacheArcLengths
  20324. && ( this.cacheArcLengths.length === divisions + 1 )
  20325. && ! this.needsUpdate ) {
  20326. //console.log( "cached", this.cacheArcLengths );
  20327. return this.cacheArcLengths;
  20328. }
  20329. this.needsUpdate = false;
  20330. var cache = [];
  20331. var current, last = this.getPoint( 0 );
  20332. var p, sum = 0;
  20333. cache.push( 0 );
  20334. for ( p = 1; p <= divisions; p ++ ) {
  20335. current = this.getPoint ( p / divisions );
  20336. sum += current.distanceTo( last );
  20337. cache.push( sum );
  20338. last = current;
  20339. }
  20340. this.cacheArcLengths = cache;
  20341. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  20342. },
  20343. updateArcLengths: function() {
  20344. this.needsUpdate = true;
  20345. this.getLengths();
  20346. },
  20347. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20348. getUtoTmapping: function ( u, distance ) {
  20349. var arcLengths = this.getLengths();
  20350. var i = 0, il = arcLengths.length;
  20351. var targetArcLength; // The targeted u distance value to get
  20352. if ( distance ) {
  20353. targetArcLength = distance;
  20354. } else {
  20355. targetArcLength = u * arcLengths[ il - 1 ];
  20356. }
  20357. //var time = Date.now();
  20358. // binary search for the index with largest value smaller than target u distance
  20359. var low = 0, high = il - 1, comparison;
  20360. while ( low <= high ) {
  20361. 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
  20362. comparison = arcLengths[ i ] - targetArcLength;
  20363. if ( comparison < 0 ) {
  20364. low = i + 1;
  20365. } else if ( comparison > 0 ) {
  20366. high = i - 1;
  20367. } else {
  20368. high = i;
  20369. break;
  20370. // DONE
  20371. }
  20372. }
  20373. i = high;
  20374. //console.log('b' , i, low, high, Date.now()- time);
  20375. if ( arcLengths[ i ] === targetArcLength ) {
  20376. var t = i / ( il - 1 );
  20377. return t;
  20378. }
  20379. // we could get finer grain at lengths, or use simple interpolation between two points
  20380. var lengthBefore = arcLengths[ i ];
  20381. var lengthAfter = arcLengths[ i + 1 ];
  20382. var segmentLength = lengthAfter - lengthBefore;
  20383. // determine where we are between the 'before' and 'after' points
  20384. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20385. // add that fractional amount to t
  20386. var t = ( i + segmentFraction ) / ( il - 1 );
  20387. return t;
  20388. },
  20389. // Returns a unit vector tangent at t
  20390. // In case any sub curve does not implement its tangent derivation,
  20391. // 2 points a small delta apart will be used to find its gradient
  20392. // which seems to give a reasonable approximation
  20393. getTangent: function( t ) {
  20394. var delta = 0.0001;
  20395. var t1 = t - delta;
  20396. var t2 = t + delta;
  20397. // Capping in case of danger
  20398. if ( t1 < 0 ) t1 = 0;
  20399. if ( t2 > 1 ) t2 = 1;
  20400. var pt1 = this.getPoint( t1 );
  20401. var pt2 = this.getPoint( t2 );
  20402. var vec = pt2.clone().sub( pt1 );
  20403. return vec.normalize();
  20404. },
  20405. getTangentAt: function ( u ) {
  20406. var t = this.getUtoTmapping( u );
  20407. return this.getTangent( t );
  20408. },
  20409. computeFrenetFrames: function ( segments, closed ) {
  20410. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20411. var normal = new Vector3();
  20412. var tangents = [];
  20413. var normals = [];
  20414. var binormals = [];
  20415. var vec = new Vector3();
  20416. var mat = new Matrix4();
  20417. var i, u, theta;
  20418. // compute the tangent vectors for each segment on the curve
  20419. for ( i = 0; i <= segments; i ++ ) {
  20420. u = i / segments;
  20421. tangents[ i ] = this.getTangentAt( u );
  20422. tangents[ i ].normalize();
  20423. }
  20424. // select an initial normal vector perpendicular to the first tangent vector,
  20425. // and in the direction of the minimum tangent xyz component
  20426. normals[ 0 ] = new Vector3();
  20427. binormals[ 0 ] = new Vector3();
  20428. var min = Number.MAX_VALUE;
  20429. var tx = Math.abs( tangents[ 0 ].x );
  20430. var ty = Math.abs( tangents[ 0 ].y );
  20431. var tz = Math.abs( tangents[ 0 ].z );
  20432. if ( tx <= min ) {
  20433. min = tx;
  20434. normal.set( 1, 0, 0 );
  20435. }
  20436. if ( ty <= min ) {
  20437. min = ty;
  20438. normal.set( 0, 1, 0 );
  20439. }
  20440. if ( tz <= min ) {
  20441. normal.set( 0, 0, 1 );
  20442. }
  20443. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20444. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20445. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20446. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  20447. for ( i = 1; i <= segments; i ++ ) {
  20448. normals[ i ] = normals[ i - 1 ].clone();
  20449. binormals[ i ] = binormals[ i - 1 ].clone();
  20450. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  20451. if ( vec.length() > Number.EPSILON ) {
  20452. vec.normalize();
  20453. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  20454. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20455. }
  20456. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20457. }
  20458. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20459. if ( closed === true ) {
  20460. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  20461. theta /= segments;
  20462. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  20463. theta = - theta;
  20464. }
  20465. for ( i = 1; i <= segments; i ++ ) {
  20466. // twist a little...
  20467. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20468. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20469. }
  20470. }
  20471. return {
  20472. tangents: tangents,
  20473. normals: normals,
  20474. binormals: binormals
  20475. };
  20476. }
  20477. };
  20478. // TODO: Transformation for Curves?
  20479. /**************************************************************
  20480. * 3D Curves
  20481. **************************************************************/
  20482. // A Factory method for creating new curve subclasses
  20483. Curve.create = function ( constructor, getPointFunc ) {
  20484. constructor.prototype = Object.create( Curve.prototype );
  20485. constructor.prototype.constructor = constructor;
  20486. constructor.prototype.getPoint = getPointFunc;
  20487. return constructor;
  20488. };
  20489. /**************************************************************
  20490. * Line
  20491. **************************************************************/
  20492. function LineCurve( v1, v2 ) {
  20493. this.v1 = v1;
  20494. this.v2 = v2;
  20495. }
  20496. LineCurve.prototype = Object.create( Curve.prototype );
  20497. LineCurve.prototype.constructor = LineCurve;
  20498. LineCurve.prototype.isLineCurve = true;
  20499. LineCurve.prototype.getPoint = function ( t ) {
  20500. if ( t === 1 ) {
  20501. return this.v2.clone();
  20502. }
  20503. var point = this.v2.clone().sub( this.v1 );
  20504. point.multiplyScalar( t ).add( this.v1 );
  20505. return point;
  20506. };
  20507. // Line curve is linear, so we can overwrite default getPointAt
  20508. LineCurve.prototype.getPointAt = function ( u ) {
  20509. return this.getPoint( u );
  20510. };
  20511. LineCurve.prototype.getTangent = function( t ) {
  20512. var tangent = this.v2.clone().sub( this.v1 );
  20513. return tangent.normalize();
  20514. };
  20515. /**
  20516. * @author zz85 / http://www.lab4games.net/zz85/blog
  20517. *
  20518. **/
  20519. /**************************************************************
  20520. * Curved Path - a curve path is simply a array of connected
  20521. * curves, but retains the api of a curve
  20522. **************************************************************/
  20523. function CurvePath() {
  20524. this.curves = [];
  20525. this.autoClose = false; // Automatically closes the path
  20526. }
  20527. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  20528. constructor: CurvePath,
  20529. add: function ( curve ) {
  20530. this.curves.push( curve );
  20531. },
  20532. closePath: function () {
  20533. // Add a line curve if start and end of lines are not connected
  20534. var startPoint = this.curves[ 0 ].getPoint( 0 );
  20535. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20536. if ( ! startPoint.equals( endPoint ) ) {
  20537. this.curves.push( new LineCurve( endPoint, startPoint ) );
  20538. }
  20539. },
  20540. // To get accurate point with reference to
  20541. // entire path distance at time t,
  20542. // following has to be done:
  20543. // 1. Length of each sub path have to be known
  20544. // 2. Locate and identify type of curve
  20545. // 3. Get t for the curve
  20546. // 4. Return curve.getPointAt(t')
  20547. getPoint: function ( t ) {
  20548. var d = t * this.getLength();
  20549. var curveLengths = this.getCurveLengths();
  20550. var i = 0;
  20551. // To think about boundaries points.
  20552. while ( i < curveLengths.length ) {
  20553. if ( curveLengths[ i ] >= d ) {
  20554. var diff = curveLengths[ i ] - d;
  20555. var curve = this.curves[ i ];
  20556. var segmentLength = curve.getLength();
  20557. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  20558. return curve.getPointAt( u );
  20559. }
  20560. i ++;
  20561. }
  20562. return null;
  20563. // loop where sum != 0, sum > d , sum+1 <d
  20564. },
  20565. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20566. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20567. // getPoint() depends on getLength
  20568. getLength: function () {
  20569. var lens = this.getCurveLengths();
  20570. return lens[ lens.length - 1 ];
  20571. },
  20572. // cacheLengths must be recalculated.
  20573. updateArcLengths: function () {
  20574. this.needsUpdate = true;
  20575. this.cacheLengths = null;
  20576. this.getLengths();
  20577. },
  20578. // Compute lengths and cache them
  20579. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20580. getCurveLengths: function () {
  20581. // We use cache values if curves and cache array are same length
  20582. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20583. return this.cacheLengths;
  20584. }
  20585. // Get length of sub-curve
  20586. // Push sums into cached array
  20587. var lengths = [], sums = 0;
  20588. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  20589. sums += this.curves[ i ].getLength();
  20590. lengths.push( sums );
  20591. }
  20592. this.cacheLengths = lengths;
  20593. return lengths;
  20594. },
  20595. getSpacedPoints: function ( divisions ) {
  20596. if ( ! divisions ) divisions = 40;
  20597. var points = [];
  20598. for ( var i = 0; i <= divisions; i ++ ) {
  20599. points.push( this.getPoint( i / divisions ) );
  20600. }
  20601. if ( this.autoClose ) {
  20602. points.push( points[ 0 ] );
  20603. }
  20604. return points;
  20605. },
  20606. getPoints: function ( divisions ) {
  20607. divisions = divisions || 12;
  20608. var points = [], last;
  20609. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  20610. var curve = curves[ i ];
  20611. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  20612. : (curve && curve.isLineCurve) ? 1
  20613. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  20614. : divisions;
  20615. var pts = curve.getPoints( resolution );
  20616. for ( var j = 0; j < pts.length; j++ ) {
  20617. var point = pts[ j ];
  20618. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  20619. points.push( point );
  20620. last = point;
  20621. }
  20622. }
  20623. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  20624. points.push( points[ 0 ] );
  20625. }
  20626. return points;
  20627. },
  20628. /**************************************************************
  20629. * Create Geometries Helpers
  20630. **************************************************************/
  20631. /// Generate geometry from path points (for Line or Points objects)
  20632. createPointsGeometry: function ( divisions ) {
  20633. var pts = this.getPoints( divisions );
  20634. return this.createGeometry( pts );
  20635. },
  20636. // Generate geometry from equidistant sampling along the path
  20637. createSpacedPointsGeometry: function ( divisions ) {
  20638. var pts = this.getSpacedPoints( divisions );
  20639. return this.createGeometry( pts );
  20640. },
  20641. createGeometry: function ( points ) {
  20642. var geometry = new Geometry();
  20643. for ( var i = 0, l = points.length; i < l; i ++ ) {
  20644. var point = points[ i ];
  20645. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  20646. }
  20647. return geometry;
  20648. }
  20649. } );
  20650. /**************************************************************
  20651. * Ellipse curve
  20652. **************************************************************/
  20653. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20654. this.aX = aX;
  20655. this.aY = aY;
  20656. this.xRadius = xRadius;
  20657. this.yRadius = yRadius;
  20658. this.aStartAngle = aStartAngle;
  20659. this.aEndAngle = aEndAngle;
  20660. this.aClockwise = aClockwise;
  20661. this.aRotation = aRotation || 0;
  20662. }
  20663. EllipseCurve.prototype = Object.create( Curve.prototype );
  20664. EllipseCurve.prototype.constructor = EllipseCurve;
  20665. EllipseCurve.prototype.isEllipseCurve = true;
  20666. EllipseCurve.prototype.getPoint = function( t ) {
  20667. var twoPi = Math.PI * 2;
  20668. var deltaAngle = this.aEndAngle - this.aStartAngle;
  20669. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  20670. // ensures that deltaAngle is 0 .. 2 PI
  20671. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  20672. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  20673. if ( deltaAngle < Number.EPSILON ) {
  20674. if ( samePoints ) {
  20675. deltaAngle = 0;
  20676. } else {
  20677. deltaAngle = twoPi;
  20678. }
  20679. }
  20680. if ( this.aClockwise === true && ! samePoints ) {
  20681. if ( deltaAngle === twoPi ) {
  20682. deltaAngle = - twoPi;
  20683. } else {
  20684. deltaAngle = deltaAngle - twoPi;
  20685. }
  20686. }
  20687. var angle = this.aStartAngle + t * deltaAngle;
  20688. var x = this.aX + this.xRadius * Math.cos( angle );
  20689. var y = this.aY + this.yRadius * Math.sin( angle );
  20690. if ( this.aRotation !== 0 ) {
  20691. var cos = Math.cos( this.aRotation );
  20692. var sin = Math.sin( this.aRotation );
  20693. var tx = x - this.aX;
  20694. var ty = y - this.aY;
  20695. // Rotate the point about the center of the ellipse.
  20696. x = tx * cos - ty * sin + this.aX;
  20697. y = tx * sin + ty * cos + this.aY;
  20698. }
  20699. return new Vector2( x, y );
  20700. };
  20701. /**
  20702. * @author zz85 / http://www.lab4games.net/zz85/blog
  20703. */
  20704. var CurveUtils = {
  20705. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  20706. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  20707. },
  20708. // Puay Bing, thanks for helping with this derivative!
  20709. tangentCubicBezier: function ( t, p0, p1, p2, p3 ) {
  20710. return - 3 * p0 * ( 1 - t ) * ( 1 - t ) +
  20711. 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) +
  20712. 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 +
  20713. 3 * t * t * p3;
  20714. },
  20715. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  20716. // To check if my formulas are correct
  20717. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  20718. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  20719. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  20720. var h11 = 3 * t * t - 2 * t; // t3 − t2
  20721. return h00 + h10 + h01 + h11;
  20722. },
  20723. // Catmull-Rom
  20724. interpolate: function( p0, p1, p2, p3, t ) {
  20725. var v0 = ( p2 - p0 ) * 0.5;
  20726. var v1 = ( p3 - p1 ) * 0.5;
  20727. var t2 = t * t;
  20728. var t3 = t * t2;
  20729. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20730. }
  20731. };
  20732. /**************************************************************
  20733. * Spline curve
  20734. **************************************************************/
  20735. function SplineCurve( points /* array of Vector2 */ ) {
  20736. this.points = ( points === undefined ) ? [] : points;
  20737. }
  20738. SplineCurve.prototype = Object.create( Curve.prototype );
  20739. SplineCurve.prototype.constructor = SplineCurve;
  20740. SplineCurve.prototype.isSplineCurve = true;
  20741. SplineCurve.prototype.getPoint = function ( t ) {
  20742. var points = this.points;
  20743. var point = ( points.length - 1 ) * t;
  20744. var intPoint = Math.floor( point );
  20745. var weight = point - intPoint;
  20746. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  20747. var point1 = points[ intPoint ];
  20748. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  20749. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  20750. var interpolate = CurveUtils.interpolate;
  20751. return new Vector2(
  20752. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  20753. interpolate( point0.y, point1.y, point2.y, point3.y, weight )
  20754. );
  20755. };
  20756. /**************************************************************
  20757. * Cubic Bezier curve
  20758. **************************************************************/
  20759. function CubicBezierCurve( v0, v1, v2, v3 ) {
  20760. this.v0 = v0;
  20761. this.v1 = v1;
  20762. this.v2 = v2;
  20763. this.v3 = v3;
  20764. }
  20765. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  20766. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  20767. CubicBezierCurve.prototype.getPoint = function ( t ) {
  20768. var b3 = ShapeUtils.b3;
  20769. return new Vector2(
  20770. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20771. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  20772. );
  20773. };
  20774. CubicBezierCurve.prototype.getTangent = function( t ) {
  20775. var tangentCubicBezier = CurveUtils.tangentCubicBezier;
  20776. return new Vector2(
  20777. tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20778. tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  20779. ).normalize();
  20780. };
  20781. /**************************************************************
  20782. * Quadratic Bezier curve
  20783. **************************************************************/
  20784. function QuadraticBezierCurve( v0, v1, v2 ) {
  20785. this.v0 = v0;
  20786. this.v1 = v1;
  20787. this.v2 = v2;
  20788. }
  20789. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  20790. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  20791. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  20792. var b2 = ShapeUtils.b2;
  20793. return new Vector2(
  20794. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  20795. b2( t, this.v0.y, this.v1.y, this.v2.y )
  20796. );
  20797. };
  20798. QuadraticBezierCurve.prototype.getTangent = function( t ) {
  20799. var tangentQuadraticBezier = CurveUtils.tangentQuadraticBezier;
  20800. return new Vector2(
  20801. tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ),
  20802. tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y )
  20803. ).normalize();
  20804. };
  20805. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  20806. fromPoints: function ( vectors ) {
  20807. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  20808. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  20809. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  20810. }
  20811. },
  20812. moveTo: function ( x, y ) {
  20813. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  20814. },
  20815. lineTo: function ( x, y ) {
  20816. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  20817. this.curves.push( curve );
  20818. this.currentPoint.set( x, y );
  20819. },
  20820. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  20821. var curve = new QuadraticBezierCurve(
  20822. this.currentPoint.clone(),
  20823. new Vector2( aCPx, aCPy ),
  20824. new Vector2( aX, aY )
  20825. );
  20826. this.curves.push( curve );
  20827. this.currentPoint.set( aX, aY );
  20828. },
  20829. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20830. var curve = new CubicBezierCurve(
  20831. this.currentPoint.clone(),
  20832. new Vector2( aCP1x, aCP1y ),
  20833. new Vector2( aCP2x, aCP2y ),
  20834. new Vector2( aX, aY )
  20835. );
  20836. this.curves.push( curve );
  20837. this.currentPoint.set( aX, aY );
  20838. },
  20839. splineThru: function ( pts /*Array of Vector*/ ) {
  20840. var npts = [ this.currentPoint.clone() ].concat( pts );
  20841. var curve = new SplineCurve( npts );
  20842. this.curves.push( curve );
  20843. this.currentPoint.copy( pts[ pts.length - 1 ] );
  20844. },
  20845. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20846. var x0 = this.currentPoint.x;
  20847. var y0 = this.currentPoint.y;
  20848. this.absarc( aX + x0, aY + y0, aRadius,
  20849. aStartAngle, aEndAngle, aClockwise );
  20850. },
  20851. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20852. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20853. },
  20854. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20855. var x0 = this.currentPoint.x;
  20856. var y0 = this.currentPoint.y;
  20857. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20858. },
  20859. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20860. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20861. if ( this.curves.length > 0 ) {
  20862. // if a previous curve is present, attempt to join
  20863. var firstPoint = curve.getPoint( 0 );
  20864. if ( ! firstPoint.equals( this.currentPoint ) ) {
  20865. this.lineTo( firstPoint.x, firstPoint.y );
  20866. }
  20867. }
  20868. this.curves.push( curve );
  20869. var lastPoint = curve.getPoint( 1 );
  20870. this.currentPoint.copy( lastPoint );
  20871. }
  20872. } );
  20873. /**
  20874. * @author zz85 / http://www.lab4games.net/zz85/blog
  20875. * Defines a 2d shape plane using paths.
  20876. **/
  20877. // STEP 1 Create a path.
  20878. // STEP 2 Turn path into shape.
  20879. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  20880. // STEP 3a - Extract points from each shape, turn to vertices
  20881. // STEP 3b - Triangulate each shape, add faces.
  20882. function Shape() {
  20883. Path.apply( this, arguments );
  20884. this.holes = [];
  20885. }
  20886. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  20887. constructor: Shape,
  20888. getPointsHoles: function ( divisions ) {
  20889. var holesPts = [];
  20890. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  20891. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20892. }
  20893. return holesPts;
  20894. },
  20895. // Get points of shape and holes (keypoints based on segments parameter)
  20896. extractAllPoints: function ( divisions ) {
  20897. return {
  20898. shape: this.getPoints( divisions ),
  20899. holes: this.getPointsHoles( divisions )
  20900. };
  20901. },
  20902. extractPoints: function ( divisions ) {
  20903. return this.extractAllPoints( divisions );
  20904. }
  20905. } );
  20906. /**
  20907. * @author zz85 / http://www.lab4games.net/zz85/blog
  20908. * Creates free form 2d path using series of points, lines or curves.
  20909. *
  20910. **/
  20911. function Path( points ) {
  20912. CurvePath.call( this );
  20913. this.currentPoint = new Vector2();
  20914. if ( points ) {
  20915. this.fromPoints( points );
  20916. }
  20917. }
  20918. Path.prototype = PathPrototype;
  20919. PathPrototype.constructor = Path;
  20920. // minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  20921. function ShapePath() {
  20922. this.subPaths = [];
  20923. this.currentPath = null;
  20924. }
  20925. ShapePath.prototype = {
  20926. moveTo: function ( x, y ) {
  20927. this.currentPath = new Path();
  20928. this.subPaths.push(this.currentPath);
  20929. this.currentPath.moveTo( x, y );
  20930. },
  20931. lineTo: function ( x, y ) {
  20932. this.currentPath.lineTo( x, y );
  20933. },
  20934. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  20935. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  20936. },
  20937. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20938. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  20939. },
  20940. splineThru: function ( pts ) {
  20941. this.currentPath.splineThru( pts );
  20942. },
  20943. toShapes: function ( isCCW, noHoles ) {
  20944. function toShapesNoHoles( inSubpaths ) {
  20945. var shapes = [];
  20946. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  20947. var tmpPath = inSubpaths[ i ];
  20948. var tmpShape = new Shape();
  20949. tmpShape.curves = tmpPath.curves;
  20950. shapes.push( tmpShape );
  20951. }
  20952. return shapes;
  20953. }
  20954. function isPointInsidePolygon( inPt, inPolygon ) {
  20955. var polyLen = inPolygon.length;
  20956. // inPt on polygon contour => immediate success or
  20957. // toggling of inside/outside at every single! intersection point of an edge
  20958. // with the horizontal line through inPt, left of inPt
  20959. // not counting lowerY endpoints of edges and whole edges on that line
  20960. var inside = false;
  20961. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  20962. var edgeLowPt = inPolygon[ p ];
  20963. var edgeHighPt = inPolygon[ q ];
  20964. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  20965. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  20966. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  20967. // not parallel
  20968. if ( edgeDy < 0 ) {
  20969. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  20970. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  20971. }
  20972. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  20973. if ( inPt.y === edgeLowPt.y ) {
  20974. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  20975. // continue; // no intersection or edgeLowPt => doesn't count !!!
  20976. } else {
  20977. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  20978. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  20979. if ( perpEdge < 0 ) continue;
  20980. inside = ! inside; // true intersection left of inPt
  20981. }
  20982. } else {
  20983. // parallel or collinear
  20984. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  20985. // edge lies on the same horizontal line as inPt
  20986. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  20987. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  20988. // continue;
  20989. }
  20990. }
  20991. return inside;
  20992. }
  20993. var isClockWise = ShapeUtils.isClockWise;
  20994. var subPaths = this.subPaths;
  20995. if ( subPaths.length === 0 ) return [];
  20996. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  20997. var solid, tmpPath, tmpShape, shapes = [];
  20998. if ( subPaths.length === 1 ) {
  20999. tmpPath = subPaths[ 0 ];
  21000. tmpShape = new Shape();
  21001. tmpShape.curves = tmpPath.curves;
  21002. shapes.push( tmpShape );
  21003. return shapes;
  21004. }
  21005. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21006. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21007. // console.log("Holes first", holesFirst);
  21008. var betterShapeHoles = [];
  21009. var newShapes = [];
  21010. var newShapeHoles = [];
  21011. var mainIdx = 0;
  21012. var tmpPoints;
  21013. newShapes[ mainIdx ] = undefined;
  21014. newShapeHoles[ mainIdx ] = [];
  21015. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  21016. tmpPath = subPaths[ i ];
  21017. tmpPoints = tmpPath.getPoints();
  21018. solid = isClockWise( tmpPoints );
  21019. solid = isCCW ? ! solid : solid;
  21020. if ( solid ) {
  21021. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21022. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21023. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21024. if ( holesFirst ) mainIdx ++;
  21025. newShapeHoles[ mainIdx ] = [];
  21026. //console.log('cw', i);
  21027. } else {
  21028. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21029. //console.log('ccw', i);
  21030. }
  21031. }
  21032. // only Holes? -> probably all Shapes with wrong orientation
  21033. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21034. if ( newShapes.length > 1 ) {
  21035. var ambiguous = false;
  21036. var toChange = [];
  21037. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21038. betterShapeHoles[ sIdx ] = [];
  21039. }
  21040. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21041. var sho = newShapeHoles[ sIdx ];
  21042. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21043. var ho = sho[ hIdx ];
  21044. var hole_unassigned = true;
  21045. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21046. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21047. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  21048. if ( hole_unassigned ) {
  21049. hole_unassigned = false;
  21050. betterShapeHoles[ s2Idx ].push( ho );
  21051. } else {
  21052. ambiguous = true;
  21053. }
  21054. }
  21055. }
  21056. if ( hole_unassigned ) {
  21057. betterShapeHoles[ sIdx ].push( ho );
  21058. }
  21059. }
  21060. }
  21061. // console.log("ambiguous: ", ambiguous);
  21062. if ( toChange.length > 0 ) {
  21063. // console.log("to change: ", toChange);
  21064. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  21065. }
  21066. }
  21067. var tmpHoles;
  21068. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  21069. tmpShape = newShapes[ i ].s;
  21070. shapes.push( tmpShape );
  21071. tmpHoles = newShapeHoles[ i ];
  21072. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21073. tmpShape.holes.push( tmpHoles[ j ].h );
  21074. }
  21075. }
  21076. //console.log("shape", shapes);
  21077. return shapes;
  21078. }
  21079. };
  21080. /**
  21081. * @author zz85 / http://www.lab4games.net/zz85/blog
  21082. * @author mrdoob / http://mrdoob.com/
  21083. */
  21084. function Font( data ) {
  21085. this.data = data;
  21086. }
  21087. Object.assign( Font.prototype, {
  21088. isFont: true,
  21089. generateShapes: function ( text, size, divisions ) {
  21090. function createPaths( text ) {
  21091. var chars = String( text ).split( '' );
  21092. var scale = size / data.resolution;
  21093. var offset = 0;
  21094. var paths = [];
  21095. for ( var i = 0; i < chars.length; i ++ ) {
  21096. var ret = createPath( chars[ i ], scale, offset );
  21097. offset += ret.offset;
  21098. paths.push( ret.path );
  21099. }
  21100. return paths;
  21101. }
  21102. function createPath( c, scale, offset ) {
  21103. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  21104. if ( ! glyph ) return;
  21105. var path = new ShapePath();
  21106. var pts = [], b2 = ShapeUtils.b2, b3 = ShapeUtils.b3;
  21107. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  21108. if ( glyph.o ) {
  21109. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  21110. for ( var i = 0, l = outline.length; i < l; ) {
  21111. var action = outline[ i ++ ];
  21112. switch ( action ) {
  21113. case 'm': // moveTo
  21114. x = outline[ i ++ ] * scale + offset;
  21115. y = outline[ i ++ ] * scale;
  21116. path.moveTo( x, y );
  21117. break;
  21118. case 'l': // lineTo
  21119. x = outline[ i ++ ] * scale + offset;
  21120. y = outline[ i ++ ] * scale;
  21121. path.lineTo( x, y );
  21122. break;
  21123. case 'q': // quadraticCurveTo
  21124. cpx = outline[ i ++ ] * scale + offset;
  21125. cpy = outline[ i ++ ] * scale;
  21126. cpx1 = outline[ i ++ ] * scale + offset;
  21127. cpy1 = outline[ i ++ ] * scale;
  21128. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  21129. laste = pts[ pts.length - 1 ];
  21130. if ( laste ) {
  21131. cpx0 = laste.x;
  21132. cpy0 = laste.y;
  21133. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21134. var t = i2 / divisions;
  21135. b2( t, cpx0, cpx1, cpx );
  21136. b2( t, cpy0, cpy1, cpy );
  21137. }
  21138. }
  21139. break;
  21140. case 'b': // bezierCurveTo
  21141. cpx = outline[ i ++ ] * scale + offset;
  21142. cpy = outline[ i ++ ] * scale;
  21143. cpx1 = outline[ i ++ ] * scale + offset;
  21144. cpy1 = outline[ i ++ ] * scale;
  21145. cpx2 = outline[ i ++ ] * scale + offset;
  21146. cpy2 = outline[ i ++ ] * scale;
  21147. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  21148. laste = pts[ pts.length - 1 ];
  21149. if ( laste ) {
  21150. cpx0 = laste.x;
  21151. cpy0 = laste.y;
  21152. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21153. var t = i2 / divisions;
  21154. b3( t, cpx0, cpx1, cpx2, cpx );
  21155. b3( t, cpy0, cpy1, cpy2, cpy );
  21156. }
  21157. }
  21158. break;
  21159. }
  21160. }
  21161. }
  21162. return { offset: glyph.ha * scale, path: path };
  21163. }
  21164. //
  21165. if ( size === undefined ) size = 100;
  21166. if ( divisions === undefined ) divisions = 4;
  21167. var data = this.data;
  21168. var paths = createPaths( text );
  21169. var shapes = [];
  21170. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  21171. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  21172. }
  21173. return shapes;
  21174. }
  21175. } );
  21176. /**
  21177. * @author mrdoob / http://mrdoob.com/
  21178. */
  21179. function FontLoader( manager ) {
  21180. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21181. }
  21182. Object.assign( FontLoader.prototype, {
  21183. load: function ( url, onLoad, onProgress, onError ) {
  21184. var scope = this;
  21185. var loader = new FileLoader( this.manager );
  21186. loader.load( url, function ( text ) {
  21187. var json;
  21188. try {
  21189. json = JSON.parse( text );
  21190. } catch ( e ) {
  21191. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  21192. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  21193. }
  21194. var font = scope.parse( json );
  21195. if ( onLoad ) onLoad( font );
  21196. }, onProgress, onError );
  21197. },
  21198. parse: function ( json ) {
  21199. return new Font( json );
  21200. }
  21201. } );
  21202. var context;
  21203. var AudioContext = {
  21204. getContext: function () {
  21205. if ( context === undefined ) {
  21206. context = new ( window.AudioContext || window.webkitAudioContext )();
  21207. }
  21208. return context;
  21209. },
  21210. setContext: function ( value ) {
  21211. context = value;
  21212. }
  21213. };
  21214. /**
  21215. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21216. */
  21217. function AudioLoader( manager ) {
  21218. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21219. }
  21220. Object.assign( AudioLoader.prototype, {
  21221. load: function ( url, onLoad, onProgress, onError ) {
  21222. var loader = new FileLoader( this.manager );
  21223. loader.setResponseType( 'arraybuffer' );
  21224. loader.load( url, function ( buffer ) {
  21225. var context = AudioContext.getContext();
  21226. context.decodeAudioData( buffer, function ( audioBuffer ) {
  21227. onLoad( audioBuffer );
  21228. } );
  21229. }, onProgress, onError );
  21230. }
  21231. } );
  21232. /**
  21233. * @author abelnation / http://github.com/abelnation
  21234. */
  21235. function RectAreaLight ( color, intensity, width, height ) {
  21236. Light.call( this, color, intensity );
  21237. this.type = 'RectAreaLight';
  21238. this.position.set( 0, 1, 0 );
  21239. this.updateMatrix();
  21240. this.width = ( width !== undefined ) ? width : 10;
  21241. this.height = ( height !== undefined ) ? height : 10;
  21242. // TODO (abelnation): distance/decay
  21243. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  21244. // TODO (abelnation): shadows
  21245. // this.shadow = new THREE.RectAreaLightShadow( new THREE.PerspectiveCamera( 90, 1, 0.5, 500 ) );
  21246. }
  21247. // TODO (abelnation): RectAreaLight update when light shape is changed
  21248. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  21249. constructor: RectAreaLight,
  21250. isRectAreaLight: true,
  21251. copy: function ( source ) {
  21252. Light.prototype.copy.call( this, source );
  21253. this.width = source.width;
  21254. this.height = source.height;
  21255. // this.shadow = source.shadow.clone();
  21256. return this;
  21257. }
  21258. } );
  21259. /**
  21260. * @author mrdoob / http://mrdoob.com/
  21261. */
  21262. function StereoCamera() {
  21263. this.type = 'StereoCamera';
  21264. this.aspect = 1;
  21265. this.eyeSep = 0.064;
  21266. this.cameraL = new PerspectiveCamera();
  21267. this.cameraL.layers.enable( 1 );
  21268. this.cameraL.matrixAutoUpdate = false;
  21269. this.cameraR = new PerspectiveCamera();
  21270. this.cameraR.layers.enable( 2 );
  21271. this.cameraR.matrixAutoUpdate = false;
  21272. }
  21273. Object.assign( StereoCamera.prototype, {
  21274. update: ( function () {
  21275. var instance, focus, fov, aspect, near, far, zoom;
  21276. var eyeRight = new Matrix4();
  21277. var eyeLeft = new Matrix4();
  21278. return function update( camera ) {
  21279. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  21280. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  21281. far !== camera.far || zoom !== camera.zoom;
  21282. if ( needsUpdate ) {
  21283. instance = this;
  21284. focus = camera.focus;
  21285. fov = camera.fov;
  21286. aspect = camera.aspect * this.aspect;
  21287. near = camera.near;
  21288. far = camera.far;
  21289. zoom = camera.zoom;
  21290. // Off-axis stereoscopic effect based on
  21291. // http://paulbourke.net/stereographics/stereorender/
  21292. var projectionMatrix = camera.projectionMatrix.clone();
  21293. var eyeSep = this.eyeSep / 2;
  21294. var eyeSepOnProjection = eyeSep * near / focus;
  21295. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  21296. var xmin, xmax;
  21297. // translate xOffset
  21298. eyeLeft.elements[ 12 ] = - eyeSep;
  21299. eyeRight.elements[ 12 ] = eyeSep;
  21300. // for left eye
  21301. xmin = - ymax * aspect + eyeSepOnProjection;
  21302. xmax = ymax * aspect + eyeSepOnProjection;
  21303. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21304. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21305. this.cameraL.projectionMatrix.copy( projectionMatrix );
  21306. // for right eye
  21307. xmin = - ymax * aspect - eyeSepOnProjection;
  21308. xmax = ymax * aspect - eyeSepOnProjection;
  21309. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21310. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21311. this.cameraR.projectionMatrix.copy( projectionMatrix );
  21312. }
  21313. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  21314. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  21315. };
  21316. } )()
  21317. } );
  21318. /**
  21319. * Camera for rendering cube maps
  21320. * - renders scene into axis-aligned cube
  21321. *
  21322. * @author alteredq / http://alteredqualia.com/
  21323. */
  21324. function CubeCamera( near, far, cubeResolution ) {
  21325. Object3D.call( this );
  21326. this.type = 'CubeCamera';
  21327. var fov = 90, aspect = 1;
  21328. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  21329. cameraPX.up.set( 0, - 1, 0 );
  21330. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  21331. this.add( cameraPX );
  21332. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  21333. cameraNX.up.set( 0, - 1, 0 );
  21334. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  21335. this.add( cameraNX );
  21336. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  21337. cameraPY.up.set( 0, 0, 1 );
  21338. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  21339. this.add( cameraPY );
  21340. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  21341. cameraNY.up.set( 0, 0, - 1 );
  21342. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  21343. this.add( cameraNY );
  21344. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  21345. cameraPZ.up.set( 0, - 1, 0 );
  21346. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  21347. this.add( cameraPZ );
  21348. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  21349. cameraNZ.up.set( 0, - 1, 0 );
  21350. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  21351. this.add( cameraNZ );
  21352. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  21353. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  21354. this.updateCubeMap = function ( renderer, scene ) {
  21355. if ( this.parent === null ) this.updateMatrixWorld();
  21356. var renderTarget = this.renderTarget;
  21357. var generateMipmaps = renderTarget.texture.generateMipmaps;
  21358. renderTarget.texture.generateMipmaps = false;
  21359. renderTarget.activeCubeFace = 0;
  21360. renderer.render( scene, cameraPX, renderTarget );
  21361. renderTarget.activeCubeFace = 1;
  21362. renderer.render( scene, cameraNX, renderTarget );
  21363. renderTarget.activeCubeFace = 2;
  21364. renderer.render( scene, cameraPY, renderTarget );
  21365. renderTarget.activeCubeFace = 3;
  21366. renderer.render( scene, cameraNY, renderTarget );
  21367. renderTarget.activeCubeFace = 4;
  21368. renderer.render( scene, cameraPZ, renderTarget );
  21369. renderTarget.texture.generateMipmaps = generateMipmaps;
  21370. renderTarget.activeCubeFace = 5;
  21371. renderer.render( scene, cameraNZ, renderTarget );
  21372. renderer.setRenderTarget( null );
  21373. };
  21374. }
  21375. CubeCamera.prototype = Object.create( Object3D.prototype );
  21376. CubeCamera.prototype.constructor = CubeCamera;
  21377. /**
  21378. * @author mrdoob / http://mrdoob.com/
  21379. */
  21380. function AudioListener() {
  21381. Object3D.call( this );
  21382. this.type = 'AudioListener';
  21383. this.context = AudioContext.getContext();
  21384. this.gain = this.context.createGain();
  21385. this.gain.connect( this.context.destination );
  21386. this.filter = null;
  21387. }
  21388. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21389. constructor: AudioListener,
  21390. getInput: function () {
  21391. return this.gain;
  21392. },
  21393. removeFilter: function ( ) {
  21394. if ( this.filter !== null ) {
  21395. this.gain.disconnect( this.filter );
  21396. this.filter.disconnect( this.context.destination );
  21397. this.gain.connect( this.context.destination );
  21398. this.filter = null;
  21399. }
  21400. },
  21401. getFilter: function () {
  21402. return this.filter;
  21403. },
  21404. setFilter: function ( value ) {
  21405. if ( this.filter !== null ) {
  21406. this.gain.disconnect( this.filter );
  21407. this.filter.disconnect( this.context.destination );
  21408. } else {
  21409. this.gain.disconnect( this.context.destination );
  21410. }
  21411. this.filter = value;
  21412. this.gain.connect( this.filter );
  21413. this.filter.connect( this.context.destination );
  21414. },
  21415. getMasterVolume: function () {
  21416. return this.gain.gain.value;
  21417. },
  21418. setMasterVolume: function ( value ) {
  21419. this.gain.gain.value = value;
  21420. },
  21421. updateMatrixWorld: ( function () {
  21422. var position = new Vector3();
  21423. var quaternion = new Quaternion();
  21424. var scale = new Vector3();
  21425. var orientation = new Vector3();
  21426. return function updateMatrixWorld( force ) {
  21427. Object3D.prototype.updateMatrixWorld.call( this, force );
  21428. var listener = this.context.listener;
  21429. var up = this.up;
  21430. this.matrixWorld.decompose( position, quaternion, scale );
  21431. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  21432. if ( listener.positionX ) {
  21433. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  21434. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  21435. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  21436. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  21437. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  21438. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  21439. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  21440. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  21441. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  21442. } else {
  21443. listener.setPosition( position.x, position.y, position.z );
  21444. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  21445. }
  21446. };
  21447. } )()
  21448. } );
  21449. /**
  21450. * @author mrdoob / http://mrdoob.com/
  21451. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21452. */
  21453. function Audio( listener ) {
  21454. Object3D.call( this );
  21455. this.type = 'Audio';
  21456. this.context = listener.context;
  21457. this.gain = this.context.createGain();
  21458. this.gain.connect( listener.getInput() );
  21459. this.autoplay = false;
  21460. this.buffer = null;
  21461. this.loop = false;
  21462. this.startTime = 0;
  21463. this.playbackRate = 1;
  21464. this.isPlaying = false;
  21465. this.hasPlaybackControl = true;
  21466. this.sourceType = 'empty';
  21467. this.filters = [];
  21468. }
  21469. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21470. constructor: Audio,
  21471. getOutput: function () {
  21472. return this.gain;
  21473. },
  21474. setNodeSource: function ( audioNode ) {
  21475. this.hasPlaybackControl = false;
  21476. this.sourceType = 'audioNode';
  21477. this.source = audioNode;
  21478. this.connect();
  21479. return this;
  21480. },
  21481. setBuffer: function ( audioBuffer ) {
  21482. this.buffer = audioBuffer;
  21483. this.sourceType = 'buffer';
  21484. if ( this.autoplay ) this.play();
  21485. return this;
  21486. },
  21487. play: function () {
  21488. if ( this.isPlaying === true ) {
  21489. console.warn( 'THREE.Audio: Audio is already playing.' );
  21490. return;
  21491. }
  21492. if ( this.hasPlaybackControl === false ) {
  21493. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21494. return;
  21495. }
  21496. var source = this.context.createBufferSource();
  21497. source.buffer = this.buffer;
  21498. source.loop = this.loop;
  21499. source.onended = this.onEnded.bind( this );
  21500. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  21501. source.start( 0, this.startTime );
  21502. this.isPlaying = true;
  21503. this.source = source;
  21504. return this.connect();
  21505. },
  21506. pause: function () {
  21507. if ( this.hasPlaybackControl === false ) {
  21508. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21509. return;
  21510. }
  21511. this.source.stop();
  21512. this.startTime = this.context.currentTime;
  21513. this.isPlaying = false;
  21514. return this;
  21515. },
  21516. stop: function () {
  21517. if ( this.hasPlaybackControl === false ) {
  21518. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21519. return;
  21520. }
  21521. this.source.stop();
  21522. this.startTime = 0;
  21523. this.isPlaying = false;
  21524. return this;
  21525. },
  21526. connect: function () {
  21527. if ( this.filters.length > 0 ) {
  21528. this.source.connect( this.filters[ 0 ] );
  21529. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21530. this.filters[ i - 1 ].connect( this.filters[ i ] );
  21531. }
  21532. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  21533. } else {
  21534. this.source.connect( this.getOutput() );
  21535. }
  21536. return this;
  21537. },
  21538. disconnect: function () {
  21539. if ( this.filters.length > 0 ) {
  21540. this.source.disconnect( this.filters[ 0 ] );
  21541. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21542. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  21543. }
  21544. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  21545. } else {
  21546. this.source.disconnect( this.getOutput() );
  21547. }
  21548. return this;
  21549. },
  21550. getFilters: function () {
  21551. return this.filters;
  21552. },
  21553. setFilters: function ( value ) {
  21554. if ( ! value ) value = [];
  21555. if ( this.isPlaying === true ) {
  21556. this.disconnect();
  21557. this.filters = value;
  21558. this.connect();
  21559. } else {
  21560. this.filters = value;
  21561. }
  21562. return this;
  21563. },
  21564. getFilter: function () {
  21565. return this.getFilters()[ 0 ];
  21566. },
  21567. setFilter: function ( filter ) {
  21568. return this.setFilters( filter ? [ filter ] : [] );
  21569. },
  21570. setPlaybackRate: function ( value ) {
  21571. if ( this.hasPlaybackControl === false ) {
  21572. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21573. return;
  21574. }
  21575. this.playbackRate = value;
  21576. if ( this.isPlaying === true ) {
  21577. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  21578. }
  21579. return this;
  21580. },
  21581. getPlaybackRate: function () {
  21582. return this.playbackRate;
  21583. },
  21584. onEnded: function () {
  21585. this.isPlaying = false;
  21586. },
  21587. getLoop: function () {
  21588. if ( this.hasPlaybackControl === false ) {
  21589. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21590. return false;
  21591. }
  21592. return this.loop;
  21593. },
  21594. setLoop: function ( value ) {
  21595. if ( this.hasPlaybackControl === false ) {
  21596. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21597. return;
  21598. }
  21599. this.loop = value;
  21600. if ( this.isPlaying === true ) {
  21601. this.source.loop = this.loop;
  21602. }
  21603. return this;
  21604. },
  21605. getVolume: function () {
  21606. return this.gain.gain.value;
  21607. },
  21608. setVolume: function ( value ) {
  21609. this.gain.gain.value = value;
  21610. return this;
  21611. }
  21612. } );
  21613. /**
  21614. * @author mrdoob / http://mrdoob.com/
  21615. */
  21616. function PositionalAudio( listener ) {
  21617. Audio.call( this, listener );
  21618. this.panner = this.context.createPanner();
  21619. this.panner.connect( this.gain );
  21620. }
  21621. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  21622. constructor: PositionalAudio,
  21623. getOutput: function () {
  21624. return this.panner;
  21625. },
  21626. getRefDistance: function () {
  21627. return this.panner.refDistance;
  21628. },
  21629. setRefDistance: function ( value ) {
  21630. this.panner.refDistance = value;
  21631. },
  21632. getRolloffFactor: function () {
  21633. return this.panner.rolloffFactor;
  21634. },
  21635. setRolloffFactor: function ( value ) {
  21636. this.panner.rolloffFactor = value;
  21637. },
  21638. getDistanceModel: function () {
  21639. return this.panner.distanceModel;
  21640. },
  21641. setDistanceModel: function ( value ) {
  21642. this.panner.distanceModel = value;
  21643. },
  21644. getMaxDistance: function () {
  21645. return this.panner.maxDistance;
  21646. },
  21647. setMaxDistance: function ( value ) {
  21648. this.panner.maxDistance = value;
  21649. },
  21650. updateMatrixWorld: ( function () {
  21651. var position = new Vector3();
  21652. return function updateMatrixWorld( force ) {
  21653. Object3D.prototype.updateMatrixWorld.call( this, force );
  21654. position.setFromMatrixPosition( this.matrixWorld );
  21655. this.panner.setPosition( position.x, position.y, position.z );
  21656. };
  21657. } )()
  21658. } );
  21659. /**
  21660. * @author mrdoob / http://mrdoob.com/
  21661. */
  21662. function AudioAnalyser( audio, fftSize ) {
  21663. this.analyser = audio.context.createAnalyser();
  21664. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  21665. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  21666. audio.getOutput().connect( this.analyser );
  21667. }
  21668. Object.assign( AudioAnalyser.prototype, {
  21669. getFrequencyData: function () {
  21670. this.analyser.getByteFrequencyData( this.data );
  21671. return this.data;
  21672. },
  21673. getAverageFrequency: function () {
  21674. var value = 0, data = this.getFrequencyData();
  21675. for ( var i = 0; i < data.length; i ++ ) {
  21676. value += data[ i ];
  21677. }
  21678. return value / data.length;
  21679. }
  21680. } );
  21681. /**
  21682. *
  21683. * Buffered scene graph property that allows weighted accumulation.
  21684. *
  21685. *
  21686. * @author Ben Houston / http://clara.io/
  21687. * @author David Sarno / http://lighthaus.us/
  21688. * @author tschw
  21689. */
  21690. function PropertyMixer( binding, typeName, valueSize ) {
  21691. this.binding = binding;
  21692. this.valueSize = valueSize;
  21693. var bufferType = Float64Array,
  21694. mixFunction;
  21695. switch ( typeName ) {
  21696. case 'quaternion': mixFunction = this._slerp; break;
  21697. case 'string':
  21698. case 'bool':
  21699. bufferType = Array, mixFunction = this._select; break;
  21700. default: mixFunction = this._lerp;
  21701. }
  21702. this.buffer = new bufferType( valueSize * 4 );
  21703. // layout: [ incoming | accu0 | accu1 | orig ]
  21704. //
  21705. // interpolators can use .buffer as their .result
  21706. // the data then goes to 'incoming'
  21707. //
  21708. // 'accu0' and 'accu1' are used frame-interleaved for
  21709. // the cumulative result and are compared to detect
  21710. // changes
  21711. //
  21712. // 'orig' stores the original state of the property
  21713. this._mixBufferRegion = mixFunction;
  21714. this.cumulativeWeight = 0;
  21715. this.useCount = 0;
  21716. this.referenceCount = 0;
  21717. }
  21718. PropertyMixer.prototype = {
  21719. constructor: PropertyMixer,
  21720. // accumulate data in the 'incoming' region into 'accu<i>'
  21721. accumulate: function( accuIndex, weight ) {
  21722. // note: happily accumulating nothing when weight = 0, the caller knows
  21723. // the weight and shouldn't have made the call in the first place
  21724. var buffer = this.buffer,
  21725. stride = this.valueSize,
  21726. offset = accuIndex * stride + stride,
  21727. currentWeight = this.cumulativeWeight;
  21728. if ( currentWeight === 0 ) {
  21729. // accuN := incoming * weight
  21730. for ( var i = 0; i !== stride; ++ i ) {
  21731. buffer[ offset + i ] = buffer[ i ];
  21732. }
  21733. currentWeight = weight;
  21734. } else {
  21735. // accuN := accuN + incoming * weight
  21736. currentWeight += weight;
  21737. var mix = weight / currentWeight;
  21738. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  21739. }
  21740. this.cumulativeWeight = currentWeight;
  21741. },
  21742. // apply the state of 'accu<i>' to the binding when accus differ
  21743. apply: function( accuIndex ) {
  21744. var stride = this.valueSize,
  21745. buffer = this.buffer,
  21746. offset = accuIndex * stride + stride,
  21747. weight = this.cumulativeWeight,
  21748. binding = this.binding;
  21749. this.cumulativeWeight = 0;
  21750. if ( weight < 1 ) {
  21751. // accuN := accuN + original * ( 1 - cumulativeWeight )
  21752. var originalValueOffset = stride * 3;
  21753. this._mixBufferRegion(
  21754. buffer, offset, originalValueOffset, 1 - weight, stride );
  21755. }
  21756. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  21757. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  21758. // value has changed -> update scene graph
  21759. binding.setValue( buffer, offset );
  21760. break;
  21761. }
  21762. }
  21763. },
  21764. // remember the state of the bound property and copy it to both accus
  21765. saveOriginalState: function() {
  21766. var binding = this.binding;
  21767. var buffer = this.buffer,
  21768. stride = this.valueSize,
  21769. originalValueOffset = stride * 3;
  21770. binding.getValue( buffer, originalValueOffset );
  21771. // accu[0..1] := orig -- initially detect changes against the original
  21772. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  21773. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  21774. }
  21775. this.cumulativeWeight = 0;
  21776. },
  21777. // apply the state previously taken via 'saveOriginalState' to the binding
  21778. restoreOriginalState: function() {
  21779. var originalValueOffset = this.valueSize * 3;
  21780. this.binding.setValue( this.buffer, originalValueOffset );
  21781. },
  21782. // mix functions
  21783. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  21784. if ( t >= 0.5 ) {
  21785. for ( var i = 0; i !== stride; ++ i ) {
  21786. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  21787. }
  21788. }
  21789. },
  21790. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  21791. Quaternion.slerpFlat( buffer, dstOffset,
  21792. buffer, dstOffset, buffer, srcOffset, t );
  21793. },
  21794. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  21795. var s = 1 - t;
  21796. for ( var i = 0; i !== stride; ++ i ) {
  21797. var j = dstOffset + i;
  21798. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  21799. }
  21800. }
  21801. };
  21802. /**
  21803. *
  21804. * A reference to a real property in the scene graph.
  21805. *
  21806. *
  21807. * @author Ben Houston / http://clara.io/
  21808. * @author David Sarno / http://lighthaus.us/
  21809. * @author tschw
  21810. */
  21811. function PropertyBinding( rootNode, path, parsedPath ) {
  21812. this.path = path;
  21813. this.parsedPath = parsedPath ||
  21814. PropertyBinding.parseTrackName( path );
  21815. this.node = PropertyBinding.findNode(
  21816. rootNode, this.parsedPath.nodeName ) || rootNode;
  21817. this.rootNode = rootNode;
  21818. }
  21819. PropertyBinding.prototype = {
  21820. constructor: PropertyBinding,
  21821. getValue: function getValue_unbound( targetArray, offset ) {
  21822. this.bind();
  21823. this.getValue( targetArray, offset );
  21824. // Note: This class uses a State pattern on a per-method basis:
  21825. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  21826. // prototype version of these methods with one that represents
  21827. // the bound state. When the property is not found, the methods
  21828. // become no-ops.
  21829. },
  21830. setValue: function getValue_unbound( sourceArray, offset ) {
  21831. this.bind();
  21832. this.setValue( sourceArray, offset );
  21833. },
  21834. // create getter / setter pair for a property in the scene graph
  21835. bind: function() {
  21836. var targetObject = this.node,
  21837. parsedPath = this.parsedPath,
  21838. objectName = parsedPath.objectName,
  21839. propertyName = parsedPath.propertyName,
  21840. propertyIndex = parsedPath.propertyIndex;
  21841. if ( ! targetObject ) {
  21842. targetObject = PropertyBinding.findNode(
  21843. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  21844. this.node = targetObject;
  21845. }
  21846. // set fail state so we can just 'return' on error
  21847. this.getValue = this._getValue_unavailable;
  21848. this.setValue = this._setValue_unavailable;
  21849. // ensure there is a value node
  21850. if ( ! targetObject ) {
  21851. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  21852. return;
  21853. }
  21854. if ( objectName ) {
  21855. var objectIndex = parsedPath.objectIndex;
  21856. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  21857. switch ( objectName ) {
  21858. case 'materials':
  21859. if ( ! targetObject.material ) {
  21860. console.error( ' can not bind to material as node does not have a material', this );
  21861. return;
  21862. }
  21863. if ( ! targetObject.material.materials ) {
  21864. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  21865. return;
  21866. }
  21867. targetObject = targetObject.material.materials;
  21868. break;
  21869. case 'bones':
  21870. if ( ! targetObject.skeleton ) {
  21871. console.error( ' can not bind to bones as node does not have a skeleton', this );
  21872. return;
  21873. }
  21874. // potential future optimization: skip this if propertyIndex is already an integer
  21875. // and convert the integer string to a true integer.
  21876. targetObject = targetObject.skeleton.bones;
  21877. // support resolving morphTarget names into indices.
  21878. for ( var i = 0; i < targetObject.length; i ++ ) {
  21879. if ( targetObject[ i ].name === objectIndex ) {
  21880. objectIndex = i;
  21881. break;
  21882. }
  21883. }
  21884. break;
  21885. default:
  21886. if ( targetObject[ objectName ] === undefined ) {
  21887. console.error( ' can not bind to objectName of node, undefined', this );
  21888. return;
  21889. }
  21890. targetObject = targetObject[ objectName ];
  21891. }
  21892. if ( objectIndex !== undefined ) {
  21893. if ( targetObject[ objectIndex ] === undefined ) {
  21894. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  21895. return;
  21896. }
  21897. targetObject = targetObject[ objectIndex ];
  21898. }
  21899. }
  21900. // resolve property
  21901. var nodeProperty = targetObject[ propertyName ];
  21902. if ( nodeProperty === undefined ) {
  21903. var nodeName = parsedPath.nodeName;
  21904. console.error( " trying to update property for track: " + nodeName +
  21905. '.' + propertyName + " but it wasn't found.", targetObject );
  21906. return;
  21907. }
  21908. // determine versioning scheme
  21909. var versioning = this.Versioning.None;
  21910. if ( targetObject.needsUpdate !== undefined ) { // material
  21911. versioning = this.Versioning.NeedsUpdate;
  21912. this.targetObject = targetObject;
  21913. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  21914. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  21915. this.targetObject = targetObject;
  21916. }
  21917. // determine how the property gets bound
  21918. var bindingType = this.BindingType.Direct;
  21919. if ( propertyIndex !== undefined ) {
  21920. // access a sub element of the property array (only primitives are supported right now)
  21921. if ( propertyName === "morphTargetInfluences" ) {
  21922. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  21923. // support resolving morphTarget names into indices.
  21924. if ( ! targetObject.geometry ) {
  21925. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  21926. return;
  21927. }
  21928. if ( ! targetObject.geometry.morphTargets ) {
  21929. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  21930. return;
  21931. }
  21932. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  21933. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  21934. propertyIndex = i;
  21935. break;
  21936. }
  21937. }
  21938. }
  21939. bindingType = this.BindingType.ArrayElement;
  21940. this.resolvedProperty = nodeProperty;
  21941. this.propertyIndex = propertyIndex;
  21942. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  21943. // must use copy for Object3D.Euler/Quaternion
  21944. bindingType = this.BindingType.HasFromToArray;
  21945. this.resolvedProperty = nodeProperty;
  21946. } else if ( nodeProperty.length !== undefined ) {
  21947. bindingType = this.BindingType.EntireArray;
  21948. this.resolvedProperty = nodeProperty;
  21949. } else {
  21950. this.propertyName = propertyName;
  21951. }
  21952. // select getter / setter
  21953. this.getValue = this.GetterByBindingType[ bindingType ];
  21954. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  21955. },
  21956. unbind: function() {
  21957. this.node = null;
  21958. // back to the prototype version of getValue / setValue
  21959. // note: avoiding to mutate the shape of 'this' via 'delete'
  21960. this.getValue = this._getValue_unbound;
  21961. this.setValue = this._setValue_unbound;
  21962. }
  21963. };
  21964. Object.assign( PropertyBinding.prototype, { // prototype, continued
  21965. // these are used to "bind" a nonexistent property
  21966. _getValue_unavailable: function() {},
  21967. _setValue_unavailable: function() {},
  21968. // initial state of these methods that calls 'bind'
  21969. _getValue_unbound: PropertyBinding.prototype.getValue,
  21970. _setValue_unbound: PropertyBinding.prototype.setValue,
  21971. BindingType: {
  21972. Direct: 0,
  21973. EntireArray: 1,
  21974. ArrayElement: 2,
  21975. HasFromToArray: 3
  21976. },
  21977. Versioning: {
  21978. None: 0,
  21979. NeedsUpdate: 1,
  21980. MatrixWorldNeedsUpdate: 2
  21981. },
  21982. GetterByBindingType: [
  21983. function getValue_direct( buffer, offset ) {
  21984. buffer[ offset ] = this.node[ this.propertyName ];
  21985. },
  21986. function getValue_array( buffer, offset ) {
  21987. var source = this.resolvedProperty;
  21988. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  21989. buffer[ offset ++ ] = source[ i ];
  21990. }
  21991. },
  21992. function getValue_arrayElement( buffer, offset ) {
  21993. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  21994. },
  21995. function getValue_toArray( buffer, offset ) {
  21996. this.resolvedProperty.toArray( buffer, offset );
  21997. }
  21998. ],
  21999. SetterByBindingTypeAndVersioning: [
  22000. [
  22001. // Direct
  22002. function setValue_direct( buffer, offset ) {
  22003. this.node[ this.propertyName ] = buffer[ offset ];
  22004. },
  22005. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  22006. this.node[ this.propertyName ] = buffer[ offset ];
  22007. this.targetObject.needsUpdate = true;
  22008. },
  22009. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22010. this.node[ this.propertyName ] = buffer[ offset ];
  22011. this.targetObject.matrixWorldNeedsUpdate = true;
  22012. }
  22013. ], [
  22014. // EntireArray
  22015. function setValue_array( buffer, offset ) {
  22016. var dest = this.resolvedProperty;
  22017. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22018. dest[ i ] = buffer[ offset ++ ];
  22019. }
  22020. },
  22021. function setValue_array_setNeedsUpdate( buffer, offset ) {
  22022. var dest = this.resolvedProperty;
  22023. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22024. dest[ i ] = buffer[ offset ++ ];
  22025. }
  22026. this.targetObject.needsUpdate = true;
  22027. },
  22028. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22029. var dest = this.resolvedProperty;
  22030. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22031. dest[ i ] = buffer[ offset ++ ];
  22032. }
  22033. this.targetObject.matrixWorldNeedsUpdate = true;
  22034. }
  22035. ], [
  22036. // ArrayElement
  22037. function setValue_arrayElement( buffer, offset ) {
  22038. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22039. },
  22040. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  22041. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22042. this.targetObject.needsUpdate = true;
  22043. },
  22044. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22045. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22046. this.targetObject.matrixWorldNeedsUpdate = true;
  22047. }
  22048. ], [
  22049. // HasToFromArray
  22050. function setValue_fromArray( buffer, offset ) {
  22051. this.resolvedProperty.fromArray( buffer, offset );
  22052. },
  22053. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  22054. this.resolvedProperty.fromArray( buffer, offset );
  22055. this.targetObject.needsUpdate = true;
  22056. },
  22057. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22058. this.resolvedProperty.fromArray( buffer, offset );
  22059. this.targetObject.matrixWorldNeedsUpdate = true;
  22060. }
  22061. ]
  22062. ]
  22063. } );
  22064. PropertyBinding.Composite =
  22065. function( targetGroup, path, optionalParsedPath ) {
  22066. var parsedPath = optionalParsedPath ||
  22067. PropertyBinding.parseTrackName( path );
  22068. this._targetGroup = targetGroup;
  22069. this._bindings = targetGroup.subscribe_( path, parsedPath );
  22070. };
  22071. PropertyBinding.Composite.prototype = {
  22072. constructor: PropertyBinding.Composite,
  22073. getValue: function( array, offset ) {
  22074. this.bind(); // bind all binding
  22075. var firstValidIndex = this._targetGroup.nCachedObjects_,
  22076. binding = this._bindings[ firstValidIndex ];
  22077. // and only call .getValue on the first
  22078. if ( binding !== undefined ) binding.getValue( array, offset );
  22079. },
  22080. setValue: function( array, offset ) {
  22081. var bindings = this._bindings;
  22082. for ( var i = this._targetGroup.nCachedObjects_,
  22083. n = bindings.length; i !== n; ++ i ) {
  22084. bindings[ i ].setValue( array, offset );
  22085. }
  22086. },
  22087. bind: function() {
  22088. var bindings = this._bindings;
  22089. for ( var i = this._targetGroup.nCachedObjects_,
  22090. n = bindings.length; i !== n; ++ i ) {
  22091. bindings[ i ].bind();
  22092. }
  22093. },
  22094. unbind: function() {
  22095. var bindings = this._bindings;
  22096. for ( var i = this._targetGroup.nCachedObjects_,
  22097. n = bindings.length; i !== n; ++ i ) {
  22098. bindings[ i ].unbind();
  22099. }
  22100. }
  22101. };
  22102. PropertyBinding.create = function( root, path, parsedPath ) {
  22103. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  22104. return new PropertyBinding( root, path, parsedPath );
  22105. } else {
  22106. return new PropertyBinding.Composite( root, path, parsedPath );
  22107. }
  22108. };
  22109. PropertyBinding.parseTrackName = function( trackName ) {
  22110. // matches strings in the form of:
  22111. // nodeName.property
  22112. // nodeName.property[accessor]
  22113. // nodeName.material.property[accessor]
  22114. // uuid.property[accessor]
  22115. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  22116. // parentName/nodeName.property
  22117. // parentName/parentName/nodeName.property[index]
  22118. // .bone[Armature.DEF_cog].position
  22119. // scene:helium_balloon_model:helium_balloon_model.position
  22120. // created and tested via https://regex101.com/#javascript
  22121. var re = /^((?:[\w-]+[\/:])*)([\w-]+)?(?:\.([\w-]+)(?:\[(.+)\])?)?\.([\w-]+)(?:\[(.+)\])?$/;
  22122. var matches = re.exec( trackName );
  22123. if ( ! matches ) {
  22124. throw new Error( "cannot parse trackName at all: " + trackName );
  22125. }
  22126. var results = {
  22127. // directoryName: matches[ 1 ], // (tschw) currently unused
  22128. nodeName: matches[ 2 ], // allowed to be null, specified root node.
  22129. objectName: matches[ 3 ],
  22130. objectIndex: matches[ 4 ],
  22131. propertyName: matches[ 5 ],
  22132. propertyIndex: matches[ 6 ] // allowed to be null, specifies that the whole property is set.
  22133. };
  22134. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  22135. throw new Error( "can not parse propertyName from trackName: " + trackName );
  22136. }
  22137. return results;
  22138. };
  22139. PropertyBinding.findNode = function( root, nodeName ) {
  22140. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  22141. return root;
  22142. }
  22143. // search into skeleton bones.
  22144. if ( root.skeleton ) {
  22145. var searchSkeleton = function( skeleton ) {
  22146. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  22147. var bone = skeleton.bones[ i ];
  22148. if ( bone.name === nodeName ) {
  22149. return bone;
  22150. }
  22151. }
  22152. return null;
  22153. };
  22154. var bone = searchSkeleton( root.skeleton );
  22155. if ( bone ) {
  22156. return bone;
  22157. }
  22158. }
  22159. // search into node subtree.
  22160. if ( root.children ) {
  22161. var searchNodeSubtree = function( children ) {
  22162. for( var i = 0; i < children.length; i ++ ) {
  22163. var childNode = children[ i ];
  22164. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  22165. return childNode;
  22166. }
  22167. var result = searchNodeSubtree( childNode.children );
  22168. if ( result ) return result;
  22169. }
  22170. return null;
  22171. };
  22172. var subTreeNode = searchNodeSubtree( root.children );
  22173. if ( subTreeNode ) {
  22174. return subTreeNode;
  22175. }
  22176. }
  22177. return null;
  22178. };
  22179. /**
  22180. *
  22181. * A group of objects that receives a shared animation state.
  22182. *
  22183. * Usage:
  22184. *
  22185. * - Add objects you would otherwise pass as 'root' to the
  22186. * constructor or the .clipAction method of AnimationMixer.
  22187. *
  22188. * - Instead pass this object as 'root'.
  22189. *
  22190. * - You can also add and remove objects later when the mixer
  22191. * is running.
  22192. *
  22193. * Note:
  22194. *
  22195. * Objects of this class appear as one object to the mixer,
  22196. * so cache control of the individual objects must be done
  22197. * on the group.
  22198. *
  22199. * Limitation:
  22200. *
  22201. * - The animated properties must be compatible among the
  22202. * all objects in the group.
  22203. *
  22204. * - A single property can either be controlled through a
  22205. * target group or directly, but not both.
  22206. *
  22207. * @author tschw
  22208. */
  22209. function AnimationObjectGroup( var_args ) {
  22210. this.uuid = _Math.generateUUID();
  22211. // cached objects followed by the active ones
  22212. this._objects = Array.prototype.slice.call( arguments );
  22213. this.nCachedObjects_ = 0; // threshold
  22214. // note: read by PropertyBinding.Composite
  22215. var indices = {};
  22216. this._indicesByUUID = indices; // for bookkeeping
  22217. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22218. indices[ arguments[ i ].uuid ] = i;
  22219. }
  22220. this._paths = []; // inside: string
  22221. this._parsedPaths = []; // inside: { we don't care, here }
  22222. this._bindings = []; // inside: Array< PropertyBinding >
  22223. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  22224. var scope = this;
  22225. this.stats = {
  22226. objects: {
  22227. get total() { return scope._objects.length; },
  22228. get inUse() { return this.total - scope.nCachedObjects_; }
  22229. },
  22230. get bindingsPerObject() { return scope._bindings.length; }
  22231. };
  22232. }
  22233. AnimationObjectGroup.prototype = {
  22234. constructor: AnimationObjectGroup,
  22235. isAnimationObjectGroup: true,
  22236. add: function( var_args ) {
  22237. var objects = this._objects,
  22238. nObjects = objects.length,
  22239. nCachedObjects = this.nCachedObjects_,
  22240. indicesByUUID = this._indicesByUUID,
  22241. paths = this._paths,
  22242. parsedPaths = this._parsedPaths,
  22243. bindings = this._bindings,
  22244. nBindings = bindings.length;
  22245. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22246. var object = arguments[ i ],
  22247. uuid = object.uuid,
  22248. index = indicesByUUID[ uuid ];
  22249. if ( index === undefined ) {
  22250. // unknown object -> add it to the ACTIVE region
  22251. index = nObjects ++;
  22252. indicesByUUID[ uuid ] = index;
  22253. objects.push( object );
  22254. // accounting is done, now do the same for all bindings
  22255. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22256. bindings[ j ].push(
  22257. new PropertyBinding(
  22258. object, paths[ j ], parsedPaths[ j ] ) );
  22259. }
  22260. } else if ( index < nCachedObjects ) {
  22261. var knownObject = objects[ index ];
  22262. // move existing object to the ACTIVE region
  22263. var firstActiveIndex = -- nCachedObjects,
  22264. lastCachedObject = objects[ firstActiveIndex ];
  22265. indicesByUUID[ lastCachedObject.uuid ] = index;
  22266. objects[ index ] = lastCachedObject;
  22267. indicesByUUID[ uuid ] = firstActiveIndex;
  22268. objects[ firstActiveIndex ] = object;
  22269. // accounting is done, now do the same for all bindings
  22270. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22271. var bindingsForPath = bindings[ j ],
  22272. lastCached = bindingsForPath[ firstActiveIndex ],
  22273. binding = bindingsForPath[ index ];
  22274. bindingsForPath[ index ] = lastCached;
  22275. if ( binding === undefined ) {
  22276. // since we do not bother to create new bindings
  22277. // for objects that are cached, the binding may
  22278. // or may not exist
  22279. binding = new PropertyBinding(
  22280. object, paths[ j ], parsedPaths[ j ] );
  22281. }
  22282. bindingsForPath[ firstActiveIndex ] = binding;
  22283. }
  22284. } else if ( objects[ index ] !== knownObject) {
  22285. console.error( "Different objects with the same UUID " +
  22286. "detected. Clean the caches or recreate your " +
  22287. "infrastructure when reloading scenes..." );
  22288. } // else the object is already where we want it to be
  22289. } // for arguments
  22290. this.nCachedObjects_ = nCachedObjects;
  22291. },
  22292. remove: function( var_args ) {
  22293. var objects = this._objects,
  22294. nCachedObjects = this.nCachedObjects_,
  22295. indicesByUUID = this._indicesByUUID,
  22296. bindings = this._bindings,
  22297. nBindings = bindings.length;
  22298. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22299. var object = arguments[ i ],
  22300. uuid = object.uuid,
  22301. index = indicesByUUID[ uuid ];
  22302. if ( index !== undefined && index >= nCachedObjects ) {
  22303. // move existing object into the CACHED region
  22304. var lastCachedIndex = nCachedObjects ++,
  22305. firstActiveObject = objects[ lastCachedIndex ];
  22306. indicesByUUID[ firstActiveObject.uuid ] = index;
  22307. objects[ index ] = firstActiveObject;
  22308. indicesByUUID[ uuid ] = lastCachedIndex;
  22309. objects[ lastCachedIndex ] = object;
  22310. // accounting is done, now do the same for all bindings
  22311. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22312. var bindingsForPath = bindings[ j ],
  22313. firstActive = bindingsForPath[ lastCachedIndex ],
  22314. binding = bindingsForPath[ index ];
  22315. bindingsForPath[ index ] = firstActive;
  22316. bindingsForPath[ lastCachedIndex ] = binding;
  22317. }
  22318. }
  22319. } // for arguments
  22320. this.nCachedObjects_ = nCachedObjects;
  22321. },
  22322. // remove & forget
  22323. uncache: function( var_args ) {
  22324. var objects = this._objects,
  22325. nObjects = objects.length,
  22326. nCachedObjects = this.nCachedObjects_,
  22327. indicesByUUID = this._indicesByUUID,
  22328. bindings = this._bindings,
  22329. nBindings = bindings.length;
  22330. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22331. var object = arguments[ i ],
  22332. uuid = object.uuid,
  22333. index = indicesByUUID[ uuid ];
  22334. if ( index !== undefined ) {
  22335. delete indicesByUUID[ uuid ];
  22336. if ( index < nCachedObjects ) {
  22337. // object is cached, shrink the CACHED region
  22338. var firstActiveIndex = -- nCachedObjects,
  22339. lastCachedObject = objects[ firstActiveIndex ],
  22340. lastIndex = -- nObjects,
  22341. lastObject = objects[ lastIndex ];
  22342. // last cached object takes this object's place
  22343. indicesByUUID[ lastCachedObject.uuid ] = index;
  22344. objects[ index ] = lastCachedObject;
  22345. // last object goes to the activated slot and pop
  22346. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  22347. objects[ firstActiveIndex ] = lastObject;
  22348. objects.pop();
  22349. // accounting is done, now do the same for all bindings
  22350. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22351. var bindingsForPath = bindings[ j ],
  22352. lastCached = bindingsForPath[ firstActiveIndex ],
  22353. last = bindingsForPath[ lastIndex ];
  22354. bindingsForPath[ index ] = lastCached;
  22355. bindingsForPath[ firstActiveIndex ] = last;
  22356. bindingsForPath.pop();
  22357. }
  22358. } else {
  22359. // object is active, just swap with the last and pop
  22360. var lastIndex = -- nObjects,
  22361. lastObject = objects[ lastIndex ];
  22362. indicesByUUID[ lastObject.uuid ] = index;
  22363. objects[ index ] = lastObject;
  22364. objects.pop();
  22365. // accounting is done, now do the same for all bindings
  22366. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22367. var bindingsForPath = bindings[ j ];
  22368. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  22369. bindingsForPath.pop();
  22370. }
  22371. } // cached or active
  22372. } // if object is known
  22373. } // for arguments
  22374. this.nCachedObjects_ = nCachedObjects;
  22375. },
  22376. // Internal interface used by befriended PropertyBinding.Composite:
  22377. subscribe_: function( path, parsedPath ) {
  22378. // returns an array of bindings for the given path that is changed
  22379. // according to the contained objects in the group
  22380. var indicesByPath = this._bindingsIndicesByPath,
  22381. index = indicesByPath[ path ],
  22382. bindings = this._bindings;
  22383. if ( index !== undefined ) return bindings[ index ];
  22384. var paths = this._paths,
  22385. parsedPaths = this._parsedPaths,
  22386. objects = this._objects,
  22387. nObjects = objects.length,
  22388. nCachedObjects = this.nCachedObjects_,
  22389. bindingsForPath = new Array( nObjects );
  22390. index = bindings.length;
  22391. indicesByPath[ path ] = index;
  22392. paths.push( path );
  22393. parsedPaths.push( parsedPath );
  22394. bindings.push( bindingsForPath );
  22395. for ( var i = nCachedObjects,
  22396. n = objects.length; i !== n; ++ i ) {
  22397. var object = objects[ i ];
  22398. bindingsForPath[ i ] =
  22399. new PropertyBinding( object, path, parsedPath );
  22400. }
  22401. return bindingsForPath;
  22402. },
  22403. unsubscribe_: function( path ) {
  22404. // tells the group to forget about a property path and no longer
  22405. // update the array previously obtained with 'subscribe_'
  22406. var indicesByPath = this._bindingsIndicesByPath,
  22407. index = indicesByPath[ path ];
  22408. if ( index !== undefined ) {
  22409. var paths = this._paths,
  22410. parsedPaths = this._parsedPaths,
  22411. bindings = this._bindings,
  22412. lastBindingsIndex = bindings.length - 1,
  22413. lastBindings = bindings[ lastBindingsIndex ],
  22414. lastBindingsPath = path[ lastBindingsIndex ];
  22415. indicesByPath[ lastBindingsPath ] = index;
  22416. bindings[ index ] = lastBindings;
  22417. bindings.pop();
  22418. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  22419. parsedPaths.pop();
  22420. paths[ index ] = paths[ lastBindingsIndex ];
  22421. paths.pop();
  22422. }
  22423. }
  22424. };
  22425. /**
  22426. *
  22427. * Action provided by AnimationMixer for scheduling clip playback on specific
  22428. * objects.
  22429. *
  22430. * @author Ben Houston / http://clara.io/
  22431. * @author David Sarno / http://lighthaus.us/
  22432. * @author tschw
  22433. *
  22434. */
  22435. function AnimationAction( mixer, clip, localRoot ) {
  22436. this._mixer = mixer;
  22437. this._clip = clip;
  22438. this._localRoot = localRoot || null;
  22439. var tracks = clip.tracks,
  22440. nTracks = tracks.length,
  22441. interpolants = new Array( nTracks );
  22442. var interpolantSettings = {
  22443. endingStart: ZeroCurvatureEnding,
  22444. endingEnd: ZeroCurvatureEnding
  22445. };
  22446. for ( var i = 0; i !== nTracks; ++ i ) {
  22447. var interpolant = tracks[ i ].createInterpolant( null );
  22448. interpolants[ i ] = interpolant;
  22449. interpolant.settings = interpolantSettings;
  22450. }
  22451. this._interpolantSettings = interpolantSettings;
  22452. this._interpolants = interpolants; // bound by the mixer
  22453. // inside: PropertyMixer (managed by the mixer)
  22454. this._propertyBindings = new Array( nTracks );
  22455. this._cacheIndex = null; // for the memory manager
  22456. this._byClipCacheIndex = null; // for the memory manager
  22457. this._timeScaleInterpolant = null;
  22458. this._weightInterpolant = null;
  22459. this.loop = LoopRepeat;
  22460. this._loopCount = -1;
  22461. // global mixer time when the action is to be started
  22462. // it's set back to 'null' upon start of the action
  22463. this._startTime = null;
  22464. // scaled local time of the action
  22465. // gets clamped or wrapped to 0..clip.duration according to loop
  22466. this.time = 0;
  22467. this.timeScale = 1;
  22468. this._effectiveTimeScale = 1;
  22469. this.weight = 1;
  22470. this._effectiveWeight = 1;
  22471. this.repetitions = Infinity; // no. of repetitions when looping
  22472. this.paused = false; // false -> zero effective time scale
  22473. this.enabled = true; // true -> zero effective weight
  22474. this.clampWhenFinished = false; // keep feeding the last frame?
  22475. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  22476. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  22477. }
  22478. AnimationAction.prototype = {
  22479. constructor: AnimationAction,
  22480. // State & Scheduling
  22481. play: function() {
  22482. this._mixer._activateAction( this );
  22483. return this;
  22484. },
  22485. stop: function() {
  22486. this._mixer._deactivateAction( this );
  22487. return this.reset();
  22488. },
  22489. reset: function() {
  22490. this.paused = false;
  22491. this.enabled = true;
  22492. this.time = 0; // restart clip
  22493. this._loopCount = -1; // forget previous loops
  22494. this._startTime = null; // forget scheduling
  22495. return this.stopFading().stopWarping();
  22496. },
  22497. isRunning: function() {
  22498. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  22499. this._startTime === null && this._mixer._isActiveAction( this );
  22500. },
  22501. // return true when play has been called
  22502. isScheduled: function() {
  22503. return this._mixer._isActiveAction( this );
  22504. },
  22505. startAt: function( time ) {
  22506. this._startTime = time;
  22507. return this;
  22508. },
  22509. setLoop: function( mode, repetitions ) {
  22510. this.loop = mode;
  22511. this.repetitions = repetitions;
  22512. return this;
  22513. },
  22514. // Weight
  22515. // set the weight stopping any scheduled fading
  22516. // although .enabled = false yields an effective weight of zero, this
  22517. // method does *not* change .enabled, because it would be confusing
  22518. setEffectiveWeight: function( weight ) {
  22519. this.weight = weight;
  22520. // note: same logic as when updated at runtime
  22521. this._effectiveWeight = this.enabled ? weight : 0;
  22522. return this.stopFading();
  22523. },
  22524. // return the weight considering fading and .enabled
  22525. getEffectiveWeight: function() {
  22526. return this._effectiveWeight;
  22527. },
  22528. fadeIn: function( duration ) {
  22529. return this._scheduleFading( duration, 0, 1 );
  22530. },
  22531. fadeOut: function( duration ) {
  22532. return this._scheduleFading( duration, 1, 0 );
  22533. },
  22534. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  22535. fadeOutAction.fadeOut( duration );
  22536. this.fadeIn( duration );
  22537. if( warp ) {
  22538. var fadeInDuration = this._clip.duration,
  22539. fadeOutDuration = fadeOutAction._clip.duration,
  22540. startEndRatio = fadeOutDuration / fadeInDuration,
  22541. endStartRatio = fadeInDuration / fadeOutDuration;
  22542. fadeOutAction.warp( 1.0, startEndRatio, duration );
  22543. this.warp( endStartRatio, 1.0, duration );
  22544. }
  22545. return this;
  22546. },
  22547. crossFadeTo: function( fadeInAction, duration, warp ) {
  22548. return fadeInAction.crossFadeFrom( this, duration, warp );
  22549. },
  22550. stopFading: function() {
  22551. var weightInterpolant = this._weightInterpolant;
  22552. if ( weightInterpolant !== null ) {
  22553. this._weightInterpolant = null;
  22554. this._mixer._takeBackControlInterpolant( weightInterpolant );
  22555. }
  22556. return this;
  22557. },
  22558. // Time Scale Control
  22559. // set the weight stopping any scheduled warping
  22560. // although .paused = true yields an effective time scale of zero, this
  22561. // method does *not* change .paused, because it would be confusing
  22562. setEffectiveTimeScale: function( timeScale ) {
  22563. this.timeScale = timeScale;
  22564. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  22565. return this.stopWarping();
  22566. },
  22567. // return the time scale considering warping and .paused
  22568. getEffectiveTimeScale: function() {
  22569. return this._effectiveTimeScale;
  22570. },
  22571. setDuration: function( duration ) {
  22572. this.timeScale = this._clip.duration / duration;
  22573. return this.stopWarping();
  22574. },
  22575. syncWith: function( action ) {
  22576. this.time = action.time;
  22577. this.timeScale = action.timeScale;
  22578. return this.stopWarping();
  22579. },
  22580. halt: function( duration ) {
  22581. return this.warp( this._effectiveTimeScale, 0, duration );
  22582. },
  22583. warp: function( startTimeScale, endTimeScale, duration ) {
  22584. var mixer = this._mixer, now = mixer.time,
  22585. interpolant = this._timeScaleInterpolant,
  22586. timeScale = this.timeScale;
  22587. if ( interpolant === null ) {
  22588. interpolant = mixer._lendControlInterpolant(),
  22589. this._timeScaleInterpolant = interpolant;
  22590. }
  22591. var times = interpolant.parameterPositions,
  22592. values = interpolant.sampleValues;
  22593. times[ 0 ] = now;
  22594. times[ 1 ] = now + duration;
  22595. values[ 0 ] = startTimeScale / timeScale;
  22596. values[ 1 ] = endTimeScale / timeScale;
  22597. return this;
  22598. },
  22599. stopWarping: function() {
  22600. var timeScaleInterpolant = this._timeScaleInterpolant;
  22601. if ( timeScaleInterpolant !== null ) {
  22602. this._timeScaleInterpolant = null;
  22603. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  22604. }
  22605. return this;
  22606. },
  22607. // Object Accessors
  22608. getMixer: function() {
  22609. return this._mixer;
  22610. },
  22611. getClip: function() {
  22612. return this._clip;
  22613. },
  22614. getRoot: function() {
  22615. return this._localRoot || this._mixer._root;
  22616. },
  22617. // Interna
  22618. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  22619. // called by the mixer
  22620. var startTime = this._startTime;
  22621. if ( startTime !== null ) {
  22622. // check for scheduled start of action
  22623. var timeRunning = ( time - startTime ) * timeDirection;
  22624. if ( timeRunning < 0 || timeDirection === 0 ) {
  22625. return; // yet to come / don't decide when delta = 0
  22626. }
  22627. // start
  22628. this._startTime = null; // unschedule
  22629. deltaTime = timeDirection * timeRunning;
  22630. }
  22631. // apply time scale and advance time
  22632. deltaTime *= this._updateTimeScale( time );
  22633. var clipTime = this._updateTime( deltaTime );
  22634. // note: _updateTime may disable the action resulting in
  22635. // an effective weight of 0
  22636. var weight = this._updateWeight( time );
  22637. if ( weight > 0 ) {
  22638. var interpolants = this._interpolants;
  22639. var propertyMixers = this._propertyBindings;
  22640. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  22641. interpolants[ j ].evaluate( clipTime );
  22642. propertyMixers[ j ].accumulate( accuIndex, weight );
  22643. }
  22644. }
  22645. },
  22646. _updateWeight: function( time ) {
  22647. var weight = 0;
  22648. if ( this.enabled ) {
  22649. weight = this.weight;
  22650. var interpolant = this._weightInterpolant;
  22651. if ( interpolant !== null ) {
  22652. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  22653. weight *= interpolantValue;
  22654. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22655. this.stopFading();
  22656. if ( interpolantValue === 0 ) {
  22657. // faded out, disable
  22658. this.enabled = false;
  22659. }
  22660. }
  22661. }
  22662. }
  22663. this._effectiveWeight = weight;
  22664. return weight;
  22665. },
  22666. _updateTimeScale: function( time ) {
  22667. var timeScale = 0;
  22668. if ( ! this.paused ) {
  22669. timeScale = this.timeScale;
  22670. var interpolant = this._timeScaleInterpolant;
  22671. if ( interpolant !== null ) {
  22672. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  22673. timeScale *= interpolantValue;
  22674. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22675. this.stopWarping();
  22676. if ( timeScale === 0 ) {
  22677. // motion has halted, pause
  22678. this.paused = true;
  22679. } else {
  22680. // warp done - apply final time scale
  22681. this.timeScale = timeScale;
  22682. }
  22683. }
  22684. }
  22685. }
  22686. this._effectiveTimeScale = timeScale;
  22687. return timeScale;
  22688. },
  22689. _updateTime: function( deltaTime ) {
  22690. var time = this.time + deltaTime;
  22691. if ( deltaTime === 0 ) return time;
  22692. var duration = this._clip.duration,
  22693. loop = this.loop,
  22694. loopCount = this._loopCount;
  22695. if ( loop === LoopOnce ) {
  22696. if ( loopCount === -1 ) {
  22697. // just started
  22698. this.loopCount = 0;
  22699. this._setEndings( true, true, false );
  22700. }
  22701. handle_stop: {
  22702. if ( time >= duration ) {
  22703. time = duration;
  22704. } else if ( time < 0 ) {
  22705. time = 0;
  22706. } else break handle_stop;
  22707. if ( this.clampWhenFinished ) this.paused = true;
  22708. else this.enabled = false;
  22709. this._mixer.dispatchEvent( {
  22710. type: 'finished', action: this,
  22711. direction: deltaTime < 0 ? -1 : 1
  22712. } );
  22713. }
  22714. } else { // repetitive Repeat or PingPong
  22715. var pingPong = ( loop === LoopPingPong );
  22716. if ( loopCount === -1 ) {
  22717. // just started
  22718. if ( deltaTime >= 0 ) {
  22719. loopCount = 0;
  22720. this._setEndings(
  22721. true, this.repetitions === 0, pingPong );
  22722. } else {
  22723. // when looping in reverse direction, the initial
  22724. // transition through zero counts as a repetition,
  22725. // so leave loopCount at -1
  22726. this._setEndings(
  22727. this.repetitions === 0, true, pingPong );
  22728. }
  22729. }
  22730. if ( time >= duration || time < 0 ) {
  22731. // wrap around
  22732. var loopDelta = Math.floor( time / duration ); // signed
  22733. time -= duration * loopDelta;
  22734. loopCount += Math.abs( loopDelta );
  22735. var pending = this.repetitions - loopCount;
  22736. if ( pending < 0 ) {
  22737. // have to stop (switch state, clamp time, fire event)
  22738. if ( this.clampWhenFinished ) this.paused = true;
  22739. else this.enabled = false;
  22740. time = deltaTime > 0 ? duration : 0;
  22741. this._mixer.dispatchEvent( {
  22742. type: 'finished', action: this,
  22743. direction: deltaTime > 0 ? 1 : -1
  22744. } );
  22745. } else {
  22746. // keep running
  22747. if ( pending === 0 ) {
  22748. // entering the last round
  22749. var atStart = deltaTime < 0;
  22750. this._setEndings( atStart, ! atStart, pingPong );
  22751. } else {
  22752. this._setEndings( false, false, pingPong );
  22753. }
  22754. this._loopCount = loopCount;
  22755. this._mixer.dispatchEvent( {
  22756. type: 'loop', action: this, loopDelta: loopDelta
  22757. } );
  22758. }
  22759. }
  22760. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  22761. // invert time for the "pong round"
  22762. this.time = time;
  22763. return duration - time;
  22764. }
  22765. }
  22766. this.time = time;
  22767. return time;
  22768. },
  22769. _setEndings: function( atStart, atEnd, pingPong ) {
  22770. var settings = this._interpolantSettings;
  22771. if ( pingPong ) {
  22772. settings.endingStart = ZeroSlopeEnding;
  22773. settings.endingEnd = ZeroSlopeEnding;
  22774. } else {
  22775. // assuming for LoopOnce atStart == atEnd == true
  22776. if ( atStart ) {
  22777. settings.endingStart = this.zeroSlopeAtStart ?
  22778. ZeroSlopeEnding : ZeroCurvatureEnding;
  22779. } else {
  22780. settings.endingStart = WrapAroundEnding;
  22781. }
  22782. if ( atEnd ) {
  22783. settings.endingEnd = this.zeroSlopeAtEnd ?
  22784. ZeroSlopeEnding : ZeroCurvatureEnding;
  22785. } else {
  22786. settings.endingEnd = WrapAroundEnding;
  22787. }
  22788. }
  22789. },
  22790. _scheduleFading: function( duration, weightNow, weightThen ) {
  22791. var mixer = this._mixer, now = mixer.time,
  22792. interpolant = this._weightInterpolant;
  22793. if ( interpolant === null ) {
  22794. interpolant = mixer._lendControlInterpolant(),
  22795. this._weightInterpolant = interpolant;
  22796. }
  22797. var times = interpolant.parameterPositions,
  22798. values = interpolant.sampleValues;
  22799. times[ 0 ] = now; values[ 0 ] = weightNow;
  22800. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  22801. return this;
  22802. }
  22803. };
  22804. /**
  22805. *
  22806. * Player for AnimationClips.
  22807. *
  22808. *
  22809. * @author Ben Houston / http://clara.io/
  22810. * @author David Sarno / http://lighthaus.us/
  22811. * @author tschw
  22812. */
  22813. function AnimationMixer( root ) {
  22814. this._root = root;
  22815. this._initMemoryManager();
  22816. this._accuIndex = 0;
  22817. this.time = 0;
  22818. this.timeScale = 1.0;
  22819. }
  22820. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, {
  22821. // return an action for a clip optionally using a custom root target
  22822. // object (this method allocates a lot of dynamic memory in case a
  22823. // previously unknown clip/root combination is specified)
  22824. clipAction: function( clip, optionalRoot ) {
  22825. var root = optionalRoot || this._root,
  22826. rootUuid = root.uuid,
  22827. clipObject = typeof clip === 'string' ?
  22828. AnimationClip.findByName( root, clip ) : clip,
  22829. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  22830. actionsForClip = this._actionsByClip[ clipUuid ],
  22831. prototypeAction = null;
  22832. if ( actionsForClip !== undefined ) {
  22833. var existingAction =
  22834. actionsForClip.actionByRoot[ rootUuid ];
  22835. if ( existingAction !== undefined ) {
  22836. return existingAction;
  22837. }
  22838. // we know the clip, so we don't have to parse all
  22839. // the bindings again but can just copy
  22840. prototypeAction = actionsForClip.knownActions[ 0 ];
  22841. // also, take the clip from the prototype action
  22842. if ( clipObject === null )
  22843. clipObject = prototypeAction._clip;
  22844. }
  22845. // clip must be known when specified via string
  22846. if ( clipObject === null ) return null;
  22847. // allocate all resources required to run it
  22848. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  22849. this._bindAction( newAction, prototypeAction );
  22850. // and make the action known to the memory manager
  22851. this._addInactiveAction( newAction, clipUuid, rootUuid );
  22852. return newAction;
  22853. },
  22854. // get an existing action
  22855. existingAction: function( clip, optionalRoot ) {
  22856. var root = optionalRoot || this._root,
  22857. rootUuid = root.uuid,
  22858. clipObject = typeof clip === 'string' ?
  22859. AnimationClip.findByName( root, clip ) : clip,
  22860. clipUuid = clipObject ? clipObject.uuid : clip,
  22861. actionsForClip = this._actionsByClip[ clipUuid ];
  22862. if ( actionsForClip !== undefined ) {
  22863. return actionsForClip.actionByRoot[ rootUuid ] || null;
  22864. }
  22865. return null;
  22866. },
  22867. // deactivates all previously scheduled actions
  22868. stopAllAction: function() {
  22869. var actions = this._actions,
  22870. nActions = this._nActiveActions,
  22871. bindings = this._bindings,
  22872. nBindings = this._nActiveBindings;
  22873. this._nActiveActions = 0;
  22874. this._nActiveBindings = 0;
  22875. for ( var i = 0; i !== nActions; ++ i ) {
  22876. actions[ i ].reset();
  22877. }
  22878. for ( var i = 0; i !== nBindings; ++ i ) {
  22879. bindings[ i ].useCount = 0;
  22880. }
  22881. return this;
  22882. },
  22883. // advance the time and update apply the animation
  22884. update: function( deltaTime ) {
  22885. deltaTime *= this.timeScale;
  22886. var actions = this._actions,
  22887. nActions = this._nActiveActions,
  22888. time = this.time += deltaTime,
  22889. timeDirection = Math.sign( deltaTime ),
  22890. accuIndex = this._accuIndex ^= 1;
  22891. // run active actions
  22892. for ( var i = 0; i !== nActions; ++ i ) {
  22893. var action = actions[ i ];
  22894. if ( action.enabled ) {
  22895. action._update( time, deltaTime, timeDirection, accuIndex );
  22896. }
  22897. }
  22898. // update scene graph
  22899. var bindings = this._bindings,
  22900. nBindings = this._nActiveBindings;
  22901. for ( var i = 0; i !== nBindings; ++ i ) {
  22902. bindings[ i ].apply( accuIndex );
  22903. }
  22904. return this;
  22905. },
  22906. // return this mixer's root target object
  22907. getRoot: function() {
  22908. return this._root;
  22909. },
  22910. // free all resources specific to a particular clip
  22911. uncacheClip: function( clip ) {
  22912. var actions = this._actions,
  22913. clipUuid = clip.uuid,
  22914. actionsByClip = this._actionsByClip,
  22915. actionsForClip = actionsByClip[ clipUuid ];
  22916. if ( actionsForClip !== undefined ) {
  22917. // note: just calling _removeInactiveAction would mess up the
  22918. // iteration state and also require updating the state we can
  22919. // just throw away
  22920. var actionsToRemove = actionsForClip.knownActions;
  22921. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  22922. var action = actionsToRemove[ i ];
  22923. this._deactivateAction( action );
  22924. var cacheIndex = action._cacheIndex,
  22925. lastInactiveAction = actions[ actions.length - 1 ];
  22926. action._cacheIndex = null;
  22927. action._byClipCacheIndex = null;
  22928. lastInactiveAction._cacheIndex = cacheIndex;
  22929. actions[ cacheIndex ] = lastInactiveAction;
  22930. actions.pop();
  22931. this._removeInactiveBindingsForAction( action );
  22932. }
  22933. delete actionsByClip[ clipUuid ];
  22934. }
  22935. },
  22936. // free all resources specific to a particular root target object
  22937. uncacheRoot: function( root ) {
  22938. var rootUuid = root.uuid,
  22939. actionsByClip = this._actionsByClip;
  22940. for ( var clipUuid in actionsByClip ) {
  22941. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  22942. action = actionByRoot[ rootUuid ];
  22943. if ( action !== undefined ) {
  22944. this._deactivateAction( action );
  22945. this._removeInactiveAction( action );
  22946. }
  22947. }
  22948. var bindingsByRoot = this._bindingsByRootAndName,
  22949. bindingByName = bindingsByRoot[ rootUuid ];
  22950. if ( bindingByName !== undefined ) {
  22951. for ( var trackName in bindingByName ) {
  22952. var binding = bindingByName[ trackName ];
  22953. binding.restoreOriginalState();
  22954. this._removeInactiveBinding( binding );
  22955. }
  22956. }
  22957. },
  22958. // remove a targeted clip from the cache
  22959. uncacheAction: function( clip, optionalRoot ) {
  22960. var action = this.existingAction( clip, optionalRoot );
  22961. if ( action !== null ) {
  22962. this._deactivateAction( action );
  22963. this._removeInactiveAction( action );
  22964. }
  22965. }
  22966. } );
  22967. // Implementation details:
  22968. Object.assign( AnimationMixer.prototype, {
  22969. _bindAction: function( action, prototypeAction ) {
  22970. var root = action._localRoot || this._root,
  22971. tracks = action._clip.tracks,
  22972. nTracks = tracks.length,
  22973. bindings = action._propertyBindings,
  22974. interpolants = action._interpolants,
  22975. rootUuid = root.uuid,
  22976. bindingsByRoot = this._bindingsByRootAndName,
  22977. bindingsByName = bindingsByRoot[ rootUuid ];
  22978. if ( bindingsByName === undefined ) {
  22979. bindingsByName = {};
  22980. bindingsByRoot[ rootUuid ] = bindingsByName;
  22981. }
  22982. for ( var i = 0; i !== nTracks; ++ i ) {
  22983. var track = tracks[ i ],
  22984. trackName = track.name,
  22985. binding = bindingsByName[ trackName ];
  22986. if ( binding !== undefined ) {
  22987. bindings[ i ] = binding;
  22988. } else {
  22989. binding = bindings[ i ];
  22990. if ( binding !== undefined ) {
  22991. // existing binding, make sure the cache knows
  22992. if ( binding._cacheIndex === null ) {
  22993. ++ binding.referenceCount;
  22994. this._addInactiveBinding( binding, rootUuid, trackName );
  22995. }
  22996. continue;
  22997. }
  22998. var path = prototypeAction && prototypeAction.
  22999. _propertyBindings[ i ].binding.parsedPath;
  23000. binding = new PropertyMixer(
  23001. PropertyBinding.create( root, trackName, path ),
  23002. track.ValueTypeName, track.getValueSize() );
  23003. ++ binding.referenceCount;
  23004. this._addInactiveBinding( binding, rootUuid, trackName );
  23005. bindings[ i ] = binding;
  23006. }
  23007. interpolants[ i ].resultBuffer = binding.buffer;
  23008. }
  23009. },
  23010. _activateAction: function( action ) {
  23011. if ( ! this._isActiveAction( action ) ) {
  23012. if ( action._cacheIndex === null ) {
  23013. // this action has been forgotten by the cache, but the user
  23014. // appears to be still using it -> rebind
  23015. var rootUuid = ( action._localRoot || this._root ).uuid,
  23016. clipUuid = action._clip.uuid,
  23017. actionsForClip = this._actionsByClip[ clipUuid ];
  23018. this._bindAction( action,
  23019. actionsForClip && actionsForClip.knownActions[ 0 ] );
  23020. this._addInactiveAction( action, clipUuid, rootUuid );
  23021. }
  23022. var bindings = action._propertyBindings;
  23023. // increment reference counts / sort out state
  23024. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23025. var binding = bindings[ i ];
  23026. if ( binding.useCount ++ === 0 ) {
  23027. this._lendBinding( binding );
  23028. binding.saveOriginalState();
  23029. }
  23030. }
  23031. this._lendAction( action );
  23032. }
  23033. },
  23034. _deactivateAction: function( action ) {
  23035. if ( this._isActiveAction( action ) ) {
  23036. var bindings = action._propertyBindings;
  23037. // decrement reference counts / sort out state
  23038. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23039. var binding = bindings[ i ];
  23040. if ( -- binding.useCount === 0 ) {
  23041. binding.restoreOriginalState();
  23042. this._takeBackBinding( binding );
  23043. }
  23044. }
  23045. this._takeBackAction( action );
  23046. }
  23047. },
  23048. // Memory manager
  23049. _initMemoryManager: function() {
  23050. this._actions = []; // 'nActiveActions' followed by inactive ones
  23051. this._nActiveActions = 0;
  23052. this._actionsByClip = {};
  23053. // inside:
  23054. // {
  23055. // knownActions: Array< AnimationAction > - used as prototypes
  23056. // actionByRoot: AnimationAction - lookup
  23057. // }
  23058. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  23059. this._nActiveBindings = 0;
  23060. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  23061. this._controlInterpolants = []; // same game as above
  23062. this._nActiveControlInterpolants = 0;
  23063. var scope = this;
  23064. this.stats = {
  23065. actions: {
  23066. get total() { return scope._actions.length; },
  23067. get inUse() { return scope._nActiveActions; }
  23068. },
  23069. bindings: {
  23070. get total() { return scope._bindings.length; },
  23071. get inUse() { return scope._nActiveBindings; }
  23072. },
  23073. controlInterpolants: {
  23074. get total() { return scope._controlInterpolants.length; },
  23075. get inUse() { return scope._nActiveControlInterpolants; }
  23076. }
  23077. };
  23078. },
  23079. // Memory management for AnimationAction objects
  23080. _isActiveAction: function( action ) {
  23081. var index = action._cacheIndex;
  23082. return index !== null && index < this._nActiveActions;
  23083. },
  23084. _addInactiveAction: function( action, clipUuid, rootUuid ) {
  23085. var actions = this._actions,
  23086. actionsByClip = this._actionsByClip,
  23087. actionsForClip = actionsByClip[ clipUuid ];
  23088. if ( actionsForClip === undefined ) {
  23089. actionsForClip = {
  23090. knownActions: [ action ],
  23091. actionByRoot: {}
  23092. };
  23093. action._byClipCacheIndex = 0;
  23094. actionsByClip[ clipUuid ] = actionsForClip;
  23095. } else {
  23096. var knownActions = actionsForClip.knownActions;
  23097. action._byClipCacheIndex = knownActions.length;
  23098. knownActions.push( action );
  23099. }
  23100. action._cacheIndex = actions.length;
  23101. actions.push( action );
  23102. actionsForClip.actionByRoot[ rootUuid ] = action;
  23103. },
  23104. _removeInactiveAction: function( action ) {
  23105. var actions = this._actions,
  23106. lastInactiveAction = actions[ actions.length - 1 ],
  23107. cacheIndex = action._cacheIndex;
  23108. lastInactiveAction._cacheIndex = cacheIndex;
  23109. actions[ cacheIndex ] = lastInactiveAction;
  23110. actions.pop();
  23111. action._cacheIndex = null;
  23112. var clipUuid = action._clip.uuid,
  23113. actionsByClip = this._actionsByClip,
  23114. actionsForClip = actionsByClip[ clipUuid ],
  23115. knownActionsForClip = actionsForClip.knownActions,
  23116. lastKnownAction =
  23117. knownActionsForClip[ knownActionsForClip.length - 1 ],
  23118. byClipCacheIndex = action._byClipCacheIndex;
  23119. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  23120. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  23121. knownActionsForClip.pop();
  23122. action._byClipCacheIndex = null;
  23123. var actionByRoot = actionsForClip.actionByRoot,
  23124. rootUuid = ( actions._localRoot || this._root ).uuid;
  23125. delete actionByRoot[ rootUuid ];
  23126. if ( knownActionsForClip.length === 0 ) {
  23127. delete actionsByClip[ clipUuid ];
  23128. }
  23129. this._removeInactiveBindingsForAction( action );
  23130. },
  23131. _removeInactiveBindingsForAction: function( action ) {
  23132. var bindings = action._propertyBindings;
  23133. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23134. var binding = bindings[ i ];
  23135. if ( -- binding.referenceCount === 0 ) {
  23136. this._removeInactiveBinding( binding );
  23137. }
  23138. }
  23139. },
  23140. _lendAction: function( action ) {
  23141. // [ active actions | inactive actions ]
  23142. // [ active actions >| inactive actions ]
  23143. // s a
  23144. // <-swap->
  23145. // a s
  23146. var actions = this._actions,
  23147. prevIndex = action._cacheIndex,
  23148. lastActiveIndex = this._nActiveActions ++,
  23149. firstInactiveAction = actions[ lastActiveIndex ];
  23150. action._cacheIndex = lastActiveIndex;
  23151. actions[ lastActiveIndex ] = action;
  23152. firstInactiveAction._cacheIndex = prevIndex;
  23153. actions[ prevIndex ] = firstInactiveAction;
  23154. },
  23155. _takeBackAction: function( action ) {
  23156. // [ active actions | inactive actions ]
  23157. // [ active actions |< inactive actions ]
  23158. // a s
  23159. // <-swap->
  23160. // s a
  23161. var actions = this._actions,
  23162. prevIndex = action._cacheIndex,
  23163. firstInactiveIndex = -- this._nActiveActions,
  23164. lastActiveAction = actions[ firstInactiveIndex ];
  23165. action._cacheIndex = firstInactiveIndex;
  23166. actions[ firstInactiveIndex ] = action;
  23167. lastActiveAction._cacheIndex = prevIndex;
  23168. actions[ prevIndex ] = lastActiveAction;
  23169. },
  23170. // Memory management for PropertyMixer objects
  23171. _addInactiveBinding: function( binding, rootUuid, trackName ) {
  23172. var bindingsByRoot = this._bindingsByRootAndName,
  23173. bindingByName = bindingsByRoot[ rootUuid ],
  23174. bindings = this._bindings;
  23175. if ( bindingByName === undefined ) {
  23176. bindingByName = {};
  23177. bindingsByRoot[ rootUuid ] = bindingByName;
  23178. }
  23179. bindingByName[ trackName ] = binding;
  23180. binding._cacheIndex = bindings.length;
  23181. bindings.push( binding );
  23182. },
  23183. _removeInactiveBinding: function( binding ) {
  23184. var bindings = this._bindings,
  23185. propBinding = binding.binding,
  23186. rootUuid = propBinding.rootNode.uuid,
  23187. trackName = propBinding.path,
  23188. bindingsByRoot = this._bindingsByRootAndName,
  23189. bindingByName = bindingsByRoot[ rootUuid ],
  23190. lastInactiveBinding = bindings[ bindings.length - 1 ],
  23191. cacheIndex = binding._cacheIndex;
  23192. lastInactiveBinding._cacheIndex = cacheIndex;
  23193. bindings[ cacheIndex ] = lastInactiveBinding;
  23194. bindings.pop();
  23195. delete bindingByName[ trackName ];
  23196. remove_empty_map: {
  23197. for ( var _ in bindingByName ) break remove_empty_map;
  23198. delete bindingsByRoot[ rootUuid ];
  23199. }
  23200. },
  23201. _lendBinding: function( binding ) {
  23202. var bindings = this._bindings,
  23203. prevIndex = binding._cacheIndex,
  23204. lastActiveIndex = this._nActiveBindings ++,
  23205. firstInactiveBinding = bindings[ lastActiveIndex ];
  23206. binding._cacheIndex = lastActiveIndex;
  23207. bindings[ lastActiveIndex ] = binding;
  23208. firstInactiveBinding._cacheIndex = prevIndex;
  23209. bindings[ prevIndex ] = firstInactiveBinding;
  23210. },
  23211. _takeBackBinding: function( binding ) {
  23212. var bindings = this._bindings,
  23213. prevIndex = binding._cacheIndex,
  23214. firstInactiveIndex = -- this._nActiveBindings,
  23215. lastActiveBinding = bindings[ firstInactiveIndex ];
  23216. binding._cacheIndex = firstInactiveIndex;
  23217. bindings[ firstInactiveIndex ] = binding;
  23218. lastActiveBinding._cacheIndex = prevIndex;
  23219. bindings[ prevIndex ] = lastActiveBinding;
  23220. },
  23221. // Memory management of Interpolants for weight and time scale
  23222. _lendControlInterpolant: function() {
  23223. var interpolants = this._controlInterpolants,
  23224. lastActiveIndex = this._nActiveControlInterpolants ++,
  23225. interpolant = interpolants[ lastActiveIndex ];
  23226. if ( interpolant === undefined ) {
  23227. interpolant = new LinearInterpolant(
  23228. new Float32Array( 2 ), new Float32Array( 2 ),
  23229. 1, this._controlInterpolantsResultBuffer );
  23230. interpolant.__cacheIndex = lastActiveIndex;
  23231. interpolants[ lastActiveIndex ] = interpolant;
  23232. }
  23233. return interpolant;
  23234. },
  23235. _takeBackControlInterpolant: function( interpolant ) {
  23236. var interpolants = this._controlInterpolants,
  23237. prevIndex = interpolant.__cacheIndex,
  23238. firstInactiveIndex = -- this._nActiveControlInterpolants,
  23239. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  23240. interpolant.__cacheIndex = firstInactiveIndex;
  23241. interpolants[ firstInactiveIndex ] = interpolant;
  23242. lastActiveInterpolant.__cacheIndex = prevIndex;
  23243. interpolants[ prevIndex ] = lastActiveInterpolant;
  23244. },
  23245. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  23246. } );
  23247. /**
  23248. * @author mrdoob / http://mrdoob.com/
  23249. */
  23250. function Uniform( value ) {
  23251. if ( typeof value === 'string' ) {
  23252. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  23253. value = arguments[ 1 ];
  23254. }
  23255. this.value = value;
  23256. }
  23257. Uniform.prototype.clone = function () {
  23258. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  23259. };
  23260. /**
  23261. * @author benaadams / https://twitter.com/ben_a_adams
  23262. */
  23263. function InstancedBufferGeometry() {
  23264. BufferGeometry.call( this );
  23265. this.type = 'InstancedBufferGeometry';
  23266. this.maxInstancedCount = undefined;
  23267. }
  23268. InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23269. InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry;
  23270. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  23271. InstancedBufferGeometry.prototype.addGroup = function ( start, count, materialIndex ) {
  23272. this.groups.push( {
  23273. start: start,
  23274. count: count,
  23275. materialIndex: materialIndex
  23276. } );
  23277. };
  23278. InstancedBufferGeometry.prototype.copy = function ( source ) {
  23279. var index = source.index;
  23280. if ( index !== null ) {
  23281. this.setIndex( index.clone() );
  23282. }
  23283. var attributes = source.attributes;
  23284. for ( var name in attributes ) {
  23285. var attribute = attributes[ name ];
  23286. this.addAttribute( name, attribute.clone() );
  23287. }
  23288. var groups = source.groups;
  23289. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  23290. var group = groups[ i ];
  23291. this.addGroup( group.start, group.count, group.materialIndex );
  23292. }
  23293. return this;
  23294. };
  23295. /**
  23296. * @author benaadams / https://twitter.com/ben_a_adams
  23297. */
  23298. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  23299. this.uuid = _Math.generateUUID();
  23300. this.data = interleavedBuffer;
  23301. this.itemSize = itemSize;
  23302. this.offset = offset;
  23303. this.normalized = normalized === true;
  23304. }
  23305. InterleavedBufferAttribute.prototype = {
  23306. constructor: InterleavedBufferAttribute,
  23307. isInterleavedBufferAttribute: true,
  23308. get count() {
  23309. return this.data.count;
  23310. },
  23311. get array() {
  23312. return this.data.array;
  23313. },
  23314. setX: function ( index, x ) {
  23315. this.data.array[ index * this.data.stride + this.offset ] = x;
  23316. return this;
  23317. },
  23318. setY: function ( index, y ) {
  23319. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  23320. return this;
  23321. },
  23322. setZ: function ( index, z ) {
  23323. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  23324. return this;
  23325. },
  23326. setW: function ( index, w ) {
  23327. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  23328. return this;
  23329. },
  23330. getX: function ( index ) {
  23331. return this.data.array[ index * this.data.stride + this.offset ];
  23332. },
  23333. getY: function ( index ) {
  23334. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  23335. },
  23336. getZ: function ( index ) {
  23337. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  23338. },
  23339. getW: function ( index ) {
  23340. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  23341. },
  23342. setXY: function ( index, x, y ) {
  23343. index = index * this.data.stride + this.offset;
  23344. this.data.array[ index + 0 ] = x;
  23345. this.data.array[ index + 1 ] = y;
  23346. return this;
  23347. },
  23348. setXYZ: function ( index, x, y, z ) {
  23349. index = index * this.data.stride + this.offset;
  23350. this.data.array[ index + 0 ] = x;
  23351. this.data.array[ index + 1 ] = y;
  23352. this.data.array[ index + 2 ] = z;
  23353. return this;
  23354. },
  23355. setXYZW: function ( index, x, y, z, w ) {
  23356. index = index * this.data.stride + this.offset;
  23357. this.data.array[ index + 0 ] = x;
  23358. this.data.array[ index + 1 ] = y;
  23359. this.data.array[ index + 2 ] = z;
  23360. this.data.array[ index + 3 ] = w;
  23361. return this;
  23362. }
  23363. };
  23364. /**
  23365. * @author benaadams / https://twitter.com/ben_a_adams
  23366. */
  23367. function InterleavedBuffer( array, stride ) {
  23368. this.uuid = _Math.generateUUID();
  23369. this.array = array;
  23370. this.stride = stride;
  23371. this.count = array !== undefined ? array.length / stride : 0;
  23372. this.dynamic = false;
  23373. this.updateRange = { offset: 0, count: - 1 };
  23374. this.onUploadCallback = function () {};
  23375. this.version = 0;
  23376. }
  23377. InterleavedBuffer.prototype = {
  23378. constructor: InterleavedBuffer,
  23379. isInterleavedBuffer: true,
  23380. set needsUpdate( value ) {
  23381. if ( value === true ) this.version ++;
  23382. },
  23383. setArray: function ( array ) {
  23384. if ( Array.isArray( array ) ) {
  23385. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  23386. }
  23387. this.count = array !== undefined ? array.length / this.stride : 0;
  23388. this.array = array;
  23389. },
  23390. setDynamic: function ( value ) {
  23391. this.dynamic = value;
  23392. return this;
  23393. },
  23394. copy: function ( source ) {
  23395. this.array = new source.array.constructor( source.array );
  23396. this.count = source.count;
  23397. this.stride = source.stride;
  23398. this.dynamic = source.dynamic;
  23399. return this;
  23400. },
  23401. copyAt: function ( index1, attribute, index2 ) {
  23402. index1 *= this.stride;
  23403. index2 *= attribute.stride;
  23404. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  23405. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  23406. }
  23407. return this;
  23408. },
  23409. set: function ( value, offset ) {
  23410. if ( offset === undefined ) offset = 0;
  23411. this.array.set( value, offset );
  23412. return this;
  23413. },
  23414. clone: function () {
  23415. return new this.constructor().copy( this );
  23416. },
  23417. onUpload: function ( callback ) {
  23418. this.onUploadCallback = callback;
  23419. return this;
  23420. }
  23421. };
  23422. /**
  23423. * @author benaadams / https://twitter.com/ben_a_adams
  23424. */
  23425. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  23426. InterleavedBuffer.call( this, array, stride );
  23427. this.meshPerAttribute = meshPerAttribute || 1;
  23428. }
  23429. InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype );
  23430. InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer;
  23431. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  23432. InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  23433. InterleavedBuffer.prototype.copy.call( this, source );
  23434. this.meshPerAttribute = source.meshPerAttribute;
  23435. return this;
  23436. };
  23437. /**
  23438. * @author benaadams / https://twitter.com/ben_a_adams
  23439. */
  23440. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  23441. BufferAttribute.call( this, array, itemSize );
  23442. this.meshPerAttribute = meshPerAttribute || 1;
  23443. }
  23444. InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  23445. InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute;
  23446. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  23447. InstancedBufferAttribute.prototype.copy = function ( source ) {
  23448. BufferAttribute.prototype.copy.call( this, source );
  23449. this.meshPerAttribute = source.meshPerAttribute;
  23450. return this;
  23451. };
  23452. /**
  23453. * @author mrdoob / http://mrdoob.com/
  23454. * @author bhouston / http://clara.io/
  23455. * @author stephomi / http://stephaneginier.com/
  23456. */
  23457. function Raycaster( origin, direction, near, far ) {
  23458. this.ray = new Ray( origin, direction );
  23459. // direction is assumed to be normalized (for accurate distance calculations)
  23460. this.near = near || 0;
  23461. this.far = far || Infinity;
  23462. this.params = {
  23463. Mesh: {},
  23464. Line: {},
  23465. LOD: {},
  23466. Points: { threshold: 1 },
  23467. Sprite: {}
  23468. };
  23469. Object.defineProperties( this.params, {
  23470. PointCloud: {
  23471. get: function () {
  23472. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  23473. return this.Points;
  23474. }
  23475. }
  23476. } );
  23477. }
  23478. function ascSort( a, b ) {
  23479. return a.distance - b.distance;
  23480. }
  23481. function intersectObject( object, raycaster, intersects, recursive ) {
  23482. if ( object.visible === false ) return;
  23483. object.raycast( raycaster, intersects );
  23484. if ( recursive === true ) {
  23485. var children = object.children;
  23486. for ( var i = 0, l = children.length; i < l; i ++ ) {
  23487. intersectObject( children[ i ], raycaster, intersects, true );
  23488. }
  23489. }
  23490. }
  23491. //
  23492. Raycaster.prototype = {
  23493. constructor: Raycaster,
  23494. linePrecision: 1,
  23495. set: function ( origin, direction ) {
  23496. // direction is assumed to be normalized (for accurate distance calculations)
  23497. this.ray.set( origin, direction );
  23498. },
  23499. setFromCamera: function ( coords, camera ) {
  23500. if ( (camera && camera.isPerspectiveCamera) ) {
  23501. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  23502. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  23503. } else if ( (camera && camera.isOrthographicCamera) ) {
  23504. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  23505. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  23506. } else {
  23507. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  23508. }
  23509. },
  23510. intersectObject: function ( object, recursive ) {
  23511. var intersects = [];
  23512. intersectObject( object, this, intersects, recursive );
  23513. intersects.sort( ascSort );
  23514. return intersects;
  23515. },
  23516. intersectObjects: function ( objects, recursive ) {
  23517. var intersects = [];
  23518. if ( Array.isArray( objects ) === false ) {
  23519. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  23520. return intersects;
  23521. }
  23522. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  23523. intersectObject( objects[ i ], this, intersects, recursive );
  23524. }
  23525. intersects.sort( ascSort );
  23526. return intersects;
  23527. }
  23528. };
  23529. /**
  23530. * @author alteredq / http://alteredqualia.com/
  23531. */
  23532. function Clock( autoStart ) {
  23533. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  23534. this.startTime = 0;
  23535. this.oldTime = 0;
  23536. this.elapsedTime = 0;
  23537. this.running = false;
  23538. }
  23539. Clock.prototype = {
  23540. constructor: Clock,
  23541. start: function () {
  23542. this.startTime = ( performance || Date ).now();
  23543. this.oldTime = this.startTime;
  23544. this.elapsedTime = 0;
  23545. this.running = true;
  23546. },
  23547. stop: function () {
  23548. this.getElapsedTime();
  23549. this.running = false;
  23550. },
  23551. getElapsedTime: function () {
  23552. this.getDelta();
  23553. return this.elapsedTime;
  23554. },
  23555. getDelta: function () {
  23556. var diff = 0;
  23557. if ( this.autoStart && ! this.running ) {
  23558. this.start();
  23559. }
  23560. if ( this.running ) {
  23561. var newTime = ( performance || Date ).now();
  23562. diff = ( newTime - this.oldTime ) / 1000;
  23563. this.oldTime = newTime;
  23564. this.elapsedTime += diff;
  23565. }
  23566. return diff;
  23567. }
  23568. };
  23569. /**
  23570. * Spline from Tween.js, slightly optimized (and trashed)
  23571. * http://sole.github.com/tween.js/examples/05_spline.html
  23572. *
  23573. * @author mrdoob / http://mrdoob.com/
  23574. * @author alteredq / http://alteredqualia.com/
  23575. */
  23576. function Spline( points ) {
  23577. this.points = points;
  23578. var c = [], v3 = { x: 0, y: 0, z: 0 },
  23579. point, intPoint, weight, w2, w3,
  23580. pa, pb, pc, pd;
  23581. this.initFromArray = function ( a ) {
  23582. this.points = [];
  23583. for ( var i = 0; i < a.length; i ++ ) {
  23584. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  23585. }
  23586. };
  23587. this.getPoint = function ( k ) {
  23588. point = ( this.points.length - 1 ) * k;
  23589. intPoint = Math.floor( point );
  23590. weight = point - intPoint;
  23591. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  23592. c[ 1 ] = intPoint;
  23593. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  23594. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  23595. pa = this.points[ c[ 0 ] ];
  23596. pb = this.points[ c[ 1 ] ];
  23597. pc = this.points[ c[ 2 ] ];
  23598. pd = this.points[ c[ 3 ] ];
  23599. w2 = weight * weight;
  23600. w3 = weight * w2;
  23601. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  23602. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  23603. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  23604. return v3;
  23605. };
  23606. this.getControlPointsArray = function () {
  23607. var i, p, l = this.points.length,
  23608. coords = [];
  23609. for ( i = 0; i < l; i ++ ) {
  23610. p = this.points[ i ];
  23611. coords[ i ] = [ p.x, p.y, p.z ];
  23612. }
  23613. return coords;
  23614. };
  23615. // approximate length by summing linear segments
  23616. this.getLength = function ( nSubDivisions ) {
  23617. var i, index, nSamples, position,
  23618. point = 0, intPoint = 0, oldIntPoint = 0,
  23619. oldPosition = new Vector3(),
  23620. tmpVec = new Vector3(),
  23621. chunkLengths = [],
  23622. totalLength = 0;
  23623. // first point has 0 length
  23624. chunkLengths[ 0 ] = 0;
  23625. if ( ! nSubDivisions ) nSubDivisions = 100;
  23626. nSamples = this.points.length * nSubDivisions;
  23627. oldPosition.copy( this.points[ 0 ] );
  23628. for ( i = 1; i < nSamples; i ++ ) {
  23629. index = i / nSamples;
  23630. position = this.getPoint( index );
  23631. tmpVec.copy( position );
  23632. totalLength += tmpVec.distanceTo( oldPosition );
  23633. oldPosition.copy( position );
  23634. point = ( this.points.length - 1 ) * index;
  23635. intPoint = Math.floor( point );
  23636. if ( intPoint !== oldIntPoint ) {
  23637. chunkLengths[ intPoint ] = totalLength;
  23638. oldIntPoint = intPoint;
  23639. }
  23640. }
  23641. // last point ends with total length
  23642. chunkLengths[ chunkLengths.length ] = totalLength;
  23643. return { chunks: chunkLengths, total: totalLength };
  23644. };
  23645. this.reparametrizeByArcLength = function ( samplingCoef ) {
  23646. var i, j,
  23647. index, indexCurrent, indexNext,
  23648. realDistance,
  23649. sampling, position,
  23650. newpoints = [],
  23651. tmpVec = new Vector3(),
  23652. sl = this.getLength();
  23653. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  23654. for ( i = 1; i < this.points.length; i ++ ) {
  23655. //tmpVec.copy( this.points[ i - 1 ] );
  23656. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  23657. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  23658. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  23659. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  23660. indexNext = i / ( this.points.length - 1 );
  23661. for ( j = 1; j < sampling - 1; j ++ ) {
  23662. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  23663. position = this.getPoint( index );
  23664. newpoints.push( tmpVec.copy( position ).clone() );
  23665. }
  23666. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  23667. }
  23668. this.points = newpoints;
  23669. };
  23670. // Catmull-Rom
  23671. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  23672. var v0 = ( p2 - p0 ) * 0.5,
  23673. v1 = ( p3 - p1 ) * 0.5;
  23674. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23675. }
  23676. }
  23677. /**
  23678. * @author bhouston / http://clara.io
  23679. * @author WestLangley / http://github.com/WestLangley
  23680. *
  23681. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  23682. *
  23683. * The poles (phi) are at the positive and negative y axis.
  23684. * The equator starts at positive z.
  23685. */
  23686. function Spherical( radius, phi, theta ) {
  23687. this.radius = ( radius !== undefined ) ? radius : 1.0;
  23688. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  23689. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  23690. return this;
  23691. }
  23692. Spherical.prototype = {
  23693. constructor: Spherical,
  23694. set: function ( radius, phi, theta ) {
  23695. this.radius = radius;
  23696. this.phi = phi;
  23697. this.theta = theta;
  23698. return this;
  23699. },
  23700. clone: function () {
  23701. return new this.constructor().copy( this );
  23702. },
  23703. copy: function ( other ) {
  23704. this.radius = other.radius;
  23705. this.phi = other.phi;
  23706. this.theta = other.theta;
  23707. return this;
  23708. },
  23709. // restrict phi to be betwee EPS and PI-EPS
  23710. makeSafe: function() {
  23711. var EPS = 0.000001;
  23712. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  23713. return this;
  23714. },
  23715. setFromVector3: function( vec3 ) {
  23716. this.radius = vec3.length();
  23717. if ( this.radius === 0 ) {
  23718. this.theta = 0;
  23719. this.phi = 0;
  23720. } else {
  23721. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  23722. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  23723. }
  23724. return this;
  23725. }
  23726. };
  23727. /**
  23728. * @author Mugen87 / https://github.com/Mugen87
  23729. *
  23730. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  23731. *
  23732. */
  23733. function Cylindrical( radius, theta, y ) {
  23734. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  23735. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  23736. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  23737. return this;
  23738. }
  23739. Cylindrical.prototype = {
  23740. constructor: Cylindrical,
  23741. set: function ( radius, theta, y ) {
  23742. this.radius = radius;
  23743. this.theta = theta;
  23744. this.y = y;
  23745. return this;
  23746. },
  23747. clone: function () {
  23748. return new this.constructor().copy( this );
  23749. },
  23750. copy: function ( other ) {
  23751. this.radius = other.radius;
  23752. this.theta = other.theta;
  23753. this.y = other.y;
  23754. return this;
  23755. },
  23756. setFromVector3: function( vec3 ) {
  23757. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  23758. this.theta = Math.atan2( vec3.x, vec3.z );
  23759. this.y = vec3.y;
  23760. return this;
  23761. }
  23762. };
  23763. /**
  23764. * @author alteredq / http://alteredqualia.com/
  23765. */
  23766. function MorphBlendMesh( geometry, material ) {
  23767. Mesh.call( this, geometry, material );
  23768. this.animationsMap = {};
  23769. this.animationsList = [];
  23770. // prepare default animation
  23771. // (all frames played together in 1 second)
  23772. var numFrames = this.geometry.morphTargets.length;
  23773. var name = "__default";
  23774. var startFrame = 0;
  23775. var endFrame = numFrames - 1;
  23776. var fps = numFrames / 1;
  23777. this.createAnimation( name, startFrame, endFrame, fps );
  23778. this.setAnimationWeight( name, 1 );
  23779. }
  23780. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  23781. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  23782. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  23783. var animation = {
  23784. start: start,
  23785. end: end,
  23786. length: end - start + 1,
  23787. fps: fps,
  23788. duration: ( end - start ) / fps,
  23789. lastFrame: 0,
  23790. currentFrame: 0,
  23791. active: false,
  23792. time: 0,
  23793. direction: 1,
  23794. weight: 1,
  23795. directionBackwards: false,
  23796. mirroredLoop: false
  23797. };
  23798. this.animationsMap[ name ] = animation;
  23799. this.animationsList.push( animation );
  23800. };
  23801. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  23802. var pattern = /([a-z]+)_?(\d+)/i;
  23803. var firstAnimation, frameRanges = {};
  23804. var geometry = this.geometry;
  23805. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  23806. var morph = geometry.morphTargets[ i ];
  23807. var chunks = morph.name.match( pattern );
  23808. if ( chunks && chunks.length > 1 ) {
  23809. var name = chunks[ 1 ];
  23810. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  23811. var range = frameRanges[ name ];
  23812. if ( i < range.start ) range.start = i;
  23813. if ( i > range.end ) range.end = i;
  23814. if ( ! firstAnimation ) firstAnimation = name;
  23815. }
  23816. }
  23817. for ( var name in frameRanges ) {
  23818. var range = frameRanges[ name ];
  23819. this.createAnimation( name, range.start, range.end, fps );
  23820. }
  23821. this.firstAnimation = firstAnimation;
  23822. };
  23823. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  23824. var animation = this.animationsMap[ name ];
  23825. if ( animation ) {
  23826. animation.direction = 1;
  23827. animation.directionBackwards = false;
  23828. }
  23829. };
  23830. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  23831. var animation = this.animationsMap[ name ];
  23832. if ( animation ) {
  23833. animation.direction = - 1;
  23834. animation.directionBackwards = true;
  23835. }
  23836. };
  23837. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  23838. var animation = this.animationsMap[ name ];
  23839. if ( animation ) {
  23840. animation.fps = fps;
  23841. animation.duration = ( animation.end - animation.start ) / animation.fps;
  23842. }
  23843. };
  23844. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  23845. var animation = this.animationsMap[ name ];
  23846. if ( animation ) {
  23847. animation.duration = duration;
  23848. animation.fps = ( animation.end - animation.start ) / animation.duration;
  23849. }
  23850. };
  23851. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  23852. var animation = this.animationsMap[ name ];
  23853. if ( animation ) {
  23854. animation.weight = weight;
  23855. }
  23856. };
  23857. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  23858. var animation = this.animationsMap[ name ];
  23859. if ( animation ) {
  23860. animation.time = time;
  23861. }
  23862. };
  23863. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  23864. var time = 0;
  23865. var animation = this.animationsMap[ name ];
  23866. if ( animation ) {
  23867. time = animation.time;
  23868. }
  23869. return time;
  23870. };
  23871. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  23872. var duration = - 1;
  23873. var animation = this.animationsMap[ name ];
  23874. if ( animation ) {
  23875. duration = animation.duration;
  23876. }
  23877. return duration;
  23878. };
  23879. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  23880. var animation = this.animationsMap[ name ];
  23881. if ( animation ) {
  23882. animation.time = 0;
  23883. animation.active = true;
  23884. } else {
  23885. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  23886. }
  23887. };
  23888. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  23889. var animation = this.animationsMap[ name ];
  23890. if ( animation ) {
  23891. animation.active = false;
  23892. }
  23893. };
  23894. MorphBlendMesh.prototype.update = function ( delta ) {
  23895. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  23896. var animation = this.animationsList[ i ];
  23897. if ( ! animation.active ) continue;
  23898. var frameTime = animation.duration / animation.length;
  23899. animation.time += animation.direction * delta;
  23900. if ( animation.mirroredLoop ) {
  23901. if ( animation.time > animation.duration || animation.time < 0 ) {
  23902. animation.direction *= - 1;
  23903. if ( animation.time > animation.duration ) {
  23904. animation.time = animation.duration;
  23905. animation.directionBackwards = true;
  23906. }
  23907. if ( animation.time < 0 ) {
  23908. animation.time = 0;
  23909. animation.directionBackwards = false;
  23910. }
  23911. }
  23912. } else {
  23913. animation.time = animation.time % animation.duration;
  23914. if ( animation.time < 0 ) animation.time += animation.duration;
  23915. }
  23916. var keyframe = animation.start + _Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  23917. var weight = animation.weight;
  23918. if ( keyframe !== animation.currentFrame ) {
  23919. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  23920. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  23921. this.morphTargetInfluences[ keyframe ] = 0;
  23922. animation.lastFrame = animation.currentFrame;
  23923. animation.currentFrame = keyframe;
  23924. }
  23925. var mix = ( animation.time % frameTime ) / frameTime;
  23926. if ( animation.directionBackwards ) mix = 1 - mix;
  23927. if ( animation.currentFrame !== animation.lastFrame ) {
  23928. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  23929. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  23930. } else {
  23931. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  23932. }
  23933. }
  23934. };
  23935. /**
  23936. * @author alteredq / http://alteredqualia.com/
  23937. */
  23938. function ImmediateRenderObject( material ) {
  23939. Object3D.call( this );
  23940. this.material = material;
  23941. this.render = function ( renderCallback ) {};
  23942. }
  23943. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  23944. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  23945. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  23946. /**
  23947. * @author mrdoob / http://mrdoob.com/
  23948. * @author WestLangley / http://github.com/WestLangley
  23949. */
  23950. function VertexNormalsHelper( object, size, hex, linewidth ) {
  23951. this.object = object;
  23952. this.size = ( size !== undefined ) ? size : 1;
  23953. var color = ( hex !== undefined ) ? hex : 0xff0000;
  23954. var width = ( linewidth !== undefined ) ? linewidth : 1;
  23955. //
  23956. var nNormals = 0;
  23957. var objGeometry = this.object.geometry;
  23958. if ( objGeometry && objGeometry.isGeometry ) {
  23959. nNormals = objGeometry.faces.length * 3;
  23960. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  23961. nNormals = objGeometry.attributes.normal.count;
  23962. }
  23963. //
  23964. var geometry = new BufferGeometry();
  23965. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  23966. geometry.addAttribute( 'position', positions );
  23967. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  23968. //
  23969. this.matrixAutoUpdate = false;
  23970. this.update();
  23971. }
  23972. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  23973. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  23974. VertexNormalsHelper.prototype.update = ( function () {
  23975. var v1 = new Vector3();
  23976. var v2 = new Vector3();
  23977. var normalMatrix = new Matrix3();
  23978. return function update() {
  23979. var keys = [ 'a', 'b', 'c' ];
  23980. this.object.updateMatrixWorld( true );
  23981. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  23982. var matrixWorld = this.object.matrixWorld;
  23983. var position = this.geometry.attributes.position;
  23984. //
  23985. var objGeometry = this.object.geometry;
  23986. if ( objGeometry && objGeometry.isGeometry ) {
  23987. var vertices = objGeometry.vertices;
  23988. var faces = objGeometry.faces;
  23989. var idx = 0;
  23990. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23991. var face = faces[ i ];
  23992. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  23993. var vertex = vertices[ face[ keys[ j ] ] ];
  23994. var normal = face.vertexNormals[ j ];
  23995. v1.copy( vertex ).applyMatrix4( matrixWorld );
  23996. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23997. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23998. idx = idx + 1;
  23999. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24000. idx = idx + 1;
  24001. }
  24002. }
  24003. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24004. var objPos = objGeometry.attributes.position;
  24005. var objNorm = objGeometry.attributes.normal;
  24006. var idx = 0;
  24007. // for simplicity, ignore index and drawcalls, and render every normal
  24008. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  24009. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  24010. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  24011. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24012. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24013. idx = idx + 1;
  24014. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24015. idx = idx + 1;
  24016. }
  24017. }
  24018. position.needsUpdate = true;
  24019. return this;
  24020. };
  24021. }() );
  24022. /**
  24023. * @author alteredq / http://alteredqualia.com/
  24024. * @author mrdoob / http://mrdoob.com/
  24025. * @author WestLangley / http://github.com/WestLangley
  24026. */
  24027. function SpotLightHelper( light ) {
  24028. Object3D.call( this );
  24029. this.light = light;
  24030. this.light.updateMatrixWorld();
  24031. this.matrix = light.matrixWorld;
  24032. this.matrixAutoUpdate = false;
  24033. var geometry = new BufferGeometry();
  24034. var positions = [
  24035. 0, 0, 0, 0, 0, 1,
  24036. 0, 0, 0, 1, 0, 1,
  24037. 0, 0, 0, - 1, 0, 1,
  24038. 0, 0, 0, 0, 1, 1,
  24039. 0, 0, 0, 0, - 1, 1
  24040. ];
  24041. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  24042. var p1 = ( i / l ) * Math.PI * 2;
  24043. var p2 = ( j / l ) * Math.PI * 2;
  24044. positions.push(
  24045. Math.cos( p1 ), Math.sin( p1 ), 1,
  24046. Math.cos( p2 ), Math.sin( p2 ), 1
  24047. );
  24048. }
  24049. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  24050. var material = new LineBasicMaterial( { fog: false } );
  24051. this.cone = new LineSegments( geometry, material );
  24052. this.add( this.cone );
  24053. this.update();
  24054. }
  24055. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  24056. SpotLightHelper.prototype.constructor = SpotLightHelper;
  24057. SpotLightHelper.prototype.dispose = function () {
  24058. this.cone.geometry.dispose();
  24059. this.cone.material.dispose();
  24060. };
  24061. SpotLightHelper.prototype.update = function () {
  24062. var vector = new Vector3();
  24063. var vector2 = new Vector3();
  24064. return function update() {
  24065. var coneLength = this.light.distance ? this.light.distance : 1000;
  24066. var coneWidth = coneLength * Math.tan( this.light.angle );
  24067. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  24068. vector.setFromMatrixPosition( this.light.matrixWorld );
  24069. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24070. this.cone.lookAt( vector2.sub( vector ) );
  24071. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24072. };
  24073. }();
  24074. /**
  24075. * @author Sean Griffin / http://twitter.com/sgrif
  24076. * @author Michael Guerrero / http://realitymeltdown.com
  24077. * @author mrdoob / http://mrdoob.com/
  24078. * @author ikerr / http://verold.com
  24079. * @author Mugen87 / https://github.com/Mugen87
  24080. */
  24081. function SkeletonHelper( object ) {
  24082. this.bones = this.getBoneList( object );
  24083. var geometry = new BufferGeometry();
  24084. var vertices = [];
  24085. var colors = [];
  24086. var color1 = new Color( 0, 0, 1 );
  24087. var color2 = new Color( 0, 1, 0 );
  24088. for ( var i = 0; i < this.bones.length; i ++ ) {
  24089. var bone = this.bones[ i ];
  24090. if ( bone.parent && bone.parent.isBone ) {
  24091. vertices.push( 0, 0, 0 );
  24092. vertices.push( 0, 0, 0 );
  24093. colors.push( color1.r, color1.g, color1.b );
  24094. colors.push( color2.r, color2.g, color2.b );
  24095. }
  24096. }
  24097. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24098. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24099. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  24100. LineSegments.call( this, geometry, material );
  24101. this.root = object;
  24102. this.matrix = object.matrixWorld;
  24103. this.matrixAutoUpdate = false;
  24104. this.update();
  24105. }
  24106. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  24107. SkeletonHelper.prototype.constructor = SkeletonHelper;
  24108. SkeletonHelper.prototype.getBoneList = function( object ) {
  24109. var boneList = [];
  24110. if ( object && object.isBone ) {
  24111. boneList.push( object );
  24112. }
  24113. for ( var i = 0; i < object.children.length; i ++ ) {
  24114. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  24115. }
  24116. return boneList;
  24117. };
  24118. SkeletonHelper.prototype.update = function () {
  24119. var vector = new Vector3();
  24120. var boneMatrix = new Matrix4();
  24121. var matrixWorldInv = new Matrix4();
  24122. return function update() {
  24123. var geometry = this.geometry;
  24124. var position = geometry.getAttribute( 'position' );
  24125. matrixWorldInv.getInverse( this.root.matrixWorld );
  24126. for ( var i = 0, j = 0; i < this.bones.length; i ++ ) {
  24127. var bone = this.bones[ i ];
  24128. if ( bone.parent && bone.parent.isBone ) {
  24129. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  24130. vector.setFromMatrixPosition( boneMatrix );
  24131. position.setXYZ( j, vector.x, vector.y, vector.z );
  24132. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  24133. vector.setFromMatrixPosition( boneMatrix );
  24134. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  24135. j += 2;
  24136. }
  24137. }
  24138. geometry.getAttribute( 'position' ).needsUpdate = true;
  24139. };
  24140. }();
  24141. /**
  24142. * @author alteredq / http://alteredqualia.com/
  24143. * @author mrdoob / http://mrdoob.com/
  24144. */
  24145. function PointLightHelper( light, sphereSize ) {
  24146. this.light = light;
  24147. this.light.updateMatrixWorld();
  24148. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  24149. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  24150. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24151. Mesh.call( this, geometry, material );
  24152. this.matrix = this.light.matrixWorld;
  24153. this.matrixAutoUpdate = false;
  24154. /*
  24155. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  24156. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  24157. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  24158. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  24159. var d = light.distance;
  24160. if ( d === 0.0 ) {
  24161. this.lightDistance.visible = false;
  24162. } else {
  24163. this.lightDistance.scale.set( d, d, d );
  24164. }
  24165. this.add( this.lightDistance );
  24166. */
  24167. }
  24168. PointLightHelper.prototype = Object.create( Mesh.prototype );
  24169. PointLightHelper.prototype.constructor = PointLightHelper;
  24170. PointLightHelper.prototype.dispose = function () {
  24171. this.geometry.dispose();
  24172. this.material.dispose();
  24173. };
  24174. PointLightHelper.prototype.update = function () {
  24175. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24176. /*
  24177. var d = this.light.distance;
  24178. if ( d === 0.0 ) {
  24179. this.lightDistance.visible = false;
  24180. } else {
  24181. this.lightDistance.visible = true;
  24182. this.lightDistance.scale.set( d, d, d );
  24183. }
  24184. */
  24185. };
  24186. /**
  24187. * @author abelnation / http://github.com/abelnation
  24188. * @author Mugen87 / http://github.com/Mugen87
  24189. */
  24190. function RectAreaLightHelper( light ) {
  24191. Object3D.call( this );
  24192. this.light = light;
  24193. this.light.updateMatrixWorld();
  24194. var materialFront = new MeshBasicMaterial( {
  24195. color: light.color,
  24196. fog: false
  24197. } );
  24198. var materialBack = new MeshBasicMaterial( {
  24199. color: light.color,
  24200. fog: false,
  24201. wireframe: true
  24202. } );
  24203. var geometry = new BufferGeometry();
  24204. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 6 * 3 ), 3 ) );
  24205. // shows the "front" of the light, e.g. where light comes from
  24206. this.add( new Mesh( geometry, materialFront ) );
  24207. // shows the "back" of the light, which does not emit light
  24208. this.add( new Mesh( geometry, materialBack ) );
  24209. this.update();
  24210. }
  24211. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  24212. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  24213. RectAreaLightHelper.prototype.dispose = function () {
  24214. this.children[ 0 ].geometry.dispose();
  24215. this.children[ 0 ].material.dispose();
  24216. this.children[ 1 ].geometry.dispose();
  24217. this.children[ 1 ].material.dispose();
  24218. };
  24219. RectAreaLightHelper.prototype.update = function () {
  24220. var vector1 = new Vector3();
  24221. var vector2 = new Vector3();
  24222. return function update() {
  24223. var mesh1 = this.children[ 0 ];
  24224. var mesh2 = this.children[ 1 ];
  24225. if ( this.light.target ) {
  24226. vector1.setFromMatrixPosition( this.light.matrixWorld );
  24227. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24228. var lookVec = vector2.clone().sub( vector1 );
  24229. mesh1.lookAt( lookVec );
  24230. mesh2.lookAt( lookVec );
  24231. }
  24232. // update materials
  24233. mesh1.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24234. mesh2.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24235. // calculate new dimensions of the helper
  24236. var hx = this.light.width * 0.5;
  24237. var hy = this.light.height * 0.5;
  24238. // because the buffer attribute is shared over both geometries, we only have to update once
  24239. var position = mesh1.geometry.getAttribute( 'position' );
  24240. var array = position.array;
  24241. // first face
  24242. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  24243. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  24244. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  24245. // second face
  24246. array[ 9 ] = - hx; array[ 10 ] = hy; array[ 11 ] = 0;
  24247. array[ 12 ] = - hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  24248. array[ 15 ] = hx; array[ 16 ] = - hy; array[ 17 ] = 0;
  24249. position.needsUpdate = true;
  24250. };
  24251. }();
  24252. /**
  24253. * @author alteredq / http://alteredqualia.com/
  24254. * @author mrdoob / http://mrdoob.com/
  24255. * @author Mugen87 / https://github.com/Mugen87
  24256. */
  24257. function HemisphereLightHelper( light, size ) {
  24258. Object3D.call( this );
  24259. this.light = light;
  24260. this.light.updateMatrixWorld();
  24261. this.matrix = light.matrixWorld;
  24262. this.matrixAutoUpdate = false;
  24263. var geometry = new OctahedronBufferGeometry( size );
  24264. geometry.rotateY( Math.PI * 0.5 );
  24265. var material = new MeshBasicMaterial( { vertexColors: VertexColors, wireframe: true } );
  24266. var position = geometry.getAttribute( 'position' );
  24267. var colors = new Float32Array( position.count * 3 );
  24268. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  24269. this.add( new Mesh( geometry, material ) );
  24270. this.update();
  24271. }
  24272. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  24273. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  24274. HemisphereLightHelper.prototype.dispose = function () {
  24275. this.children[ 0 ].geometry.dispose();
  24276. this.children[ 0 ].material.dispose();
  24277. };
  24278. HemisphereLightHelper.prototype.update = function () {
  24279. var vector = new Vector3();
  24280. var color1 = new Color();
  24281. var color2 = new Color();
  24282. return function update() {
  24283. var mesh = this.children[ 0 ];
  24284. var colors = mesh.geometry.getAttribute( 'color' );
  24285. color1.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24286. color2.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  24287. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  24288. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  24289. colors.setXYZ( i, color.r, color.g, color.b );
  24290. }
  24291. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  24292. colors.needsUpdate = true;
  24293. };
  24294. }();
  24295. /**
  24296. * @author mrdoob / http://mrdoob.com/
  24297. */
  24298. function GridHelper( size, divisions, color1, color2 ) {
  24299. size = size || 10;
  24300. divisions = divisions || 10;
  24301. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24302. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24303. var center = divisions / 2;
  24304. var step = ( size * 2 ) / divisions;
  24305. var vertices = [], colors = [];
  24306. for ( var i = 0, j = 0, k = - size; i <= divisions; i ++, k += step ) {
  24307. vertices.push( - size, 0, k, size, 0, k );
  24308. vertices.push( k, 0, - size, k, 0, size );
  24309. var color = i === center ? color1 : color2;
  24310. color.toArray( colors, j ); j += 3;
  24311. color.toArray( colors, j ); j += 3;
  24312. color.toArray( colors, j ); j += 3;
  24313. color.toArray( colors, j ); j += 3;
  24314. }
  24315. var geometry = new BufferGeometry();
  24316. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24317. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24318. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24319. LineSegments.call( this, geometry, material );
  24320. }
  24321. GridHelper.prototype = Object.create( LineSegments.prototype );
  24322. GridHelper.prototype.constructor = GridHelper;
  24323. /**
  24324. * @author mrdoob / http://mrdoob.com/
  24325. * @author Mugen87 / http://github.com/Mugen87
  24326. * @author Hectate / http://www.github.com/Hectate
  24327. */
  24328. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  24329. radius = radius || 10;
  24330. radials = radials || 16;
  24331. circles = circles || 8;
  24332. divisions = divisions || 64;
  24333. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24334. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24335. var vertices = [];
  24336. var colors = [];
  24337. var x, z;
  24338. var v, i, j, r, color;
  24339. // create the radials
  24340. for ( i = 0; i <= radials; i ++ ) {
  24341. v = ( i / radials ) * ( Math.PI * 2 );
  24342. x = Math.sin( v ) * radius;
  24343. z = Math.cos( v ) * radius;
  24344. vertices.push( 0, 0, 0 );
  24345. vertices.push( x, 0, z );
  24346. color = ( i & 1 ) ? color1 : color2;
  24347. colors.push( color.r, color.g, color.b );
  24348. colors.push( color.r, color.g, color.b );
  24349. }
  24350. // create the circles
  24351. for ( i = 0; i <= circles; i ++ ) {
  24352. color = ( i & 1 ) ? color1 : color2;
  24353. r = radius - ( radius / circles * i );
  24354. for ( j = 0; j < divisions; j ++ ) {
  24355. // first vertex
  24356. v = ( j / divisions ) * ( Math.PI * 2 );
  24357. x = Math.sin( v ) * r;
  24358. z = Math.cos( v ) * r;
  24359. vertices.push( x, 0, z );
  24360. colors.push( color.r, color.g, color.b );
  24361. // second vertex
  24362. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  24363. x = Math.sin( v ) * r;
  24364. z = Math.cos( v ) * r;
  24365. vertices.push( x, 0, z );
  24366. colors.push( color.r, color.g, color.b );
  24367. }
  24368. }
  24369. var geometry = new BufferGeometry();
  24370. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24371. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24372. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24373. LineSegments.call( this, geometry, material );
  24374. }
  24375. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  24376. PolarGridHelper.prototype.constructor = PolarGridHelper;
  24377. /**
  24378. * @author mrdoob / http://mrdoob.com/
  24379. * @author WestLangley / http://github.com/WestLangley
  24380. */
  24381. function FaceNormalsHelper( object, size, hex, linewidth ) {
  24382. // FaceNormalsHelper only supports THREE.Geometry
  24383. this.object = object;
  24384. this.size = ( size !== undefined ) ? size : 1;
  24385. var color = ( hex !== undefined ) ? hex : 0xffff00;
  24386. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24387. //
  24388. var nNormals = 0;
  24389. var objGeometry = this.object.geometry;
  24390. if ( objGeometry && objGeometry.isGeometry ) {
  24391. nNormals = objGeometry.faces.length;
  24392. } else {
  24393. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  24394. }
  24395. //
  24396. var geometry = new BufferGeometry();
  24397. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24398. geometry.addAttribute( 'position', positions );
  24399. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24400. //
  24401. this.matrixAutoUpdate = false;
  24402. this.update();
  24403. }
  24404. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24405. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  24406. FaceNormalsHelper.prototype.update = ( function () {
  24407. var v1 = new Vector3();
  24408. var v2 = new Vector3();
  24409. var normalMatrix = new Matrix3();
  24410. return function update() {
  24411. this.object.updateMatrixWorld( true );
  24412. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24413. var matrixWorld = this.object.matrixWorld;
  24414. var position = this.geometry.attributes.position;
  24415. //
  24416. var objGeometry = this.object.geometry;
  24417. var vertices = objGeometry.vertices;
  24418. var faces = objGeometry.faces;
  24419. var idx = 0;
  24420. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24421. var face = faces[ i ];
  24422. var normal = face.normal;
  24423. v1.copy( vertices[ face.a ] )
  24424. .add( vertices[ face.b ] )
  24425. .add( vertices[ face.c ] )
  24426. .divideScalar( 3 )
  24427. .applyMatrix4( matrixWorld );
  24428. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24429. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24430. idx = idx + 1;
  24431. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24432. idx = idx + 1;
  24433. }
  24434. position.needsUpdate = true;
  24435. return this;
  24436. };
  24437. }() );
  24438. /**
  24439. * @author alteredq / http://alteredqualia.com/
  24440. * @author mrdoob / http://mrdoob.com/
  24441. * @author WestLangley / http://github.com/WestLangley
  24442. */
  24443. function DirectionalLightHelper( light, size ) {
  24444. Object3D.call( this );
  24445. this.light = light;
  24446. this.light.updateMatrixWorld();
  24447. this.matrix = light.matrixWorld;
  24448. this.matrixAutoUpdate = false;
  24449. if ( size === undefined ) size = 1;
  24450. var geometry = new BufferGeometry();
  24451. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  24452. - size, size, 0,
  24453. size, size, 0,
  24454. size, - size, 0,
  24455. - size, - size, 0,
  24456. - size, size, 0
  24457. ], 3 ) );
  24458. var material = new LineBasicMaterial( { fog: false } );
  24459. this.add( new Line( geometry, material ) );
  24460. geometry = new BufferGeometry();
  24461. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  24462. this.add( new Line( geometry, material ));
  24463. this.update();
  24464. }
  24465. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  24466. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  24467. DirectionalLightHelper.prototype.dispose = function () {
  24468. var lightPlane = this.children[ 0 ];
  24469. var targetLine = this.children[ 1 ];
  24470. lightPlane.geometry.dispose();
  24471. lightPlane.material.dispose();
  24472. targetLine.geometry.dispose();
  24473. targetLine.material.dispose();
  24474. };
  24475. DirectionalLightHelper.prototype.update = function () {
  24476. var v1 = new Vector3();
  24477. var v2 = new Vector3();
  24478. var v3 = new Vector3();
  24479. return function update() {
  24480. v1.setFromMatrixPosition( this.light.matrixWorld );
  24481. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  24482. v3.subVectors( v2, v1 );
  24483. var lightPlane = this.children[ 0 ];
  24484. var targetLine = this.children[ 1 ];
  24485. lightPlane.lookAt( v3 );
  24486. lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24487. targetLine.lookAt( v3 );
  24488. targetLine.scale.z = v3.length();
  24489. };
  24490. }();
  24491. /**
  24492. * @author alteredq / http://alteredqualia.com/
  24493. * @author Mugen87 / https://github.com/Mugen87
  24494. *
  24495. * - shows frustum, line of sight and up of the camera
  24496. * - suitable for fast updates
  24497. * - based on frustum visualization in lightgl.js shadowmap example
  24498. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  24499. */
  24500. function CameraHelper( camera ) {
  24501. var geometry = new BufferGeometry();
  24502. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  24503. var vertices = [];
  24504. var colors = [];
  24505. var pointMap = {};
  24506. // colors
  24507. var colorFrustum = new Color( 0xffaa00 );
  24508. var colorCone = new Color( 0xff0000 );
  24509. var colorUp = new Color( 0x00aaff );
  24510. var colorTarget = new Color( 0xffffff );
  24511. var colorCross = new Color( 0x333333 );
  24512. // near
  24513. addLine( "n1", "n2", colorFrustum );
  24514. addLine( "n2", "n4", colorFrustum );
  24515. addLine( "n4", "n3", colorFrustum );
  24516. addLine( "n3", "n1", colorFrustum );
  24517. // far
  24518. addLine( "f1", "f2", colorFrustum );
  24519. addLine( "f2", "f4", colorFrustum );
  24520. addLine( "f4", "f3", colorFrustum );
  24521. addLine( "f3", "f1", colorFrustum );
  24522. // sides
  24523. addLine( "n1", "f1", colorFrustum );
  24524. addLine( "n2", "f2", colorFrustum );
  24525. addLine( "n3", "f3", colorFrustum );
  24526. addLine( "n4", "f4", colorFrustum );
  24527. // cone
  24528. addLine( "p", "n1", colorCone );
  24529. addLine( "p", "n2", colorCone );
  24530. addLine( "p", "n3", colorCone );
  24531. addLine( "p", "n4", colorCone );
  24532. // up
  24533. addLine( "u1", "u2", colorUp );
  24534. addLine( "u2", "u3", colorUp );
  24535. addLine( "u3", "u1", colorUp );
  24536. // target
  24537. addLine( "c", "t", colorTarget );
  24538. addLine( "p", "c", colorCross );
  24539. // cross
  24540. addLine( "cn1", "cn2", colorCross );
  24541. addLine( "cn3", "cn4", colorCross );
  24542. addLine( "cf1", "cf2", colorCross );
  24543. addLine( "cf3", "cf4", colorCross );
  24544. function addLine( a, b, color ) {
  24545. addPoint( a, color );
  24546. addPoint( b, color );
  24547. }
  24548. function addPoint( id, color ) {
  24549. vertices.push( 0, 0, 0 );
  24550. colors.push( color.r, color.g, color.b );
  24551. if ( pointMap[ id ] === undefined ) {
  24552. pointMap[ id ] = [];
  24553. }
  24554. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  24555. }
  24556. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24557. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24558. LineSegments.call( this, geometry, material );
  24559. this.camera = camera;
  24560. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  24561. this.matrix = camera.matrixWorld;
  24562. this.matrixAutoUpdate = false;
  24563. this.pointMap = pointMap;
  24564. this.update();
  24565. }
  24566. CameraHelper.prototype = Object.create( LineSegments.prototype );
  24567. CameraHelper.prototype.constructor = CameraHelper;
  24568. CameraHelper.prototype.update = function () {
  24569. var geometry, pointMap;
  24570. var vector = new Vector3();
  24571. var camera = new Camera();
  24572. function setPoint( point, x, y, z ) {
  24573. vector.set( x, y, z ).unproject( camera );
  24574. var points = pointMap[ point ];
  24575. if ( points !== undefined ) {
  24576. var position = geometry.getAttribute( 'position' );
  24577. for ( var i = 0, l = points.length; i < l; i ++ ) {
  24578. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  24579. }
  24580. }
  24581. }
  24582. return function update() {
  24583. geometry = this.geometry;
  24584. pointMap = this.pointMap;
  24585. var w = 1, h = 1;
  24586. // we need just camera projection matrix
  24587. // world matrix must be identity
  24588. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  24589. // center / target
  24590. setPoint( "c", 0, 0, - 1 );
  24591. setPoint( "t", 0, 0, 1 );
  24592. // near
  24593. setPoint( "n1", - w, - h, - 1 );
  24594. setPoint( "n2", w, - h, - 1 );
  24595. setPoint( "n3", - w, h, - 1 );
  24596. setPoint( "n4", w, h, - 1 );
  24597. // far
  24598. setPoint( "f1", - w, - h, 1 );
  24599. setPoint( "f2", w, - h, 1 );
  24600. setPoint( "f3", - w, h, 1 );
  24601. setPoint( "f4", w, h, 1 );
  24602. // up
  24603. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  24604. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  24605. setPoint( "u3", 0, h * 2, - 1 );
  24606. // cross
  24607. setPoint( "cf1", - w, 0, 1 );
  24608. setPoint( "cf2", w, 0, 1 );
  24609. setPoint( "cf3", 0, - h, 1 );
  24610. setPoint( "cf4", 0, h, 1 );
  24611. setPoint( "cn1", - w, 0, - 1 );
  24612. setPoint( "cn2", w, 0, - 1 );
  24613. setPoint( "cn3", 0, - h, - 1 );
  24614. setPoint( "cn4", 0, h, - 1 );
  24615. geometry.getAttribute( 'position' ).needsUpdate = true;
  24616. };
  24617. }();
  24618. /**
  24619. * @author mrdoob / http://mrdoob.com/
  24620. */
  24621. function BoxHelper( object, color ) {
  24622. if ( color === undefined ) color = 0xffff00;
  24623. 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 ] );
  24624. var positions = new Float32Array( 8 * 3 );
  24625. var geometry = new BufferGeometry();
  24626. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  24627. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  24628. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  24629. if ( object !== undefined ) {
  24630. this.update( object );
  24631. }
  24632. }
  24633. BoxHelper.prototype = Object.create( LineSegments.prototype );
  24634. BoxHelper.prototype.constructor = BoxHelper;
  24635. BoxHelper.prototype.update = ( function () {
  24636. var box = new Box3();
  24637. return function update( object ) {
  24638. if ( object && object.isBox3 ) {
  24639. box.copy( object );
  24640. } else {
  24641. box.setFromObject( object );
  24642. }
  24643. if ( box.isEmpty() ) return;
  24644. var min = box.min;
  24645. var max = box.max;
  24646. /*
  24647. 5____4
  24648. 1/___0/|
  24649. | 6__|_7
  24650. 2/___3/
  24651. 0: max.x, max.y, max.z
  24652. 1: min.x, max.y, max.z
  24653. 2: min.x, min.y, max.z
  24654. 3: max.x, min.y, max.z
  24655. 4: max.x, max.y, min.z
  24656. 5: min.x, max.y, min.z
  24657. 6: min.x, min.y, min.z
  24658. 7: max.x, min.y, min.z
  24659. */
  24660. var position = this.geometry.attributes.position;
  24661. var array = position.array;
  24662. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  24663. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  24664. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  24665. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  24666. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  24667. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  24668. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  24669. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  24670. position.needsUpdate = true;
  24671. this.geometry.computeBoundingSphere();
  24672. };
  24673. } )();
  24674. /**
  24675. * @author WestLangley / http://github.com/WestLangley
  24676. * @author zz85 / http://github.com/zz85
  24677. * @author bhouston / http://clara.io
  24678. *
  24679. * Creates an arrow for visualizing directions
  24680. *
  24681. * Parameters:
  24682. * dir - Vector3
  24683. * origin - Vector3
  24684. * length - Number
  24685. * color - color in hex value
  24686. * headLength - Number
  24687. * headWidth - Number
  24688. */
  24689. var lineGeometry = new BufferGeometry();
  24690. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  24691. var coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  24692. coneGeometry.translate( 0, - 0.5, 0 );
  24693. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  24694. // dir is assumed to be normalized
  24695. Object3D.call( this );
  24696. if ( color === undefined ) color = 0xffff00;
  24697. if ( length === undefined ) length = 1;
  24698. if ( headLength === undefined ) headLength = 0.2 * length;
  24699. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24700. this.position.copy( origin );
  24701. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  24702. this.line.matrixAutoUpdate = false;
  24703. this.add( this.line );
  24704. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  24705. this.cone.matrixAutoUpdate = false;
  24706. this.add( this.cone );
  24707. this.setDirection( dir );
  24708. this.setLength( length, headLength, headWidth );
  24709. }
  24710. ArrowHelper.prototype = Object.create( Object3D.prototype );
  24711. ArrowHelper.prototype.constructor = ArrowHelper;
  24712. ArrowHelper.prototype.setDirection = ( function () {
  24713. var axis = new Vector3();
  24714. var radians;
  24715. return function setDirection( dir ) {
  24716. // dir is assumed to be normalized
  24717. if ( dir.y > 0.99999 ) {
  24718. this.quaternion.set( 0, 0, 0, 1 );
  24719. } else if ( dir.y < - 0.99999 ) {
  24720. this.quaternion.set( 1, 0, 0, 0 );
  24721. } else {
  24722. axis.set( dir.z, 0, - dir.x ).normalize();
  24723. radians = Math.acos( dir.y );
  24724. this.quaternion.setFromAxisAngle( axis, radians );
  24725. }
  24726. };
  24727. }() );
  24728. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  24729. if ( headLength === undefined ) headLength = 0.2 * length;
  24730. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24731. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  24732. this.line.updateMatrix();
  24733. this.cone.scale.set( headWidth, headLength, headWidth );
  24734. this.cone.position.y = length;
  24735. this.cone.updateMatrix();
  24736. };
  24737. ArrowHelper.prototype.setColor = function ( color ) {
  24738. this.line.material.color.copy( color );
  24739. this.cone.material.color.copy( color );
  24740. };
  24741. /**
  24742. * @author sroucheray / http://sroucheray.org/
  24743. * @author mrdoob / http://mrdoob.com/
  24744. */
  24745. function AxisHelper( size ) {
  24746. size = size || 1;
  24747. var vertices = [
  24748. 0, 0, 0, size, 0, 0,
  24749. 0, 0, 0, 0, size, 0,
  24750. 0, 0, 0, 0, 0, size
  24751. ];
  24752. var colors = [
  24753. 1, 0, 0, 1, 0.6, 0,
  24754. 0, 1, 0, 0.6, 1, 0,
  24755. 0, 0, 1, 0, 0.6, 1
  24756. ];
  24757. var geometry = new BufferGeometry();
  24758. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24759. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24760. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24761. LineSegments.call( this, geometry, material );
  24762. }
  24763. AxisHelper.prototype = Object.create( LineSegments.prototype );
  24764. AxisHelper.prototype.constructor = AxisHelper;
  24765. /**
  24766. * @author zz85 https://github.com/zz85
  24767. *
  24768. * Centripetal CatmullRom Curve - which is useful for avoiding
  24769. * cusps and self-intersections in non-uniform catmull rom curves.
  24770. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  24771. *
  24772. * curve.type accepts centripetal(default), chordal and catmullrom
  24773. * curve.tension is used for catmullrom which defaults to 0.5
  24774. */
  24775. var CatmullRomCurve3 = ( function() {
  24776. var
  24777. tmp = new Vector3(),
  24778. px = new CubicPoly(),
  24779. py = new CubicPoly(),
  24780. pz = new CubicPoly();
  24781. /*
  24782. Based on an optimized c++ solution in
  24783. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  24784. - http://ideone.com/NoEbVM
  24785. This CubicPoly class could be used for reusing some variables and calculations,
  24786. but for three.js curve use, it could be possible inlined and flatten into a single function call
  24787. which can be placed in CurveUtils.
  24788. */
  24789. function CubicPoly() {}
  24790. /*
  24791. * Compute coefficients for a cubic polynomial
  24792. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  24793. * such that
  24794. * p(0) = x0, p(1) = x1
  24795. * and
  24796. * p'(0) = t0, p'(1) = t1.
  24797. */
  24798. CubicPoly.prototype.init = function( x0, x1, t0, t1 ) {
  24799. this.c0 = x0;
  24800. this.c1 = t0;
  24801. this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  24802. this.c3 = 2 * x0 - 2 * x1 + t0 + t1;
  24803. };
  24804. CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  24805. // compute tangents when parameterized in [t1,t2]
  24806. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  24807. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  24808. // rescale tangents for parametrization in [0,1]
  24809. t1 *= dt1;
  24810. t2 *= dt1;
  24811. // initCubicPoly
  24812. this.init( x1, x2, t1, t2 );
  24813. };
  24814. // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4
  24815. CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) {
  24816. this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  24817. };
  24818. CubicPoly.prototype.calc = function( t ) {
  24819. var t2 = t * t;
  24820. var t3 = t2 * t;
  24821. return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3;
  24822. };
  24823. // Subclass Three.js curve
  24824. return Curve.create(
  24825. function ( p /* array of Vector3 */ ) {
  24826. this.points = p || [];
  24827. this.closed = false;
  24828. },
  24829. function ( t ) {
  24830. var points = this.points,
  24831. point, intPoint, weight, l;
  24832. l = points.length;
  24833. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  24834. point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  24835. intPoint = Math.floor( point );
  24836. weight = point - intPoint;
  24837. if ( this.closed ) {
  24838. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  24839. } else if ( weight === 0 && intPoint === l - 1 ) {
  24840. intPoint = l - 2;
  24841. weight = 1;
  24842. }
  24843. var p0, p1, p2, p3; // 4 points
  24844. if ( this.closed || intPoint > 0 ) {
  24845. p0 = points[ ( intPoint - 1 ) % l ];
  24846. } else {
  24847. // extrapolate first point
  24848. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  24849. p0 = tmp;
  24850. }
  24851. p1 = points[ intPoint % l ];
  24852. p2 = points[ ( intPoint + 1 ) % l ];
  24853. if ( this.closed || intPoint + 2 < l ) {
  24854. p3 = points[ ( intPoint + 2 ) % l ];
  24855. } else {
  24856. // extrapolate last point
  24857. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24858. p3 = tmp;
  24859. }
  24860. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  24861. // init Centripetal / Chordal Catmull-Rom
  24862. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  24863. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24864. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24865. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24866. // safety check for repeated points
  24867. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24868. if ( dt0 < 1e-4 ) dt0 = dt1;
  24869. if ( dt2 < 1e-4 ) dt2 = dt1;
  24870. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24871. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24872. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24873. } else if ( this.type === 'catmullrom' ) {
  24874. var tension = this.tension !== undefined ? this.tension : 0.5;
  24875. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  24876. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  24877. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  24878. }
  24879. var v = new Vector3(
  24880. px.calc( weight ),
  24881. py.calc( weight ),
  24882. pz.calc( weight )
  24883. );
  24884. return v;
  24885. }
  24886. );
  24887. } )();
  24888. /**************************************************************
  24889. * Spline 3D curve
  24890. **************************************************************/
  24891. var SplineCurve3 = Curve.create(
  24892. function ( points /* array of Vector3 */ ) {
  24893. console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' );
  24894. this.points = ( points === undefined ) ? [] : points;
  24895. },
  24896. function ( t ) {
  24897. var points = this.points;
  24898. var point = ( points.length - 1 ) * t;
  24899. var intPoint = Math.floor( point );
  24900. var weight = point - intPoint;
  24901. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  24902. var point1 = points[ intPoint ];
  24903. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24904. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24905. var interpolate = CurveUtils.interpolate;
  24906. return new Vector3(
  24907. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  24908. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  24909. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  24910. );
  24911. }
  24912. );
  24913. /**************************************************************
  24914. * Cubic Bezier 3D curve
  24915. **************************************************************/
  24916. var CubicBezierCurve3 = Curve.create(
  24917. function ( v0, v1, v2, v3 ) {
  24918. this.v0 = v0;
  24919. this.v1 = v1;
  24920. this.v2 = v2;
  24921. this.v3 = v3;
  24922. },
  24923. function ( t ) {
  24924. var b3 = ShapeUtils.b3;
  24925. return new Vector3(
  24926. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  24927. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ),
  24928. b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z )
  24929. );
  24930. }
  24931. );
  24932. /**************************************************************
  24933. * Quadratic Bezier 3D curve
  24934. **************************************************************/
  24935. var QuadraticBezierCurve3 = Curve.create(
  24936. function ( v0, v1, v2 ) {
  24937. this.v0 = v0;
  24938. this.v1 = v1;
  24939. this.v2 = v2;
  24940. },
  24941. function ( t ) {
  24942. var b2 = ShapeUtils.b2;
  24943. return new Vector3(
  24944. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  24945. b2( t, this.v0.y, this.v1.y, this.v2.y ),
  24946. b2( t, this.v0.z, this.v1.z, this.v2.z )
  24947. );
  24948. }
  24949. );
  24950. /**************************************************************
  24951. * Line3D
  24952. **************************************************************/
  24953. var LineCurve3 = Curve.create(
  24954. function ( v1, v2 ) {
  24955. this.v1 = v1;
  24956. this.v2 = v2;
  24957. },
  24958. function ( t ) {
  24959. if ( t === 1 ) {
  24960. return this.v2.clone();
  24961. }
  24962. var vector = new Vector3();
  24963. vector.subVectors( this.v2, this.v1 ); // diff
  24964. vector.multiplyScalar( t );
  24965. vector.add( this.v1 );
  24966. return vector;
  24967. }
  24968. );
  24969. /**************************************************************
  24970. * Arc curve
  24971. **************************************************************/
  24972. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24973. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24974. }
  24975. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  24976. ArcCurve.prototype.constructor = ArcCurve;
  24977. /**
  24978. * @author alteredq / http://alteredqualia.com/
  24979. */
  24980. var SceneUtils = {
  24981. createMultiMaterialObject: function ( geometry, materials ) {
  24982. var group = new Group();
  24983. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  24984. group.add( new Mesh( geometry, materials[ i ] ) );
  24985. }
  24986. return group;
  24987. },
  24988. detach: function ( child, parent, scene ) {
  24989. child.applyMatrix( parent.matrixWorld );
  24990. parent.remove( child );
  24991. scene.add( child );
  24992. },
  24993. attach: function ( child, scene, parent ) {
  24994. var matrixWorldInverse = new Matrix4();
  24995. matrixWorldInverse.getInverse( parent.matrixWorld );
  24996. child.applyMatrix( matrixWorldInverse );
  24997. scene.remove( child );
  24998. parent.add( child );
  24999. }
  25000. };
  25001. /**
  25002. * @author mrdoob / http://mrdoob.com/
  25003. */
  25004. function Face4( a, b, c, d, normal, color, materialIndex ) {
  25005. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  25006. return new Face3( a, b, c, normal, color, materialIndex );
  25007. }
  25008. var LineStrip = 0;
  25009. var LinePieces = 1;
  25010. function MeshFaceMaterial( materials ) {
  25011. console.warn( 'THREE.MeshFaceMaterial has been renamed to THREE.MultiMaterial.' );
  25012. return new MultiMaterial( materials );
  25013. }
  25014. function PointCloud( geometry, material ) {
  25015. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  25016. return new Points( geometry, material );
  25017. }
  25018. function Particle( material ) {
  25019. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  25020. return new Sprite( material );
  25021. }
  25022. function ParticleSystem( geometry, material ) {
  25023. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  25024. return new Points( geometry, material );
  25025. }
  25026. function PointCloudMaterial( parameters ) {
  25027. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  25028. return new PointsMaterial( parameters );
  25029. }
  25030. function ParticleBasicMaterial( parameters ) {
  25031. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  25032. return new PointsMaterial( parameters );
  25033. }
  25034. function ParticleSystemMaterial( parameters ) {
  25035. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  25036. return new PointsMaterial( parameters );
  25037. }
  25038. function Vertex( x, y, z ) {
  25039. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  25040. return new Vector3( x, y, z );
  25041. }
  25042. //
  25043. function DynamicBufferAttribute( array, itemSize ) {
  25044. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  25045. return new BufferAttribute( array, itemSize ).setDynamic( true );
  25046. }
  25047. function Int8Attribute( array, itemSize ) {
  25048. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  25049. return new Int8BufferAttribute( array, itemSize );
  25050. }
  25051. function Uint8Attribute( array, itemSize ) {
  25052. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  25053. return new Uint8BufferAttribute( array, itemSize );
  25054. }
  25055. function Uint8ClampedAttribute( array, itemSize ) {
  25056. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  25057. return new Uint8ClampedBufferAttribute( array, itemSize );
  25058. }
  25059. function Int16Attribute( array, itemSize ) {
  25060. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  25061. return new Int16BufferAttribute( array, itemSize );
  25062. }
  25063. function Uint16Attribute( array, itemSize ) {
  25064. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  25065. return new Uint16BufferAttribute( array, itemSize );
  25066. }
  25067. function Int32Attribute( array, itemSize ) {
  25068. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  25069. return new Int32BufferAttribute( array, itemSize );
  25070. }
  25071. function Uint32Attribute( array, itemSize ) {
  25072. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  25073. return new Uint32BufferAttribute( array, itemSize );
  25074. }
  25075. function Float32Attribute( array, itemSize ) {
  25076. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  25077. return new Float32BufferAttribute( array, itemSize );
  25078. }
  25079. function Float64Attribute( array, itemSize ) {
  25080. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  25081. return new Float64BufferAttribute( array, itemSize );
  25082. }
  25083. //
  25084. function ClosedSplineCurve3( points ) {
  25085. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25086. CatmullRomCurve3.call( this, points );
  25087. this.type = 'catmullrom';
  25088. this.closed = true;
  25089. }
  25090. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25091. //
  25092. function BoundingBoxHelper( object, color ) {
  25093. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  25094. return new BoxHelper( object, color );
  25095. }
  25096. function EdgesHelper( object, hex ) {
  25097. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  25098. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25099. }
  25100. GridHelper.prototype.setColors = function () {
  25101. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  25102. };
  25103. function WireframeHelper( object, hex ) {
  25104. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  25105. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25106. }
  25107. //
  25108. function XHRLoader( manager ) {
  25109. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  25110. return new FileLoader( manager );
  25111. }
  25112. //
  25113. Object.assign( Box2.prototype, {
  25114. center: function ( optionalTarget ) {
  25115. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  25116. return this.getCenter( optionalTarget );
  25117. },
  25118. empty: function () {
  25119. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  25120. return this.isEmpty();
  25121. },
  25122. isIntersectionBox: function ( box ) {
  25123. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25124. return this.intersectsBox( box );
  25125. },
  25126. size: function ( optionalTarget ) {
  25127. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  25128. return this.getSize( optionalTarget );
  25129. }
  25130. } );
  25131. Object.assign( Box3.prototype, {
  25132. center: function ( optionalTarget ) {
  25133. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  25134. return this.getCenter( optionalTarget );
  25135. },
  25136. empty: function () {
  25137. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  25138. return this.isEmpty();
  25139. },
  25140. isIntersectionBox: function ( box ) {
  25141. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25142. return this.intersectsBox( box );
  25143. },
  25144. isIntersectionSphere: function ( sphere ) {
  25145. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25146. return this.intersectsSphere( sphere );
  25147. },
  25148. size: function ( optionalTarget ) {
  25149. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  25150. return this.getSize( optionalTarget );
  25151. }
  25152. } );
  25153. Line3.prototype.center = function ( optionalTarget ) {
  25154. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  25155. return this.getCenter( optionalTarget );
  25156. };
  25157. _Math.random16 = function () {
  25158. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  25159. return Math.random();
  25160. };
  25161. Object.assign( Matrix3.prototype, {
  25162. flattenToArrayOffset: function ( array, offset ) {
  25163. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25164. return this.toArray( array, offset );
  25165. },
  25166. multiplyVector3: function ( vector ) {
  25167. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  25168. return vector.applyMatrix3( this );
  25169. },
  25170. multiplyVector3Array: function ( a ) {
  25171. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  25172. return this.applyToVector3Array( a );
  25173. }
  25174. } );
  25175. Object.assign( Matrix4.prototype, {
  25176. extractPosition: function ( m ) {
  25177. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  25178. return this.copyPosition( m );
  25179. },
  25180. flattenToArrayOffset: function ( array, offset ) {
  25181. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25182. return this.toArray( array, offset );
  25183. },
  25184. getPosition: function () {
  25185. var v1;
  25186. return function getPosition() {
  25187. if ( v1 === undefined ) v1 = new Vector3();
  25188. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  25189. return v1.setFromMatrixColumn( this, 3 );
  25190. };
  25191. }(),
  25192. setRotationFromQuaternion: function ( q ) {
  25193. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  25194. return this.makeRotationFromQuaternion( q );
  25195. },
  25196. multiplyVector3: function ( vector ) {
  25197. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  25198. return vector.applyProjection( this );
  25199. },
  25200. multiplyVector4: function ( vector ) {
  25201. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25202. return vector.applyMatrix4( this );
  25203. },
  25204. multiplyVector3Array: function ( a ) {
  25205. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  25206. return this.applyToVector3Array( a );
  25207. },
  25208. rotateAxis: function ( v ) {
  25209. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  25210. v.transformDirection( this );
  25211. },
  25212. crossVector: function ( vector ) {
  25213. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25214. return vector.applyMatrix4( this );
  25215. },
  25216. translate: function () {
  25217. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  25218. },
  25219. rotateX: function () {
  25220. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  25221. },
  25222. rotateY: function () {
  25223. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  25224. },
  25225. rotateZ: function () {
  25226. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  25227. },
  25228. rotateByAxis: function () {
  25229. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  25230. }
  25231. } );
  25232. Plane.prototype.isIntersectionLine = function ( line ) {
  25233. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  25234. return this.intersectsLine( line );
  25235. };
  25236. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  25237. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  25238. return vector.applyQuaternion( this );
  25239. };
  25240. Object.assign( Ray.prototype, {
  25241. isIntersectionBox: function ( box ) {
  25242. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25243. return this.intersectsBox( box );
  25244. },
  25245. isIntersectionPlane: function ( plane ) {
  25246. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  25247. return this.intersectsPlane( plane );
  25248. },
  25249. isIntersectionSphere: function ( sphere ) {
  25250. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25251. return this.intersectsSphere( sphere );
  25252. }
  25253. } );
  25254. Object.assign( Shape.prototype, {
  25255. extrude: function ( options ) {
  25256. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  25257. return new ExtrudeGeometry( this, options );
  25258. },
  25259. makeGeometry: function ( options ) {
  25260. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  25261. return new ShapeGeometry( this, options );
  25262. }
  25263. } );
  25264. Object.assign( Vector3.prototype, {
  25265. setEulerFromRotationMatrix: function () {
  25266. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  25267. },
  25268. setEulerFromQuaternion: function () {
  25269. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  25270. },
  25271. getPositionFromMatrix: function ( m ) {
  25272. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  25273. return this.setFromMatrixPosition( m );
  25274. },
  25275. getScaleFromMatrix: function ( m ) {
  25276. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  25277. return this.setFromMatrixScale( m );
  25278. },
  25279. getColumnFromMatrix: function ( index, matrix ) {
  25280. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  25281. return this.setFromMatrixColumn( matrix, index );
  25282. }
  25283. } );
  25284. //
  25285. Geometry.prototype.computeTangents = function () {
  25286. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  25287. };
  25288. Object.assign( Object3D.prototype, {
  25289. getChildByName: function ( name ) {
  25290. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  25291. return this.getObjectByName( name );
  25292. },
  25293. renderDepth: function () {
  25294. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  25295. },
  25296. translate: function ( distance, axis ) {
  25297. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  25298. return this.translateOnAxis( axis, distance );
  25299. }
  25300. } );
  25301. Object.defineProperties( Object3D.prototype, {
  25302. eulerOrder: {
  25303. get: function () {
  25304. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25305. return this.rotation.order;
  25306. },
  25307. set: function ( value ) {
  25308. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25309. this.rotation.order = value;
  25310. }
  25311. },
  25312. useQuaternion: {
  25313. get: function () {
  25314. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25315. },
  25316. set: function () {
  25317. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25318. }
  25319. }
  25320. } );
  25321. Object.defineProperties( LOD.prototype, {
  25322. objects: {
  25323. get: function () {
  25324. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  25325. return this.levels;
  25326. }
  25327. }
  25328. } );
  25329. //
  25330. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  25331. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  25332. "Use .setFocalLength and .filmGauge for a photographic setup." );
  25333. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  25334. this.setFocalLength( focalLength );
  25335. };
  25336. //
  25337. Object.defineProperties( Light.prototype, {
  25338. onlyShadow: {
  25339. set: function () {
  25340. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  25341. }
  25342. },
  25343. shadowCameraFov: {
  25344. set: function ( value ) {
  25345. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  25346. this.shadow.camera.fov = value;
  25347. }
  25348. },
  25349. shadowCameraLeft: {
  25350. set: function ( value ) {
  25351. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  25352. this.shadow.camera.left = value;
  25353. }
  25354. },
  25355. shadowCameraRight: {
  25356. set: function ( value ) {
  25357. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  25358. this.shadow.camera.right = value;
  25359. }
  25360. },
  25361. shadowCameraTop: {
  25362. set: function ( value ) {
  25363. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  25364. this.shadow.camera.top = value;
  25365. }
  25366. },
  25367. shadowCameraBottom: {
  25368. set: function ( value ) {
  25369. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  25370. this.shadow.camera.bottom = value;
  25371. }
  25372. },
  25373. shadowCameraNear: {
  25374. set: function ( value ) {
  25375. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  25376. this.shadow.camera.near = value;
  25377. }
  25378. },
  25379. shadowCameraFar: {
  25380. set: function ( value ) {
  25381. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  25382. this.shadow.camera.far = value;
  25383. }
  25384. },
  25385. shadowCameraVisible: {
  25386. set: function () {
  25387. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  25388. }
  25389. },
  25390. shadowBias: {
  25391. set: function ( value ) {
  25392. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  25393. this.shadow.bias = value;
  25394. }
  25395. },
  25396. shadowDarkness: {
  25397. set: function () {
  25398. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  25399. }
  25400. },
  25401. shadowMapWidth: {
  25402. set: function ( value ) {
  25403. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  25404. this.shadow.mapSize.width = value;
  25405. }
  25406. },
  25407. shadowMapHeight: {
  25408. set: function ( value ) {
  25409. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  25410. this.shadow.mapSize.height = value;
  25411. }
  25412. }
  25413. } );
  25414. //
  25415. Object.defineProperties( BufferAttribute.prototype, {
  25416. length: {
  25417. get: function () {
  25418. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  25419. return this.array.length;
  25420. }
  25421. }
  25422. } );
  25423. Object.assign( BufferGeometry.prototype, {
  25424. addIndex: function ( index ) {
  25425. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  25426. this.setIndex( index );
  25427. },
  25428. addDrawCall: function ( start, count, indexOffset ) {
  25429. if ( indexOffset !== undefined ) {
  25430. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  25431. }
  25432. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  25433. this.addGroup( start, count );
  25434. },
  25435. clearDrawCalls: function () {
  25436. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  25437. this.clearGroups();
  25438. },
  25439. computeTangents: function () {
  25440. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  25441. },
  25442. computeOffsets: function () {
  25443. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  25444. }
  25445. } );
  25446. Object.defineProperties( BufferGeometry.prototype, {
  25447. drawcalls: {
  25448. get: function () {
  25449. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  25450. return this.groups;
  25451. }
  25452. },
  25453. offsets: {
  25454. get: function () {
  25455. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  25456. return this.groups;
  25457. }
  25458. }
  25459. } );
  25460. //
  25461. Object.defineProperties( Uniform.prototype, {
  25462. dynamic: {
  25463. set: function () {
  25464. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  25465. }
  25466. },
  25467. onUpdate: {
  25468. value: function () {
  25469. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  25470. return this;
  25471. }
  25472. }
  25473. } );
  25474. //
  25475. Object.defineProperties( Material.prototype, {
  25476. wrapAround: {
  25477. get: function () {
  25478. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  25479. },
  25480. set: function () {
  25481. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  25482. }
  25483. },
  25484. wrapRGB: {
  25485. get: function () {
  25486. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  25487. return new Color();
  25488. }
  25489. }
  25490. } );
  25491. Object.defineProperties( MeshPhongMaterial.prototype, {
  25492. metal: {
  25493. get: function () {
  25494. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  25495. return false;
  25496. },
  25497. set: function () {
  25498. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  25499. }
  25500. }
  25501. } );
  25502. Object.defineProperties( ShaderMaterial.prototype, {
  25503. derivatives: {
  25504. get: function () {
  25505. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25506. return this.extensions.derivatives;
  25507. },
  25508. set: function ( value ) {
  25509. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25510. this.extensions.derivatives = value;
  25511. }
  25512. }
  25513. } );
  25514. //
  25515. EventDispatcher.prototype = Object.assign( Object.create( {
  25516. // Note: Extra base ensures these properties are not 'assign'ed.
  25517. constructor: EventDispatcher,
  25518. apply: function ( target ) {
  25519. console.warn( "THREE.EventDispatcher: .apply is deprecated, " +
  25520. "just inherit or Object.assign the prototype to mix-in." );
  25521. Object.assign( target, this );
  25522. }
  25523. } ), EventDispatcher.prototype );
  25524. //
  25525. Object.assign( WebGLRenderer.prototype, {
  25526. supportsFloatTextures: function () {
  25527. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  25528. return this.extensions.get( 'OES_texture_float' );
  25529. },
  25530. supportsHalfFloatTextures: function () {
  25531. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  25532. return this.extensions.get( 'OES_texture_half_float' );
  25533. },
  25534. supportsStandardDerivatives: function () {
  25535. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  25536. return this.extensions.get( 'OES_standard_derivatives' );
  25537. },
  25538. supportsCompressedTextureS3TC: function () {
  25539. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  25540. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  25541. },
  25542. supportsCompressedTexturePVRTC: function () {
  25543. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  25544. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  25545. },
  25546. supportsBlendMinMax: function () {
  25547. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  25548. return this.extensions.get( 'EXT_blend_minmax' );
  25549. },
  25550. supportsVertexTextures: function () {
  25551. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  25552. return this.capabilities.vertexTextures;
  25553. },
  25554. supportsInstancedArrays: function () {
  25555. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  25556. return this.extensions.get( 'ANGLE_instanced_arrays' );
  25557. },
  25558. enableScissorTest: function ( boolean ) {
  25559. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  25560. this.setScissorTest( boolean );
  25561. },
  25562. initMaterial: function () {
  25563. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  25564. },
  25565. addPrePlugin: function () {
  25566. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  25567. },
  25568. addPostPlugin: function () {
  25569. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  25570. },
  25571. updateShadowMap: function () {
  25572. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  25573. }
  25574. } );
  25575. Object.defineProperties( WebGLRenderer.prototype, {
  25576. shadowMapEnabled: {
  25577. get: function () {
  25578. return this.shadowMap.enabled;
  25579. },
  25580. set: function ( value ) {
  25581. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  25582. this.shadowMap.enabled = value;
  25583. }
  25584. },
  25585. shadowMapType: {
  25586. get: function () {
  25587. return this.shadowMap.type;
  25588. },
  25589. set: function ( value ) {
  25590. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  25591. this.shadowMap.type = value;
  25592. }
  25593. },
  25594. shadowMapCullFace: {
  25595. get: function () {
  25596. return this.shadowMap.cullFace;
  25597. },
  25598. set: function ( value ) {
  25599. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  25600. this.shadowMap.cullFace = value;
  25601. }
  25602. }
  25603. } );
  25604. Object.defineProperties( WebGLShadowMap.prototype, {
  25605. cullFace: {
  25606. get: function () {
  25607. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  25608. },
  25609. set: function ( cullFace ) {
  25610. var value = ( cullFace !== CullFaceBack );
  25611. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  25612. this.renderReverseSided = value;
  25613. }
  25614. }
  25615. } );
  25616. //
  25617. Object.defineProperties( WebGLRenderTarget.prototype, {
  25618. wrapS: {
  25619. get: function () {
  25620. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25621. return this.texture.wrapS;
  25622. },
  25623. set: function ( value ) {
  25624. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25625. this.texture.wrapS = value;
  25626. }
  25627. },
  25628. wrapT: {
  25629. get: function () {
  25630. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25631. return this.texture.wrapT;
  25632. },
  25633. set: function ( value ) {
  25634. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25635. this.texture.wrapT = value;
  25636. }
  25637. },
  25638. magFilter: {
  25639. get: function () {
  25640. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25641. return this.texture.magFilter;
  25642. },
  25643. set: function ( value ) {
  25644. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25645. this.texture.magFilter = value;
  25646. }
  25647. },
  25648. minFilter: {
  25649. get: function () {
  25650. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25651. return this.texture.minFilter;
  25652. },
  25653. set: function ( value ) {
  25654. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25655. this.texture.minFilter = value;
  25656. }
  25657. },
  25658. anisotropy: {
  25659. get: function () {
  25660. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25661. return this.texture.anisotropy;
  25662. },
  25663. set: function ( value ) {
  25664. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25665. this.texture.anisotropy = value;
  25666. }
  25667. },
  25668. offset: {
  25669. get: function () {
  25670. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25671. return this.texture.offset;
  25672. },
  25673. set: function ( value ) {
  25674. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25675. this.texture.offset = value;
  25676. }
  25677. },
  25678. repeat: {
  25679. get: function () {
  25680. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25681. return this.texture.repeat;
  25682. },
  25683. set: function ( value ) {
  25684. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25685. this.texture.repeat = value;
  25686. }
  25687. },
  25688. format: {
  25689. get: function () {
  25690. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25691. return this.texture.format;
  25692. },
  25693. set: function ( value ) {
  25694. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25695. this.texture.format = value;
  25696. }
  25697. },
  25698. type: {
  25699. get: function () {
  25700. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25701. return this.texture.type;
  25702. },
  25703. set: function ( value ) {
  25704. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25705. this.texture.type = value;
  25706. }
  25707. },
  25708. generateMipmaps: {
  25709. get: function () {
  25710. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25711. return this.texture.generateMipmaps;
  25712. },
  25713. set: function ( value ) {
  25714. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25715. this.texture.generateMipmaps = value;
  25716. }
  25717. }
  25718. } );
  25719. //
  25720. Audio.prototype.load = function ( file ) {
  25721. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  25722. var scope = this;
  25723. var audioLoader = new AudioLoader();
  25724. audioLoader.load( file, function ( buffer ) {
  25725. scope.setBuffer( buffer );
  25726. } );
  25727. return this;
  25728. };
  25729. AudioAnalyser.prototype.getData = function () {
  25730. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  25731. return this.getFrequencyData();
  25732. };
  25733. //
  25734. var GeometryUtils = {
  25735. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  25736. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  25737. var matrix;
  25738. if ( geometry2.isMesh ) {
  25739. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  25740. matrix = geometry2.matrix;
  25741. geometry2 = geometry2.geometry;
  25742. }
  25743. geometry1.merge( geometry2, matrix, materialIndexOffset );
  25744. },
  25745. center: function ( geometry ) {
  25746. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  25747. return geometry.center();
  25748. }
  25749. };
  25750. var ImageUtils = {
  25751. crossOrigin: undefined,
  25752. loadTexture: function ( url, mapping, onLoad, onError ) {
  25753. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  25754. var loader = new TextureLoader();
  25755. loader.setCrossOrigin( this.crossOrigin );
  25756. var texture = loader.load( url, onLoad, undefined, onError );
  25757. if ( mapping ) texture.mapping = mapping;
  25758. return texture;
  25759. },
  25760. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  25761. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  25762. var loader = new CubeTextureLoader();
  25763. loader.setCrossOrigin( this.crossOrigin );
  25764. var texture = loader.load( urls, onLoad, undefined, onError );
  25765. if ( mapping ) texture.mapping = mapping;
  25766. return texture;
  25767. },
  25768. loadCompressedTexture: function () {
  25769. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  25770. },
  25771. loadCompressedTextureCube: function () {
  25772. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  25773. }
  25774. };
  25775. var UniformsUtils = {
  25776. merge: function ( uniforms ) {
  25777. console.warn( 'THREE.UniformsUtils.merge() has been deprecated. Use Object.assign() instead.' );
  25778. var merged = {};
  25779. for ( var u = 0; u < uniforms.length; u ++ ) {
  25780. var tmp = this.clone( uniforms[ u ] );
  25781. for ( var p in tmp ) {
  25782. merged[ p ] = tmp[ p ];
  25783. }
  25784. }
  25785. return merged;
  25786. },
  25787. clone: function ( uniforms_src ) {
  25788. console.warn( 'THREE.UniformsUtils.clone() has been deprecated.' );
  25789. var uniforms_dst = {};
  25790. for ( var u in uniforms_src ) {
  25791. uniforms_dst[ u ] = {};
  25792. for ( var p in uniforms_src[ u ] ) {
  25793. var parameter_src = uniforms_src[ u ][ p ];
  25794. if ( parameter_src && ( parameter_src.isColor ||
  25795. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  25796. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  25797. parameter_src.isTexture ) ) {
  25798. uniforms_dst[ u ][ p ] = parameter_src.clone();
  25799. } else if ( Array.isArray( parameter_src ) ) {
  25800. uniforms_dst[ u ][ p ] = parameter_src.slice();
  25801. } else {
  25802. uniforms_dst[ u ][ p ] = parameter_src;
  25803. }
  25804. }
  25805. }
  25806. return uniforms_dst;
  25807. }
  25808. };
  25809. //
  25810. function Projector() {
  25811. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  25812. this.projectVector = function ( vector, camera ) {
  25813. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  25814. vector.project( camera );
  25815. };
  25816. this.unprojectVector = function ( vector, camera ) {
  25817. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  25818. vector.unproject( camera );
  25819. };
  25820. this.pickingRay = function () {
  25821. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  25822. };
  25823. }
  25824. //
  25825. function CanvasRenderer() {
  25826. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  25827. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  25828. this.clear = function () {};
  25829. this.render = function () {};
  25830. this.setClearColor = function () {};
  25831. this.setSize = function () {};
  25832. }
  25833. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  25834. exports.WebGLRenderTarget = WebGLRenderTarget;
  25835. exports.WebGLRenderer = WebGLRenderer;
  25836. exports.ShaderLib = ShaderLib;
  25837. exports.UniformsLib = UniformsLib;
  25838. exports.ShaderChunk = ShaderChunk;
  25839. exports.FogExp2 = FogExp2;
  25840. exports.Fog = Fog;
  25841. exports.Scene = Scene;
  25842. exports.LensFlare = LensFlare;
  25843. exports.Sprite = Sprite;
  25844. exports.LOD = LOD;
  25845. exports.SkinnedMesh = SkinnedMesh;
  25846. exports.Skeleton = Skeleton;
  25847. exports.Bone = Bone;
  25848. exports.Mesh = Mesh;
  25849. exports.LineSegments = LineSegments;
  25850. exports.Line = Line;
  25851. exports.Points = Points;
  25852. exports.Group = Group;
  25853. exports.VideoTexture = VideoTexture;
  25854. exports.DataTexture = DataTexture;
  25855. exports.CompressedTexture = CompressedTexture;
  25856. exports.CubeTexture = CubeTexture;
  25857. exports.CanvasTexture = CanvasTexture;
  25858. exports.DepthTexture = DepthTexture;
  25859. exports.Texture = Texture;
  25860. exports.CompressedTextureLoader = CompressedTextureLoader;
  25861. exports.BinaryTextureLoader = BinaryTextureLoader;
  25862. exports.DataTextureLoader = DataTextureLoader;
  25863. exports.CubeTextureLoader = CubeTextureLoader;
  25864. exports.TextureLoader = TextureLoader;
  25865. exports.ObjectLoader = ObjectLoader;
  25866. exports.MaterialLoader = MaterialLoader;
  25867. exports.BufferGeometryLoader = BufferGeometryLoader;
  25868. exports.DefaultLoadingManager = DefaultLoadingManager;
  25869. exports.LoadingManager = LoadingManager;
  25870. exports.JSONLoader = JSONLoader;
  25871. exports.ImageLoader = ImageLoader;
  25872. exports.FontLoader = FontLoader;
  25873. exports.FileLoader = FileLoader;
  25874. exports.Loader = Loader;
  25875. exports.Cache = Cache;
  25876. exports.AudioLoader = AudioLoader;
  25877. exports.SpotLightShadow = SpotLightShadow;
  25878. exports.SpotLight = SpotLight;
  25879. exports.PointLight = PointLight;
  25880. exports.RectAreaLight = RectAreaLight;
  25881. exports.HemisphereLight = HemisphereLight;
  25882. exports.DirectionalLightShadow = DirectionalLightShadow;
  25883. exports.DirectionalLight = DirectionalLight;
  25884. exports.AmbientLight = AmbientLight;
  25885. exports.LightShadow = LightShadow;
  25886. exports.Light = Light;
  25887. exports.StereoCamera = StereoCamera;
  25888. exports.PerspectiveCamera = PerspectiveCamera;
  25889. exports.OrthographicCamera = OrthographicCamera;
  25890. exports.CubeCamera = CubeCamera;
  25891. exports.Camera = Camera;
  25892. exports.AudioListener = AudioListener;
  25893. exports.PositionalAudio = PositionalAudio;
  25894. exports.AudioContext = AudioContext;
  25895. exports.AudioAnalyser = AudioAnalyser;
  25896. exports.Audio = Audio;
  25897. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  25898. exports.StringKeyframeTrack = StringKeyframeTrack;
  25899. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  25900. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  25901. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  25902. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  25903. exports.PropertyMixer = PropertyMixer;
  25904. exports.PropertyBinding = PropertyBinding;
  25905. exports.KeyframeTrack = KeyframeTrack;
  25906. exports.AnimationUtils = AnimationUtils;
  25907. exports.AnimationObjectGroup = AnimationObjectGroup;
  25908. exports.AnimationMixer = AnimationMixer;
  25909. exports.AnimationClip = AnimationClip;
  25910. exports.Uniform = Uniform;
  25911. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  25912. exports.BufferGeometry = BufferGeometry;
  25913. exports.GeometryIdCount = GeometryIdCount;
  25914. exports.Geometry = Geometry;
  25915. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  25916. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  25917. exports.InterleavedBuffer = InterleavedBuffer;
  25918. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  25919. exports.Face3 = Face3;
  25920. exports.Object3D = Object3D;
  25921. exports.Raycaster = Raycaster;
  25922. exports.Layers = Layers;
  25923. exports.EventDispatcher = EventDispatcher;
  25924. exports.Clock = Clock;
  25925. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  25926. exports.LinearInterpolant = LinearInterpolant;
  25927. exports.DiscreteInterpolant = DiscreteInterpolant;
  25928. exports.CubicInterpolant = CubicInterpolant;
  25929. exports.Interpolant = Interpolant;
  25930. exports.Triangle = Triangle;
  25931. exports.Spline = Spline;
  25932. exports.Math = _Math;
  25933. exports.Spherical = Spherical;
  25934. exports.Cylindrical = Cylindrical;
  25935. exports.Plane = Plane;
  25936. exports.Frustum = Frustum;
  25937. exports.Sphere = Sphere;
  25938. exports.Ray = Ray;
  25939. exports.Matrix4 = Matrix4;
  25940. exports.Matrix3 = Matrix3;
  25941. exports.Box3 = Box3;
  25942. exports.Box2 = Box2;
  25943. exports.Line3 = Line3;
  25944. exports.Euler = Euler;
  25945. exports.Vector4 = Vector4;
  25946. exports.Vector3 = Vector3;
  25947. exports.Vector2 = Vector2;
  25948. exports.Quaternion = Quaternion;
  25949. exports.Color = Color;
  25950. exports.MorphBlendMesh = MorphBlendMesh;
  25951. exports.ImmediateRenderObject = ImmediateRenderObject;
  25952. exports.VertexNormalsHelper = VertexNormalsHelper;
  25953. exports.SpotLightHelper = SpotLightHelper;
  25954. exports.SkeletonHelper = SkeletonHelper;
  25955. exports.PointLightHelper = PointLightHelper;
  25956. exports.RectAreaLightHelper = RectAreaLightHelper;
  25957. exports.HemisphereLightHelper = HemisphereLightHelper;
  25958. exports.GridHelper = GridHelper;
  25959. exports.PolarGridHelper = PolarGridHelper;
  25960. exports.FaceNormalsHelper = FaceNormalsHelper;
  25961. exports.DirectionalLightHelper = DirectionalLightHelper;
  25962. exports.CameraHelper = CameraHelper;
  25963. exports.BoxHelper = BoxHelper;
  25964. exports.ArrowHelper = ArrowHelper;
  25965. exports.AxisHelper = AxisHelper;
  25966. exports.CatmullRomCurve3 = CatmullRomCurve3;
  25967. exports.SplineCurve3 = SplineCurve3;
  25968. exports.CubicBezierCurve3 = CubicBezierCurve3;
  25969. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  25970. exports.LineCurve3 = LineCurve3;
  25971. exports.ArcCurve = ArcCurve;
  25972. exports.EllipseCurve = EllipseCurve;
  25973. exports.SplineCurve = SplineCurve;
  25974. exports.CubicBezierCurve = CubicBezierCurve;
  25975. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  25976. exports.LineCurve = LineCurve;
  25977. exports.Shape = Shape;
  25978. exports.ShapePath = ShapePath;
  25979. exports.Path = Path;
  25980. exports.Font = Font;
  25981. exports.CurvePath = CurvePath;
  25982. exports.Curve = Curve;
  25983. exports.ShapeUtils = ShapeUtils;
  25984. exports.SceneUtils = SceneUtils;
  25985. exports.CurveUtils = CurveUtils;
  25986. exports.WireframeGeometry = WireframeGeometry;
  25987. exports.ParametricGeometry = ParametricGeometry;
  25988. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  25989. exports.TetrahedronGeometry = TetrahedronGeometry;
  25990. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  25991. exports.OctahedronGeometry = OctahedronGeometry;
  25992. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  25993. exports.IcosahedronGeometry = IcosahedronGeometry;
  25994. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  25995. exports.DodecahedronGeometry = DodecahedronGeometry;
  25996. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  25997. exports.PolyhedronGeometry = PolyhedronGeometry;
  25998. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  25999. exports.TubeGeometry = TubeGeometry;
  26000. exports.TubeBufferGeometry = TubeBufferGeometry;
  26001. exports.TorusKnotGeometry = TorusKnotGeometry;
  26002. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  26003. exports.TorusGeometry = TorusGeometry;
  26004. exports.TorusBufferGeometry = TorusBufferGeometry;
  26005. exports.TextGeometry = TextGeometry;
  26006. exports.SphereBufferGeometry = SphereBufferGeometry;
  26007. exports.SphereGeometry = SphereGeometry;
  26008. exports.RingGeometry = RingGeometry;
  26009. exports.RingBufferGeometry = RingBufferGeometry;
  26010. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  26011. exports.PlaneGeometry = PlaneGeometry;
  26012. exports.LatheGeometry = LatheGeometry;
  26013. exports.LatheBufferGeometry = LatheBufferGeometry;
  26014. exports.ShapeGeometry = ShapeGeometry;
  26015. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  26016. exports.ExtrudeGeometry = ExtrudeGeometry;
  26017. exports.EdgesGeometry = EdgesGeometry;
  26018. exports.ConeGeometry = ConeGeometry;
  26019. exports.ConeBufferGeometry = ConeBufferGeometry;
  26020. exports.CylinderGeometry = CylinderGeometry;
  26021. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  26022. exports.CircleBufferGeometry = CircleBufferGeometry;
  26023. exports.CircleGeometry = CircleGeometry;
  26024. exports.BoxBufferGeometry = BoxBufferGeometry;
  26025. exports.BoxGeometry = BoxGeometry;
  26026. exports.ShadowMaterial = ShadowMaterial;
  26027. exports.SpriteMaterial = SpriteMaterial;
  26028. exports.RawShaderMaterial = RawShaderMaterial;
  26029. exports.ShaderMaterial = ShaderMaterial;
  26030. exports.PointsMaterial = PointsMaterial;
  26031. exports.MultiMaterial = MultiMaterial;
  26032. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  26033. exports.MeshStandardMaterial = MeshStandardMaterial;
  26034. exports.MeshPhongMaterial = MeshPhongMaterial;
  26035. exports.MeshToonMaterial = MeshToonMaterial;
  26036. exports.MeshNormalMaterial = MeshNormalMaterial;
  26037. exports.MeshLambertMaterial = MeshLambertMaterial;
  26038. exports.MeshDepthMaterial = MeshDepthMaterial;
  26039. exports.MeshBasicMaterial = MeshBasicMaterial;
  26040. exports.LineDashedMaterial = LineDashedMaterial;
  26041. exports.LineBasicMaterial = LineBasicMaterial;
  26042. exports.Material = Material;
  26043. exports.Float64BufferAttribute = Float64BufferAttribute;
  26044. exports.Float32BufferAttribute = Float32BufferAttribute;
  26045. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  26046. exports.Int32BufferAttribute = Int32BufferAttribute;
  26047. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  26048. exports.Int16BufferAttribute = Int16BufferAttribute;
  26049. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  26050. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  26051. exports.Int8BufferAttribute = Int8BufferAttribute;
  26052. exports.BufferAttribute = BufferAttribute;
  26053. exports.REVISION = REVISION;
  26054. exports.MOUSE = MOUSE;
  26055. exports.CullFaceNone = CullFaceNone;
  26056. exports.CullFaceBack = CullFaceBack;
  26057. exports.CullFaceFront = CullFaceFront;
  26058. exports.CullFaceFrontBack = CullFaceFrontBack;
  26059. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  26060. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  26061. exports.BasicShadowMap = BasicShadowMap;
  26062. exports.PCFShadowMap = PCFShadowMap;
  26063. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  26064. exports.FrontSide = FrontSide;
  26065. exports.BackSide = BackSide;
  26066. exports.DoubleSide = DoubleSide;
  26067. exports.FlatShading = FlatShading;
  26068. exports.SmoothShading = SmoothShading;
  26069. exports.NoColors = NoColors;
  26070. exports.FaceColors = FaceColors;
  26071. exports.VertexColors = VertexColors;
  26072. exports.NoBlending = NoBlending;
  26073. exports.NormalBlending = NormalBlending;
  26074. exports.AdditiveBlending = AdditiveBlending;
  26075. exports.SubtractiveBlending = SubtractiveBlending;
  26076. exports.MultiplyBlending = MultiplyBlending;
  26077. exports.CustomBlending = CustomBlending;
  26078. exports.BlendingMode = BlendingMode;
  26079. exports.AddEquation = AddEquation;
  26080. exports.SubtractEquation = SubtractEquation;
  26081. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  26082. exports.MinEquation = MinEquation;
  26083. exports.MaxEquation = MaxEquation;
  26084. exports.ZeroFactor = ZeroFactor;
  26085. exports.OneFactor = OneFactor;
  26086. exports.SrcColorFactor = SrcColorFactor;
  26087. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  26088. exports.SrcAlphaFactor = SrcAlphaFactor;
  26089. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  26090. exports.DstAlphaFactor = DstAlphaFactor;
  26091. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  26092. exports.DstColorFactor = DstColorFactor;
  26093. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  26094. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  26095. exports.NeverDepth = NeverDepth;
  26096. exports.AlwaysDepth = AlwaysDepth;
  26097. exports.LessDepth = LessDepth;
  26098. exports.LessEqualDepth = LessEqualDepth;
  26099. exports.EqualDepth = EqualDepth;
  26100. exports.GreaterEqualDepth = GreaterEqualDepth;
  26101. exports.GreaterDepth = GreaterDepth;
  26102. exports.NotEqualDepth = NotEqualDepth;
  26103. exports.MultiplyOperation = MultiplyOperation;
  26104. exports.MixOperation = MixOperation;
  26105. exports.AddOperation = AddOperation;
  26106. exports.NoToneMapping = NoToneMapping;
  26107. exports.LinearToneMapping = LinearToneMapping;
  26108. exports.ReinhardToneMapping = ReinhardToneMapping;
  26109. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  26110. exports.CineonToneMapping = CineonToneMapping;
  26111. exports.UVMapping = UVMapping;
  26112. exports.CubeReflectionMapping = CubeReflectionMapping;
  26113. exports.CubeRefractionMapping = CubeRefractionMapping;
  26114. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  26115. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  26116. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  26117. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  26118. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  26119. exports.TextureMapping = TextureMapping;
  26120. exports.RepeatWrapping = RepeatWrapping;
  26121. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  26122. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  26123. exports.TextureWrapping = TextureWrapping;
  26124. exports.NearestFilter = NearestFilter;
  26125. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  26126. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  26127. exports.LinearFilter = LinearFilter;
  26128. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  26129. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  26130. exports.TextureFilter = TextureFilter;
  26131. exports.UnsignedByteType = UnsignedByteType;
  26132. exports.ByteType = ByteType;
  26133. exports.ShortType = ShortType;
  26134. exports.UnsignedShortType = UnsignedShortType;
  26135. exports.IntType = IntType;
  26136. exports.UnsignedIntType = UnsignedIntType;
  26137. exports.FloatType = FloatType;
  26138. exports.HalfFloatType = HalfFloatType;
  26139. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  26140. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  26141. exports.UnsignedShort565Type = UnsignedShort565Type;
  26142. exports.UnsignedInt248Type = UnsignedInt248Type;
  26143. exports.AlphaFormat = AlphaFormat;
  26144. exports.RGBFormat = RGBFormat;
  26145. exports.RGBAFormat = RGBAFormat;
  26146. exports.LuminanceFormat = LuminanceFormat;
  26147. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  26148. exports.RGBEFormat = RGBEFormat;
  26149. exports.DepthFormat = DepthFormat;
  26150. exports.DepthStencilFormat = DepthStencilFormat;
  26151. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  26152. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  26153. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  26154. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  26155. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  26156. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  26157. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  26158. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  26159. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  26160. exports.LoopOnce = LoopOnce;
  26161. exports.LoopRepeat = LoopRepeat;
  26162. exports.LoopPingPong = LoopPingPong;
  26163. exports.InterpolateDiscrete = InterpolateDiscrete;
  26164. exports.InterpolateLinear = InterpolateLinear;
  26165. exports.InterpolateSmooth = InterpolateSmooth;
  26166. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  26167. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  26168. exports.WrapAroundEnding = WrapAroundEnding;
  26169. exports.TrianglesDrawMode = TrianglesDrawMode;
  26170. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  26171. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  26172. exports.LinearEncoding = LinearEncoding;
  26173. exports.sRGBEncoding = sRGBEncoding;
  26174. exports.GammaEncoding = GammaEncoding;
  26175. exports.RGBEEncoding = RGBEEncoding;
  26176. exports.LogLuvEncoding = LogLuvEncoding;
  26177. exports.RGBM7Encoding = RGBM7Encoding;
  26178. exports.RGBM16Encoding = RGBM16Encoding;
  26179. exports.RGBDEncoding = RGBDEncoding;
  26180. exports.BasicDepthPacking = BasicDepthPacking;
  26181. exports.RGBADepthPacking = RGBADepthPacking;
  26182. exports.CubeGeometry = BoxGeometry;
  26183. exports.Face4 = Face4;
  26184. exports.LineStrip = LineStrip;
  26185. exports.LinePieces = LinePieces;
  26186. exports.MeshFaceMaterial = MeshFaceMaterial;
  26187. exports.PointCloud = PointCloud;
  26188. exports.Particle = Particle;
  26189. exports.ParticleSystem = ParticleSystem;
  26190. exports.PointCloudMaterial = PointCloudMaterial;
  26191. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  26192. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  26193. exports.Vertex = Vertex;
  26194. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  26195. exports.Int8Attribute = Int8Attribute;
  26196. exports.Uint8Attribute = Uint8Attribute;
  26197. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  26198. exports.Int16Attribute = Int16Attribute;
  26199. exports.Uint16Attribute = Uint16Attribute;
  26200. exports.Int32Attribute = Int32Attribute;
  26201. exports.Uint32Attribute = Uint32Attribute;
  26202. exports.Float32Attribute = Float32Attribute;
  26203. exports.Float64Attribute = Float64Attribute;
  26204. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  26205. exports.BoundingBoxHelper = BoundingBoxHelper;
  26206. exports.EdgesHelper = EdgesHelper;
  26207. exports.WireframeHelper = WireframeHelper;
  26208. exports.XHRLoader = XHRLoader;
  26209. exports.GeometryUtils = GeometryUtils;
  26210. exports.ImageUtils = ImageUtils;
  26211. exports.UniformsUtils = UniformsUtils;
  26212. exports.Projector = Projector;
  26213. exports.CanvasRenderer = CanvasRenderer;
  26214. Object.defineProperty(exports, '__esModule', { value: true });
  26215. })));