three.js 1006 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169
  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. setFromMatrixPosition: function ( m ) {
  1970. return this.setFromMatrixColumn( m, 3 );
  1971. },
  1972. setFromMatrixScale: function ( m ) {
  1973. var sx = this.setFromMatrixColumn( m, 0 ).length();
  1974. var sy = this.setFromMatrixColumn( m, 1 ).length();
  1975. var sz = this.setFromMatrixColumn( m, 2 ).length();
  1976. this.x = sx;
  1977. this.y = sy;
  1978. this.z = sz;
  1979. return this;
  1980. },
  1981. setFromMatrixColumn: function ( m, index ) {
  1982. if ( typeof m === 'number' ) {
  1983. console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' );
  1984. var temp = m;
  1985. m = index;
  1986. index = temp;
  1987. }
  1988. return this.fromArray( m.elements, index * 4 );
  1989. },
  1990. equals: function ( v ) {
  1991. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1992. },
  1993. fromArray: function ( array, offset ) {
  1994. if ( offset === undefined ) offset = 0;
  1995. this.x = array[ offset ];
  1996. this.y = array[ offset + 1 ];
  1997. this.z = array[ offset + 2 ];
  1998. return this;
  1999. },
  2000. toArray: function ( array, offset ) {
  2001. if ( array === undefined ) array = [];
  2002. if ( offset === undefined ) offset = 0;
  2003. array[ offset ] = this.x;
  2004. array[ offset + 1 ] = this.y;
  2005. array[ offset + 2 ] = this.z;
  2006. return array;
  2007. },
  2008. fromAttribute: function ( attribute, index, offset ) {
  2009. if ( offset === undefined ) offset = 0;
  2010. index = index * attribute.itemSize + offset;
  2011. this.x = attribute.array[ index ];
  2012. this.y = attribute.array[ index + 1 ];
  2013. this.z = attribute.array[ index + 2 ];
  2014. return this;
  2015. }
  2016. };
  2017. /**
  2018. * @author mrdoob / http://mrdoob.com/
  2019. * @author supereggbert / http://www.paulbrunt.co.uk/
  2020. * @author philogb / http://blog.thejit.org/
  2021. * @author jordi_ros / http://plattsoft.com
  2022. * @author D1plo1d / http://github.com/D1plo1d
  2023. * @author alteredq / http://alteredqualia.com/
  2024. * @author mikael emtinger / http://gomo.se/
  2025. * @author timknip / http://www.floorplanner.com/
  2026. * @author bhouston / http://clara.io
  2027. * @author WestLangley / http://github.com/WestLangley
  2028. */
  2029. function Matrix4() {
  2030. this.elements = new Float32Array( [
  2031. 1, 0, 0, 0,
  2032. 0, 1, 0, 0,
  2033. 0, 0, 1, 0,
  2034. 0, 0, 0, 1
  2035. ] );
  2036. if ( arguments.length > 0 ) {
  2037. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2038. }
  2039. }
  2040. Matrix4.prototype = {
  2041. constructor: Matrix4,
  2042. isMatrix4: true,
  2043. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2044. var te = this.elements;
  2045. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2046. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2047. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2048. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2049. return this;
  2050. },
  2051. identity: function () {
  2052. this.set(
  2053. 1, 0, 0, 0,
  2054. 0, 1, 0, 0,
  2055. 0, 0, 1, 0,
  2056. 0, 0, 0, 1
  2057. );
  2058. return this;
  2059. },
  2060. clone: function () {
  2061. return new Matrix4().fromArray( this.elements );
  2062. },
  2063. copy: function ( m ) {
  2064. this.elements.set( m.elements );
  2065. return this;
  2066. },
  2067. copyPosition: function ( m ) {
  2068. var te = this.elements;
  2069. var me = m.elements;
  2070. te[ 12 ] = me[ 12 ];
  2071. te[ 13 ] = me[ 13 ];
  2072. te[ 14 ] = me[ 14 ];
  2073. return this;
  2074. },
  2075. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2076. xAxis.setFromMatrixColumn( this, 0 );
  2077. yAxis.setFromMatrixColumn( this, 1 );
  2078. zAxis.setFromMatrixColumn( this, 2 );
  2079. return this;
  2080. },
  2081. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2082. this.set(
  2083. xAxis.x, yAxis.x, zAxis.x, 0,
  2084. xAxis.y, yAxis.y, zAxis.y, 0,
  2085. xAxis.z, yAxis.z, zAxis.z, 0,
  2086. 0, 0, 0, 1
  2087. );
  2088. return this;
  2089. },
  2090. extractRotation: function () {
  2091. var v1;
  2092. return function extractRotation( m ) {
  2093. if ( v1 === undefined ) v1 = new Vector3();
  2094. var te = this.elements;
  2095. var me = m.elements;
  2096. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  2097. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  2098. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  2099. te[ 0 ] = me[ 0 ] * scaleX;
  2100. te[ 1 ] = me[ 1 ] * scaleX;
  2101. te[ 2 ] = me[ 2 ] * scaleX;
  2102. te[ 4 ] = me[ 4 ] * scaleY;
  2103. te[ 5 ] = me[ 5 ] * scaleY;
  2104. te[ 6 ] = me[ 6 ] * scaleY;
  2105. te[ 8 ] = me[ 8 ] * scaleZ;
  2106. te[ 9 ] = me[ 9 ] * scaleZ;
  2107. te[ 10 ] = me[ 10 ] * scaleZ;
  2108. return this;
  2109. };
  2110. }(),
  2111. makeRotationFromEuler: function ( euler ) {
  2112. if ( (euler && euler.isEuler) === false ) {
  2113. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2114. }
  2115. var te = this.elements;
  2116. var x = euler.x, y = euler.y, z = euler.z;
  2117. var a = Math.cos( x ), b = Math.sin( x );
  2118. var c = Math.cos( y ), d = Math.sin( y );
  2119. var e = Math.cos( z ), f = Math.sin( z );
  2120. if ( euler.order === 'XYZ' ) {
  2121. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2122. te[ 0 ] = c * e;
  2123. te[ 4 ] = - c * f;
  2124. te[ 8 ] = d;
  2125. te[ 1 ] = af + be * d;
  2126. te[ 5 ] = ae - bf * d;
  2127. te[ 9 ] = - b * c;
  2128. te[ 2 ] = bf - ae * d;
  2129. te[ 6 ] = be + af * d;
  2130. te[ 10 ] = a * c;
  2131. } else if ( euler.order === 'YXZ' ) {
  2132. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2133. te[ 0 ] = ce + df * b;
  2134. te[ 4 ] = de * b - cf;
  2135. te[ 8 ] = a * d;
  2136. te[ 1 ] = a * f;
  2137. te[ 5 ] = a * e;
  2138. te[ 9 ] = - b;
  2139. te[ 2 ] = cf * b - de;
  2140. te[ 6 ] = df + ce * b;
  2141. te[ 10 ] = a * c;
  2142. } else if ( euler.order === 'ZXY' ) {
  2143. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2144. te[ 0 ] = ce - df * b;
  2145. te[ 4 ] = - a * f;
  2146. te[ 8 ] = de + cf * b;
  2147. te[ 1 ] = cf + de * b;
  2148. te[ 5 ] = a * e;
  2149. te[ 9 ] = df - ce * b;
  2150. te[ 2 ] = - a * d;
  2151. te[ 6 ] = b;
  2152. te[ 10 ] = a * c;
  2153. } else if ( euler.order === 'ZYX' ) {
  2154. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2155. te[ 0 ] = c * e;
  2156. te[ 4 ] = be * d - af;
  2157. te[ 8 ] = ae * d + bf;
  2158. te[ 1 ] = c * f;
  2159. te[ 5 ] = bf * d + ae;
  2160. te[ 9 ] = af * d - be;
  2161. te[ 2 ] = - d;
  2162. te[ 6 ] = b * c;
  2163. te[ 10 ] = a * c;
  2164. } else if ( euler.order === 'YZX' ) {
  2165. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2166. te[ 0 ] = c * e;
  2167. te[ 4 ] = bd - ac * f;
  2168. te[ 8 ] = bc * f + ad;
  2169. te[ 1 ] = f;
  2170. te[ 5 ] = a * e;
  2171. te[ 9 ] = - b * e;
  2172. te[ 2 ] = - d * e;
  2173. te[ 6 ] = ad * f + bc;
  2174. te[ 10 ] = ac - bd * f;
  2175. } else if ( euler.order === 'XZY' ) {
  2176. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2177. te[ 0 ] = c * e;
  2178. te[ 4 ] = - f;
  2179. te[ 8 ] = d * e;
  2180. te[ 1 ] = ac * f + bd;
  2181. te[ 5 ] = a * e;
  2182. te[ 9 ] = ad * f - bc;
  2183. te[ 2 ] = bc * f - ad;
  2184. te[ 6 ] = b * e;
  2185. te[ 10 ] = bd * f + ac;
  2186. }
  2187. // last column
  2188. te[ 3 ] = 0;
  2189. te[ 7 ] = 0;
  2190. te[ 11 ] = 0;
  2191. // bottom row
  2192. te[ 12 ] = 0;
  2193. te[ 13 ] = 0;
  2194. te[ 14 ] = 0;
  2195. te[ 15 ] = 1;
  2196. return this;
  2197. },
  2198. makeRotationFromQuaternion: function ( q ) {
  2199. var te = this.elements;
  2200. var x = q.x, y = q.y, z = q.z, w = q.w;
  2201. var x2 = x + x, y2 = y + y, z2 = z + z;
  2202. var xx = x * x2, xy = x * y2, xz = x * z2;
  2203. var yy = y * y2, yz = y * z2, zz = z * z2;
  2204. var wx = w * x2, wy = w * y2, wz = w * z2;
  2205. te[ 0 ] = 1 - ( yy + zz );
  2206. te[ 4 ] = xy - wz;
  2207. te[ 8 ] = xz + wy;
  2208. te[ 1 ] = xy + wz;
  2209. te[ 5 ] = 1 - ( xx + zz );
  2210. te[ 9 ] = yz - wx;
  2211. te[ 2 ] = xz - wy;
  2212. te[ 6 ] = yz + wx;
  2213. te[ 10 ] = 1 - ( xx + yy );
  2214. // last column
  2215. te[ 3 ] = 0;
  2216. te[ 7 ] = 0;
  2217. te[ 11 ] = 0;
  2218. // bottom row
  2219. te[ 12 ] = 0;
  2220. te[ 13 ] = 0;
  2221. te[ 14 ] = 0;
  2222. te[ 15 ] = 1;
  2223. return this;
  2224. },
  2225. lookAt: function () {
  2226. var x, y, z;
  2227. return function lookAt( eye, target, up ) {
  2228. if ( x === undefined ) {
  2229. x = new Vector3();
  2230. y = new Vector3();
  2231. z = new Vector3();
  2232. }
  2233. var te = this.elements;
  2234. z.subVectors( eye, target ).normalize();
  2235. if ( z.lengthSq() === 0 ) {
  2236. z.z = 1;
  2237. }
  2238. x.crossVectors( up, z ).normalize();
  2239. if ( x.lengthSq() === 0 ) {
  2240. z.z += 0.0001;
  2241. x.crossVectors( up, z ).normalize();
  2242. }
  2243. y.crossVectors( z, x );
  2244. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2245. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2246. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2247. return this;
  2248. };
  2249. }(),
  2250. multiply: function ( m, n ) {
  2251. if ( n !== undefined ) {
  2252. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2253. return this.multiplyMatrices( m, n );
  2254. }
  2255. return this.multiplyMatrices( this, m );
  2256. },
  2257. premultiply: function ( m ) {
  2258. return this.multiplyMatrices( m, this );
  2259. },
  2260. multiplyMatrices: function ( a, b ) {
  2261. var ae = a.elements;
  2262. var be = b.elements;
  2263. var te = this.elements;
  2264. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2265. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2266. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2267. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2268. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2269. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2270. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2271. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2272. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2273. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2274. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2275. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2276. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2277. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2278. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2279. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2280. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2281. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2282. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2283. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2284. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2285. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2286. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2287. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2288. return this;
  2289. },
  2290. multiplyToArray: function ( a, b, r ) {
  2291. var te = this.elements;
  2292. this.multiplyMatrices( a, b );
  2293. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  2294. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  2295. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  2296. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  2297. return this;
  2298. },
  2299. multiplyScalar: function ( s ) {
  2300. var te = this.elements;
  2301. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2302. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2303. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2304. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2305. return this;
  2306. },
  2307. applyToVector3Array: function () {
  2308. var v1;
  2309. return function applyToVector3Array( array, offset, length ) {
  2310. if ( v1 === undefined ) v1 = new Vector3();
  2311. if ( offset === undefined ) offset = 0;
  2312. if ( length === undefined ) length = array.length;
  2313. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2314. v1.fromArray( array, j );
  2315. v1.applyMatrix4( this );
  2316. v1.toArray( array, j );
  2317. }
  2318. return array;
  2319. };
  2320. }(),
  2321. applyToBuffer: function () {
  2322. var v1;
  2323. return function applyToBuffer( buffer, offset, length ) {
  2324. if ( v1 === undefined ) v1 = new Vector3();
  2325. if ( offset === undefined ) offset = 0;
  2326. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  2327. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  2328. v1.x = buffer.getX( j );
  2329. v1.y = buffer.getY( j );
  2330. v1.z = buffer.getZ( j );
  2331. v1.applyMatrix4( this );
  2332. buffer.setXYZ( j, v1.x, v1.y, v1.z );
  2333. }
  2334. return buffer;
  2335. };
  2336. }(),
  2337. determinant: function () {
  2338. var te = this.elements;
  2339. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2340. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2341. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2342. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2343. //TODO: make this more efficient
  2344. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2345. return (
  2346. n41 * (
  2347. + n14 * n23 * n32
  2348. - n13 * n24 * n32
  2349. - n14 * n22 * n33
  2350. + n12 * n24 * n33
  2351. + n13 * n22 * n34
  2352. - n12 * n23 * n34
  2353. ) +
  2354. n42 * (
  2355. + n11 * n23 * n34
  2356. - n11 * n24 * n33
  2357. + n14 * n21 * n33
  2358. - n13 * n21 * n34
  2359. + n13 * n24 * n31
  2360. - n14 * n23 * n31
  2361. ) +
  2362. n43 * (
  2363. + n11 * n24 * n32
  2364. - n11 * n22 * n34
  2365. - n14 * n21 * n32
  2366. + n12 * n21 * n34
  2367. + n14 * n22 * n31
  2368. - n12 * n24 * n31
  2369. ) +
  2370. n44 * (
  2371. - n13 * n22 * n31
  2372. - n11 * n23 * n32
  2373. + n11 * n22 * n33
  2374. + n13 * n21 * n32
  2375. - n12 * n21 * n33
  2376. + n12 * n23 * n31
  2377. )
  2378. );
  2379. },
  2380. transpose: function () {
  2381. var te = this.elements;
  2382. var tmp;
  2383. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  2384. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  2385. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  2386. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  2387. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  2388. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  2389. return this;
  2390. },
  2391. setPosition: function ( v ) {
  2392. var te = this.elements;
  2393. te[ 12 ] = v.x;
  2394. te[ 13 ] = v.y;
  2395. te[ 14 ] = v.z;
  2396. return this;
  2397. },
  2398. getInverse: function ( m, throwOnDegenerate ) {
  2399. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2400. var te = this.elements,
  2401. me = m.elements,
  2402. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  2403. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  2404. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  2405. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  2406. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  2407. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  2408. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  2409. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  2410. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  2411. if ( det === 0 ) {
  2412. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2413. if ( throwOnDegenerate === true ) {
  2414. throw new Error( msg );
  2415. } else {
  2416. console.warn( msg );
  2417. }
  2418. return this.identity();
  2419. }
  2420. var detInv = 1 / det;
  2421. te[ 0 ] = t11 * detInv;
  2422. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  2423. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  2424. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  2425. te[ 4 ] = t12 * detInv;
  2426. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  2427. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  2428. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  2429. te[ 8 ] = t13 * detInv;
  2430. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  2431. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  2432. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  2433. te[ 12 ] = t14 * detInv;
  2434. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  2435. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  2436. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  2437. return this;
  2438. },
  2439. scale: function ( v ) {
  2440. var te = this.elements;
  2441. var x = v.x, y = v.y, z = v.z;
  2442. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  2443. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  2444. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  2445. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  2446. return this;
  2447. },
  2448. getMaxScaleOnAxis: function () {
  2449. var te = this.elements;
  2450. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  2451. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  2452. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  2453. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  2454. },
  2455. makeTranslation: function ( x, y, z ) {
  2456. this.set(
  2457. 1, 0, 0, x,
  2458. 0, 1, 0, y,
  2459. 0, 0, 1, z,
  2460. 0, 0, 0, 1
  2461. );
  2462. return this;
  2463. },
  2464. makeRotationX: function ( theta ) {
  2465. var c = Math.cos( theta ), s = Math.sin( theta );
  2466. this.set(
  2467. 1, 0, 0, 0,
  2468. 0, c, - s, 0,
  2469. 0, s, c, 0,
  2470. 0, 0, 0, 1
  2471. );
  2472. return this;
  2473. },
  2474. makeRotationY: function ( theta ) {
  2475. var c = Math.cos( theta ), s = Math.sin( theta );
  2476. this.set(
  2477. c, 0, s, 0,
  2478. 0, 1, 0, 0,
  2479. - s, 0, c, 0,
  2480. 0, 0, 0, 1
  2481. );
  2482. return this;
  2483. },
  2484. makeRotationZ: function ( theta ) {
  2485. var c = Math.cos( theta ), s = Math.sin( theta );
  2486. this.set(
  2487. c, - s, 0, 0,
  2488. s, c, 0, 0,
  2489. 0, 0, 1, 0,
  2490. 0, 0, 0, 1
  2491. );
  2492. return this;
  2493. },
  2494. makeRotationAxis: function ( axis, angle ) {
  2495. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2496. var c = Math.cos( angle );
  2497. var s = Math.sin( angle );
  2498. var t = 1 - c;
  2499. var x = axis.x, y = axis.y, z = axis.z;
  2500. var tx = t * x, ty = t * y;
  2501. this.set(
  2502. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2503. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2504. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2505. 0, 0, 0, 1
  2506. );
  2507. return this;
  2508. },
  2509. makeScale: function ( x, y, z ) {
  2510. this.set(
  2511. x, 0, 0, 0,
  2512. 0, y, 0, 0,
  2513. 0, 0, z, 0,
  2514. 0, 0, 0, 1
  2515. );
  2516. return this;
  2517. },
  2518. makeShear: function ( x, y, z ) {
  2519. this.set(
  2520. 1, y, z, 0,
  2521. x, 1, z, 0,
  2522. x, y, 1, 0,
  2523. 0, 0, 0, 1
  2524. );
  2525. return this;
  2526. },
  2527. compose: function ( position, quaternion, scale ) {
  2528. this.makeRotationFromQuaternion( quaternion );
  2529. this.scale( scale );
  2530. this.setPosition( position );
  2531. return this;
  2532. },
  2533. decompose: function () {
  2534. var vector, matrix;
  2535. return function decompose( position, quaternion, scale ) {
  2536. if ( vector === undefined ) {
  2537. vector = new Vector3();
  2538. matrix = new Matrix4();
  2539. }
  2540. var te = this.elements;
  2541. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  2542. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  2543. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  2544. // if determine is negative, we need to invert one scale
  2545. var det = this.determinant();
  2546. if ( det < 0 ) {
  2547. sx = - sx;
  2548. }
  2549. position.x = te[ 12 ];
  2550. position.y = te[ 13 ];
  2551. position.z = te[ 14 ];
  2552. // scale the rotation part
  2553. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  2554. var invSX = 1 / sx;
  2555. var invSY = 1 / sy;
  2556. var invSZ = 1 / sz;
  2557. matrix.elements[ 0 ] *= invSX;
  2558. matrix.elements[ 1 ] *= invSX;
  2559. matrix.elements[ 2 ] *= invSX;
  2560. matrix.elements[ 4 ] *= invSY;
  2561. matrix.elements[ 5 ] *= invSY;
  2562. matrix.elements[ 6 ] *= invSY;
  2563. matrix.elements[ 8 ] *= invSZ;
  2564. matrix.elements[ 9 ] *= invSZ;
  2565. matrix.elements[ 10 ] *= invSZ;
  2566. quaternion.setFromRotationMatrix( matrix );
  2567. scale.x = sx;
  2568. scale.y = sy;
  2569. scale.z = sz;
  2570. return this;
  2571. };
  2572. }(),
  2573. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2574. var te = this.elements;
  2575. var x = 2 * near / ( right - left );
  2576. var y = 2 * near / ( top - bottom );
  2577. var a = ( right + left ) / ( right - left );
  2578. var b = ( top + bottom ) / ( top - bottom );
  2579. var c = - ( far + near ) / ( far - near );
  2580. var d = - 2 * far * near / ( far - near );
  2581. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  2582. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  2583. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  2584. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  2585. return this;
  2586. },
  2587. makePerspective: function ( fov, aspect, near, far ) {
  2588. var ymax = near * Math.tan( _Math.DEG2RAD * fov * 0.5 );
  2589. var ymin = - ymax;
  2590. var xmin = ymin * aspect;
  2591. var xmax = ymax * aspect;
  2592. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2593. },
  2594. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2595. var te = this.elements;
  2596. var w = 1.0 / ( right - left );
  2597. var h = 1.0 / ( top - bottom );
  2598. var p = 1.0 / ( far - near );
  2599. var x = ( right + left ) * w;
  2600. var y = ( top + bottom ) * h;
  2601. var z = ( far + near ) * p;
  2602. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  2603. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  2604. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  2605. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  2606. return this;
  2607. },
  2608. equals: function ( matrix ) {
  2609. var te = this.elements;
  2610. var me = matrix.elements;
  2611. for ( var i = 0; i < 16; i ++ ) {
  2612. if ( te[ i ] !== me[ i ] ) return false;
  2613. }
  2614. return true;
  2615. },
  2616. fromArray: function ( array, offset ) {
  2617. if ( offset === undefined ) offset = 0;
  2618. for( var i = 0; i < 16; i ++ ) {
  2619. this.elements[ i ] = array[ i + offset ];
  2620. }
  2621. return this;
  2622. },
  2623. toArray: function ( array, offset ) {
  2624. if ( array === undefined ) array = [];
  2625. if ( offset === undefined ) offset = 0;
  2626. var te = this.elements;
  2627. array[ offset ] = te[ 0 ];
  2628. array[ offset + 1 ] = te[ 1 ];
  2629. array[ offset + 2 ] = te[ 2 ];
  2630. array[ offset + 3 ] = te[ 3 ];
  2631. array[ offset + 4 ] = te[ 4 ];
  2632. array[ offset + 5 ] = te[ 5 ];
  2633. array[ offset + 6 ] = te[ 6 ];
  2634. array[ offset + 7 ] = te[ 7 ];
  2635. array[ offset + 8 ] = te[ 8 ];
  2636. array[ offset + 9 ] = te[ 9 ];
  2637. array[ offset + 10 ] = te[ 10 ];
  2638. array[ offset + 11 ] = te[ 11 ];
  2639. array[ offset + 12 ] = te[ 12 ];
  2640. array[ offset + 13 ] = te[ 13 ];
  2641. array[ offset + 14 ] = te[ 14 ];
  2642. array[ offset + 15 ] = te[ 15 ];
  2643. return array;
  2644. }
  2645. };
  2646. /**
  2647. * @author mrdoob / http://mrdoob.com/
  2648. */
  2649. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  2650. images = images !== undefined ? images : [];
  2651. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  2652. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2653. this.flipY = false;
  2654. }
  2655. CubeTexture.prototype = Object.create( Texture.prototype );
  2656. CubeTexture.prototype.constructor = CubeTexture;
  2657. CubeTexture.prototype.isCubeTexture = true;
  2658. Object.defineProperty( CubeTexture.prototype, 'images', {
  2659. get: function () {
  2660. return this.image;
  2661. },
  2662. set: function ( value ) {
  2663. this.image = value;
  2664. }
  2665. } );
  2666. /**
  2667. * @author tschw
  2668. *
  2669. * Uniforms of a program.
  2670. * Those form a tree structure with a special top-level container for the root,
  2671. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  2672. *
  2673. *
  2674. * Properties of inner nodes including the top-level container:
  2675. *
  2676. * .seq - array of nested uniforms
  2677. * .map - nested uniforms by name
  2678. *
  2679. *
  2680. * Methods of all nodes except the top-level container:
  2681. *
  2682. * .setValue( gl, value, [renderer] )
  2683. *
  2684. * uploads a uniform value(s)
  2685. * the 'renderer' parameter is needed for sampler uniforms
  2686. *
  2687. *
  2688. * Static methods of the top-level container (renderer factorizations):
  2689. *
  2690. * .upload( gl, seq, values, renderer )
  2691. *
  2692. * sets uniforms in 'seq' to 'values[id].value'
  2693. *
  2694. * .seqWithValue( seq, values ) : filteredSeq
  2695. *
  2696. * filters 'seq' entries with corresponding entry in values
  2697. *
  2698. *
  2699. * Methods of the top-level container (renderer factorizations):
  2700. *
  2701. * .setValue( gl, name, value )
  2702. *
  2703. * sets uniform with name 'name' to 'value'
  2704. *
  2705. * .set( gl, obj, prop )
  2706. *
  2707. * sets uniform from object and property with same name than uniform
  2708. *
  2709. * .setOptional( gl, obj, prop )
  2710. *
  2711. * like .set for an optional property of the object
  2712. *
  2713. */
  2714. var emptyTexture = new Texture();
  2715. var emptyCubeTexture = new CubeTexture();
  2716. // --- Base for inner nodes (including the root) ---
  2717. function UniformContainer() {
  2718. this.seq = [];
  2719. this.map = {};
  2720. }
  2721. // --- Utilities ---
  2722. // Array Caches (provide typed arrays for temporary by size)
  2723. var arrayCacheF32 = [];
  2724. var arrayCacheI32 = [];
  2725. // Flattening for arrays of vectors and matrices
  2726. function flatten( array, nBlocks, blockSize ) {
  2727. var firstElem = array[ 0 ];
  2728. if ( firstElem <= 0 || firstElem > 0 ) return array;
  2729. // unoptimized: ! isNaN( firstElem )
  2730. // see http://jacksondunstan.com/articles/983
  2731. var n = nBlocks * blockSize,
  2732. r = arrayCacheF32[ n ];
  2733. if ( r === undefined ) {
  2734. r = new Float32Array( n );
  2735. arrayCacheF32[ n ] = r;
  2736. }
  2737. if ( nBlocks !== 0 ) {
  2738. firstElem.toArray( r, 0 );
  2739. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  2740. offset += blockSize;
  2741. array[ i ].toArray( r, offset );
  2742. }
  2743. }
  2744. return r;
  2745. }
  2746. // Texture unit allocation
  2747. function allocTexUnits( renderer, n ) {
  2748. var r = arrayCacheI32[ n ];
  2749. if ( r === undefined ) {
  2750. r = new Int32Array( n );
  2751. arrayCacheI32[ n ] = r;
  2752. }
  2753. for ( var i = 0; i !== n; ++ i )
  2754. r[ i ] = renderer.allocTextureUnit();
  2755. return r;
  2756. }
  2757. // --- Setters ---
  2758. // Note: Defining these methods externally, because they come in a bunch
  2759. // and this way their names minify.
  2760. // Single scalar
  2761. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  2762. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  2763. // Single float vector (from flat array or THREE.VectorN)
  2764. function setValue2fv( gl, v ) {
  2765. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  2766. else gl.uniform2f( this.addr, v.x, v.y );
  2767. }
  2768. function setValue3fv( gl, v ) {
  2769. if ( v.x !== undefined )
  2770. gl.uniform3f( this.addr, v.x, v.y, v.z );
  2771. else if ( v.r !== undefined )
  2772. gl.uniform3f( this.addr, v.r, v.g, v.b );
  2773. else
  2774. gl.uniform3fv( this.addr, v );
  2775. }
  2776. function setValue4fv( gl, v ) {
  2777. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  2778. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  2779. }
  2780. // Single matrix (from flat array or MatrixN)
  2781. function setValue2fm( gl, v ) {
  2782. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  2783. }
  2784. function setValue3fm( gl, v ) {
  2785. gl.uniformMatrix3fv( this.addr, false, v.elements || v );
  2786. }
  2787. function setValue4fm( gl, v ) {
  2788. gl.uniformMatrix4fv( this.addr, false, v.elements || v );
  2789. }
  2790. // Single texture (2D / Cube)
  2791. function setValueT1( gl, v, renderer ) {
  2792. var unit = renderer.allocTextureUnit();
  2793. gl.uniform1i( this.addr, unit );
  2794. renderer.setTexture2D( v || emptyTexture, unit );
  2795. }
  2796. function setValueT6( gl, v, renderer ) {
  2797. var unit = renderer.allocTextureUnit();
  2798. gl.uniform1i( this.addr, unit );
  2799. renderer.setTextureCube( v || emptyCubeTexture, unit );
  2800. }
  2801. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  2802. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  2803. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  2804. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  2805. // Helper to pick the right setter for the singular case
  2806. function getSingularSetter( type ) {
  2807. switch ( type ) {
  2808. case 0x1406: return setValue1f; // FLOAT
  2809. case 0x8b50: return setValue2fv; // _VEC2
  2810. case 0x8b51: return setValue3fv; // _VEC3
  2811. case 0x8b52: return setValue4fv; // _VEC4
  2812. case 0x8b5a: return setValue2fm; // _MAT2
  2813. case 0x8b5b: return setValue3fm; // _MAT3
  2814. case 0x8b5c: return setValue4fm; // _MAT4
  2815. case 0x8b5e: return setValueT1; // SAMPLER_2D
  2816. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  2817. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  2818. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2819. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2820. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2821. }
  2822. }
  2823. // Array of scalars
  2824. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  2825. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  2826. // Array of vectors (flat or from THREE classes)
  2827. function setValueV2a( gl, v ) {
  2828. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  2829. }
  2830. function setValueV3a( gl, v ) {
  2831. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  2832. }
  2833. function setValueV4a( gl, v ) {
  2834. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  2835. }
  2836. // Array of matrices (flat or from THREE clases)
  2837. function setValueM2a( gl, v ) {
  2838. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  2839. }
  2840. function setValueM3a( gl, v ) {
  2841. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  2842. }
  2843. function setValueM4a( gl, v ) {
  2844. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  2845. }
  2846. // Array of textures (2D / Cube)
  2847. function setValueT1a( gl, v, renderer ) {
  2848. var n = v.length,
  2849. units = allocTexUnits( renderer, n );
  2850. gl.uniform1iv( this.addr, units );
  2851. for ( var i = 0; i !== n; ++ i ) {
  2852. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  2853. }
  2854. }
  2855. function setValueT6a( gl, v, renderer ) {
  2856. var n = v.length,
  2857. units = allocTexUnits( renderer, n );
  2858. gl.uniform1iv( this.addr, units );
  2859. for ( var i = 0; i !== n; ++ i ) {
  2860. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  2861. }
  2862. }
  2863. // Helper to pick the right setter for a pure (bottom-level) array
  2864. function getPureArraySetter( type ) {
  2865. switch ( type ) {
  2866. case 0x1406: return setValue1fv; // FLOAT
  2867. case 0x8b50: return setValueV2a; // _VEC2
  2868. case 0x8b51: return setValueV3a; // _VEC3
  2869. case 0x8b52: return setValueV4a; // _VEC4
  2870. case 0x8b5a: return setValueM2a; // _MAT2
  2871. case 0x8b5b: return setValueM3a; // _MAT3
  2872. case 0x8b5c: return setValueM4a; // _MAT4
  2873. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  2874. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  2875. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  2876. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2877. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2878. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2879. }
  2880. }
  2881. // --- Uniform Classes ---
  2882. function SingleUniform( id, activeInfo, addr ) {
  2883. this.id = id;
  2884. this.addr = addr;
  2885. this.setValue = getSingularSetter( activeInfo.type );
  2886. // this.path = activeInfo.name; // DEBUG
  2887. }
  2888. function PureArrayUniform( id, activeInfo, addr ) {
  2889. this.id = id;
  2890. this.addr = addr;
  2891. this.size = activeInfo.size;
  2892. this.setValue = getPureArraySetter( activeInfo.type );
  2893. // this.path = activeInfo.name; // DEBUG
  2894. }
  2895. function StructuredUniform( id ) {
  2896. this.id = id;
  2897. UniformContainer.call( this ); // mix-in
  2898. }
  2899. StructuredUniform.prototype.setValue = function( gl, value ) {
  2900. // Note: Don't need an extra 'renderer' parameter, since samplers
  2901. // are not allowed in structured uniforms.
  2902. var seq = this.seq;
  2903. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2904. var u = seq[ i ];
  2905. u.setValue( gl, value[ u.id ] );
  2906. }
  2907. };
  2908. // --- Top-level ---
  2909. // Parser - builds up the property tree from the path strings
  2910. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  2911. // extracts
  2912. // - the identifier (member name or array index)
  2913. // - followed by an optional right bracket (found when array index)
  2914. // - followed by an optional left bracket or dot (type of subscript)
  2915. //
  2916. // Note: These portions can be read in a non-overlapping fashion and
  2917. // allow straightforward parsing of the hierarchy that WebGL encodes
  2918. // in the uniform names.
  2919. function addUniform( container, uniformObject ) {
  2920. container.seq.push( uniformObject );
  2921. container.map[ uniformObject.id ] = uniformObject;
  2922. }
  2923. function parseUniform( activeInfo, addr, container ) {
  2924. var path = activeInfo.name,
  2925. pathLength = path.length;
  2926. // reset RegExp object, because of the early exit of a previous run
  2927. RePathPart.lastIndex = 0;
  2928. for (; ;) {
  2929. var match = RePathPart.exec( path ),
  2930. matchEnd = RePathPart.lastIndex,
  2931. id = match[ 1 ],
  2932. idIsIndex = match[ 2 ] === ']',
  2933. subscript = match[ 3 ];
  2934. if ( idIsIndex ) id = id | 0; // convert to integer
  2935. if ( subscript === undefined ||
  2936. subscript === '[' && matchEnd + 2 === pathLength ) {
  2937. // bare name or "pure" bottom-level array "[0]" suffix
  2938. addUniform( container, subscript === undefined ?
  2939. new SingleUniform( id, activeInfo, addr ) :
  2940. new PureArrayUniform( id, activeInfo, addr ) );
  2941. break;
  2942. } else {
  2943. // step into inner node / create it in case it doesn't exist
  2944. var map = container.map,
  2945. next = map[ id ];
  2946. if ( next === undefined ) {
  2947. next = new StructuredUniform( id );
  2948. addUniform( container, next );
  2949. }
  2950. container = next;
  2951. }
  2952. }
  2953. }
  2954. // Root Container
  2955. function WebGLUniforms( gl, program, renderer ) {
  2956. UniformContainer.call( this );
  2957. this.renderer = renderer;
  2958. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  2959. for ( var i = 0; i !== n; ++ i ) {
  2960. var info = gl.getActiveUniform( program, i ),
  2961. path = info.name,
  2962. addr = gl.getUniformLocation( program, path );
  2963. parseUniform( info, addr, this );
  2964. }
  2965. }
  2966. WebGLUniforms.prototype.setValue = function( gl, name, value ) {
  2967. var u = this.map[ name ];
  2968. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  2969. };
  2970. WebGLUniforms.prototype.set = function( gl, object, name ) {
  2971. var u = this.map[ name ];
  2972. if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer );
  2973. };
  2974. WebGLUniforms.prototype.setOptional = function( gl, object, name ) {
  2975. var v = object[ name ];
  2976. if ( v !== undefined ) this.setValue( gl, name, v );
  2977. };
  2978. // Static interface
  2979. WebGLUniforms.upload = function( gl, seq, values, renderer ) {
  2980. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2981. var u = seq[ i ],
  2982. v = values[ u.id ];
  2983. if ( v.needsUpdate !== false ) {
  2984. // note: always updating when .needsUpdate is undefined
  2985. u.setValue( gl, v.value, renderer );
  2986. }
  2987. }
  2988. };
  2989. WebGLUniforms.seqWithValue = function( seq, values ) {
  2990. var r = [];
  2991. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2992. var u = seq[ i ];
  2993. if ( u.id in values ) r.push( u );
  2994. }
  2995. return r;
  2996. };
  2997. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  2998. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  2999. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  3000. 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";
  3001. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  3002. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  3003. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  3004. 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";
  3005. 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";
  3006. 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";
  3007. 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";
  3008. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  3009. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  3010. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  3011. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  3012. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  3013. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  3014. 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";
  3015. 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";
  3016. var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  3017. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  3018. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  3019. 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";
  3020. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  3021. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  3022. 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";
  3023. 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";
  3024. var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntenstiy;\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";
  3025. 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";
  3026. 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";
  3027. 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";
  3028. 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";
  3029. 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";
  3030. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  3031. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  3032. 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";
  3033. 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";
  3034. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  3035. 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";
  3036. 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";
  3037. 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";
  3038. 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";
  3039. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  3040. 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";
  3041. 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";
  3042. 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";
  3043. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  3044. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  3045. 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";
  3046. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  3047. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n#endif\n";
  3048. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  3049. 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";
  3050. 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";
  3051. 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";
  3052. 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";
  3053. 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";
  3054. 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";
  3055. 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";
  3056. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  3057. 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";
  3058. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n";
  3059. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  3060. 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";
  3061. 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";
  3062. 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";
  3063. 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";
  3064. 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";
  3065. 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";
  3066. 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";
  3067. 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";
  3068. 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";
  3069. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  3070. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  3071. 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";
  3072. 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";
  3073. 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";
  3074. 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";
  3075. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  3076. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  3077. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  3078. 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";
  3079. 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";
  3080. 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";
  3081. 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";
  3082. 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";
  3083. 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";
  3084. 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";
  3085. 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";
  3086. 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";
  3087. 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";
  3088. 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";
  3089. 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";
  3090. 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";
  3091. 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";
  3092. 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";
  3093. 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";
  3094. 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";
  3095. 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\nuniform float envMapIntensity;\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";
  3096. 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";
  3097. 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";
  3098. 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";
  3099. 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";
  3100. 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";
  3101. 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";
  3102. 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";
  3103. var ShaderChunk = {
  3104. alphamap_fragment: alphamap_fragment,
  3105. alphamap_pars_fragment: alphamap_pars_fragment,
  3106. alphatest_fragment: alphatest_fragment,
  3107. aomap_fragment: aomap_fragment,
  3108. aomap_pars_fragment: aomap_pars_fragment,
  3109. begin_vertex: begin_vertex,
  3110. beginnormal_vertex: beginnormal_vertex,
  3111. bsdfs: bsdfs,
  3112. bumpmap_pars_fragment: bumpmap_pars_fragment,
  3113. clipping_planes_fragment: clipping_planes_fragment,
  3114. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  3115. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  3116. clipping_planes_vertex: clipping_planes_vertex,
  3117. color_fragment: color_fragment,
  3118. color_pars_fragment: color_pars_fragment,
  3119. color_pars_vertex: color_pars_vertex,
  3120. color_vertex: color_vertex,
  3121. common: common,
  3122. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  3123. defaultnormal_vertex: defaultnormal_vertex,
  3124. displacementmap_pars_vertex: displacementmap_pars_vertex,
  3125. displacementmap_vertex: displacementmap_vertex,
  3126. emissivemap_fragment: emissivemap_fragment,
  3127. emissivemap_pars_fragment: emissivemap_pars_fragment,
  3128. encodings_fragment: encodings_fragment,
  3129. encodings_pars_fragment: encodings_pars_fragment,
  3130. envmap_fragment: envmap_fragment,
  3131. envmap_pars_fragment: envmap_pars_fragment,
  3132. envmap_pars_vertex: envmap_pars_vertex,
  3133. envmap_vertex: envmap_vertex,
  3134. fog_fragment: fog_fragment,
  3135. fog_pars_fragment: fog_pars_fragment,
  3136. gradientmap_pars_fragment: gradientmap_pars_fragment,
  3137. lightmap_fragment: lightmap_fragment,
  3138. lightmap_pars_fragment: lightmap_pars_fragment,
  3139. lights_lambert_vertex: lights_lambert_vertex,
  3140. lights_pars: lights_pars,
  3141. lights_phong_fragment: lights_phong_fragment,
  3142. lights_phong_pars_fragment: lights_phong_pars_fragment,
  3143. lights_physical_fragment: lights_physical_fragment,
  3144. lights_physical_pars_fragment: lights_physical_pars_fragment,
  3145. lights_template: lights_template,
  3146. logdepthbuf_fragment: logdepthbuf_fragment,
  3147. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  3148. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  3149. logdepthbuf_vertex: logdepthbuf_vertex,
  3150. map_fragment: map_fragment,
  3151. map_pars_fragment: map_pars_fragment,
  3152. map_particle_fragment: map_particle_fragment,
  3153. map_particle_pars_fragment: map_particle_pars_fragment,
  3154. metalnessmap_fragment: metalnessmap_fragment,
  3155. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  3156. morphnormal_vertex: morphnormal_vertex,
  3157. morphtarget_pars_vertex: morphtarget_pars_vertex,
  3158. morphtarget_vertex: morphtarget_vertex,
  3159. normal_flip: normal_flip,
  3160. normal_fragment: normal_fragment,
  3161. normalmap_pars_fragment: normalmap_pars_fragment,
  3162. packing: packing,
  3163. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  3164. project_vertex: project_vertex,
  3165. roughnessmap_fragment: roughnessmap_fragment,
  3166. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  3167. shadowmap_pars_fragment: shadowmap_pars_fragment,
  3168. shadowmap_pars_vertex: shadowmap_pars_vertex,
  3169. shadowmap_vertex: shadowmap_vertex,
  3170. shadowmask_pars_fragment: shadowmask_pars_fragment,
  3171. skinbase_vertex: skinbase_vertex,
  3172. skinning_pars_vertex: skinning_pars_vertex,
  3173. skinning_vertex: skinning_vertex,
  3174. skinnormal_vertex: skinnormal_vertex,
  3175. specularmap_fragment: specularmap_fragment,
  3176. specularmap_pars_fragment: specularmap_pars_fragment,
  3177. tonemapping_fragment: tonemapping_fragment,
  3178. tonemapping_pars_fragment: tonemapping_pars_fragment,
  3179. uv_pars_fragment: uv_pars_fragment,
  3180. uv_pars_vertex: uv_pars_vertex,
  3181. uv_vertex: uv_vertex,
  3182. uv2_pars_fragment: uv2_pars_fragment,
  3183. uv2_pars_vertex: uv2_pars_vertex,
  3184. uv2_vertex: uv2_vertex,
  3185. worldpos_vertex: worldpos_vertex,
  3186. cube_frag: cube_frag,
  3187. cube_vert: cube_vert,
  3188. depth_frag: depth_frag,
  3189. depth_vert: depth_vert,
  3190. distanceRGBA_frag: distanceRGBA_frag,
  3191. distanceRGBA_vert: distanceRGBA_vert,
  3192. equirect_frag: equirect_frag,
  3193. equirect_vert: equirect_vert,
  3194. linedashed_frag: linedashed_frag,
  3195. linedashed_vert: linedashed_vert,
  3196. meshbasic_frag: meshbasic_frag,
  3197. meshbasic_vert: meshbasic_vert,
  3198. meshlambert_frag: meshlambert_frag,
  3199. meshlambert_vert: meshlambert_vert,
  3200. meshphong_frag: meshphong_frag,
  3201. meshphong_vert: meshphong_vert,
  3202. meshphysical_frag: meshphysical_frag,
  3203. meshphysical_vert: meshphysical_vert,
  3204. normal_frag: normal_frag,
  3205. normal_vert: normal_vert,
  3206. points_frag: points_frag,
  3207. points_vert: points_vert,
  3208. shadow_frag: shadow_frag,
  3209. shadow_vert: shadow_vert
  3210. };
  3211. /**
  3212. * @author mrdoob / http://mrdoob.com/
  3213. */
  3214. function Color( r, g, b ) {
  3215. if ( g === undefined && b === undefined ) {
  3216. // r is THREE.Color, hex or string
  3217. return this.set( r );
  3218. }
  3219. return this.setRGB( r, g, b );
  3220. }
  3221. Color.prototype = {
  3222. constructor: Color,
  3223. isColor: true,
  3224. r: 1, g: 1, b: 1,
  3225. set: function ( value ) {
  3226. if ( value && value.isColor ) {
  3227. this.copy( value );
  3228. } else if ( typeof value === 'number' ) {
  3229. this.setHex( value );
  3230. } else if ( typeof value === 'string' ) {
  3231. this.setStyle( value );
  3232. }
  3233. return this;
  3234. },
  3235. setScalar: function ( scalar ) {
  3236. this.r = scalar;
  3237. this.g = scalar;
  3238. this.b = scalar;
  3239. return this;
  3240. },
  3241. setHex: function ( hex ) {
  3242. hex = Math.floor( hex );
  3243. this.r = ( hex >> 16 & 255 ) / 255;
  3244. this.g = ( hex >> 8 & 255 ) / 255;
  3245. this.b = ( hex & 255 ) / 255;
  3246. return this;
  3247. },
  3248. setRGB: function ( r, g, b ) {
  3249. this.r = r;
  3250. this.g = g;
  3251. this.b = b;
  3252. return this;
  3253. },
  3254. setHSL: function () {
  3255. function hue2rgb( p, q, t ) {
  3256. if ( t < 0 ) t += 1;
  3257. if ( t > 1 ) t -= 1;
  3258. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  3259. if ( t < 1 / 2 ) return q;
  3260. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  3261. return p;
  3262. }
  3263. return function setHSL( h, s, l ) {
  3264. // h,s,l ranges are in 0.0 - 1.0
  3265. h = _Math.euclideanModulo( h, 1 );
  3266. s = _Math.clamp( s, 0, 1 );
  3267. l = _Math.clamp( l, 0, 1 );
  3268. if ( s === 0 ) {
  3269. this.r = this.g = this.b = l;
  3270. } else {
  3271. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  3272. var q = ( 2 * l ) - p;
  3273. this.r = hue2rgb( q, p, h + 1 / 3 );
  3274. this.g = hue2rgb( q, p, h );
  3275. this.b = hue2rgb( q, p, h - 1 / 3 );
  3276. }
  3277. return this;
  3278. };
  3279. }(),
  3280. setStyle: function ( style ) {
  3281. function handleAlpha( string ) {
  3282. if ( string === undefined ) return;
  3283. if ( parseFloat( string ) < 1 ) {
  3284. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  3285. }
  3286. }
  3287. var m;
  3288. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  3289. // rgb / hsl
  3290. var color;
  3291. var name = m[ 1 ];
  3292. var components = m[ 2 ];
  3293. switch ( name ) {
  3294. case 'rgb':
  3295. case 'rgba':
  3296. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3297. // rgb(255,0,0) rgba(255,0,0,0.5)
  3298. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  3299. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  3300. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  3301. handleAlpha( color[ 5 ] );
  3302. return this;
  3303. }
  3304. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3305. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  3306. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  3307. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  3308. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  3309. handleAlpha( color[ 5 ] );
  3310. return this;
  3311. }
  3312. break;
  3313. case 'hsl':
  3314. case 'hsla':
  3315. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3316. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  3317. var h = parseFloat( color[ 1 ] ) / 360;
  3318. var s = parseInt( color[ 2 ], 10 ) / 100;
  3319. var l = parseInt( color[ 3 ], 10 ) / 100;
  3320. handleAlpha( color[ 5 ] );
  3321. return this.setHSL( h, s, l );
  3322. }
  3323. break;
  3324. }
  3325. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  3326. // hex color
  3327. var hex = m[ 1 ];
  3328. var size = hex.length;
  3329. if ( size === 3 ) {
  3330. // #ff0
  3331. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  3332. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  3333. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  3334. return this;
  3335. } else if ( size === 6 ) {
  3336. // #ff0000
  3337. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  3338. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  3339. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  3340. return this;
  3341. }
  3342. }
  3343. if ( style && style.length > 0 ) {
  3344. // color keywords
  3345. var hex = ColorKeywords[ style ];
  3346. if ( hex !== undefined ) {
  3347. // red
  3348. this.setHex( hex );
  3349. } else {
  3350. // unknown color
  3351. console.warn( 'THREE.Color: Unknown color ' + style );
  3352. }
  3353. }
  3354. return this;
  3355. },
  3356. clone: function () {
  3357. return new this.constructor( this.r, this.g, this.b );
  3358. },
  3359. copy: function ( color ) {
  3360. this.r = color.r;
  3361. this.g = color.g;
  3362. this.b = color.b;
  3363. return this;
  3364. },
  3365. copyGammaToLinear: function ( color, gammaFactor ) {
  3366. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3367. this.r = Math.pow( color.r, gammaFactor );
  3368. this.g = Math.pow( color.g, gammaFactor );
  3369. this.b = Math.pow( color.b, gammaFactor );
  3370. return this;
  3371. },
  3372. copyLinearToGamma: function ( color, gammaFactor ) {
  3373. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3374. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  3375. this.r = Math.pow( color.r, safeInverse );
  3376. this.g = Math.pow( color.g, safeInverse );
  3377. this.b = Math.pow( color.b, safeInverse );
  3378. return this;
  3379. },
  3380. convertGammaToLinear: function () {
  3381. var r = this.r, g = this.g, b = this.b;
  3382. this.r = r * r;
  3383. this.g = g * g;
  3384. this.b = b * b;
  3385. return this;
  3386. },
  3387. convertLinearToGamma: function () {
  3388. this.r = Math.sqrt( this.r );
  3389. this.g = Math.sqrt( this.g );
  3390. this.b = Math.sqrt( this.b );
  3391. return this;
  3392. },
  3393. getHex: function () {
  3394. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  3395. },
  3396. getHexString: function () {
  3397. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  3398. },
  3399. getHSL: function ( optionalTarget ) {
  3400. // h,s,l ranges are in 0.0 - 1.0
  3401. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  3402. var r = this.r, g = this.g, b = this.b;
  3403. var max = Math.max( r, g, b );
  3404. var min = Math.min( r, g, b );
  3405. var hue, saturation;
  3406. var lightness = ( min + max ) / 2.0;
  3407. if ( min === max ) {
  3408. hue = 0;
  3409. saturation = 0;
  3410. } else {
  3411. var delta = max - min;
  3412. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  3413. switch ( max ) {
  3414. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  3415. case g: hue = ( b - r ) / delta + 2; break;
  3416. case b: hue = ( r - g ) / delta + 4; break;
  3417. }
  3418. hue /= 6;
  3419. }
  3420. hsl.h = hue;
  3421. hsl.s = saturation;
  3422. hsl.l = lightness;
  3423. return hsl;
  3424. },
  3425. getStyle: function () {
  3426. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  3427. },
  3428. offsetHSL: function ( h, s, l ) {
  3429. var hsl = this.getHSL();
  3430. hsl.h += h; hsl.s += s; hsl.l += l;
  3431. this.setHSL( hsl.h, hsl.s, hsl.l );
  3432. return this;
  3433. },
  3434. add: function ( color ) {
  3435. this.r += color.r;
  3436. this.g += color.g;
  3437. this.b += color.b;
  3438. return this;
  3439. },
  3440. addColors: function ( color1, color2 ) {
  3441. this.r = color1.r + color2.r;
  3442. this.g = color1.g + color2.g;
  3443. this.b = color1.b + color2.b;
  3444. return this;
  3445. },
  3446. addScalar: function ( s ) {
  3447. this.r += s;
  3448. this.g += s;
  3449. this.b += s;
  3450. return this;
  3451. },
  3452. sub: function( color ) {
  3453. this.r = Math.max( 0, this.r - color.r );
  3454. this.g = Math.max( 0, this.g - color.g );
  3455. this.b = Math.max( 0, this.b - color.b );
  3456. return this;
  3457. },
  3458. multiply: function ( color ) {
  3459. this.r *= color.r;
  3460. this.g *= color.g;
  3461. this.b *= color.b;
  3462. return this;
  3463. },
  3464. multiplyScalar: function ( s ) {
  3465. this.r *= s;
  3466. this.g *= s;
  3467. this.b *= s;
  3468. return this;
  3469. },
  3470. lerp: function ( color, alpha ) {
  3471. this.r += ( color.r - this.r ) * alpha;
  3472. this.g += ( color.g - this.g ) * alpha;
  3473. this.b += ( color.b - this.b ) * alpha;
  3474. return this;
  3475. },
  3476. equals: function ( c ) {
  3477. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  3478. },
  3479. fromArray: function ( array, offset ) {
  3480. if ( offset === undefined ) offset = 0;
  3481. this.r = array[ offset ];
  3482. this.g = array[ offset + 1 ];
  3483. this.b = array[ offset + 2 ];
  3484. return this;
  3485. },
  3486. toArray: function ( array, offset ) {
  3487. if ( array === undefined ) array = [];
  3488. if ( offset === undefined ) offset = 0;
  3489. array[ offset ] = this.r;
  3490. array[ offset + 1 ] = this.g;
  3491. array[ offset + 2 ] = this.b;
  3492. return array;
  3493. },
  3494. toJSON: function () {
  3495. return this.getHex();
  3496. }
  3497. };
  3498. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  3499. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  3500. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  3501. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  3502. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  3503. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  3504. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  3505. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  3506. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  3507. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  3508. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  3509. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  3510. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  3511. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  3512. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  3513. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  3514. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  3515. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  3516. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  3517. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  3518. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  3519. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  3520. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  3521. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  3522. /**
  3523. * @author alteredq / http://alteredqualia.com/
  3524. */
  3525. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  3526. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  3527. this.image = { data: data, width: width, height: height };
  3528. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  3529. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  3530. this.generateMipmaps = false;
  3531. this.flipY = false;
  3532. this.unpackAlignment = 1;
  3533. }
  3534. DataTexture.prototype = Object.create( Texture.prototype );
  3535. DataTexture.prototype.constructor = DataTexture;
  3536. DataTexture.prototype.isDataTexture = true;
  3537. /**
  3538. * Uniforms library for shared webgl shaders
  3539. */
  3540. var UniformsLib = {
  3541. common: {
  3542. diffuse: { value: new Color( 0xeeeeee ) },
  3543. opacity: { value: 1.0 },
  3544. map: { value: null },
  3545. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) },
  3546. specularMap: { value: null },
  3547. alphaMap: { value: null },
  3548. envMap: { value: null },
  3549. flipEnvMap: { value: - 1 },
  3550. reflectivity: { value: 1.0 },
  3551. refractionRatio: { value: 0.98 }
  3552. },
  3553. aomap: {
  3554. aoMap: { value: null },
  3555. aoMapIntensity: { value: 1 }
  3556. },
  3557. lightmap: {
  3558. lightMap: { value: null },
  3559. lightMapIntensity: { value: 1 }
  3560. },
  3561. emissivemap: {
  3562. emissiveMap: { value: null }
  3563. },
  3564. bumpmap: {
  3565. bumpMap: { value: null },
  3566. bumpScale: { value: 1 }
  3567. },
  3568. normalmap: {
  3569. normalMap: { value: null },
  3570. normalScale: { value: new Vector2( 1, 1 ) }
  3571. },
  3572. displacementmap: {
  3573. displacementMap: { value: null },
  3574. displacementScale: { value: 1 },
  3575. displacementBias: { value: 0 }
  3576. },
  3577. roughnessmap: {
  3578. roughnessMap: { value: null }
  3579. },
  3580. metalnessmap: {
  3581. metalnessMap: { value: null }
  3582. },
  3583. gradientmap: {
  3584. gradientMap: { value: null }
  3585. },
  3586. fog: {
  3587. fogDensity: { value: 0.00025 },
  3588. fogNear: { value: 1 },
  3589. fogFar: { value: 2000 },
  3590. fogColor: { value: new Color( 0xffffff ) }
  3591. },
  3592. lights: {
  3593. ambientLightColor: { value: [] },
  3594. directionalLights: { value: [], properties: {
  3595. direction: {},
  3596. color: {},
  3597. shadow: {},
  3598. shadowBias: {},
  3599. shadowRadius: {},
  3600. shadowMapSize: {}
  3601. } },
  3602. directionalShadowMap: { value: [] },
  3603. directionalShadowMatrix: { value: [] },
  3604. spotLights: { value: [], properties: {
  3605. color: {},
  3606. position: {},
  3607. direction: {},
  3608. distance: {},
  3609. coneCos: {},
  3610. penumbraCos: {},
  3611. decay: {},
  3612. shadow: {},
  3613. shadowBias: {},
  3614. shadowRadius: {},
  3615. shadowMapSize: {}
  3616. } },
  3617. spotShadowMap: { value: [] },
  3618. spotShadowMatrix: { value: [] },
  3619. pointLights: { value: [], properties: {
  3620. color: {},
  3621. position: {},
  3622. decay: {},
  3623. distance: {},
  3624. shadow: {},
  3625. shadowBias: {},
  3626. shadowRadius: {},
  3627. shadowMapSize: {}
  3628. } },
  3629. pointShadowMap: { value: [] },
  3630. pointShadowMatrix: { value: [] },
  3631. hemisphereLights: { value: [], properties: {
  3632. direction: {},
  3633. skyColor: {},
  3634. groundColor: {}
  3635. } },
  3636. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  3637. rectAreaLights: { value: [], properties: {
  3638. color: {},
  3639. position: {},
  3640. width: {},
  3641. height: {},
  3642. } }
  3643. },
  3644. points: {
  3645. diffuse: { value: new Color( 0xeeeeee ) },
  3646. opacity: { value: 1.0 },
  3647. size: { value: 1.0 },
  3648. scale: { value: 1.0 },
  3649. map: { value: null },
  3650. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }
  3651. }
  3652. };
  3653. /**
  3654. * @author alteredq / http://alteredqualia.com/
  3655. * @author mrdoob / http://mrdoob.com/
  3656. * @author mikael emtinger / http://gomo.se/
  3657. */
  3658. var ShaderLib = {
  3659. basic: {
  3660. uniforms: Object.assign( {},
  3661. UniformsLib.common,
  3662. UniformsLib.aomap,
  3663. UniformsLib.lightmap,
  3664. UniformsLib.fog
  3665. ),
  3666. vertexShader: ShaderChunk.meshbasic_vert,
  3667. fragmentShader: ShaderChunk.meshbasic_frag
  3668. },
  3669. lambert: {
  3670. uniforms: Object.assign( {},
  3671. UniformsLib.common,
  3672. UniformsLib.aomap,
  3673. UniformsLib.lightmap,
  3674. UniformsLib.emissivemap,
  3675. UniformsLib.fog,
  3676. UniformsLib.lights,
  3677. {
  3678. emissive : { value: new Color( 0x000000 ) }
  3679. }
  3680. ),
  3681. vertexShader: ShaderChunk.meshlambert_vert,
  3682. fragmentShader: ShaderChunk.meshlambert_frag
  3683. },
  3684. phong: {
  3685. uniforms: Object.assign( {},
  3686. UniformsLib.common,
  3687. UniformsLib.aomap,
  3688. UniformsLib.lightmap,
  3689. UniformsLib.emissivemap,
  3690. UniformsLib.bumpmap,
  3691. UniformsLib.normalmap,
  3692. UniformsLib.displacementmap,
  3693. UniformsLib.gradientmap,
  3694. UniformsLib.fog,
  3695. UniformsLib.lights,
  3696. {
  3697. emissive : { value: new Color( 0x000000 ) },
  3698. specular : { value: new Color( 0x111111 ) },
  3699. shininess: { value: 30 }
  3700. }
  3701. ),
  3702. vertexShader: ShaderChunk.meshphong_vert,
  3703. fragmentShader: ShaderChunk.meshphong_frag
  3704. },
  3705. standard: {
  3706. uniforms: Object.assign( {},
  3707. UniformsLib.common,
  3708. UniformsLib.aomap,
  3709. UniformsLib.lightmap,
  3710. UniformsLib.emissivemap,
  3711. UniformsLib.bumpmap,
  3712. UniformsLib.normalmap,
  3713. UniformsLib.displacementmap,
  3714. UniformsLib.roughnessmap,
  3715. UniformsLib.metalnessmap,
  3716. UniformsLib.fog,
  3717. UniformsLib.lights,
  3718. {
  3719. emissive : { value: new Color( 0x000000 ) },
  3720. roughness: { value: 0.5 },
  3721. metalness: { value: 0 },
  3722. envMapIntensity : { value: 1 }, // temporary
  3723. }
  3724. ),
  3725. vertexShader: ShaderChunk.meshphysical_vert,
  3726. fragmentShader: ShaderChunk.meshphysical_frag
  3727. },
  3728. points: {
  3729. uniforms: Object.assign( {},
  3730. UniformsLib.points,
  3731. UniformsLib.fog
  3732. ),
  3733. vertexShader: ShaderChunk.points_vert,
  3734. fragmentShader: ShaderChunk.points_frag
  3735. },
  3736. dashed: {
  3737. uniforms: Object.assign( {},
  3738. UniformsLib.common,
  3739. UniformsLib.fog,
  3740. {
  3741. scale : { value: 1 },
  3742. dashSize : { value: 1 },
  3743. totalSize: { value: 2 }
  3744. }
  3745. ),
  3746. vertexShader: ShaderChunk.linedashed_vert,
  3747. fragmentShader: ShaderChunk.linedashed_frag
  3748. },
  3749. depth: {
  3750. uniforms: Object.assign( {},
  3751. UniformsLib.common,
  3752. UniformsLib.displacementmap
  3753. ),
  3754. vertexShader: ShaderChunk.depth_vert,
  3755. fragmentShader: ShaderChunk.depth_frag
  3756. },
  3757. normal: {
  3758. uniforms: {
  3759. opacity : { value: 1.0 }
  3760. },
  3761. vertexShader: ShaderChunk.normal_vert,
  3762. fragmentShader: ShaderChunk.normal_frag
  3763. },
  3764. /* -------------------------------------------------------------------------
  3765. // Cube map shader
  3766. ------------------------------------------------------------------------- */
  3767. cube: {
  3768. uniforms: {
  3769. tCube: { value: null },
  3770. tFlip: { value: - 1 },
  3771. opacity: { value: 1.0 }
  3772. },
  3773. vertexShader: ShaderChunk.cube_vert,
  3774. fragmentShader: ShaderChunk.cube_frag
  3775. },
  3776. /* -------------------------------------------------------------------------
  3777. // Cube map shader
  3778. ------------------------------------------------------------------------- */
  3779. equirect: {
  3780. uniforms: {
  3781. tEquirect: { value: null },
  3782. tFlip: { value: - 1 }
  3783. },
  3784. vertexShader: ShaderChunk.equirect_vert,
  3785. fragmentShader: ShaderChunk.equirect_frag
  3786. },
  3787. distanceRGBA: {
  3788. uniforms: {
  3789. lightPos: { value: new Vector3() }
  3790. },
  3791. vertexShader: ShaderChunk.distanceRGBA_vert,
  3792. fragmentShader: ShaderChunk.distanceRGBA_frag
  3793. }
  3794. };
  3795. ShaderLib.physical = {
  3796. uniforms: Object.assign( {},
  3797. ShaderLib.standard.uniforms,
  3798. {
  3799. clearCoat: { value: 0 },
  3800. clearCoatRoughness: { value: 0 }
  3801. }
  3802. ),
  3803. vertexShader: ShaderChunk.meshphysical_vert,
  3804. fragmentShader: ShaderChunk.meshphysical_frag
  3805. };
  3806. /**
  3807. * @author bhouston / http://clara.io
  3808. */
  3809. function Box2( min, max ) {
  3810. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  3811. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  3812. }
  3813. Box2.prototype = {
  3814. constructor: Box2,
  3815. set: function ( min, max ) {
  3816. this.min.copy( min );
  3817. this.max.copy( max );
  3818. return this;
  3819. },
  3820. setFromPoints: function ( points ) {
  3821. this.makeEmpty();
  3822. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3823. this.expandByPoint( points[ i ] );
  3824. }
  3825. return this;
  3826. },
  3827. setFromCenterAndSize: function () {
  3828. var v1 = new Vector2();
  3829. return function setFromCenterAndSize( center, size ) {
  3830. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  3831. this.min.copy( center ).sub( halfSize );
  3832. this.max.copy( center ).add( halfSize );
  3833. return this;
  3834. };
  3835. }(),
  3836. clone: function () {
  3837. return new this.constructor().copy( this );
  3838. },
  3839. copy: function ( box ) {
  3840. this.min.copy( box.min );
  3841. this.max.copy( box.max );
  3842. return this;
  3843. },
  3844. makeEmpty: function () {
  3845. this.min.x = this.min.y = + Infinity;
  3846. this.max.x = this.max.y = - Infinity;
  3847. return this;
  3848. },
  3849. isEmpty: function () {
  3850. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3851. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  3852. },
  3853. getCenter: function ( optionalTarget ) {
  3854. var result = optionalTarget || new Vector2();
  3855. return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3856. },
  3857. getSize: function ( optionalTarget ) {
  3858. var result = optionalTarget || new Vector2();
  3859. return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min );
  3860. },
  3861. expandByPoint: function ( point ) {
  3862. this.min.min( point );
  3863. this.max.max( point );
  3864. return this;
  3865. },
  3866. expandByVector: function ( vector ) {
  3867. this.min.sub( vector );
  3868. this.max.add( vector );
  3869. return this;
  3870. },
  3871. expandByScalar: function ( scalar ) {
  3872. this.min.addScalar( - scalar );
  3873. this.max.addScalar( scalar );
  3874. return this;
  3875. },
  3876. containsPoint: function ( point ) {
  3877. if ( point.x < this.min.x || point.x > this.max.x ||
  3878. point.y < this.min.y || point.y > this.max.y ) {
  3879. return false;
  3880. }
  3881. return true;
  3882. },
  3883. containsBox: function ( box ) {
  3884. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  3885. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  3886. return true;
  3887. }
  3888. return false;
  3889. },
  3890. getParameter: function ( point, optionalTarget ) {
  3891. // This can potentially have a divide by zero if the box
  3892. // has a size dimension of 0.
  3893. var result = optionalTarget || new Vector2();
  3894. return result.set(
  3895. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3896. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  3897. );
  3898. },
  3899. intersectsBox: function ( box ) {
  3900. // using 6 splitting planes to rule out intersections.
  3901. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  3902. box.max.y < this.min.y || box.min.y > this.max.y ) {
  3903. return false;
  3904. }
  3905. return true;
  3906. },
  3907. clampPoint: function ( point, optionalTarget ) {
  3908. var result = optionalTarget || new Vector2();
  3909. return result.copy( point ).clamp( this.min, this.max );
  3910. },
  3911. distanceToPoint: function () {
  3912. var v1 = new Vector2();
  3913. return function distanceToPoint( point ) {
  3914. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  3915. return clampedPoint.sub( point ).length();
  3916. };
  3917. }(),
  3918. intersect: function ( box ) {
  3919. this.min.max( box.min );
  3920. this.max.min( box.max );
  3921. return this;
  3922. },
  3923. union: function ( box ) {
  3924. this.min.min( box.min );
  3925. this.max.max( box.max );
  3926. return this;
  3927. },
  3928. translate: function ( offset ) {
  3929. this.min.add( offset );
  3930. this.max.add( offset );
  3931. return this;
  3932. },
  3933. equals: function ( box ) {
  3934. return box.min.equals( this.min ) && box.max.equals( this.max );
  3935. }
  3936. };
  3937. /**
  3938. * @author mikael emtinger / http://gomo.se/
  3939. * @author alteredq / http://alteredqualia.com/
  3940. */
  3941. function LensFlarePlugin( renderer, flares ) {
  3942. var gl = renderer.context;
  3943. var state = renderer.state;
  3944. var vertexBuffer, elementBuffer;
  3945. var shader, program, attributes, uniforms;
  3946. var tempTexture, occlusionTexture;
  3947. function init() {
  3948. var vertices = new Float32Array( [
  3949. - 1, - 1, 0, 0,
  3950. 1, - 1, 1, 0,
  3951. 1, 1, 1, 1,
  3952. - 1, 1, 0, 1
  3953. ] );
  3954. var faces = new Uint16Array( [
  3955. 0, 1, 2,
  3956. 0, 2, 3
  3957. ] );
  3958. // buffers
  3959. vertexBuffer = gl.createBuffer();
  3960. elementBuffer = gl.createBuffer();
  3961. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  3962. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  3963. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  3964. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  3965. // textures
  3966. tempTexture = gl.createTexture();
  3967. occlusionTexture = gl.createTexture();
  3968. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  3969. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  3970. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3971. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3972. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3973. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3974. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  3975. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, 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. shader = {
  3981. vertexShader: [
  3982. "uniform lowp int renderType;",
  3983. "uniform vec3 screenPosition;",
  3984. "uniform vec2 scale;",
  3985. "uniform float rotation;",
  3986. "uniform sampler2D occlusionMap;",
  3987. "attribute vec2 position;",
  3988. "attribute vec2 uv;",
  3989. "varying vec2 vUV;",
  3990. "varying float vVisibility;",
  3991. "void main() {",
  3992. "vUV = uv;",
  3993. "vec2 pos = position;",
  3994. "if ( renderType == 2 ) {",
  3995. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  3996. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  3997. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  3998. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  3999. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  4000. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  4001. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  4002. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  4003. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  4004. "vVisibility = visibility.r / 9.0;",
  4005. "vVisibility *= 1.0 - visibility.g / 9.0;",
  4006. "vVisibility *= visibility.b / 9.0;",
  4007. "vVisibility *= 1.0 - visibility.a / 9.0;",
  4008. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  4009. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  4010. "}",
  4011. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  4012. "}"
  4013. ].join( "\n" ),
  4014. fragmentShader: [
  4015. "uniform lowp int renderType;",
  4016. "uniform sampler2D map;",
  4017. "uniform float opacity;",
  4018. "uniform vec3 color;",
  4019. "varying vec2 vUV;",
  4020. "varying float vVisibility;",
  4021. "void main() {",
  4022. // pink square
  4023. "if ( renderType == 0 ) {",
  4024. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  4025. // restore
  4026. "} else if ( renderType == 1 ) {",
  4027. "gl_FragColor = texture2D( map, vUV );",
  4028. // flare
  4029. "} else {",
  4030. "vec4 texture = texture2D( map, vUV );",
  4031. "texture.a *= opacity * vVisibility;",
  4032. "gl_FragColor = texture;",
  4033. "gl_FragColor.rgb *= color;",
  4034. "}",
  4035. "}"
  4036. ].join( "\n" )
  4037. };
  4038. program = createProgram( shader );
  4039. attributes = {
  4040. vertex: gl.getAttribLocation ( program, "position" ),
  4041. uv: gl.getAttribLocation ( program, "uv" )
  4042. };
  4043. uniforms = {
  4044. renderType: gl.getUniformLocation( program, "renderType" ),
  4045. map: gl.getUniformLocation( program, "map" ),
  4046. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  4047. opacity: gl.getUniformLocation( program, "opacity" ),
  4048. color: gl.getUniformLocation( program, "color" ),
  4049. scale: gl.getUniformLocation( program, "scale" ),
  4050. rotation: gl.getUniformLocation( program, "rotation" ),
  4051. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  4052. };
  4053. }
  4054. /*
  4055. * Render lens flares
  4056. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  4057. * reads these back and calculates occlusion.
  4058. */
  4059. this.render = function ( scene, camera, viewport ) {
  4060. if ( flares.length === 0 ) return;
  4061. var tempPosition = new Vector3();
  4062. var invAspect = viewport.w / viewport.z,
  4063. halfViewportWidth = viewport.z * 0.5,
  4064. halfViewportHeight = viewport.w * 0.5;
  4065. var size = 16 / viewport.w,
  4066. scale = new Vector2( size * invAspect, size );
  4067. var screenPosition = new Vector3( 1, 1, 0 ),
  4068. screenPositionPixels = new Vector2( 1, 1 );
  4069. var validArea = new Box2();
  4070. validArea.min.set( viewport.x, viewport.y );
  4071. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  4072. if ( program === undefined ) {
  4073. init();
  4074. }
  4075. gl.useProgram( program );
  4076. state.initAttributes();
  4077. state.enableAttribute( attributes.vertex );
  4078. state.enableAttribute( attributes.uv );
  4079. state.disableUnusedAttributes();
  4080. // loop through all lens flares to update their occlusion and positions
  4081. // setup gl and common used attribs/uniforms
  4082. gl.uniform1i( uniforms.occlusionMap, 0 );
  4083. gl.uniform1i( uniforms.map, 1 );
  4084. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4085. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  4086. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4087. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4088. state.disable( gl.CULL_FACE );
  4089. state.setDepthWrite( false );
  4090. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  4091. size = 16 / viewport.w;
  4092. scale.set( size * invAspect, size );
  4093. // calc object screen position
  4094. var flare = flares[ i ];
  4095. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  4096. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  4097. tempPosition.applyProjection( camera.projectionMatrix );
  4098. // setup arrays for gl programs
  4099. screenPosition.copy( tempPosition );
  4100. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  4101. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  4102. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  4103. // screen cull
  4104. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  4105. // save current RGB to temp texture
  4106. state.activeTexture( gl.TEXTURE0 );
  4107. state.bindTexture( gl.TEXTURE_2D, null );
  4108. state.activeTexture( gl.TEXTURE1 );
  4109. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4110. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4111. // render pink quad
  4112. gl.uniform1i( uniforms.renderType, 0 );
  4113. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4114. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4115. state.disable( gl.BLEND );
  4116. state.enable( gl.DEPTH_TEST );
  4117. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4118. // copy result to occlusionMap
  4119. state.activeTexture( gl.TEXTURE0 );
  4120. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  4121. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4122. // restore graphics
  4123. gl.uniform1i( uniforms.renderType, 1 );
  4124. state.disable( gl.DEPTH_TEST );
  4125. state.activeTexture( gl.TEXTURE1 );
  4126. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4127. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4128. // update object positions
  4129. flare.positionScreen.copy( screenPosition );
  4130. if ( flare.customUpdateCallback ) {
  4131. flare.customUpdateCallback( flare );
  4132. } else {
  4133. flare.updateLensFlares();
  4134. }
  4135. // render flares
  4136. gl.uniform1i( uniforms.renderType, 2 );
  4137. state.enable( gl.BLEND );
  4138. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  4139. var sprite = flare.lensFlares[ j ];
  4140. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  4141. screenPosition.x = sprite.x;
  4142. screenPosition.y = sprite.y;
  4143. screenPosition.z = sprite.z;
  4144. size = sprite.size * sprite.scale / viewport.w;
  4145. scale.x = size * invAspect;
  4146. scale.y = size;
  4147. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4148. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4149. gl.uniform1f( uniforms.rotation, sprite.rotation );
  4150. gl.uniform1f( uniforms.opacity, sprite.opacity );
  4151. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  4152. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  4153. renderer.setTexture2D( sprite.texture, 1 );
  4154. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4155. }
  4156. }
  4157. }
  4158. }
  4159. // restore gl
  4160. state.enable( gl.CULL_FACE );
  4161. state.enable( gl.DEPTH_TEST );
  4162. state.setDepthWrite( true );
  4163. renderer.resetGLState();
  4164. };
  4165. function createProgram( shader ) {
  4166. var program = gl.createProgram();
  4167. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4168. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4169. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  4170. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  4171. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  4172. gl.compileShader( fragmentShader );
  4173. gl.compileShader( vertexShader );
  4174. gl.attachShader( program, fragmentShader );
  4175. gl.attachShader( program, vertexShader );
  4176. gl.linkProgram( program );
  4177. return program;
  4178. }
  4179. }
  4180. /**
  4181. * @author mikael emtinger / http://gomo.se/
  4182. * @author alteredq / http://alteredqualia.com/
  4183. */
  4184. function SpritePlugin( renderer, sprites ) {
  4185. var gl = renderer.context;
  4186. var state = renderer.state;
  4187. var vertexBuffer, elementBuffer;
  4188. var program, attributes, uniforms;
  4189. var texture;
  4190. // decompose matrixWorld
  4191. var spritePosition = new Vector3();
  4192. var spriteRotation = new Quaternion();
  4193. var spriteScale = new Vector3();
  4194. function init() {
  4195. var vertices = new Float32Array( [
  4196. - 0.5, - 0.5, 0, 0,
  4197. 0.5, - 0.5, 1, 0,
  4198. 0.5, 0.5, 1, 1,
  4199. - 0.5, 0.5, 0, 1
  4200. ] );
  4201. var faces = new Uint16Array( [
  4202. 0, 1, 2,
  4203. 0, 2, 3
  4204. ] );
  4205. vertexBuffer = gl.createBuffer();
  4206. elementBuffer = gl.createBuffer();
  4207. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4208. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  4209. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4210. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  4211. program = createProgram();
  4212. attributes = {
  4213. position: gl.getAttribLocation ( program, 'position' ),
  4214. uv: gl.getAttribLocation ( program, 'uv' )
  4215. };
  4216. uniforms = {
  4217. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  4218. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  4219. rotation: gl.getUniformLocation( program, 'rotation' ),
  4220. scale: gl.getUniformLocation( program, 'scale' ),
  4221. color: gl.getUniformLocation( program, 'color' ),
  4222. map: gl.getUniformLocation( program, 'map' ),
  4223. opacity: gl.getUniformLocation( program, 'opacity' ),
  4224. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  4225. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  4226. fogType: gl.getUniformLocation( program, 'fogType' ),
  4227. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  4228. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  4229. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  4230. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  4231. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  4232. };
  4233. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  4234. canvas.width = 8;
  4235. canvas.height = 8;
  4236. var context = canvas.getContext( '2d' );
  4237. context.fillStyle = 'white';
  4238. context.fillRect( 0, 0, 8, 8 );
  4239. texture = new Texture( canvas );
  4240. texture.needsUpdate = true;
  4241. }
  4242. this.render = function ( scene, camera ) {
  4243. if ( sprites.length === 0 ) return;
  4244. // setup gl
  4245. if ( program === undefined ) {
  4246. init();
  4247. }
  4248. gl.useProgram( program );
  4249. state.initAttributes();
  4250. state.enableAttribute( attributes.position );
  4251. state.enableAttribute( attributes.uv );
  4252. state.disableUnusedAttributes();
  4253. state.disable( gl.CULL_FACE );
  4254. state.enable( gl.BLEND );
  4255. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4256. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  4257. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4258. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4259. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  4260. state.activeTexture( gl.TEXTURE0 );
  4261. gl.uniform1i( uniforms.map, 0 );
  4262. var oldFogType = 0;
  4263. var sceneFogType = 0;
  4264. var fog = scene.fog;
  4265. if ( fog ) {
  4266. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  4267. if ( fog.isFog ) {
  4268. gl.uniform1f( uniforms.fogNear, fog.near );
  4269. gl.uniform1f( uniforms.fogFar, fog.far );
  4270. gl.uniform1i( uniforms.fogType, 1 );
  4271. oldFogType = 1;
  4272. sceneFogType = 1;
  4273. } else if ( fog.isFogExp2 ) {
  4274. gl.uniform1f( uniforms.fogDensity, fog.density );
  4275. gl.uniform1i( uniforms.fogType, 2 );
  4276. oldFogType = 2;
  4277. sceneFogType = 2;
  4278. }
  4279. } else {
  4280. gl.uniform1i( uniforms.fogType, 0 );
  4281. oldFogType = 0;
  4282. sceneFogType = 0;
  4283. }
  4284. // update positions and sort
  4285. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4286. var sprite = sprites[ i ];
  4287. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  4288. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  4289. }
  4290. sprites.sort( painterSortStable );
  4291. // render all sprites
  4292. var scale = [];
  4293. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4294. var sprite = sprites[ i ];
  4295. var material = sprite.material;
  4296. if ( material.visible === false ) continue;
  4297. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  4298. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  4299. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  4300. scale[ 0 ] = spriteScale.x;
  4301. scale[ 1 ] = spriteScale.y;
  4302. var fogType = 0;
  4303. if ( scene.fog && material.fog ) {
  4304. fogType = sceneFogType;
  4305. }
  4306. if ( oldFogType !== fogType ) {
  4307. gl.uniform1i( uniforms.fogType, fogType );
  4308. oldFogType = fogType;
  4309. }
  4310. if ( material.map !== null ) {
  4311. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  4312. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  4313. } else {
  4314. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  4315. gl.uniform2f( uniforms.uvScale, 1, 1 );
  4316. }
  4317. gl.uniform1f( uniforms.opacity, material.opacity );
  4318. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  4319. gl.uniform1f( uniforms.rotation, material.rotation );
  4320. gl.uniform2fv( uniforms.scale, scale );
  4321. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  4322. state.setDepthTest( material.depthTest );
  4323. state.setDepthWrite( material.depthWrite );
  4324. if ( material.map ) {
  4325. renderer.setTexture2D( material.map, 0 );
  4326. } else {
  4327. renderer.setTexture2D( texture, 0 );
  4328. }
  4329. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4330. }
  4331. // restore gl
  4332. state.enable( gl.CULL_FACE );
  4333. renderer.resetGLState();
  4334. };
  4335. function createProgram() {
  4336. var program = gl.createProgram();
  4337. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4338. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4339. gl.shaderSource( vertexShader, [
  4340. 'precision ' + renderer.getPrecision() + ' float;',
  4341. 'uniform mat4 modelViewMatrix;',
  4342. 'uniform mat4 projectionMatrix;',
  4343. 'uniform float rotation;',
  4344. 'uniform vec2 scale;',
  4345. 'uniform vec2 uvOffset;',
  4346. 'uniform vec2 uvScale;',
  4347. 'attribute vec2 position;',
  4348. 'attribute vec2 uv;',
  4349. 'varying vec2 vUV;',
  4350. 'void main() {',
  4351. 'vUV = uvOffset + uv * uvScale;',
  4352. 'vec2 alignedPosition = position * scale;',
  4353. 'vec2 rotatedPosition;',
  4354. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  4355. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  4356. 'vec4 finalPosition;',
  4357. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  4358. 'finalPosition.xy += rotatedPosition;',
  4359. 'finalPosition = projectionMatrix * finalPosition;',
  4360. 'gl_Position = finalPosition;',
  4361. '}'
  4362. ].join( '\n' ) );
  4363. gl.shaderSource( fragmentShader, [
  4364. 'precision ' + renderer.getPrecision() + ' float;',
  4365. 'uniform vec3 color;',
  4366. 'uniform sampler2D map;',
  4367. 'uniform float opacity;',
  4368. 'uniform int fogType;',
  4369. 'uniform vec3 fogColor;',
  4370. 'uniform float fogDensity;',
  4371. 'uniform float fogNear;',
  4372. 'uniform float fogFar;',
  4373. 'uniform float alphaTest;',
  4374. 'varying vec2 vUV;',
  4375. 'void main() {',
  4376. 'vec4 texture = texture2D( map, vUV );',
  4377. 'if ( texture.a < alphaTest ) discard;',
  4378. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  4379. 'if ( fogType > 0 ) {',
  4380. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  4381. 'float fogFactor = 0.0;',
  4382. 'if ( fogType == 1 ) {',
  4383. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  4384. '} else {',
  4385. 'const float LOG2 = 1.442695;',
  4386. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  4387. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  4388. '}',
  4389. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  4390. '}',
  4391. '}'
  4392. ].join( '\n' ) );
  4393. gl.compileShader( vertexShader );
  4394. gl.compileShader( fragmentShader );
  4395. gl.attachShader( program, vertexShader );
  4396. gl.attachShader( program, fragmentShader );
  4397. gl.linkProgram( program );
  4398. return program;
  4399. }
  4400. function painterSortStable( a, b ) {
  4401. if ( a.renderOrder !== b.renderOrder ) {
  4402. return a.renderOrder - b.renderOrder;
  4403. } else if ( a.z !== b.z ) {
  4404. return b.z - a.z;
  4405. } else {
  4406. return b.id - a.id;
  4407. }
  4408. }
  4409. }
  4410. /**
  4411. * @author mrdoob / http://mrdoob.com/
  4412. * @author alteredq / http://alteredqualia.com/
  4413. */
  4414. var materialId = 0;
  4415. function Material() {
  4416. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4417. this.uuid = _Math.generateUUID();
  4418. this.name = '';
  4419. this.type = 'Material';
  4420. this.fog = true;
  4421. this.lights = true;
  4422. this.blending = NormalBlending;
  4423. this.side = FrontSide;
  4424. this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading
  4425. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  4426. this.opacity = 1;
  4427. this.transparent = false;
  4428. this.blendSrc = SrcAlphaFactor;
  4429. this.blendDst = OneMinusSrcAlphaFactor;
  4430. this.blendEquation = AddEquation;
  4431. this.blendSrcAlpha = null;
  4432. this.blendDstAlpha = null;
  4433. this.blendEquationAlpha = null;
  4434. this.depthFunc = LessEqualDepth;
  4435. this.depthTest = true;
  4436. this.depthWrite = true;
  4437. this.clippingPlanes = null;
  4438. this.clipIntersection = false;
  4439. this.clipShadows = false;
  4440. this.colorWrite = true;
  4441. this.precision = null; // override the renderer's default precision for this material
  4442. this.polygonOffset = false;
  4443. this.polygonOffsetFactor = 0;
  4444. this.polygonOffsetUnits = 0;
  4445. this.alphaTest = 0;
  4446. this.premultipliedAlpha = false;
  4447. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  4448. this.visible = true;
  4449. this._needsUpdate = true;
  4450. }
  4451. Material.prototype = {
  4452. constructor: Material,
  4453. isMaterial: true,
  4454. get needsUpdate() {
  4455. return this._needsUpdate;
  4456. },
  4457. set needsUpdate( value ) {
  4458. if ( value === true ) this.update();
  4459. this._needsUpdate = value;
  4460. },
  4461. setValues: function ( values ) {
  4462. if ( values === undefined ) return;
  4463. for ( var key in values ) {
  4464. var newValue = values[ key ];
  4465. if ( newValue === undefined ) {
  4466. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  4467. continue;
  4468. }
  4469. var currentValue = this[ key ];
  4470. if ( currentValue === undefined ) {
  4471. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  4472. continue;
  4473. }
  4474. if ( currentValue && currentValue.isColor ) {
  4475. currentValue.set( newValue );
  4476. } else if ( (currentValue && currentValue.isVector3) && (newValue && newValue.isVector3) ) {
  4477. currentValue.copy( newValue );
  4478. } else if ( key === 'overdraw' ) {
  4479. // ensure overdraw is backwards-compatible with legacy boolean type
  4480. this[ key ] = Number( newValue );
  4481. } else {
  4482. this[ key ] = newValue;
  4483. }
  4484. }
  4485. },
  4486. toJSON: function ( meta ) {
  4487. var isRoot = meta === undefined;
  4488. if ( isRoot ) {
  4489. meta = {
  4490. textures: {},
  4491. images: {}
  4492. };
  4493. }
  4494. var data = {
  4495. metadata: {
  4496. version: 4.4,
  4497. type: 'Material',
  4498. generator: 'Material.toJSON'
  4499. }
  4500. };
  4501. // standard Material serialization
  4502. data.uuid = this.uuid;
  4503. data.type = this.type;
  4504. if ( this.name !== '' ) data.name = this.name;
  4505. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4506. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4507. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4508. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4509. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4510. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4511. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  4512. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  4513. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4514. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4515. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4516. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4517. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4518. data.bumpScale = this.bumpScale;
  4519. }
  4520. if ( this.normalMap && this.normalMap.isTexture ) {
  4521. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4522. data.normalScale = this.normalScale.toArray();
  4523. }
  4524. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4525. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4526. data.displacementScale = this.displacementScale;
  4527. data.displacementBias = this.displacementBias;
  4528. }
  4529. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4530. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4531. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4532. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4533. if ( this.envMap && this.envMap.isTexture ) {
  4534. data.envMap = this.envMap.toJSON( meta ).uuid;
  4535. data.reflectivity = this.reflectivity; // Scale behind envMap
  4536. }
  4537. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4538. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4539. }
  4540. if ( this.size !== undefined ) data.size = this.size;
  4541. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4542. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4543. if ( this.shading !== SmoothShading ) data.shading = this.shading;
  4544. if ( this.side !== FrontSide ) data.side = this.side;
  4545. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  4546. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4547. if ( this.transparent === true ) data.transparent = this.transparent;
  4548. data.depthFunc = this.depthFunc;
  4549. data.depthTest = this.depthTest;
  4550. data.depthWrite = this.depthWrite;
  4551. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4552. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4553. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4554. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4555. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4556. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4557. data.skinning = this.skinning;
  4558. data.morphTargets = this.morphTargets;
  4559. // TODO: Copied from Object3D.toJSON
  4560. function extractFromCache( cache ) {
  4561. var values = [];
  4562. for ( var key in cache ) {
  4563. var data = cache[ key ];
  4564. delete data.metadata;
  4565. values.push( data );
  4566. }
  4567. return values;
  4568. }
  4569. if ( isRoot ) {
  4570. var textures = extractFromCache( meta.textures );
  4571. var images = extractFromCache( meta.images );
  4572. if ( textures.length > 0 ) data.textures = textures;
  4573. if ( images.length > 0 ) data.images = images;
  4574. }
  4575. return data;
  4576. },
  4577. clone: function () {
  4578. return new this.constructor().copy( this );
  4579. },
  4580. copy: function ( source ) {
  4581. this.name = source.name;
  4582. this.fog = source.fog;
  4583. this.lights = source.lights;
  4584. this.blending = source.blending;
  4585. this.side = source.side;
  4586. this.shading = source.shading;
  4587. this.vertexColors = source.vertexColors;
  4588. this.opacity = source.opacity;
  4589. this.transparent = source.transparent;
  4590. this.blendSrc = source.blendSrc;
  4591. this.blendDst = source.blendDst;
  4592. this.blendEquation = source.blendEquation;
  4593. this.blendSrcAlpha = source.blendSrcAlpha;
  4594. this.blendDstAlpha = source.blendDstAlpha;
  4595. this.blendEquationAlpha = source.blendEquationAlpha;
  4596. this.depthFunc = source.depthFunc;
  4597. this.depthTest = source.depthTest;
  4598. this.depthWrite = source.depthWrite;
  4599. this.colorWrite = source.colorWrite;
  4600. this.precision = source.precision;
  4601. this.polygonOffset = source.polygonOffset;
  4602. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4603. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4604. this.alphaTest = source.alphaTest;
  4605. this.premultipliedAlpha = source.premultipliedAlpha;
  4606. this.overdraw = source.overdraw;
  4607. this.visible = source.visible;
  4608. this.clipShadows = source.clipShadows;
  4609. this.clipIntersection = source.clipIntersection;
  4610. var srcPlanes = source.clippingPlanes,
  4611. dstPlanes = null;
  4612. if ( srcPlanes !== null ) {
  4613. var n = srcPlanes.length;
  4614. dstPlanes = new Array( n );
  4615. for ( var i = 0; i !== n; ++ i )
  4616. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4617. }
  4618. this.clippingPlanes = dstPlanes;
  4619. return this;
  4620. },
  4621. update: function () {
  4622. this.dispatchEvent( { type: 'update' } );
  4623. },
  4624. dispose: function () {
  4625. this.dispatchEvent( { type: 'dispose' } );
  4626. }
  4627. };
  4628. Object.assign( Material.prototype, EventDispatcher.prototype );
  4629. /**
  4630. * @author alteredq / http://alteredqualia.com/
  4631. *
  4632. * parameters = {
  4633. * defines: { "label" : "value" },
  4634. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  4635. *
  4636. * fragmentShader: <string>,
  4637. * vertexShader: <string>,
  4638. *
  4639. * wireframe: <boolean>,
  4640. * wireframeLinewidth: <float>,
  4641. *
  4642. * lights: <bool>,
  4643. *
  4644. * skinning: <bool>,
  4645. * morphTargets: <bool>,
  4646. * morphNormals: <bool>
  4647. * }
  4648. */
  4649. function ShaderMaterial( parameters ) {
  4650. Material.call( this );
  4651. this.type = 'ShaderMaterial';
  4652. this.defines = {};
  4653. this.uniforms = {};
  4654. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  4655. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  4656. this.linewidth = 1;
  4657. this.wireframe = false;
  4658. this.wireframeLinewidth = 1;
  4659. this.fog = false; // set to use scene fog
  4660. this.lights = false; // set to use scene lights
  4661. this.clipping = false; // set to use user-defined clipping planes
  4662. this.skinning = false; // set to use skinning attribute streams
  4663. this.morphTargets = false; // set to use morph targets
  4664. this.morphNormals = false; // set to use morph normals
  4665. this.extensions = {
  4666. derivatives: false, // set to use derivatives
  4667. fragDepth: false, // set to use fragment depth values
  4668. drawBuffers: false, // set to use draw buffers
  4669. shaderTextureLOD: false // set to use shader texture LOD
  4670. };
  4671. // When rendered geometry doesn't include these attributes but the material does,
  4672. // use these default values in WebGL. This avoids errors when buffer data is missing.
  4673. this.defaultAttributeValues = {
  4674. 'color': [ 1, 1, 1 ],
  4675. 'uv': [ 0, 0 ],
  4676. 'uv2': [ 0, 0 ]
  4677. };
  4678. this.index0AttributeName = undefined;
  4679. if ( parameters !== undefined ) {
  4680. if ( parameters.attributes !== undefined ) {
  4681. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  4682. }
  4683. this.setValues( parameters );
  4684. }
  4685. }
  4686. ShaderMaterial.prototype = Object.create( Material.prototype );
  4687. ShaderMaterial.prototype.constructor = ShaderMaterial;
  4688. ShaderMaterial.prototype.isShaderMaterial = true;
  4689. ShaderMaterial.prototype.copy = function ( source ) {
  4690. Material.prototype.copy.call( this, source );
  4691. this.fragmentShader = source.fragmentShader;
  4692. this.vertexShader = source.vertexShader;
  4693. this.uniforms = Object.assign( {}, source.uniforms );
  4694. this.defines = source.defines;
  4695. this.wireframe = source.wireframe;
  4696. this.wireframeLinewidth = source.wireframeLinewidth;
  4697. this.lights = source.lights;
  4698. this.clipping = source.clipping;
  4699. this.skinning = source.skinning;
  4700. this.morphTargets = source.morphTargets;
  4701. this.morphNormals = source.morphNormals;
  4702. this.extensions = source.extensions;
  4703. return this;
  4704. };
  4705. ShaderMaterial.prototype.toJSON = function ( meta ) {
  4706. var data = Material.prototype.toJSON.call( this, meta );
  4707. data.uniforms = this.uniforms;
  4708. data.vertexShader = this.vertexShader;
  4709. data.fragmentShader = this.fragmentShader;
  4710. return data;
  4711. };
  4712. /**
  4713. * @author mrdoob / http://mrdoob.com/
  4714. * @author alteredq / http://alteredqualia.com/
  4715. * @author bhouston / https://clara.io
  4716. * @author WestLangley / http://github.com/WestLangley
  4717. *
  4718. * parameters = {
  4719. *
  4720. * opacity: <float>,
  4721. *
  4722. * map: new THREE.Texture( <Image> ),
  4723. *
  4724. * alphaMap: new THREE.Texture( <Image> ),
  4725. *
  4726. * displacementMap: new THREE.Texture( <Image> ),
  4727. * displacementScale: <float>,
  4728. * displacementBias: <float>,
  4729. *
  4730. * wireframe: <boolean>,
  4731. * wireframeLinewidth: <float>
  4732. * }
  4733. */
  4734. function MeshDepthMaterial( parameters ) {
  4735. Material.call( this );
  4736. this.type = 'MeshDepthMaterial';
  4737. this.depthPacking = BasicDepthPacking;
  4738. this.skinning = false;
  4739. this.morphTargets = false;
  4740. this.map = null;
  4741. this.alphaMap = null;
  4742. this.displacementMap = null;
  4743. this.displacementScale = 1;
  4744. this.displacementBias = 0;
  4745. this.wireframe = false;
  4746. this.wireframeLinewidth = 1;
  4747. this.fog = false;
  4748. this.lights = false;
  4749. this.setValues( parameters );
  4750. }
  4751. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  4752. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  4753. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  4754. MeshDepthMaterial.prototype.copy = function ( source ) {
  4755. Material.prototype.copy.call( this, source );
  4756. this.depthPacking = source.depthPacking;
  4757. this.skinning = source.skinning;
  4758. this.morphTargets = source.morphTargets;
  4759. this.map = source.map;
  4760. this.alphaMap = source.alphaMap;
  4761. this.displacementMap = source.displacementMap;
  4762. this.displacementScale = source.displacementScale;
  4763. this.displacementBias = source.displacementBias;
  4764. this.wireframe = source.wireframe;
  4765. this.wireframeLinewidth = source.wireframeLinewidth;
  4766. return this;
  4767. };
  4768. /**
  4769. * @author bhouston / http://clara.io
  4770. * @author WestLangley / http://github.com/WestLangley
  4771. */
  4772. function Box3( min, max ) {
  4773. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  4774. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  4775. }
  4776. Box3.prototype = {
  4777. constructor: Box3,
  4778. isBox3: true,
  4779. set: function ( min, max ) {
  4780. this.min.copy( min );
  4781. this.max.copy( max );
  4782. return this;
  4783. },
  4784. setFromArray: function ( array ) {
  4785. var minX = + Infinity;
  4786. var minY = + Infinity;
  4787. var minZ = + Infinity;
  4788. var maxX = - Infinity;
  4789. var maxY = - Infinity;
  4790. var maxZ = - Infinity;
  4791. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  4792. var x = array[ i ];
  4793. var y = array[ i + 1 ];
  4794. var z = array[ i + 2 ];
  4795. if ( x < minX ) minX = x;
  4796. if ( y < minY ) minY = y;
  4797. if ( z < minZ ) minZ = z;
  4798. if ( x > maxX ) maxX = x;
  4799. if ( y > maxY ) maxY = y;
  4800. if ( z > maxZ ) maxZ = z;
  4801. }
  4802. this.min.set( minX, minY, minZ );
  4803. this.max.set( maxX, maxY, maxZ );
  4804. },
  4805. setFromPoints: function ( points ) {
  4806. this.makeEmpty();
  4807. for ( var i = 0, il = points.length; i < il; i ++ ) {
  4808. this.expandByPoint( points[ i ] );
  4809. }
  4810. return this;
  4811. },
  4812. setFromCenterAndSize: function () {
  4813. var v1 = new Vector3();
  4814. return function setFromCenterAndSize( center, size ) {
  4815. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  4816. this.min.copy( center ).sub( halfSize );
  4817. this.max.copy( center ).add( halfSize );
  4818. return this;
  4819. };
  4820. }(),
  4821. setFromObject: function () {
  4822. // Computes the world-axis-aligned bounding box of an object (including its children),
  4823. // accounting for both the object's, and children's, world transforms
  4824. var v1 = new Vector3();
  4825. return function setFromObject( object ) {
  4826. var scope = this;
  4827. object.updateMatrixWorld( true );
  4828. this.makeEmpty();
  4829. object.traverse( function ( node ) {
  4830. var geometry = node.geometry;
  4831. if ( geometry !== undefined ) {
  4832. if ( geometry.isGeometry ) {
  4833. var vertices = geometry.vertices;
  4834. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4835. v1.copy( vertices[ i ] );
  4836. v1.applyMatrix4( node.matrixWorld );
  4837. scope.expandByPoint( v1 );
  4838. }
  4839. } else if ( geometry.isBufferGeometry ) {
  4840. var attribute = geometry.attributes.position;
  4841. if ( attribute !== undefined ) {
  4842. var array, offset, stride;
  4843. if ( attribute.isInterleavedBufferAttribute ) {
  4844. array = attribute.data.array;
  4845. offset = attribute.offset;
  4846. stride = attribute.data.stride;
  4847. } else {
  4848. array = attribute.array;
  4849. offset = 0;
  4850. stride = 3;
  4851. }
  4852. for ( var i = offset, il = array.length; i < il; i += stride ) {
  4853. v1.fromArray( array, i );
  4854. v1.applyMatrix4( node.matrixWorld );
  4855. scope.expandByPoint( v1 );
  4856. }
  4857. }
  4858. }
  4859. }
  4860. } );
  4861. return this;
  4862. };
  4863. }(),
  4864. clone: function () {
  4865. return new this.constructor().copy( this );
  4866. },
  4867. copy: function ( box ) {
  4868. this.min.copy( box.min );
  4869. this.max.copy( box.max );
  4870. return this;
  4871. },
  4872. makeEmpty: function () {
  4873. this.min.x = this.min.y = this.min.z = + Infinity;
  4874. this.max.x = this.max.y = this.max.z = - Infinity;
  4875. return this;
  4876. },
  4877. isEmpty: function () {
  4878. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4879. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  4880. },
  4881. getCenter: function ( optionalTarget ) {
  4882. var result = optionalTarget || new Vector3();
  4883. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  4884. },
  4885. getSize: function ( optionalTarget ) {
  4886. var result = optionalTarget || new Vector3();
  4887. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  4888. },
  4889. expandByPoint: function ( point ) {
  4890. this.min.min( point );
  4891. this.max.max( point );
  4892. return this;
  4893. },
  4894. expandByVector: function ( vector ) {
  4895. this.min.sub( vector );
  4896. this.max.add( vector );
  4897. return this;
  4898. },
  4899. expandByScalar: function ( scalar ) {
  4900. this.min.addScalar( - scalar );
  4901. this.max.addScalar( scalar );
  4902. return this;
  4903. },
  4904. containsPoint: function ( point ) {
  4905. if ( point.x < this.min.x || point.x > this.max.x ||
  4906. point.y < this.min.y || point.y > this.max.y ||
  4907. point.z < this.min.z || point.z > this.max.z ) {
  4908. return false;
  4909. }
  4910. return true;
  4911. },
  4912. containsBox: function ( box ) {
  4913. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  4914. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  4915. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  4916. return true;
  4917. }
  4918. return false;
  4919. },
  4920. getParameter: function ( point, optionalTarget ) {
  4921. // This can potentially have a divide by zero if the box
  4922. // has a size dimension of 0.
  4923. var result = optionalTarget || new Vector3();
  4924. return result.set(
  4925. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  4926. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  4927. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  4928. );
  4929. },
  4930. intersectsBox: function ( box ) {
  4931. // using 6 splitting planes to rule out intersections.
  4932. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  4933. box.max.y < this.min.y || box.min.y > this.max.y ||
  4934. box.max.z < this.min.z || box.min.z > this.max.z ) {
  4935. return false;
  4936. }
  4937. return true;
  4938. },
  4939. intersectsSphere: ( function () {
  4940. var closestPoint;
  4941. return function intersectsSphere( sphere ) {
  4942. if ( closestPoint === undefined ) closestPoint = new Vector3();
  4943. // Find the point on the AABB closest to the sphere center.
  4944. this.clampPoint( sphere.center, closestPoint );
  4945. // If that point is inside the sphere, the AABB and sphere intersect.
  4946. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  4947. };
  4948. } )(),
  4949. intersectsPlane: function ( plane ) {
  4950. // We compute the minimum and maximum dot product values. If those values
  4951. // are on the same side (back or front) of the plane, then there is no intersection.
  4952. var min, max;
  4953. if ( plane.normal.x > 0 ) {
  4954. min = plane.normal.x * this.min.x;
  4955. max = plane.normal.x * this.max.x;
  4956. } else {
  4957. min = plane.normal.x * this.max.x;
  4958. max = plane.normal.x * this.min.x;
  4959. }
  4960. if ( plane.normal.y > 0 ) {
  4961. min += plane.normal.y * this.min.y;
  4962. max += plane.normal.y * this.max.y;
  4963. } else {
  4964. min += plane.normal.y * this.max.y;
  4965. max += plane.normal.y * this.min.y;
  4966. }
  4967. if ( plane.normal.z > 0 ) {
  4968. min += plane.normal.z * this.min.z;
  4969. max += plane.normal.z * this.max.z;
  4970. } else {
  4971. min += plane.normal.z * this.max.z;
  4972. max += plane.normal.z * this.min.z;
  4973. }
  4974. return ( min <= plane.constant && max >= plane.constant );
  4975. },
  4976. clampPoint: function ( point, optionalTarget ) {
  4977. var result = optionalTarget || new Vector3();
  4978. return result.copy( point ).clamp( this.min, this.max );
  4979. },
  4980. distanceToPoint: function () {
  4981. var v1 = new Vector3();
  4982. return function distanceToPoint( point ) {
  4983. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  4984. return clampedPoint.sub( point ).length();
  4985. };
  4986. }(),
  4987. getBoundingSphere: function () {
  4988. var v1 = new Vector3();
  4989. return function getBoundingSphere( optionalTarget ) {
  4990. var result = optionalTarget || new Sphere();
  4991. this.getCenter( result.center );
  4992. result.radius = this.getSize( v1 ).length() * 0.5;
  4993. return result;
  4994. };
  4995. }(),
  4996. intersect: function ( box ) {
  4997. this.min.max( box.min );
  4998. this.max.min( box.max );
  4999. // 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.
  5000. if( this.isEmpty() ) this.makeEmpty();
  5001. return this;
  5002. },
  5003. union: function ( box ) {
  5004. this.min.min( box.min );
  5005. this.max.max( box.max );
  5006. return this;
  5007. },
  5008. applyMatrix4: function () {
  5009. var points = [
  5010. new Vector3(),
  5011. new Vector3(),
  5012. new Vector3(),
  5013. new Vector3(),
  5014. new Vector3(),
  5015. new Vector3(),
  5016. new Vector3(),
  5017. new Vector3()
  5018. ];
  5019. return function applyMatrix4( matrix ) {
  5020. // transform of empty box is an empty box.
  5021. if( this.isEmpty() ) return this;
  5022. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5023. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  5024. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  5025. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  5026. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  5027. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  5028. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  5029. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  5030. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  5031. this.setFromPoints( points );
  5032. return this;
  5033. };
  5034. }(),
  5035. translate: function ( offset ) {
  5036. this.min.add( offset );
  5037. this.max.add( offset );
  5038. return this;
  5039. },
  5040. equals: function ( box ) {
  5041. return box.min.equals( this.min ) && box.max.equals( this.max );
  5042. }
  5043. };
  5044. /**
  5045. * @author bhouston / http://clara.io
  5046. * @author mrdoob / http://mrdoob.com/
  5047. */
  5048. function Sphere( center, radius ) {
  5049. this.center = ( center !== undefined ) ? center : new Vector3();
  5050. this.radius = ( radius !== undefined ) ? radius : 0;
  5051. }
  5052. Sphere.prototype = {
  5053. constructor: Sphere,
  5054. set: function ( center, radius ) {
  5055. this.center.copy( center );
  5056. this.radius = radius;
  5057. return this;
  5058. },
  5059. setFromPoints: function () {
  5060. var box = new Box3();
  5061. return function setFromPoints( points, optionalCenter ) {
  5062. var center = this.center;
  5063. if ( optionalCenter !== undefined ) {
  5064. center.copy( optionalCenter );
  5065. } else {
  5066. box.setFromPoints( points ).getCenter( center );
  5067. }
  5068. var maxRadiusSq = 0;
  5069. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5070. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5071. }
  5072. this.radius = Math.sqrt( maxRadiusSq );
  5073. return this;
  5074. };
  5075. }(),
  5076. clone: function () {
  5077. return new this.constructor().copy( this );
  5078. },
  5079. copy: function ( sphere ) {
  5080. this.center.copy( sphere.center );
  5081. this.radius = sphere.radius;
  5082. return this;
  5083. },
  5084. empty: function () {
  5085. return ( this.radius <= 0 );
  5086. },
  5087. containsPoint: function ( point ) {
  5088. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5089. },
  5090. distanceToPoint: function ( point ) {
  5091. return ( point.distanceTo( this.center ) - this.radius );
  5092. },
  5093. intersectsSphere: function ( sphere ) {
  5094. var radiusSum = this.radius + sphere.radius;
  5095. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5096. },
  5097. intersectsBox: function ( box ) {
  5098. return box.intersectsSphere( this );
  5099. },
  5100. intersectsPlane: function ( plane ) {
  5101. // We use the following equation to compute the signed distance from
  5102. // the center of the sphere to the plane.
  5103. //
  5104. // distance = q * n - d
  5105. //
  5106. // If this distance is greater than the radius of the sphere,
  5107. // then there is no intersection.
  5108. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  5109. },
  5110. clampPoint: function ( point, optionalTarget ) {
  5111. var deltaLengthSq = this.center.distanceToSquared( point );
  5112. var result = optionalTarget || new Vector3();
  5113. result.copy( point );
  5114. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5115. result.sub( this.center ).normalize();
  5116. result.multiplyScalar( this.radius ).add( this.center );
  5117. }
  5118. return result;
  5119. },
  5120. getBoundingBox: function ( optionalTarget ) {
  5121. var box = optionalTarget || new Box3();
  5122. box.set( this.center, this.center );
  5123. box.expandByScalar( this.radius );
  5124. return box;
  5125. },
  5126. applyMatrix4: function ( matrix ) {
  5127. this.center.applyMatrix4( matrix );
  5128. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5129. return this;
  5130. },
  5131. translate: function ( offset ) {
  5132. this.center.add( offset );
  5133. return this;
  5134. },
  5135. equals: function ( sphere ) {
  5136. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  5137. }
  5138. };
  5139. /**
  5140. * @author alteredq / http://alteredqualia.com/
  5141. * @author WestLangley / http://github.com/WestLangley
  5142. * @author bhouston / http://clara.io
  5143. * @author tschw
  5144. */
  5145. function Matrix3() {
  5146. this.elements = new Float32Array( [
  5147. 1, 0, 0,
  5148. 0, 1, 0,
  5149. 0, 0, 1
  5150. ] );
  5151. if ( arguments.length > 0 ) {
  5152. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  5153. }
  5154. }
  5155. Matrix3.prototype = {
  5156. constructor: Matrix3,
  5157. isMatrix3: true,
  5158. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  5159. var te = this.elements;
  5160. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  5161. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  5162. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  5163. return this;
  5164. },
  5165. identity: function () {
  5166. this.set(
  5167. 1, 0, 0,
  5168. 0, 1, 0,
  5169. 0, 0, 1
  5170. );
  5171. return this;
  5172. },
  5173. clone: function () {
  5174. return new this.constructor().fromArray( this.elements );
  5175. },
  5176. copy: function ( m ) {
  5177. var me = m.elements;
  5178. this.set(
  5179. me[ 0 ], me[ 3 ], me[ 6 ],
  5180. me[ 1 ], me[ 4 ], me[ 7 ],
  5181. me[ 2 ], me[ 5 ], me[ 8 ]
  5182. );
  5183. return this;
  5184. },
  5185. setFromMatrix4: function( m ) {
  5186. var me = m.elements;
  5187. this.set(
  5188. me[ 0 ], me[ 4 ], me[ 8 ],
  5189. me[ 1 ], me[ 5 ], me[ 9 ],
  5190. me[ 2 ], me[ 6 ], me[ 10 ]
  5191. );
  5192. return this;
  5193. },
  5194. applyToVector3Array: function () {
  5195. var v1;
  5196. return function applyToVector3Array( array, offset, length ) {
  5197. if ( v1 === undefined ) v1 = new Vector3();
  5198. if ( offset === undefined ) offset = 0;
  5199. if ( length === undefined ) length = array.length;
  5200. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  5201. v1.fromArray( array, j );
  5202. v1.applyMatrix3( this );
  5203. v1.toArray( array, j );
  5204. }
  5205. return array;
  5206. };
  5207. }(),
  5208. applyToBuffer: function () {
  5209. var v1;
  5210. return function applyToBuffer( buffer, offset, length ) {
  5211. if ( v1 === undefined ) v1 = new Vector3();
  5212. if ( offset === undefined ) offset = 0;
  5213. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  5214. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  5215. v1.x = buffer.getX( j );
  5216. v1.y = buffer.getY( j );
  5217. v1.z = buffer.getZ( j );
  5218. v1.applyMatrix3( this );
  5219. buffer.setXYZ( j, v1.x, v1.y, v1.z );
  5220. }
  5221. return buffer;
  5222. };
  5223. }(),
  5224. multiplyScalar: function ( s ) {
  5225. var te = this.elements;
  5226. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  5227. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  5228. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  5229. return this;
  5230. },
  5231. determinant: function () {
  5232. var te = this.elements;
  5233. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  5234. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  5235. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  5236. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  5237. },
  5238. getInverse: function ( matrix, throwOnDegenerate ) {
  5239. if ( matrix && matrix.isMatrix4 ) {
  5240. console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." );
  5241. }
  5242. var me = matrix.elements,
  5243. te = this.elements,
  5244. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  5245. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  5246. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  5247. t11 = n33 * n22 - n32 * n23,
  5248. t12 = n32 * n13 - n33 * n12,
  5249. t13 = n23 * n12 - n22 * n13,
  5250. det = n11 * t11 + n21 * t12 + n31 * t13;
  5251. if ( det === 0 ) {
  5252. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  5253. if ( throwOnDegenerate === true ) {
  5254. throw new Error( msg );
  5255. } else {
  5256. console.warn( msg );
  5257. }
  5258. return this.identity();
  5259. }
  5260. var detInv = 1 / det;
  5261. te[ 0 ] = t11 * detInv;
  5262. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  5263. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  5264. te[ 3 ] = t12 * detInv;
  5265. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  5266. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  5267. te[ 6 ] = t13 * detInv;
  5268. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  5269. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  5270. return this;
  5271. },
  5272. transpose: function () {
  5273. var tmp, m = this.elements;
  5274. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  5275. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  5276. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  5277. return this;
  5278. },
  5279. getNormalMatrix: function ( matrix4 ) {
  5280. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  5281. },
  5282. transposeIntoArray: function ( r ) {
  5283. var m = this.elements;
  5284. r[ 0 ] = m[ 0 ];
  5285. r[ 1 ] = m[ 3 ];
  5286. r[ 2 ] = m[ 6 ];
  5287. r[ 3 ] = m[ 1 ];
  5288. r[ 4 ] = m[ 4 ];
  5289. r[ 5 ] = m[ 7 ];
  5290. r[ 6 ] = m[ 2 ];
  5291. r[ 7 ] = m[ 5 ];
  5292. r[ 8 ] = m[ 8 ];
  5293. return this;
  5294. },
  5295. fromArray: function ( array, offset ) {
  5296. if ( offset === undefined ) offset = 0;
  5297. for( var i = 0; i < 9; i ++ ) {
  5298. this.elements[ i ] = array[ i + offset ];
  5299. }
  5300. return this;
  5301. },
  5302. toArray: function ( array, offset ) {
  5303. if ( array === undefined ) array = [];
  5304. if ( offset === undefined ) offset = 0;
  5305. var te = this.elements;
  5306. array[ offset ] = te[ 0 ];
  5307. array[ offset + 1 ] = te[ 1 ];
  5308. array[ offset + 2 ] = te[ 2 ];
  5309. array[ offset + 3 ] = te[ 3 ];
  5310. array[ offset + 4 ] = te[ 4 ];
  5311. array[ offset + 5 ] = te[ 5 ];
  5312. array[ offset + 6 ] = te[ 6 ];
  5313. array[ offset + 7 ] = te[ 7 ];
  5314. array[ offset + 8 ] = te[ 8 ];
  5315. return array;
  5316. }
  5317. };
  5318. /**
  5319. * @author bhouston / http://clara.io
  5320. */
  5321. function Plane( normal, constant ) {
  5322. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  5323. this.constant = ( constant !== undefined ) ? constant : 0;
  5324. }
  5325. Plane.prototype = {
  5326. constructor: Plane,
  5327. set: function ( normal, constant ) {
  5328. this.normal.copy( normal );
  5329. this.constant = constant;
  5330. return this;
  5331. },
  5332. setComponents: function ( x, y, z, w ) {
  5333. this.normal.set( x, y, z );
  5334. this.constant = w;
  5335. return this;
  5336. },
  5337. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  5338. this.normal.copy( normal );
  5339. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  5340. return this;
  5341. },
  5342. setFromCoplanarPoints: function () {
  5343. var v1 = new Vector3();
  5344. var v2 = new Vector3();
  5345. return function setFromCoplanarPoints( a, b, c ) {
  5346. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  5347. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5348. this.setFromNormalAndCoplanarPoint( normal, a );
  5349. return this;
  5350. };
  5351. }(),
  5352. clone: function () {
  5353. return new this.constructor().copy( this );
  5354. },
  5355. copy: function ( plane ) {
  5356. this.normal.copy( plane.normal );
  5357. this.constant = plane.constant;
  5358. return this;
  5359. },
  5360. normalize: function () {
  5361. // Note: will lead to a divide by zero if the plane is invalid.
  5362. var inverseNormalLength = 1.0 / this.normal.length();
  5363. this.normal.multiplyScalar( inverseNormalLength );
  5364. this.constant *= inverseNormalLength;
  5365. return this;
  5366. },
  5367. negate: function () {
  5368. this.constant *= - 1;
  5369. this.normal.negate();
  5370. return this;
  5371. },
  5372. distanceToPoint: function ( point ) {
  5373. return this.normal.dot( point ) + this.constant;
  5374. },
  5375. distanceToSphere: function ( sphere ) {
  5376. return this.distanceToPoint( sphere.center ) - sphere.radius;
  5377. },
  5378. projectPoint: function ( point, optionalTarget ) {
  5379. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  5380. },
  5381. orthoPoint: function ( point, optionalTarget ) {
  5382. var perpendicularMagnitude = this.distanceToPoint( point );
  5383. var result = optionalTarget || new Vector3();
  5384. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  5385. },
  5386. intersectLine: function () {
  5387. var v1 = new Vector3();
  5388. return function intersectLine( line, optionalTarget ) {
  5389. var result = optionalTarget || new Vector3();
  5390. var direction = line.delta( v1 );
  5391. var denominator = this.normal.dot( direction );
  5392. if ( denominator === 0 ) {
  5393. // line is coplanar, return origin
  5394. if ( this.distanceToPoint( line.start ) === 0 ) {
  5395. return result.copy( line.start );
  5396. }
  5397. // Unsure if this is the correct method to handle this case.
  5398. return undefined;
  5399. }
  5400. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  5401. if ( t < 0 || t > 1 ) {
  5402. return undefined;
  5403. }
  5404. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  5405. };
  5406. }(),
  5407. intersectsLine: function ( line ) {
  5408. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5409. var startSign = this.distanceToPoint( line.start );
  5410. var endSign = this.distanceToPoint( line.end );
  5411. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  5412. },
  5413. intersectsBox: function ( box ) {
  5414. return box.intersectsPlane( this );
  5415. },
  5416. intersectsSphere: function ( sphere ) {
  5417. return sphere.intersectsPlane( this );
  5418. },
  5419. coplanarPoint: function ( optionalTarget ) {
  5420. var result = optionalTarget || new Vector3();
  5421. return result.copy( this.normal ).multiplyScalar( - this.constant );
  5422. },
  5423. applyMatrix4: function () {
  5424. var v1 = new Vector3();
  5425. var m1 = new Matrix3();
  5426. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  5427. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  5428. // transform normal based on theory here:
  5429. // http://www.songho.ca/opengl/gl_normaltransform.html
  5430. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  5431. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  5432. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  5433. this.constant = - referencePoint.dot( normal );
  5434. return this;
  5435. };
  5436. }(),
  5437. translate: function ( offset ) {
  5438. this.constant = this.constant - offset.dot( this.normal );
  5439. return this;
  5440. },
  5441. equals: function ( plane ) {
  5442. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  5443. }
  5444. };
  5445. /**
  5446. * @author mrdoob / http://mrdoob.com/
  5447. * @author alteredq / http://alteredqualia.com/
  5448. * @author bhouston / http://clara.io
  5449. */
  5450. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  5451. this.planes = [
  5452. ( p0 !== undefined ) ? p0 : new Plane(),
  5453. ( p1 !== undefined ) ? p1 : new Plane(),
  5454. ( p2 !== undefined ) ? p2 : new Plane(),
  5455. ( p3 !== undefined ) ? p3 : new Plane(),
  5456. ( p4 !== undefined ) ? p4 : new Plane(),
  5457. ( p5 !== undefined ) ? p5 : new Plane()
  5458. ];
  5459. }
  5460. Frustum.prototype = {
  5461. constructor: Frustum,
  5462. set: function ( p0, p1, p2, p3, p4, p5 ) {
  5463. var planes = this.planes;
  5464. planes[ 0 ].copy( p0 );
  5465. planes[ 1 ].copy( p1 );
  5466. planes[ 2 ].copy( p2 );
  5467. planes[ 3 ].copy( p3 );
  5468. planes[ 4 ].copy( p4 );
  5469. planes[ 5 ].copy( p5 );
  5470. return this;
  5471. },
  5472. clone: function () {
  5473. return new this.constructor().copy( this );
  5474. },
  5475. copy: function ( frustum ) {
  5476. var planes = this.planes;
  5477. for ( var i = 0; i < 6; i ++ ) {
  5478. planes[ i ].copy( frustum.planes[ i ] );
  5479. }
  5480. return this;
  5481. },
  5482. setFromMatrix: function ( m ) {
  5483. var planes = this.planes;
  5484. var me = m.elements;
  5485. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  5486. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  5487. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  5488. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  5489. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  5490. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  5491. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  5492. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  5493. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  5494. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  5495. return this;
  5496. },
  5497. intersectsObject: function () {
  5498. var sphere = new Sphere();
  5499. return function intersectsObject( object ) {
  5500. var geometry = object.geometry;
  5501. if ( geometry.boundingSphere === null )
  5502. geometry.computeBoundingSphere();
  5503. sphere.copy( geometry.boundingSphere )
  5504. .applyMatrix4( object.matrixWorld );
  5505. return this.intersectsSphere( sphere );
  5506. };
  5507. }(),
  5508. intersectsSprite: function () {
  5509. var sphere = new Sphere();
  5510. return function intersectsSprite( sprite ) {
  5511. sphere.center.set( 0, 0, 0 );
  5512. sphere.radius = 0.7071067811865476;
  5513. sphere.applyMatrix4( sprite.matrixWorld );
  5514. return this.intersectsSphere( sphere );
  5515. };
  5516. }(),
  5517. intersectsSphere: function ( sphere ) {
  5518. var planes = this.planes;
  5519. var center = sphere.center;
  5520. var negRadius = - sphere.radius;
  5521. for ( var i = 0; i < 6; i ++ ) {
  5522. var distance = planes[ i ].distanceToPoint( center );
  5523. if ( distance < negRadius ) {
  5524. return false;
  5525. }
  5526. }
  5527. return true;
  5528. },
  5529. intersectsBox: function () {
  5530. var p1 = new Vector3(),
  5531. p2 = new Vector3();
  5532. return function intersectsBox( box ) {
  5533. var planes = this.planes;
  5534. for ( var i = 0; i < 6 ; i ++ ) {
  5535. var plane = planes[ i ];
  5536. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  5537. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  5538. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  5539. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  5540. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  5541. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  5542. var d1 = plane.distanceToPoint( p1 );
  5543. var d2 = plane.distanceToPoint( p2 );
  5544. // if both outside plane, no intersection
  5545. if ( d1 < 0 && d2 < 0 ) {
  5546. return false;
  5547. }
  5548. }
  5549. return true;
  5550. };
  5551. }(),
  5552. containsPoint: function ( point ) {
  5553. var planes = this.planes;
  5554. for ( var i = 0; i < 6; i ++ ) {
  5555. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  5556. return false;
  5557. }
  5558. }
  5559. return true;
  5560. }
  5561. };
  5562. /**
  5563. * @author alteredq / http://alteredqualia.com/
  5564. * @author mrdoob / http://mrdoob.com/
  5565. */
  5566. function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) {
  5567. var _gl = _renderer.context,
  5568. _state = _renderer.state,
  5569. _frustum = new Frustum(),
  5570. _projScreenMatrix = new Matrix4(),
  5571. _lightShadows = _lights.shadows,
  5572. _shadowMapSize = new Vector2(),
  5573. _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ),
  5574. _lookTarget = new Vector3(),
  5575. _lightPositionWorld = new Vector3(),
  5576. _renderList = [],
  5577. _MorphingFlag = 1,
  5578. _SkinningFlag = 2,
  5579. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  5580. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  5581. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  5582. _materialCache = {};
  5583. var cubeDirections = [
  5584. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  5585. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  5586. ];
  5587. var cubeUps = [
  5588. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  5589. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  5590. ];
  5591. var cube2DViewPorts = [
  5592. new Vector4(), new Vector4(), new Vector4(),
  5593. new Vector4(), new Vector4(), new Vector4()
  5594. ];
  5595. // init
  5596. var depthMaterialTemplate = new MeshDepthMaterial();
  5597. depthMaterialTemplate.depthPacking = RGBADepthPacking;
  5598. depthMaterialTemplate.clipping = true;
  5599. var distanceShader = ShaderLib[ "distanceRGBA" ];
  5600. var distanceUniforms = Object.assign( {}, distanceShader.uniforms );
  5601. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  5602. var useMorphing = ( i & _MorphingFlag ) !== 0;
  5603. var useSkinning = ( i & _SkinningFlag ) !== 0;
  5604. var depthMaterial = depthMaterialTemplate.clone();
  5605. depthMaterial.morphTargets = useMorphing;
  5606. depthMaterial.skinning = useSkinning;
  5607. _depthMaterials[ i ] = depthMaterial;
  5608. var distanceMaterial = new ShaderMaterial( {
  5609. defines: {
  5610. 'USE_SHADOWMAP': ''
  5611. },
  5612. uniforms: distanceUniforms,
  5613. vertexShader: distanceShader.vertexShader,
  5614. fragmentShader: distanceShader.fragmentShader,
  5615. morphTargets: useMorphing,
  5616. skinning: useSkinning,
  5617. clipping: true
  5618. } );
  5619. _distanceMaterials[ i ] = distanceMaterial;
  5620. }
  5621. //
  5622. var scope = this;
  5623. this.enabled = false;
  5624. this.autoUpdate = true;
  5625. this.needsUpdate = false;
  5626. this.type = PCFShadowMap;
  5627. this.renderReverseSided = true;
  5628. this.renderSingleSided = true;
  5629. this.render = function ( scene, camera ) {
  5630. if ( scope.enabled === false ) return;
  5631. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  5632. if ( _lightShadows.length === 0 ) return;
  5633. // Set GL state for depth map.
  5634. _state.buffers.color.setClear( 1, 1, 1, 1 );
  5635. _state.disable( _gl.BLEND );
  5636. _state.setDepthTest( true );
  5637. _state.setScissorTest( false );
  5638. // render depth map
  5639. var faceCount, isPointLight;
  5640. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  5641. var light = _lightShadows[ i ];
  5642. var shadow = light.shadow;
  5643. if ( shadow === undefined ) {
  5644. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  5645. continue;
  5646. }
  5647. var shadowCamera = shadow.camera;
  5648. _shadowMapSize.copy( shadow.mapSize );
  5649. _shadowMapSize.min( _maxShadowMapSize );
  5650. if ( light && light.isPointLight ) {
  5651. faceCount = 6;
  5652. isPointLight = true;
  5653. var vpWidth = _shadowMapSize.x;
  5654. var vpHeight = _shadowMapSize.y;
  5655. // These viewports map a cube-map onto a 2D texture with the
  5656. // following orientation:
  5657. //
  5658. // xzXZ
  5659. // y Y
  5660. //
  5661. // X - Positive x direction
  5662. // x - Negative x direction
  5663. // Y - Positive y direction
  5664. // y - Negative y direction
  5665. // Z - Positive z direction
  5666. // z - Negative z direction
  5667. // positive X
  5668. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  5669. // negative X
  5670. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  5671. // positive Z
  5672. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  5673. // negative Z
  5674. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  5675. // positive Y
  5676. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  5677. // negative Y
  5678. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  5679. _shadowMapSize.x *= 4.0;
  5680. _shadowMapSize.y *= 2.0;
  5681. } else {
  5682. faceCount = 1;
  5683. isPointLight = false;
  5684. }
  5685. if ( shadow.map === null ) {
  5686. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  5687. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  5688. shadowCamera.updateProjectionMatrix();
  5689. }
  5690. if ( shadow.isSpotLightShadow ) {
  5691. shadow.update( light );
  5692. }
  5693. // TODO (abelnation / sam-g-steel): is this needed?
  5694. if (shadow && shadow.isRectAreaLightShadow ) {
  5695. shadow.update( light );
  5696. }
  5697. var shadowMap = shadow.map;
  5698. var shadowMatrix = shadow.matrix;
  5699. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  5700. shadowCamera.position.copy( _lightPositionWorld );
  5701. _renderer.setRenderTarget( shadowMap );
  5702. _renderer.clear();
  5703. // render shadow map for each cube face (if omni-directional) or
  5704. // run a single pass if not
  5705. for ( var face = 0; face < faceCount; face ++ ) {
  5706. if ( isPointLight ) {
  5707. _lookTarget.copy( shadowCamera.position );
  5708. _lookTarget.add( cubeDirections[ face ] );
  5709. shadowCamera.up.copy( cubeUps[ face ] );
  5710. shadowCamera.lookAt( _lookTarget );
  5711. var vpDimensions = cube2DViewPorts[ face ];
  5712. _state.viewport( vpDimensions );
  5713. } else {
  5714. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  5715. shadowCamera.lookAt( _lookTarget );
  5716. }
  5717. shadowCamera.updateMatrixWorld();
  5718. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  5719. // compute shadow matrix
  5720. shadowMatrix.set(
  5721. 0.5, 0.0, 0.0, 0.5,
  5722. 0.0, 0.5, 0.0, 0.5,
  5723. 0.0, 0.0, 0.5, 0.5,
  5724. 0.0, 0.0, 0.0, 1.0
  5725. );
  5726. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  5727. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  5728. // update camera matrices and frustum
  5729. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  5730. _frustum.setFromMatrix( _projScreenMatrix );
  5731. // set object matrices & frustum culling
  5732. _renderList.length = 0;
  5733. projectObject( scene, camera, shadowCamera );
  5734. // render shadow map
  5735. // render regular objects
  5736. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  5737. var object = _renderList[ j ];
  5738. var geometry = _objects.update( object );
  5739. var material = object.material;
  5740. if ( material && material.isMultiMaterial ) {
  5741. var groups = geometry.groups;
  5742. var materials = material.materials;
  5743. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  5744. var group = groups[ k ];
  5745. var groupMaterial = materials[ group.materialIndex ];
  5746. if ( groupMaterial.visible === true ) {
  5747. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  5748. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  5749. }
  5750. }
  5751. } else {
  5752. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  5753. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  5754. }
  5755. }
  5756. }
  5757. }
  5758. // Restore GL state.
  5759. var clearColor = _renderer.getClearColor(),
  5760. clearAlpha = _renderer.getClearAlpha();
  5761. _renderer.setClearColor( clearColor, clearAlpha );
  5762. scope.needsUpdate = false;
  5763. };
  5764. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  5765. var geometry = object.geometry;
  5766. var result = null;
  5767. var materialVariants = _depthMaterials;
  5768. var customMaterial = object.customDepthMaterial;
  5769. if ( isPointLight ) {
  5770. materialVariants = _distanceMaterials;
  5771. customMaterial = object.customDistanceMaterial;
  5772. }
  5773. if ( ! customMaterial ) {
  5774. var useMorphing = false;
  5775. if ( material.morphTargets ) {
  5776. if ( geometry && geometry.isBufferGeometry ) {
  5777. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  5778. } else if ( geometry && geometry.isGeometry ) {
  5779. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  5780. }
  5781. }
  5782. var useSkinning = object.isSkinnedMesh && material.skinning;
  5783. var variantIndex = 0;
  5784. if ( useMorphing ) variantIndex |= _MorphingFlag;
  5785. if ( useSkinning ) variantIndex |= _SkinningFlag;
  5786. result = materialVariants[ variantIndex ];
  5787. } else {
  5788. result = customMaterial;
  5789. }
  5790. if ( _renderer.localClippingEnabled &&
  5791. material.clipShadows === true &&
  5792. material.clippingPlanes.length !== 0 ) {
  5793. // in this case we need a unique material instance reflecting the
  5794. // appropriate state
  5795. var keyA = result.uuid, keyB = material.uuid;
  5796. var materialsForVariant = _materialCache[ keyA ];
  5797. if ( materialsForVariant === undefined ) {
  5798. materialsForVariant = {};
  5799. _materialCache[ keyA ] = materialsForVariant;
  5800. }
  5801. var cachedMaterial = materialsForVariant[ keyB ];
  5802. if ( cachedMaterial === undefined ) {
  5803. cachedMaterial = result.clone();
  5804. materialsForVariant[ keyB ] = cachedMaterial;
  5805. }
  5806. result = cachedMaterial;
  5807. }
  5808. result.visible = material.visible;
  5809. result.wireframe = material.wireframe;
  5810. var side = material.side;
  5811. if ( scope.renderSingleSided && side == DoubleSide ) {
  5812. side = FrontSide;
  5813. }
  5814. if ( scope.renderReverseSided ) {
  5815. if ( side === FrontSide ) side = BackSide;
  5816. else if ( side === BackSide ) side = FrontSide;
  5817. }
  5818. result.side = side;
  5819. result.clipShadows = material.clipShadows;
  5820. result.clippingPlanes = material.clippingPlanes;
  5821. result.wireframeLinewidth = material.wireframeLinewidth;
  5822. result.linewidth = material.linewidth;
  5823. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  5824. result.uniforms.lightPos.value.copy( lightPositionWorld );
  5825. }
  5826. return result;
  5827. }
  5828. function projectObject( object, camera, shadowCamera ) {
  5829. if ( object.visible === false ) return;
  5830. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  5831. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  5832. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  5833. var material = object.material;
  5834. if ( material.visible === true ) {
  5835. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  5836. _renderList.push( object );
  5837. }
  5838. }
  5839. }
  5840. var children = object.children;
  5841. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5842. projectObject( children[ i ], camera, shadowCamera );
  5843. }
  5844. }
  5845. }
  5846. /**
  5847. * @author bhouston / http://clara.io
  5848. */
  5849. function Ray( origin, direction ) {
  5850. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  5851. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  5852. }
  5853. Ray.prototype = {
  5854. constructor: Ray,
  5855. set: function ( origin, direction ) {
  5856. this.origin.copy( origin );
  5857. this.direction.copy( direction );
  5858. return this;
  5859. },
  5860. clone: function () {
  5861. return new this.constructor().copy( this );
  5862. },
  5863. copy: function ( ray ) {
  5864. this.origin.copy( ray.origin );
  5865. this.direction.copy( ray.direction );
  5866. return this;
  5867. },
  5868. at: function ( t, optionalTarget ) {
  5869. var result = optionalTarget || new Vector3();
  5870. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  5871. },
  5872. lookAt: function ( v ) {
  5873. this.direction.copy( v ).sub( this.origin ).normalize();
  5874. return this;
  5875. },
  5876. recast: function () {
  5877. var v1 = new Vector3();
  5878. return function recast( t ) {
  5879. this.origin.copy( this.at( t, v1 ) );
  5880. return this;
  5881. };
  5882. }(),
  5883. closestPointToPoint: function ( point, optionalTarget ) {
  5884. var result = optionalTarget || new Vector3();
  5885. result.subVectors( point, this.origin );
  5886. var directionDistance = result.dot( this.direction );
  5887. if ( directionDistance < 0 ) {
  5888. return result.copy( this.origin );
  5889. }
  5890. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  5891. },
  5892. distanceToPoint: function ( point ) {
  5893. return Math.sqrt( this.distanceSqToPoint( point ) );
  5894. },
  5895. distanceSqToPoint: function () {
  5896. var v1 = new Vector3();
  5897. return function distanceSqToPoint( point ) {
  5898. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  5899. // point behind the ray
  5900. if ( directionDistance < 0 ) {
  5901. return this.origin.distanceToSquared( point );
  5902. }
  5903. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  5904. return v1.distanceToSquared( point );
  5905. };
  5906. }(),
  5907. distanceSqToSegment: function () {
  5908. var segCenter = new Vector3();
  5909. var segDir = new Vector3();
  5910. var diff = new Vector3();
  5911. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  5912. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  5913. // It returns the min distance between the ray and the segment
  5914. // defined by v0 and v1
  5915. // It can also set two optional targets :
  5916. // - The closest point on the ray
  5917. // - The closest point on the segment
  5918. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  5919. segDir.copy( v1 ).sub( v0 ).normalize();
  5920. diff.copy( this.origin ).sub( segCenter );
  5921. var segExtent = v0.distanceTo( v1 ) * 0.5;
  5922. var a01 = - this.direction.dot( segDir );
  5923. var b0 = diff.dot( this.direction );
  5924. var b1 = - diff.dot( segDir );
  5925. var c = diff.lengthSq();
  5926. var det = Math.abs( 1 - a01 * a01 );
  5927. var s0, s1, sqrDist, extDet;
  5928. if ( det > 0 ) {
  5929. // The ray and segment are not parallel.
  5930. s0 = a01 * b1 - b0;
  5931. s1 = a01 * b0 - b1;
  5932. extDet = segExtent * det;
  5933. if ( s0 >= 0 ) {
  5934. if ( s1 >= - extDet ) {
  5935. if ( s1 <= extDet ) {
  5936. // region 0
  5937. // Minimum at interior points of ray and segment.
  5938. var invDet = 1 / det;
  5939. s0 *= invDet;
  5940. s1 *= invDet;
  5941. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  5942. } else {
  5943. // region 1
  5944. s1 = segExtent;
  5945. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5946. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5947. }
  5948. } else {
  5949. // region 5
  5950. s1 = - segExtent;
  5951. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5952. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5953. }
  5954. } else {
  5955. if ( s1 <= - extDet ) {
  5956. // region 4
  5957. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  5958. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5959. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5960. } else if ( s1 <= extDet ) {
  5961. // region 3
  5962. s0 = 0;
  5963. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5964. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  5965. } else {
  5966. // region 2
  5967. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  5968. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5969. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5970. }
  5971. }
  5972. } else {
  5973. // Ray and segment are parallel.
  5974. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  5975. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5976. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5977. }
  5978. if ( optionalPointOnRay ) {
  5979. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  5980. }
  5981. if ( optionalPointOnSegment ) {
  5982. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  5983. }
  5984. return sqrDist;
  5985. };
  5986. }(),
  5987. intersectSphere: function () {
  5988. var v1 = new Vector3();
  5989. return function intersectSphere( sphere, optionalTarget ) {
  5990. v1.subVectors( sphere.center, this.origin );
  5991. var tca = v1.dot( this.direction );
  5992. var d2 = v1.dot( v1 ) - tca * tca;
  5993. var radius2 = sphere.radius * sphere.radius;
  5994. if ( d2 > radius2 ) return null;
  5995. var thc = Math.sqrt( radius2 - d2 );
  5996. // t0 = first intersect point - entrance on front of sphere
  5997. var t0 = tca - thc;
  5998. // t1 = second intersect point - exit point on back of sphere
  5999. var t1 = tca + thc;
  6000. // test to see if both t0 and t1 are behind the ray - if so, return null
  6001. if ( t0 < 0 && t1 < 0 ) return null;
  6002. // test to see if t0 is behind the ray:
  6003. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  6004. // in order to always return an intersect point that is in front of the ray.
  6005. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  6006. // else t0 is in front of the ray, so return the first collision point scaled by t0
  6007. return this.at( t0, optionalTarget );
  6008. };
  6009. }(),
  6010. intersectsSphere: function ( sphere ) {
  6011. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  6012. },
  6013. distanceToPlane: function ( plane ) {
  6014. var denominator = plane.normal.dot( this.direction );
  6015. if ( denominator === 0 ) {
  6016. // line is coplanar, return origin
  6017. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  6018. return 0;
  6019. }
  6020. // Null is preferable to undefined since undefined means.... it is undefined
  6021. return null;
  6022. }
  6023. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  6024. // Return if the ray never intersects the plane
  6025. return t >= 0 ? t : null;
  6026. },
  6027. intersectPlane: function ( plane, optionalTarget ) {
  6028. var t = this.distanceToPlane( plane );
  6029. if ( t === null ) {
  6030. return null;
  6031. }
  6032. return this.at( t, optionalTarget );
  6033. },
  6034. intersectsPlane: function ( plane ) {
  6035. // check if the ray lies on the plane first
  6036. var distToPoint = plane.distanceToPoint( this.origin );
  6037. if ( distToPoint === 0 ) {
  6038. return true;
  6039. }
  6040. var denominator = plane.normal.dot( this.direction );
  6041. if ( denominator * distToPoint < 0 ) {
  6042. return true;
  6043. }
  6044. // ray origin is behind the plane (and is pointing behind it)
  6045. return false;
  6046. },
  6047. intersectBox: function ( box, optionalTarget ) {
  6048. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  6049. var invdirx = 1 / this.direction.x,
  6050. invdiry = 1 / this.direction.y,
  6051. invdirz = 1 / this.direction.z;
  6052. var origin = this.origin;
  6053. if ( invdirx >= 0 ) {
  6054. tmin = ( box.min.x - origin.x ) * invdirx;
  6055. tmax = ( box.max.x - origin.x ) * invdirx;
  6056. } else {
  6057. tmin = ( box.max.x - origin.x ) * invdirx;
  6058. tmax = ( box.min.x - origin.x ) * invdirx;
  6059. }
  6060. if ( invdiry >= 0 ) {
  6061. tymin = ( box.min.y - origin.y ) * invdiry;
  6062. tymax = ( box.max.y - origin.y ) * invdiry;
  6063. } else {
  6064. tymin = ( box.max.y - origin.y ) * invdiry;
  6065. tymax = ( box.min.y - origin.y ) * invdiry;
  6066. }
  6067. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  6068. // These lines also handle the case where tmin or tmax is NaN
  6069. // (result of 0 * Infinity). x !== x returns true if x is NaN
  6070. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  6071. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  6072. if ( invdirz >= 0 ) {
  6073. tzmin = ( box.min.z - origin.z ) * invdirz;
  6074. tzmax = ( box.max.z - origin.z ) * invdirz;
  6075. } else {
  6076. tzmin = ( box.max.z - origin.z ) * invdirz;
  6077. tzmax = ( box.min.z - origin.z ) * invdirz;
  6078. }
  6079. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  6080. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  6081. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  6082. //return point closest to the ray (positive side)
  6083. if ( tmax < 0 ) return null;
  6084. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  6085. },
  6086. intersectsBox: ( function () {
  6087. var v = new Vector3();
  6088. return function intersectsBox( box ) {
  6089. return this.intersectBox( box, v ) !== null;
  6090. };
  6091. } )(),
  6092. intersectTriangle: function () {
  6093. // Compute the offset origin, edges, and normal.
  6094. var diff = new Vector3();
  6095. var edge1 = new Vector3();
  6096. var edge2 = new Vector3();
  6097. var normal = new Vector3();
  6098. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  6099. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6100. edge1.subVectors( b, a );
  6101. edge2.subVectors( c, a );
  6102. normal.crossVectors( edge1, edge2 );
  6103. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6104. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6105. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6106. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6107. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6108. var DdN = this.direction.dot( normal );
  6109. var sign;
  6110. if ( DdN > 0 ) {
  6111. if ( backfaceCulling ) return null;
  6112. sign = 1;
  6113. } else if ( DdN < 0 ) {
  6114. sign = - 1;
  6115. DdN = - DdN;
  6116. } else {
  6117. return null;
  6118. }
  6119. diff.subVectors( this.origin, a );
  6120. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  6121. // b1 < 0, no intersection
  6122. if ( DdQxE2 < 0 ) {
  6123. return null;
  6124. }
  6125. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  6126. // b2 < 0, no intersection
  6127. if ( DdE1xQ < 0 ) {
  6128. return null;
  6129. }
  6130. // b1+b2 > 1, no intersection
  6131. if ( DdQxE2 + DdE1xQ > DdN ) {
  6132. return null;
  6133. }
  6134. // Line intersects triangle, check if ray does.
  6135. var QdN = - sign * diff.dot( normal );
  6136. // t < 0, no intersection
  6137. if ( QdN < 0 ) {
  6138. return null;
  6139. }
  6140. // Ray intersects triangle.
  6141. return this.at( QdN / DdN, optionalTarget );
  6142. };
  6143. }(),
  6144. applyMatrix4: function ( matrix4 ) {
  6145. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  6146. this.origin.applyMatrix4( matrix4 );
  6147. this.direction.sub( this.origin );
  6148. this.direction.normalize();
  6149. return this;
  6150. },
  6151. equals: function ( ray ) {
  6152. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  6153. }
  6154. };
  6155. /**
  6156. * @author mrdoob / http://mrdoob.com/
  6157. * @author WestLangley / http://github.com/WestLangley
  6158. * @author bhouston / http://clara.io
  6159. */
  6160. function Euler( x, y, z, order ) {
  6161. this._x = x || 0;
  6162. this._y = y || 0;
  6163. this._z = z || 0;
  6164. this._order = order || Euler.DefaultOrder;
  6165. }
  6166. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  6167. Euler.DefaultOrder = 'XYZ';
  6168. Euler.prototype = {
  6169. constructor: Euler,
  6170. isEuler: true,
  6171. get x () {
  6172. return this._x;
  6173. },
  6174. set x ( value ) {
  6175. this._x = value;
  6176. this.onChangeCallback();
  6177. },
  6178. get y () {
  6179. return this._y;
  6180. },
  6181. set y ( value ) {
  6182. this._y = value;
  6183. this.onChangeCallback();
  6184. },
  6185. get z () {
  6186. return this._z;
  6187. },
  6188. set z ( value ) {
  6189. this._z = value;
  6190. this.onChangeCallback();
  6191. },
  6192. get order () {
  6193. return this._order;
  6194. },
  6195. set order ( value ) {
  6196. this._order = value;
  6197. this.onChangeCallback();
  6198. },
  6199. set: function ( x, y, z, order ) {
  6200. this._x = x;
  6201. this._y = y;
  6202. this._z = z;
  6203. this._order = order || this._order;
  6204. this.onChangeCallback();
  6205. return this;
  6206. },
  6207. clone: function () {
  6208. return new this.constructor( this._x, this._y, this._z, this._order );
  6209. },
  6210. copy: function ( euler ) {
  6211. this._x = euler._x;
  6212. this._y = euler._y;
  6213. this._z = euler._z;
  6214. this._order = euler._order;
  6215. this.onChangeCallback();
  6216. return this;
  6217. },
  6218. setFromRotationMatrix: function ( m, order, update ) {
  6219. var clamp = _Math.clamp;
  6220. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6221. var te = m.elements;
  6222. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  6223. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  6224. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6225. order = order || this._order;
  6226. if ( order === 'XYZ' ) {
  6227. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  6228. if ( Math.abs( m13 ) < 0.99999 ) {
  6229. this._x = Math.atan2( - m23, m33 );
  6230. this._z = Math.atan2( - m12, m11 );
  6231. } else {
  6232. this._x = Math.atan2( m32, m22 );
  6233. this._z = 0;
  6234. }
  6235. } else if ( order === 'YXZ' ) {
  6236. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  6237. if ( Math.abs( m23 ) < 0.99999 ) {
  6238. this._y = Math.atan2( m13, m33 );
  6239. this._z = Math.atan2( m21, m22 );
  6240. } else {
  6241. this._y = Math.atan2( - m31, m11 );
  6242. this._z = 0;
  6243. }
  6244. } else if ( order === 'ZXY' ) {
  6245. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  6246. if ( Math.abs( m32 ) < 0.99999 ) {
  6247. this._y = Math.atan2( - m31, m33 );
  6248. this._z = Math.atan2( - m12, m22 );
  6249. } else {
  6250. this._y = 0;
  6251. this._z = Math.atan2( m21, m11 );
  6252. }
  6253. } else if ( order === 'ZYX' ) {
  6254. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  6255. if ( Math.abs( m31 ) < 0.99999 ) {
  6256. this._x = Math.atan2( m32, m33 );
  6257. this._z = Math.atan2( m21, m11 );
  6258. } else {
  6259. this._x = 0;
  6260. this._z = Math.atan2( - m12, m22 );
  6261. }
  6262. } else if ( order === 'YZX' ) {
  6263. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  6264. if ( Math.abs( m21 ) < 0.99999 ) {
  6265. this._x = Math.atan2( - m23, m22 );
  6266. this._y = Math.atan2( - m31, m11 );
  6267. } else {
  6268. this._x = 0;
  6269. this._y = Math.atan2( m13, m33 );
  6270. }
  6271. } else if ( order === 'XZY' ) {
  6272. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  6273. if ( Math.abs( m12 ) < 0.99999 ) {
  6274. this._x = Math.atan2( m32, m22 );
  6275. this._y = Math.atan2( m13, m11 );
  6276. } else {
  6277. this._x = Math.atan2( - m23, m33 );
  6278. this._y = 0;
  6279. }
  6280. } else {
  6281. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  6282. }
  6283. this._order = order;
  6284. if ( update !== false ) this.onChangeCallback();
  6285. return this;
  6286. },
  6287. setFromQuaternion: function () {
  6288. var matrix;
  6289. return function setFromQuaternion( q, order, update ) {
  6290. if ( matrix === undefined ) matrix = new Matrix4();
  6291. matrix.makeRotationFromQuaternion( q );
  6292. return this.setFromRotationMatrix( matrix, order, update );
  6293. };
  6294. }(),
  6295. setFromVector3: function ( v, order ) {
  6296. return this.set( v.x, v.y, v.z, order || this._order );
  6297. },
  6298. reorder: function () {
  6299. // WARNING: this discards revolution information -bhouston
  6300. var q = new Quaternion();
  6301. return function reorder( newOrder ) {
  6302. q.setFromEuler( this );
  6303. return this.setFromQuaternion( q, newOrder );
  6304. };
  6305. }(),
  6306. equals: function ( euler ) {
  6307. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  6308. },
  6309. fromArray: function ( array ) {
  6310. this._x = array[ 0 ];
  6311. this._y = array[ 1 ];
  6312. this._z = array[ 2 ];
  6313. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  6314. this.onChangeCallback();
  6315. return this;
  6316. },
  6317. toArray: function ( array, offset ) {
  6318. if ( array === undefined ) array = [];
  6319. if ( offset === undefined ) offset = 0;
  6320. array[ offset ] = this._x;
  6321. array[ offset + 1 ] = this._y;
  6322. array[ offset + 2 ] = this._z;
  6323. array[ offset + 3 ] = this._order;
  6324. return array;
  6325. },
  6326. toVector3: function ( optionalResult ) {
  6327. if ( optionalResult ) {
  6328. return optionalResult.set( this._x, this._y, this._z );
  6329. } else {
  6330. return new Vector3( this._x, this._y, this._z );
  6331. }
  6332. },
  6333. onChange: function ( callback ) {
  6334. this.onChangeCallback = callback;
  6335. return this;
  6336. },
  6337. onChangeCallback: function () {}
  6338. };
  6339. /**
  6340. * @author mrdoob / http://mrdoob.com/
  6341. */
  6342. function Layers() {
  6343. this.mask = 1;
  6344. }
  6345. Layers.prototype = {
  6346. constructor: Layers,
  6347. set: function ( channel ) {
  6348. this.mask = 1 << channel;
  6349. },
  6350. enable: function ( channel ) {
  6351. this.mask |= 1 << channel;
  6352. },
  6353. toggle: function ( channel ) {
  6354. this.mask ^= 1 << channel;
  6355. },
  6356. disable: function ( channel ) {
  6357. this.mask &= ~ ( 1 << channel );
  6358. },
  6359. test: function ( layers ) {
  6360. return ( this.mask & layers.mask ) !== 0;
  6361. }
  6362. };
  6363. /**
  6364. * @author mrdoob / http://mrdoob.com/
  6365. * @author mikael emtinger / http://gomo.se/
  6366. * @author alteredq / http://alteredqualia.com/
  6367. * @author WestLangley / http://github.com/WestLangley
  6368. * @author elephantatwork / www.elephantatwork.ch
  6369. */
  6370. var object3DId = 0;
  6371. function Object3D() {
  6372. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  6373. this.uuid = _Math.generateUUID();
  6374. this.name = '';
  6375. this.type = 'Object3D';
  6376. this.parent = null;
  6377. this.children = [];
  6378. this.up = Object3D.DefaultUp.clone();
  6379. var position = new Vector3();
  6380. var rotation = new Euler();
  6381. var quaternion = new Quaternion();
  6382. var scale = new Vector3( 1, 1, 1 );
  6383. function onRotationChange() {
  6384. quaternion.setFromEuler( rotation, false );
  6385. }
  6386. function onQuaternionChange() {
  6387. rotation.setFromQuaternion( quaternion, undefined, false );
  6388. }
  6389. rotation.onChange( onRotationChange );
  6390. quaternion.onChange( onQuaternionChange );
  6391. Object.defineProperties( this, {
  6392. position: {
  6393. enumerable: true,
  6394. value: position
  6395. },
  6396. rotation: {
  6397. enumerable: true,
  6398. value: rotation
  6399. },
  6400. quaternion: {
  6401. enumerable: true,
  6402. value: quaternion
  6403. },
  6404. scale: {
  6405. enumerable: true,
  6406. value: scale
  6407. },
  6408. modelViewMatrix: {
  6409. value: new Matrix4()
  6410. },
  6411. normalMatrix: {
  6412. value: new Matrix3()
  6413. }
  6414. } );
  6415. this.matrix = new Matrix4();
  6416. this.matrixWorld = new Matrix4();
  6417. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  6418. this.matrixWorldNeedsUpdate = false;
  6419. this.layers = new Layers();
  6420. this.visible = true;
  6421. this.castShadow = false;
  6422. this.receiveShadow = false;
  6423. this.frustumCulled = true;
  6424. this.renderOrder = 0;
  6425. this.userData = {};
  6426. this.onBeforeRender = function(){};
  6427. this.onAfterRender = function(){};
  6428. }
  6429. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  6430. Object3D.DefaultMatrixAutoUpdate = true;
  6431. Object.assign( Object3D.prototype, EventDispatcher.prototype, {
  6432. isObject3D: true,
  6433. applyMatrix: function ( matrix ) {
  6434. this.matrix.multiplyMatrices( matrix, this.matrix );
  6435. this.matrix.decompose( this.position, this.quaternion, this.scale );
  6436. },
  6437. setRotationFromAxisAngle: function ( axis, angle ) {
  6438. // assumes axis is normalized
  6439. this.quaternion.setFromAxisAngle( axis, angle );
  6440. },
  6441. setRotationFromEuler: function ( euler ) {
  6442. this.quaternion.setFromEuler( euler, true );
  6443. },
  6444. setRotationFromMatrix: function ( m ) {
  6445. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6446. this.quaternion.setFromRotationMatrix( m );
  6447. },
  6448. setRotationFromQuaternion: function ( q ) {
  6449. // assumes q is normalized
  6450. this.quaternion.copy( q );
  6451. },
  6452. rotateOnAxis: function () {
  6453. // rotate object on axis in object space
  6454. // axis is assumed to be normalized
  6455. var q1 = new Quaternion();
  6456. return function rotateOnAxis( axis, angle ) {
  6457. q1.setFromAxisAngle( axis, angle );
  6458. this.quaternion.multiply( q1 );
  6459. return this;
  6460. };
  6461. }(),
  6462. rotateX: function () {
  6463. var v1 = new Vector3( 1, 0, 0 );
  6464. return function rotateX( angle ) {
  6465. return this.rotateOnAxis( v1, angle );
  6466. };
  6467. }(),
  6468. rotateY: function () {
  6469. var v1 = new Vector3( 0, 1, 0 );
  6470. return function rotateY( angle ) {
  6471. return this.rotateOnAxis( v1, angle );
  6472. };
  6473. }(),
  6474. rotateZ: function () {
  6475. var v1 = new Vector3( 0, 0, 1 );
  6476. return function rotateZ( angle ) {
  6477. return this.rotateOnAxis( v1, angle );
  6478. };
  6479. }(),
  6480. translateOnAxis: function () {
  6481. // translate object by distance along axis in object space
  6482. // axis is assumed to be normalized
  6483. var v1 = new Vector3();
  6484. return function translateOnAxis( axis, distance ) {
  6485. v1.copy( axis ).applyQuaternion( this.quaternion );
  6486. this.position.add( v1.multiplyScalar( distance ) );
  6487. return this;
  6488. };
  6489. }(),
  6490. translateX: function () {
  6491. var v1 = new Vector3( 1, 0, 0 );
  6492. return function translateX( distance ) {
  6493. return this.translateOnAxis( v1, distance );
  6494. };
  6495. }(),
  6496. translateY: function () {
  6497. var v1 = new Vector3( 0, 1, 0 );
  6498. return function translateY( distance ) {
  6499. return this.translateOnAxis( v1, distance );
  6500. };
  6501. }(),
  6502. translateZ: function () {
  6503. var v1 = new Vector3( 0, 0, 1 );
  6504. return function translateZ( distance ) {
  6505. return this.translateOnAxis( v1, distance );
  6506. };
  6507. }(),
  6508. localToWorld: function ( vector ) {
  6509. return vector.applyMatrix4( this.matrixWorld );
  6510. },
  6511. worldToLocal: function () {
  6512. var m1 = new Matrix4();
  6513. return function worldToLocal( vector ) {
  6514. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  6515. };
  6516. }(),
  6517. lookAt: function () {
  6518. // This routine does not support objects with rotated and/or translated parent(s)
  6519. var m1 = new Matrix4();
  6520. return function lookAt( vector ) {
  6521. m1.lookAt( vector, this.position, this.up );
  6522. this.quaternion.setFromRotationMatrix( m1 );
  6523. };
  6524. }(),
  6525. add: function ( object ) {
  6526. if ( arguments.length > 1 ) {
  6527. for ( var i = 0; i < arguments.length; i ++ ) {
  6528. this.add( arguments[ i ] );
  6529. }
  6530. return this;
  6531. }
  6532. if ( object === this ) {
  6533. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  6534. return this;
  6535. }
  6536. if ( (object && object.isObject3D) ) {
  6537. if ( object.parent !== null ) {
  6538. object.parent.remove( object );
  6539. }
  6540. object.parent = this;
  6541. object.dispatchEvent( { type: 'added' } );
  6542. this.children.push( object );
  6543. } else {
  6544. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  6545. }
  6546. return this;
  6547. },
  6548. remove: function ( object ) {
  6549. if ( arguments.length > 1 ) {
  6550. for ( var i = 0; i < arguments.length; i ++ ) {
  6551. this.remove( arguments[ i ] );
  6552. }
  6553. }
  6554. var index = this.children.indexOf( object );
  6555. if ( index !== - 1 ) {
  6556. object.parent = null;
  6557. object.dispatchEvent( { type: 'removed' } );
  6558. this.children.splice( index, 1 );
  6559. }
  6560. },
  6561. getObjectById: function ( id ) {
  6562. return this.getObjectByProperty( 'id', id );
  6563. },
  6564. getObjectByName: function ( name ) {
  6565. return this.getObjectByProperty( 'name', name );
  6566. },
  6567. getObjectByProperty: function ( name, value ) {
  6568. if ( this[ name ] === value ) return this;
  6569. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6570. var child = this.children[ i ];
  6571. var object = child.getObjectByProperty( name, value );
  6572. if ( object !== undefined ) {
  6573. return object;
  6574. }
  6575. }
  6576. return undefined;
  6577. },
  6578. getWorldPosition: function ( optionalTarget ) {
  6579. var result = optionalTarget || new Vector3();
  6580. this.updateMatrixWorld( true );
  6581. return result.setFromMatrixPosition( this.matrixWorld );
  6582. },
  6583. getWorldQuaternion: function () {
  6584. var position = new Vector3();
  6585. var scale = new Vector3();
  6586. return function getWorldQuaternion( optionalTarget ) {
  6587. var result = optionalTarget || new Quaternion();
  6588. this.updateMatrixWorld( true );
  6589. this.matrixWorld.decompose( position, result, scale );
  6590. return result;
  6591. };
  6592. }(),
  6593. getWorldRotation: function () {
  6594. var quaternion = new Quaternion();
  6595. return function getWorldRotation( optionalTarget ) {
  6596. var result = optionalTarget || new Euler();
  6597. this.getWorldQuaternion( quaternion );
  6598. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  6599. };
  6600. }(),
  6601. getWorldScale: function () {
  6602. var position = new Vector3();
  6603. var quaternion = new Quaternion();
  6604. return function getWorldScale( optionalTarget ) {
  6605. var result = optionalTarget || new Vector3();
  6606. this.updateMatrixWorld( true );
  6607. this.matrixWorld.decompose( position, quaternion, result );
  6608. return result;
  6609. };
  6610. }(),
  6611. getWorldDirection: function () {
  6612. var quaternion = new Quaternion();
  6613. return function getWorldDirection( optionalTarget ) {
  6614. var result = optionalTarget || new Vector3();
  6615. this.getWorldQuaternion( quaternion );
  6616. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  6617. };
  6618. }(),
  6619. raycast: function () {},
  6620. traverse: function ( callback ) {
  6621. callback( this );
  6622. var children = this.children;
  6623. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6624. children[ i ].traverse( callback );
  6625. }
  6626. },
  6627. traverseVisible: function ( callback ) {
  6628. if ( this.visible === false ) return;
  6629. callback( this );
  6630. var children = this.children;
  6631. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6632. children[ i ].traverseVisible( callback );
  6633. }
  6634. },
  6635. traverseAncestors: function ( callback ) {
  6636. var parent = this.parent;
  6637. if ( parent !== null ) {
  6638. callback( parent );
  6639. parent.traverseAncestors( callback );
  6640. }
  6641. },
  6642. updateMatrix: function () {
  6643. this.matrix.compose( this.position, this.quaternion, this.scale );
  6644. this.matrixWorldNeedsUpdate = true;
  6645. },
  6646. updateMatrixWorld: function ( force ) {
  6647. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  6648. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  6649. if ( this.parent === null ) {
  6650. this.matrixWorld.copy( this.matrix );
  6651. } else {
  6652. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  6653. }
  6654. this.matrixWorldNeedsUpdate = false;
  6655. force = true;
  6656. }
  6657. // update children
  6658. var children = this.children;
  6659. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6660. children[ i ].updateMatrixWorld( force );
  6661. }
  6662. },
  6663. toJSON: function ( meta ) {
  6664. // meta is '' when called from JSON.stringify
  6665. var isRootObject = ( meta === undefined || meta === '' );
  6666. var output = {};
  6667. // meta is a hash used to collect geometries, materials.
  6668. // not providing it implies that this is the root object
  6669. // being serialized.
  6670. if ( isRootObject ) {
  6671. // initialize meta obj
  6672. meta = {
  6673. geometries: {},
  6674. materials: {},
  6675. textures: {},
  6676. images: {}
  6677. };
  6678. output.metadata = {
  6679. version: 4.4,
  6680. type: 'Object',
  6681. generator: 'Object3D.toJSON'
  6682. };
  6683. }
  6684. // standard Object3D serialization
  6685. var object = {};
  6686. object.uuid = this.uuid;
  6687. object.type = this.type;
  6688. if ( this.name !== '' ) object.name = this.name;
  6689. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  6690. if ( this.castShadow === true ) object.castShadow = true;
  6691. if ( this.receiveShadow === true ) object.receiveShadow = true;
  6692. if ( this.visible === false ) object.visible = false;
  6693. object.matrix = this.matrix.toArray();
  6694. //
  6695. if ( this.geometry !== undefined ) {
  6696. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  6697. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  6698. }
  6699. object.geometry = this.geometry.uuid;
  6700. }
  6701. if ( this.material !== undefined ) {
  6702. if ( meta.materials[ this.material.uuid ] === undefined ) {
  6703. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  6704. }
  6705. object.material = this.material.uuid;
  6706. }
  6707. //
  6708. if ( this.children.length > 0 ) {
  6709. object.children = [];
  6710. for ( var i = 0; i < this.children.length; i ++ ) {
  6711. object.children.push( this.children[ i ].toJSON( meta ).object );
  6712. }
  6713. }
  6714. if ( isRootObject ) {
  6715. var geometries = extractFromCache( meta.geometries );
  6716. var materials = extractFromCache( meta.materials );
  6717. var textures = extractFromCache( meta.textures );
  6718. var images = extractFromCache( meta.images );
  6719. if ( geometries.length > 0 ) output.geometries = geometries;
  6720. if ( materials.length > 0 ) output.materials = materials;
  6721. if ( textures.length > 0 ) output.textures = textures;
  6722. if ( images.length > 0 ) output.images = images;
  6723. }
  6724. output.object = object;
  6725. return output;
  6726. // extract data from the cache hash
  6727. // remove metadata on each item
  6728. // and return as array
  6729. function extractFromCache( cache ) {
  6730. var values = [];
  6731. for ( var key in cache ) {
  6732. var data = cache[ key ];
  6733. delete data.metadata;
  6734. values.push( data );
  6735. }
  6736. return values;
  6737. }
  6738. },
  6739. clone: function ( recursive ) {
  6740. return new this.constructor().copy( this, recursive );
  6741. },
  6742. copy: function ( source, recursive ) {
  6743. if ( recursive === undefined ) recursive = true;
  6744. this.name = source.name;
  6745. this.up.copy( source.up );
  6746. this.position.copy( source.position );
  6747. this.quaternion.copy( source.quaternion );
  6748. this.scale.copy( source.scale );
  6749. this.matrix.copy( source.matrix );
  6750. this.matrixWorld.copy( source.matrixWorld );
  6751. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6752. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  6753. this.visible = source.visible;
  6754. this.castShadow = source.castShadow;
  6755. this.receiveShadow = source.receiveShadow;
  6756. this.frustumCulled = source.frustumCulled;
  6757. this.renderOrder = source.renderOrder;
  6758. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6759. if ( recursive === true ) {
  6760. for ( var i = 0; i < source.children.length; i ++ ) {
  6761. var child = source.children[ i ];
  6762. this.add( child.clone() );
  6763. }
  6764. }
  6765. return this;
  6766. }
  6767. } );
  6768. /**
  6769. * @author bhouston / http://clara.io
  6770. */
  6771. function Line3( start, end ) {
  6772. this.start = ( start !== undefined ) ? start : new Vector3();
  6773. this.end = ( end !== undefined ) ? end : new Vector3();
  6774. }
  6775. Line3.prototype = {
  6776. constructor: Line3,
  6777. set: function ( start, end ) {
  6778. this.start.copy( start );
  6779. this.end.copy( end );
  6780. return this;
  6781. },
  6782. clone: function () {
  6783. return new this.constructor().copy( this );
  6784. },
  6785. copy: function ( line ) {
  6786. this.start.copy( line.start );
  6787. this.end.copy( line.end );
  6788. return this;
  6789. },
  6790. getCenter: function ( optionalTarget ) {
  6791. var result = optionalTarget || new Vector3();
  6792. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  6793. },
  6794. delta: function ( optionalTarget ) {
  6795. var result = optionalTarget || new Vector3();
  6796. return result.subVectors( this.end, this.start );
  6797. },
  6798. distanceSq: function () {
  6799. return this.start.distanceToSquared( this.end );
  6800. },
  6801. distance: function () {
  6802. return this.start.distanceTo( this.end );
  6803. },
  6804. at: function ( t, optionalTarget ) {
  6805. var result = optionalTarget || new Vector3();
  6806. return this.delta( result ).multiplyScalar( t ).add( this.start );
  6807. },
  6808. closestPointToPointParameter: function () {
  6809. var startP = new Vector3();
  6810. var startEnd = new Vector3();
  6811. return function closestPointToPointParameter( point, clampToLine ) {
  6812. startP.subVectors( point, this.start );
  6813. startEnd.subVectors( this.end, this.start );
  6814. var startEnd2 = startEnd.dot( startEnd );
  6815. var startEnd_startP = startEnd.dot( startP );
  6816. var t = startEnd_startP / startEnd2;
  6817. if ( clampToLine ) {
  6818. t = _Math.clamp( t, 0, 1 );
  6819. }
  6820. return t;
  6821. };
  6822. }(),
  6823. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  6824. var t = this.closestPointToPointParameter( point, clampToLine );
  6825. var result = optionalTarget || new Vector3();
  6826. return this.delta( result ).multiplyScalar( t ).add( this.start );
  6827. },
  6828. applyMatrix4: function ( matrix ) {
  6829. this.start.applyMatrix4( matrix );
  6830. this.end.applyMatrix4( matrix );
  6831. return this;
  6832. },
  6833. equals: function ( line ) {
  6834. return line.start.equals( this.start ) && line.end.equals( this.end );
  6835. }
  6836. };
  6837. /**
  6838. * @author bhouston / http://clara.io
  6839. * @author mrdoob / http://mrdoob.com/
  6840. */
  6841. function Triangle( a, b, c ) {
  6842. this.a = ( a !== undefined ) ? a : new Vector3();
  6843. this.b = ( b !== undefined ) ? b : new Vector3();
  6844. this.c = ( c !== undefined ) ? c : new Vector3();
  6845. }
  6846. Triangle.normal = function () {
  6847. var v0 = new Vector3();
  6848. return function normal( a, b, c, optionalTarget ) {
  6849. var result = optionalTarget || new Vector3();
  6850. result.subVectors( c, b );
  6851. v0.subVectors( a, b );
  6852. result.cross( v0 );
  6853. var resultLengthSq = result.lengthSq();
  6854. if ( resultLengthSq > 0 ) {
  6855. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  6856. }
  6857. return result.set( 0, 0, 0 );
  6858. };
  6859. }();
  6860. // static/instance method to calculate barycentric coordinates
  6861. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  6862. Triangle.barycoordFromPoint = function () {
  6863. var v0 = new Vector3();
  6864. var v1 = new Vector3();
  6865. var v2 = new Vector3();
  6866. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  6867. v0.subVectors( c, a );
  6868. v1.subVectors( b, a );
  6869. v2.subVectors( point, a );
  6870. var dot00 = v0.dot( v0 );
  6871. var dot01 = v0.dot( v1 );
  6872. var dot02 = v0.dot( v2 );
  6873. var dot11 = v1.dot( v1 );
  6874. var dot12 = v1.dot( v2 );
  6875. var denom = ( dot00 * dot11 - dot01 * dot01 );
  6876. var result = optionalTarget || new Vector3();
  6877. // collinear or singular triangle
  6878. if ( denom === 0 ) {
  6879. // arbitrary location outside of triangle?
  6880. // not sure if this is the best idea, maybe should be returning undefined
  6881. return result.set( - 2, - 1, - 1 );
  6882. }
  6883. var invDenom = 1 / denom;
  6884. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  6885. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  6886. // barycentric coordinates must always sum to 1
  6887. return result.set( 1 - u - v, v, u );
  6888. };
  6889. }();
  6890. Triangle.containsPoint = function () {
  6891. var v1 = new Vector3();
  6892. return function containsPoint( point, a, b, c ) {
  6893. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  6894. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  6895. };
  6896. }();
  6897. Triangle.prototype = {
  6898. constructor: Triangle,
  6899. set: function ( a, b, c ) {
  6900. this.a.copy( a );
  6901. this.b.copy( b );
  6902. this.c.copy( c );
  6903. return this;
  6904. },
  6905. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  6906. this.a.copy( points[ i0 ] );
  6907. this.b.copy( points[ i1 ] );
  6908. this.c.copy( points[ i2 ] );
  6909. return this;
  6910. },
  6911. clone: function () {
  6912. return new this.constructor().copy( this );
  6913. },
  6914. copy: function ( triangle ) {
  6915. this.a.copy( triangle.a );
  6916. this.b.copy( triangle.b );
  6917. this.c.copy( triangle.c );
  6918. return this;
  6919. },
  6920. area: function () {
  6921. var v0 = new Vector3();
  6922. var v1 = new Vector3();
  6923. return function area() {
  6924. v0.subVectors( this.c, this.b );
  6925. v1.subVectors( this.a, this.b );
  6926. return v0.cross( v1 ).length() * 0.5;
  6927. };
  6928. }(),
  6929. midpoint: function ( optionalTarget ) {
  6930. var result = optionalTarget || new Vector3();
  6931. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  6932. },
  6933. normal: function ( optionalTarget ) {
  6934. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  6935. },
  6936. plane: function ( optionalTarget ) {
  6937. var result = optionalTarget || new Plane();
  6938. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  6939. },
  6940. barycoordFromPoint: function ( point, optionalTarget ) {
  6941. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  6942. },
  6943. containsPoint: function ( point ) {
  6944. return Triangle.containsPoint( point, this.a, this.b, this.c );
  6945. },
  6946. closestPointToPoint: function () {
  6947. var plane, edgeList, projectedPoint, closestPoint;
  6948. return function closestPointToPoint( point, optionalTarget ) {
  6949. if ( plane === undefined ) {
  6950. plane = new Plane();
  6951. edgeList = [ new Line3(), new Line3(), new Line3() ];
  6952. projectedPoint = new Vector3();
  6953. closestPoint = new Vector3();
  6954. }
  6955. var result = optionalTarget || new Vector3();
  6956. var minDistance = Infinity;
  6957. // project the point onto the plane of the triangle
  6958. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  6959. plane.projectPoint( point, projectedPoint );
  6960. // check if the projection lies within the triangle
  6961. if( this.containsPoint( projectedPoint ) === true ) {
  6962. // if so, this is the closest point
  6963. result.copy( projectedPoint );
  6964. } else {
  6965. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  6966. edgeList[ 0 ].set( this.a, this.b );
  6967. edgeList[ 1 ].set( this.b, this.c );
  6968. edgeList[ 2 ].set( this.c, this.a );
  6969. for( var i = 0; i < edgeList.length; i ++ ) {
  6970. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  6971. var distance = projectedPoint.distanceToSquared( closestPoint );
  6972. if( distance < minDistance ) {
  6973. minDistance = distance;
  6974. result.copy( closestPoint );
  6975. }
  6976. }
  6977. }
  6978. return result;
  6979. };
  6980. }(),
  6981. equals: function ( triangle ) {
  6982. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  6983. }
  6984. };
  6985. /**
  6986. * @author mrdoob / http://mrdoob.com/
  6987. * @author alteredq / http://alteredqualia.com/
  6988. */
  6989. function Face3( a, b, c, normal, color, materialIndex ) {
  6990. this.a = a;
  6991. this.b = b;
  6992. this.c = c;
  6993. this.normal = (normal && normal.isVector3) ? normal : new Vector3();
  6994. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  6995. this.color = (color && color.isColor) ? color : new Color();
  6996. this.vertexColors = Array.isArray( color ) ? color : [];
  6997. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6998. }
  6999. Face3.prototype = {
  7000. constructor: Face3,
  7001. clone: function () {
  7002. return new this.constructor().copy( this );
  7003. },
  7004. copy: function ( source ) {
  7005. this.a = source.a;
  7006. this.b = source.b;
  7007. this.c = source.c;
  7008. this.normal.copy( source.normal );
  7009. this.color.copy( source.color );
  7010. this.materialIndex = source.materialIndex;
  7011. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  7012. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  7013. }
  7014. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  7015. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  7016. }
  7017. return this;
  7018. }
  7019. };
  7020. /**
  7021. * @author mrdoob / http://mrdoob.com/
  7022. * @author alteredq / http://alteredqualia.com/
  7023. *
  7024. * parameters = {
  7025. * color: <hex>,
  7026. * opacity: <float>,
  7027. * map: new THREE.Texture( <Image> ),
  7028. *
  7029. * lightMap: new THREE.Texture( <Image> ),
  7030. * lightMapIntensity: <float>
  7031. *
  7032. * aoMap: new THREE.Texture( <Image> ),
  7033. * aoMapIntensity: <float>
  7034. *
  7035. * specularMap: new THREE.Texture( <Image> ),
  7036. *
  7037. * alphaMap: new THREE.Texture( <Image> ),
  7038. *
  7039. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7040. * combine: THREE.Multiply,
  7041. * reflectivity: <float>,
  7042. * refractionRatio: <float>,
  7043. *
  7044. * shading: THREE.SmoothShading,
  7045. * depthTest: <bool>,
  7046. * depthWrite: <bool>,
  7047. *
  7048. * wireframe: <boolean>,
  7049. * wireframeLinewidth: <float>,
  7050. *
  7051. * skinning: <bool>,
  7052. * morphTargets: <bool>
  7053. * }
  7054. */
  7055. function MeshBasicMaterial( parameters ) {
  7056. Material.call( this );
  7057. this.type = 'MeshBasicMaterial';
  7058. this.color = new Color( 0xffffff ); // emissive
  7059. this.map = null;
  7060. this.lightMap = null;
  7061. this.lightMapIntensity = 1.0;
  7062. this.aoMap = null;
  7063. this.aoMapIntensity = 1.0;
  7064. this.specularMap = null;
  7065. this.alphaMap = null;
  7066. this.envMap = null;
  7067. this.combine = MultiplyOperation;
  7068. this.reflectivity = 1;
  7069. this.refractionRatio = 0.98;
  7070. this.wireframe = false;
  7071. this.wireframeLinewidth = 1;
  7072. this.wireframeLinecap = 'round';
  7073. this.wireframeLinejoin = 'round';
  7074. this.skinning = false;
  7075. this.morphTargets = false;
  7076. this.lights = false;
  7077. this.setValues( parameters );
  7078. }
  7079. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  7080. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  7081. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  7082. MeshBasicMaterial.prototype.copy = function ( source ) {
  7083. Material.prototype.copy.call( this, source );
  7084. this.color.copy( source.color );
  7085. this.map = source.map;
  7086. this.lightMap = source.lightMap;
  7087. this.lightMapIntensity = source.lightMapIntensity;
  7088. this.aoMap = source.aoMap;
  7089. this.aoMapIntensity = source.aoMapIntensity;
  7090. this.specularMap = source.specularMap;
  7091. this.alphaMap = source.alphaMap;
  7092. this.envMap = source.envMap;
  7093. this.combine = source.combine;
  7094. this.reflectivity = source.reflectivity;
  7095. this.refractionRatio = source.refractionRatio;
  7096. this.wireframe = source.wireframe;
  7097. this.wireframeLinewidth = source.wireframeLinewidth;
  7098. this.wireframeLinecap = source.wireframeLinecap;
  7099. this.wireframeLinejoin = source.wireframeLinejoin;
  7100. this.skinning = source.skinning;
  7101. this.morphTargets = source.morphTargets;
  7102. return this;
  7103. };
  7104. /**
  7105. * @author mrdoob / http://mrdoob.com/
  7106. */
  7107. function BufferAttribute( array, itemSize, normalized ) {
  7108. if ( Array.isArray( array ) ) {
  7109. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7110. }
  7111. this.uuid = _Math.generateUUID();
  7112. this.array = array;
  7113. this.itemSize = itemSize;
  7114. this.count = array !== undefined ? array.length / itemSize : 0;
  7115. this.normalized = normalized === true;
  7116. this.dynamic = false;
  7117. this.updateRange = { offset: 0, count: - 1 };
  7118. this.onUploadCallback = function () {};
  7119. this.version = 0;
  7120. }
  7121. BufferAttribute.prototype = {
  7122. constructor: BufferAttribute,
  7123. isBufferAttribute: true,
  7124. set needsUpdate( value ) {
  7125. if ( value === true ) this.version ++;
  7126. },
  7127. setArray: function ( array ) {
  7128. if ( Array.isArray( array ) ) {
  7129. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7130. }
  7131. this.count = array !== undefined ? array.length / this.itemSize : 0;
  7132. this.array = array;
  7133. },
  7134. setDynamic: function ( value ) {
  7135. this.dynamic = value;
  7136. return this;
  7137. },
  7138. copy: function ( source ) {
  7139. this.array = new source.array.constructor( source.array );
  7140. this.itemSize = source.itemSize;
  7141. this.count = source.count;
  7142. this.normalized = source.normalized;
  7143. this.dynamic = source.dynamic;
  7144. return this;
  7145. },
  7146. copyAt: function ( index1, attribute, index2 ) {
  7147. index1 *= this.itemSize;
  7148. index2 *= attribute.itemSize;
  7149. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  7150. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7151. }
  7152. return this;
  7153. },
  7154. copyArray: function ( array ) {
  7155. this.array.set( array );
  7156. return this;
  7157. },
  7158. copyColorsArray: function ( colors ) {
  7159. var array = this.array, offset = 0;
  7160. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  7161. var color = colors[ i ];
  7162. if ( color === undefined ) {
  7163. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  7164. color = new Color();
  7165. }
  7166. array[ offset ++ ] = color.r;
  7167. array[ offset ++ ] = color.g;
  7168. array[ offset ++ ] = color.b;
  7169. }
  7170. return this;
  7171. },
  7172. copyIndicesArray: function ( indices ) {
  7173. var array = this.array, offset = 0;
  7174. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  7175. var index = indices[ i ];
  7176. array[ offset ++ ] = index.a;
  7177. array[ offset ++ ] = index.b;
  7178. array[ offset ++ ] = index.c;
  7179. }
  7180. return this;
  7181. },
  7182. copyVector2sArray: function ( vectors ) {
  7183. var array = this.array, offset = 0;
  7184. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7185. var vector = vectors[ i ];
  7186. if ( vector === undefined ) {
  7187. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  7188. vector = new Vector2();
  7189. }
  7190. array[ offset ++ ] = vector.x;
  7191. array[ offset ++ ] = vector.y;
  7192. }
  7193. return this;
  7194. },
  7195. copyVector3sArray: function ( vectors ) {
  7196. var array = this.array, offset = 0;
  7197. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7198. var vector = vectors[ i ];
  7199. if ( vector === undefined ) {
  7200. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  7201. vector = new Vector3();
  7202. }
  7203. array[ offset ++ ] = vector.x;
  7204. array[ offset ++ ] = vector.y;
  7205. array[ offset ++ ] = vector.z;
  7206. }
  7207. return this;
  7208. },
  7209. copyVector4sArray: function ( vectors ) {
  7210. var array = this.array, offset = 0;
  7211. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7212. var vector = vectors[ i ];
  7213. if ( vector === undefined ) {
  7214. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  7215. vector = new Vector4();
  7216. }
  7217. array[ offset ++ ] = vector.x;
  7218. array[ offset ++ ] = vector.y;
  7219. array[ offset ++ ] = vector.z;
  7220. array[ offset ++ ] = vector.w;
  7221. }
  7222. return this;
  7223. },
  7224. set: function ( value, offset ) {
  7225. if ( offset === undefined ) offset = 0;
  7226. this.array.set( value, offset );
  7227. return this;
  7228. },
  7229. getX: function ( index ) {
  7230. return this.array[ index * this.itemSize ];
  7231. },
  7232. setX: function ( index, x ) {
  7233. this.array[ index * this.itemSize ] = x;
  7234. return this;
  7235. },
  7236. getY: function ( index ) {
  7237. return this.array[ index * this.itemSize + 1 ];
  7238. },
  7239. setY: function ( index, y ) {
  7240. this.array[ index * this.itemSize + 1 ] = y;
  7241. return this;
  7242. },
  7243. getZ: function ( index ) {
  7244. return this.array[ index * this.itemSize + 2 ];
  7245. },
  7246. setZ: function ( index, z ) {
  7247. this.array[ index * this.itemSize + 2 ] = z;
  7248. return this;
  7249. },
  7250. getW: function ( index ) {
  7251. return this.array[ index * this.itemSize + 3 ];
  7252. },
  7253. setW: function ( index, w ) {
  7254. this.array[ index * this.itemSize + 3 ] = w;
  7255. return this;
  7256. },
  7257. setXY: function ( index, x, y ) {
  7258. index *= this.itemSize;
  7259. this.array[ index + 0 ] = x;
  7260. this.array[ index + 1 ] = y;
  7261. return this;
  7262. },
  7263. setXYZ: function ( index, x, y, z ) {
  7264. index *= this.itemSize;
  7265. this.array[ index + 0 ] = x;
  7266. this.array[ index + 1 ] = y;
  7267. this.array[ index + 2 ] = z;
  7268. return this;
  7269. },
  7270. setXYZW: function ( index, x, y, z, w ) {
  7271. index *= this.itemSize;
  7272. this.array[ index + 0 ] = x;
  7273. this.array[ index + 1 ] = y;
  7274. this.array[ index + 2 ] = z;
  7275. this.array[ index + 3 ] = w;
  7276. return this;
  7277. },
  7278. onUpload: function ( callback ) {
  7279. this.onUploadCallback = callback;
  7280. return this;
  7281. },
  7282. clone: function () {
  7283. return new this.constructor().copy( this );
  7284. }
  7285. };
  7286. //
  7287. function Int8BufferAttribute( array, itemSize ) {
  7288. BufferAttribute.call( this, new Int8Array( array ), itemSize );
  7289. }
  7290. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7291. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7292. function Uint8BufferAttribute( array, itemSize ) {
  7293. BufferAttribute.call( this, new Uint8Array( array ), itemSize );
  7294. }
  7295. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7296. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7297. function Uint8ClampedBufferAttribute( array, itemSize ) {
  7298. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize );
  7299. }
  7300. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7301. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7302. function Int16BufferAttribute( array, itemSize ) {
  7303. BufferAttribute.call( this, new Int16Array( array ), itemSize );
  7304. }
  7305. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7306. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7307. function Uint16BufferAttribute( array, itemSize ) {
  7308. BufferAttribute.call( this, new Uint16Array( array ), itemSize );
  7309. }
  7310. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7311. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7312. function Int32BufferAttribute( array, itemSize ) {
  7313. BufferAttribute.call( this, new Int32Array( array ), itemSize );
  7314. }
  7315. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7316. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7317. function Uint32BufferAttribute( array, itemSize ) {
  7318. BufferAttribute.call( this, new Uint32Array( array ), itemSize );
  7319. }
  7320. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7321. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7322. function Float32BufferAttribute( array, itemSize ) {
  7323. BufferAttribute.call( this, new Float32Array( array ), itemSize );
  7324. }
  7325. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7326. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  7327. function Float64BufferAttribute( array, itemSize ) {
  7328. BufferAttribute.call( this, new Float64Array( array ), itemSize );
  7329. }
  7330. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7331. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  7332. /**
  7333. * @author mrdoob / http://mrdoob.com/
  7334. */
  7335. function DirectGeometry() {
  7336. this.indices = [];
  7337. this.vertices = [];
  7338. this.normals = [];
  7339. this.colors = [];
  7340. this.uvs = [];
  7341. this.uvs2 = [];
  7342. this.groups = [];
  7343. this.morphTargets = {};
  7344. this.skinWeights = [];
  7345. this.skinIndices = [];
  7346. // this.lineDistances = [];
  7347. this.boundingBox = null;
  7348. this.boundingSphere = null;
  7349. // update flags
  7350. this.verticesNeedUpdate = false;
  7351. this.normalsNeedUpdate = false;
  7352. this.colorsNeedUpdate = false;
  7353. this.uvsNeedUpdate = false;
  7354. this.groupsNeedUpdate = false;
  7355. }
  7356. Object.assign( DirectGeometry.prototype, {
  7357. computeGroups: function ( geometry ) {
  7358. var group;
  7359. var groups = [];
  7360. var materialIndex;
  7361. var faces = geometry.faces;
  7362. for ( var i = 0; i < faces.length; i ++ ) {
  7363. var face = faces[ i ];
  7364. // materials
  7365. if ( face.materialIndex !== materialIndex ) {
  7366. materialIndex = face.materialIndex;
  7367. if ( group !== undefined ) {
  7368. group.count = ( i * 3 ) - group.start;
  7369. groups.push( group );
  7370. }
  7371. group = {
  7372. start: i * 3,
  7373. materialIndex: materialIndex
  7374. };
  7375. }
  7376. }
  7377. if ( group !== undefined ) {
  7378. group.count = ( i * 3 ) - group.start;
  7379. groups.push( group );
  7380. }
  7381. this.groups = groups;
  7382. },
  7383. fromGeometry: function ( geometry ) {
  7384. var faces = geometry.faces;
  7385. var vertices = geometry.vertices;
  7386. var faceVertexUvs = geometry.faceVertexUvs;
  7387. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  7388. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  7389. // morphs
  7390. var morphTargets = geometry.morphTargets;
  7391. var morphTargetsLength = morphTargets.length;
  7392. var morphTargetsPosition;
  7393. if ( morphTargetsLength > 0 ) {
  7394. morphTargetsPosition = [];
  7395. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  7396. morphTargetsPosition[ i ] = [];
  7397. }
  7398. this.morphTargets.position = morphTargetsPosition;
  7399. }
  7400. var morphNormals = geometry.morphNormals;
  7401. var morphNormalsLength = morphNormals.length;
  7402. var morphTargetsNormal;
  7403. if ( morphNormalsLength > 0 ) {
  7404. morphTargetsNormal = [];
  7405. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  7406. morphTargetsNormal[ i ] = [];
  7407. }
  7408. this.morphTargets.normal = morphTargetsNormal;
  7409. }
  7410. // skins
  7411. var skinIndices = geometry.skinIndices;
  7412. var skinWeights = geometry.skinWeights;
  7413. var hasSkinIndices = skinIndices.length === vertices.length;
  7414. var hasSkinWeights = skinWeights.length === vertices.length;
  7415. //
  7416. for ( var i = 0; i < faces.length; i ++ ) {
  7417. var face = faces[ i ];
  7418. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  7419. var vertexNormals = face.vertexNormals;
  7420. if ( vertexNormals.length === 3 ) {
  7421. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  7422. } else {
  7423. var normal = face.normal;
  7424. this.normals.push( normal, normal, normal );
  7425. }
  7426. var vertexColors = face.vertexColors;
  7427. if ( vertexColors.length === 3 ) {
  7428. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  7429. } else {
  7430. var color = face.color;
  7431. this.colors.push( color, color, color );
  7432. }
  7433. if ( hasFaceVertexUv === true ) {
  7434. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  7435. if ( vertexUvs !== undefined ) {
  7436. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7437. } else {
  7438. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  7439. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  7440. }
  7441. }
  7442. if ( hasFaceVertexUv2 === true ) {
  7443. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  7444. if ( vertexUvs !== undefined ) {
  7445. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7446. } else {
  7447. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  7448. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  7449. }
  7450. }
  7451. // morphs
  7452. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  7453. var morphTarget = morphTargets[ j ].vertices;
  7454. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  7455. }
  7456. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  7457. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  7458. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  7459. }
  7460. // skins
  7461. if ( hasSkinIndices ) {
  7462. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  7463. }
  7464. if ( hasSkinWeights ) {
  7465. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  7466. }
  7467. }
  7468. this.computeGroups( geometry );
  7469. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7470. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7471. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7472. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7473. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7474. return this;
  7475. }
  7476. } );
  7477. /**
  7478. * @author mrdoob / http://mrdoob.com/
  7479. * @author kile / http://kile.stravaganza.org/
  7480. * @author alteredq / http://alteredqualia.com/
  7481. * @author mikael emtinger / http://gomo.se/
  7482. * @author zz85 / http://www.lab4games.net/zz85/blog
  7483. * @author bhouston / http://clara.io
  7484. */
  7485. function Geometry() {
  7486. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  7487. this.uuid = _Math.generateUUID();
  7488. this.name = '';
  7489. this.type = 'Geometry';
  7490. this.vertices = [];
  7491. this.colors = [];
  7492. this.faces = [];
  7493. this.faceVertexUvs = [ [] ];
  7494. this.morphTargets = [];
  7495. this.morphNormals = [];
  7496. this.skinWeights = [];
  7497. this.skinIndices = [];
  7498. this.lineDistances = [];
  7499. this.boundingBox = null;
  7500. this.boundingSphere = null;
  7501. // update flags
  7502. this.elementsNeedUpdate = false;
  7503. this.verticesNeedUpdate = false;
  7504. this.uvsNeedUpdate = false;
  7505. this.normalsNeedUpdate = false;
  7506. this.colorsNeedUpdate = false;
  7507. this.lineDistancesNeedUpdate = false;
  7508. this.groupsNeedUpdate = false;
  7509. }
  7510. Object.assign( Geometry.prototype, EventDispatcher.prototype, {
  7511. isGeometry: true,
  7512. applyMatrix: function ( matrix ) {
  7513. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7514. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  7515. var vertex = this.vertices[ i ];
  7516. vertex.applyMatrix4( matrix );
  7517. }
  7518. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  7519. var face = this.faces[ i ];
  7520. face.normal.applyMatrix3( normalMatrix ).normalize();
  7521. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  7522. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  7523. }
  7524. }
  7525. if ( this.boundingBox !== null ) {
  7526. this.computeBoundingBox();
  7527. }
  7528. if ( this.boundingSphere !== null ) {
  7529. this.computeBoundingSphere();
  7530. }
  7531. this.verticesNeedUpdate = true;
  7532. this.normalsNeedUpdate = true;
  7533. return this;
  7534. },
  7535. rotateX: function () {
  7536. // rotate geometry around world x-axis
  7537. var m1;
  7538. return function rotateX( angle ) {
  7539. if ( m1 === undefined ) m1 = new Matrix4();
  7540. m1.makeRotationX( angle );
  7541. this.applyMatrix( m1 );
  7542. return this;
  7543. };
  7544. }(),
  7545. rotateY: function () {
  7546. // rotate geometry around world y-axis
  7547. var m1;
  7548. return function rotateY( angle ) {
  7549. if ( m1 === undefined ) m1 = new Matrix4();
  7550. m1.makeRotationY( angle );
  7551. this.applyMatrix( m1 );
  7552. return this;
  7553. };
  7554. }(),
  7555. rotateZ: function () {
  7556. // rotate geometry around world z-axis
  7557. var m1;
  7558. return function rotateZ( angle ) {
  7559. if ( m1 === undefined ) m1 = new Matrix4();
  7560. m1.makeRotationZ( angle );
  7561. this.applyMatrix( m1 );
  7562. return this;
  7563. };
  7564. }(),
  7565. translate: function () {
  7566. // translate geometry
  7567. var m1;
  7568. return function translate( x, y, z ) {
  7569. if ( m1 === undefined ) m1 = new Matrix4();
  7570. m1.makeTranslation( x, y, z );
  7571. this.applyMatrix( m1 );
  7572. return this;
  7573. };
  7574. }(),
  7575. scale: function () {
  7576. // scale geometry
  7577. var m1;
  7578. return function scale( x, y, z ) {
  7579. if ( m1 === undefined ) m1 = new Matrix4();
  7580. m1.makeScale( x, y, z );
  7581. this.applyMatrix( m1 );
  7582. return this;
  7583. };
  7584. }(),
  7585. lookAt: function () {
  7586. var obj;
  7587. return function lookAt( vector ) {
  7588. if ( obj === undefined ) obj = new Object3D();
  7589. obj.lookAt( vector );
  7590. obj.updateMatrix();
  7591. this.applyMatrix( obj.matrix );
  7592. };
  7593. }(),
  7594. fromBufferGeometry: function ( geometry ) {
  7595. var scope = this;
  7596. var indices = geometry.index !== null ? geometry.index.array : undefined;
  7597. var attributes = geometry.attributes;
  7598. var positions = attributes.position.array;
  7599. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  7600. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  7601. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  7602. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  7603. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  7604. var tempNormals = [];
  7605. var tempUVs = [];
  7606. var tempUVs2 = [];
  7607. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  7608. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  7609. if ( normals !== undefined ) {
  7610. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  7611. }
  7612. if ( colors !== undefined ) {
  7613. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  7614. }
  7615. if ( uvs !== undefined ) {
  7616. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  7617. }
  7618. if ( uvs2 !== undefined ) {
  7619. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  7620. }
  7621. }
  7622. function addFace( a, b, c, materialIndex ) {
  7623. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  7624. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  7625. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  7626. scope.faces.push( face );
  7627. if ( uvs !== undefined ) {
  7628. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  7629. }
  7630. if ( uvs2 !== undefined ) {
  7631. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  7632. }
  7633. }
  7634. if ( indices !== undefined ) {
  7635. var groups = geometry.groups;
  7636. if ( groups.length > 0 ) {
  7637. for ( var i = 0; i < groups.length; i ++ ) {
  7638. var group = groups[ i ];
  7639. var start = group.start;
  7640. var count = group.count;
  7641. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  7642. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  7643. }
  7644. }
  7645. } else {
  7646. for ( var i = 0; i < indices.length; i += 3 ) {
  7647. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  7648. }
  7649. }
  7650. } else {
  7651. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  7652. addFace( i, i + 1, i + 2 );
  7653. }
  7654. }
  7655. this.computeFaceNormals();
  7656. if ( geometry.boundingBox !== null ) {
  7657. this.boundingBox = geometry.boundingBox.clone();
  7658. }
  7659. if ( geometry.boundingSphere !== null ) {
  7660. this.boundingSphere = geometry.boundingSphere.clone();
  7661. }
  7662. return this;
  7663. },
  7664. center: function () {
  7665. this.computeBoundingBox();
  7666. var offset = this.boundingBox.getCenter().negate();
  7667. this.translate( offset.x, offset.y, offset.z );
  7668. return offset;
  7669. },
  7670. normalize: function () {
  7671. this.computeBoundingSphere();
  7672. var center = this.boundingSphere.center;
  7673. var radius = this.boundingSphere.radius;
  7674. var s = radius === 0 ? 1 : 1.0 / radius;
  7675. var matrix = new Matrix4();
  7676. matrix.set(
  7677. s, 0, 0, - s * center.x,
  7678. 0, s, 0, - s * center.y,
  7679. 0, 0, s, - s * center.z,
  7680. 0, 0, 0, 1
  7681. );
  7682. this.applyMatrix( matrix );
  7683. return this;
  7684. },
  7685. computeFaceNormals: function () {
  7686. var cb = new Vector3(), ab = new Vector3();
  7687. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7688. var face = this.faces[ f ];
  7689. var vA = this.vertices[ face.a ];
  7690. var vB = this.vertices[ face.b ];
  7691. var vC = this.vertices[ face.c ];
  7692. cb.subVectors( vC, vB );
  7693. ab.subVectors( vA, vB );
  7694. cb.cross( ab );
  7695. cb.normalize();
  7696. face.normal.copy( cb );
  7697. }
  7698. },
  7699. computeVertexNormals: function ( areaWeighted ) {
  7700. if ( areaWeighted === undefined ) areaWeighted = true;
  7701. var v, vl, f, fl, face, vertices;
  7702. vertices = new Array( this.vertices.length );
  7703. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7704. vertices[ v ] = new Vector3();
  7705. }
  7706. if ( areaWeighted ) {
  7707. // vertex normals weighted by triangle areas
  7708. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7709. var vA, vB, vC;
  7710. var cb = new Vector3(), ab = new Vector3();
  7711. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7712. face = this.faces[ f ];
  7713. vA = this.vertices[ face.a ];
  7714. vB = this.vertices[ face.b ];
  7715. vC = this.vertices[ face.c ];
  7716. cb.subVectors( vC, vB );
  7717. ab.subVectors( vA, vB );
  7718. cb.cross( ab );
  7719. vertices[ face.a ].add( cb );
  7720. vertices[ face.b ].add( cb );
  7721. vertices[ face.c ].add( cb );
  7722. }
  7723. } else {
  7724. this.computeFaceNormals();
  7725. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7726. face = this.faces[ f ];
  7727. vertices[ face.a ].add( face.normal );
  7728. vertices[ face.b ].add( face.normal );
  7729. vertices[ face.c ].add( face.normal );
  7730. }
  7731. }
  7732. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7733. vertices[ v ].normalize();
  7734. }
  7735. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7736. face = this.faces[ f ];
  7737. var vertexNormals = face.vertexNormals;
  7738. if ( vertexNormals.length === 3 ) {
  7739. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  7740. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  7741. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  7742. } else {
  7743. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  7744. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  7745. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  7746. }
  7747. }
  7748. if ( this.faces.length > 0 ) {
  7749. this.normalsNeedUpdate = true;
  7750. }
  7751. },
  7752. computeFlatVertexNormals: function () {
  7753. var f, fl, face;
  7754. this.computeFaceNormals();
  7755. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7756. face = this.faces[ f ];
  7757. var vertexNormals = face.vertexNormals;
  7758. if ( vertexNormals.length === 3 ) {
  7759. vertexNormals[ 0 ].copy( face.normal );
  7760. vertexNormals[ 1 ].copy( face.normal );
  7761. vertexNormals[ 2 ].copy( face.normal );
  7762. } else {
  7763. vertexNormals[ 0 ] = face.normal.clone();
  7764. vertexNormals[ 1 ] = face.normal.clone();
  7765. vertexNormals[ 2 ] = face.normal.clone();
  7766. }
  7767. }
  7768. if ( this.faces.length > 0 ) {
  7769. this.normalsNeedUpdate = true;
  7770. }
  7771. },
  7772. computeMorphNormals: function () {
  7773. var i, il, f, fl, face;
  7774. // save original normals
  7775. // - create temp variables on first access
  7776. // otherwise just copy (for faster repeated calls)
  7777. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7778. face = this.faces[ f ];
  7779. if ( ! face.__originalFaceNormal ) {
  7780. face.__originalFaceNormal = face.normal.clone();
  7781. } else {
  7782. face.__originalFaceNormal.copy( face.normal );
  7783. }
  7784. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  7785. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  7786. if ( ! face.__originalVertexNormals[ i ] ) {
  7787. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  7788. } else {
  7789. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  7790. }
  7791. }
  7792. }
  7793. // use temp geometry to compute face and vertex normals for each morph
  7794. var tmpGeo = new Geometry();
  7795. tmpGeo.faces = this.faces;
  7796. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  7797. // create on first access
  7798. if ( ! this.morphNormals[ i ] ) {
  7799. this.morphNormals[ i ] = {};
  7800. this.morphNormals[ i ].faceNormals = [];
  7801. this.morphNormals[ i ].vertexNormals = [];
  7802. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  7803. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  7804. var faceNormal, vertexNormals;
  7805. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7806. faceNormal = new Vector3();
  7807. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  7808. dstNormalsFace.push( faceNormal );
  7809. dstNormalsVertex.push( vertexNormals );
  7810. }
  7811. }
  7812. var morphNormals = this.morphNormals[ i ];
  7813. // set vertices to morph target
  7814. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  7815. // compute morph normals
  7816. tmpGeo.computeFaceNormals();
  7817. tmpGeo.computeVertexNormals();
  7818. // store morph normals
  7819. var faceNormal, vertexNormals;
  7820. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7821. face = this.faces[ f ];
  7822. faceNormal = morphNormals.faceNormals[ f ];
  7823. vertexNormals = morphNormals.vertexNormals[ f ];
  7824. faceNormal.copy( face.normal );
  7825. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  7826. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  7827. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  7828. }
  7829. }
  7830. // restore original normals
  7831. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7832. face = this.faces[ f ];
  7833. face.normal = face.__originalFaceNormal;
  7834. face.vertexNormals = face.__originalVertexNormals;
  7835. }
  7836. },
  7837. computeLineDistances: function () {
  7838. var d = 0;
  7839. var vertices = this.vertices;
  7840. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  7841. if ( i > 0 ) {
  7842. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  7843. }
  7844. this.lineDistances[ i ] = d;
  7845. }
  7846. },
  7847. computeBoundingBox: function () {
  7848. if ( this.boundingBox === null ) {
  7849. this.boundingBox = new Box3();
  7850. }
  7851. this.boundingBox.setFromPoints( this.vertices );
  7852. },
  7853. computeBoundingSphere: function () {
  7854. if ( this.boundingSphere === null ) {
  7855. this.boundingSphere = new Sphere();
  7856. }
  7857. this.boundingSphere.setFromPoints( this.vertices );
  7858. },
  7859. merge: function ( geometry, matrix, materialIndexOffset ) {
  7860. if ( (geometry && geometry.isGeometry) === false ) {
  7861. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  7862. return;
  7863. }
  7864. var normalMatrix,
  7865. vertexOffset = this.vertices.length,
  7866. vertices1 = this.vertices,
  7867. vertices2 = geometry.vertices,
  7868. faces1 = this.faces,
  7869. faces2 = geometry.faces,
  7870. uvs1 = this.faceVertexUvs[ 0 ],
  7871. uvs2 = geometry.faceVertexUvs[ 0 ],
  7872. colors1 = this.colors,
  7873. colors2 = geometry.colors;
  7874. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  7875. if ( matrix !== undefined ) {
  7876. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7877. }
  7878. // vertices
  7879. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  7880. var vertex = vertices2[ i ];
  7881. var vertexCopy = vertex.clone();
  7882. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  7883. vertices1.push( vertexCopy );
  7884. }
  7885. // colors
  7886. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  7887. colors1.push( colors2[ i ].clone() );
  7888. }
  7889. // faces
  7890. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  7891. var face = faces2[ i ], faceCopy, normal, color,
  7892. faceVertexNormals = face.vertexNormals,
  7893. faceVertexColors = face.vertexColors;
  7894. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  7895. faceCopy.normal.copy( face.normal );
  7896. if ( normalMatrix !== undefined ) {
  7897. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  7898. }
  7899. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  7900. normal = faceVertexNormals[ j ].clone();
  7901. if ( normalMatrix !== undefined ) {
  7902. normal.applyMatrix3( normalMatrix ).normalize();
  7903. }
  7904. faceCopy.vertexNormals.push( normal );
  7905. }
  7906. faceCopy.color.copy( face.color );
  7907. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  7908. color = faceVertexColors[ j ];
  7909. faceCopy.vertexColors.push( color.clone() );
  7910. }
  7911. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  7912. faces1.push( faceCopy );
  7913. }
  7914. // uvs
  7915. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  7916. var uv = uvs2[ i ], uvCopy = [];
  7917. if ( uv === undefined ) {
  7918. continue;
  7919. }
  7920. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  7921. uvCopy.push( uv[ j ].clone() );
  7922. }
  7923. uvs1.push( uvCopy );
  7924. }
  7925. },
  7926. mergeMesh: function ( mesh ) {
  7927. if ( (mesh && mesh.isMesh) === false ) {
  7928. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  7929. return;
  7930. }
  7931. mesh.matrixAutoUpdate && mesh.updateMatrix();
  7932. this.merge( mesh.geometry, mesh.matrix );
  7933. },
  7934. /*
  7935. * Checks for duplicate vertices with hashmap.
  7936. * Duplicated vertices are removed
  7937. * and faces' vertices are updated.
  7938. */
  7939. mergeVertices: function () {
  7940. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  7941. var unique = [], changes = [];
  7942. var v, key;
  7943. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  7944. var precision = Math.pow( 10, precisionPoints );
  7945. var i, il, face;
  7946. var indices, j, jl;
  7947. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  7948. v = this.vertices[ i ];
  7949. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  7950. if ( verticesMap[ key ] === undefined ) {
  7951. verticesMap[ key ] = i;
  7952. unique.push( this.vertices[ i ] );
  7953. changes[ i ] = unique.length - 1;
  7954. } else {
  7955. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  7956. changes[ i ] = changes[ verticesMap[ key ] ];
  7957. }
  7958. }
  7959. // if faces are completely degenerate after merging vertices, we
  7960. // have to remove them from the geometry.
  7961. var faceIndicesToRemove = [];
  7962. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  7963. face = this.faces[ i ];
  7964. face.a = changes[ face.a ];
  7965. face.b = changes[ face.b ];
  7966. face.c = changes[ face.c ];
  7967. indices = [ face.a, face.b, face.c ];
  7968. var dupIndex = - 1;
  7969. // if any duplicate vertices are found in a Face3
  7970. // we have to remove the face as nothing can be saved
  7971. for ( var n = 0; n < 3; n ++ ) {
  7972. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  7973. dupIndex = n;
  7974. faceIndicesToRemove.push( i );
  7975. break;
  7976. }
  7977. }
  7978. }
  7979. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  7980. var idx = faceIndicesToRemove[ i ];
  7981. this.faces.splice( idx, 1 );
  7982. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  7983. this.faceVertexUvs[ j ].splice( idx, 1 );
  7984. }
  7985. }
  7986. // Use unique set of vertices
  7987. var diff = this.vertices.length - unique.length;
  7988. this.vertices = unique;
  7989. return diff;
  7990. },
  7991. sortFacesByMaterialIndex: function () {
  7992. var faces = this.faces;
  7993. var length = faces.length;
  7994. // tag faces
  7995. for ( var i = 0; i < length; i ++ ) {
  7996. faces[ i ]._id = i;
  7997. }
  7998. // sort faces
  7999. function materialIndexSort( a, b ) {
  8000. return a.materialIndex - b.materialIndex;
  8001. }
  8002. faces.sort( materialIndexSort );
  8003. // sort uvs
  8004. var uvs1 = this.faceVertexUvs[ 0 ];
  8005. var uvs2 = this.faceVertexUvs[ 1 ];
  8006. var newUvs1, newUvs2;
  8007. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  8008. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  8009. for ( var i = 0; i < length; i ++ ) {
  8010. var id = faces[ i ]._id;
  8011. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  8012. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  8013. }
  8014. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  8015. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  8016. },
  8017. toJSON: function () {
  8018. var data = {
  8019. metadata: {
  8020. version: 4.4,
  8021. type: 'Geometry',
  8022. generator: 'Geometry.toJSON'
  8023. }
  8024. };
  8025. // standard Geometry serialization
  8026. data.uuid = this.uuid;
  8027. data.type = this.type;
  8028. if ( this.name !== '' ) data.name = this.name;
  8029. if ( this.parameters !== undefined ) {
  8030. var parameters = this.parameters;
  8031. for ( var key in parameters ) {
  8032. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8033. }
  8034. return data;
  8035. }
  8036. var vertices = [];
  8037. for ( var i = 0; i < this.vertices.length; i ++ ) {
  8038. var vertex = this.vertices[ i ];
  8039. vertices.push( vertex.x, vertex.y, vertex.z );
  8040. }
  8041. var faces = [];
  8042. var normals = [];
  8043. var normalsHash = {};
  8044. var colors = [];
  8045. var colorsHash = {};
  8046. var uvs = [];
  8047. var uvsHash = {};
  8048. for ( var i = 0; i < this.faces.length; i ++ ) {
  8049. var face = this.faces[ i ];
  8050. var hasMaterial = true;
  8051. var hasFaceUv = false; // deprecated
  8052. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  8053. var hasFaceNormal = face.normal.length() > 0;
  8054. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  8055. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  8056. var hasFaceVertexColor = face.vertexColors.length > 0;
  8057. var faceType = 0;
  8058. faceType = setBit( faceType, 0, 0 ); // isQuad
  8059. faceType = setBit( faceType, 1, hasMaterial );
  8060. faceType = setBit( faceType, 2, hasFaceUv );
  8061. faceType = setBit( faceType, 3, hasFaceVertexUv );
  8062. faceType = setBit( faceType, 4, hasFaceNormal );
  8063. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  8064. faceType = setBit( faceType, 6, hasFaceColor );
  8065. faceType = setBit( faceType, 7, hasFaceVertexColor );
  8066. faces.push( faceType );
  8067. faces.push( face.a, face.b, face.c );
  8068. faces.push( face.materialIndex );
  8069. if ( hasFaceVertexUv ) {
  8070. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  8071. faces.push(
  8072. getUvIndex( faceVertexUvs[ 0 ] ),
  8073. getUvIndex( faceVertexUvs[ 1 ] ),
  8074. getUvIndex( faceVertexUvs[ 2 ] )
  8075. );
  8076. }
  8077. if ( hasFaceNormal ) {
  8078. faces.push( getNormalIndex( face.normal ) );
  8079. }
  8080. if ( hasFaceVertexNormal ) {
  8081. var vertexNormals = face.vertexNormals;
  8082. faces.push(
  8083. getNormalIndex( vertexNormals[ 0 ] ),
  8084. getNormalIndex( vertexNormals[ 1 ] ),
  8085. getNormalIndex( vertexNormals[ 2 ] )
  8086. );
  8087. }
  8088. if ( hasFaceColor ) {
  8089. faces.push( getColorIndex( face.color ) );
  8090. }
  8091. if ( hasFaceVertexColor ) {
  8092. var vertexColors = face.vertexColors;
  8093. faces.push(
  8094. getColorIndex( vertexColors[ 0 ] ),
  8095. getColorIndex( vertexColors[ 1 ] ),
  8096. getColorIndex( vertexColors[ 2 ] )
  8097. );
  8098. }
  8099. }
  8100. function setBit( value, position, enabled ) {
  8101. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  8102. }
  8103. function getNormalIndex( normal ) {
  8104. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  8105. if ( normalsHash[ hash ] !== undefined ) {
  8106. return normalsHash[ hash ];
  8107. }
  8108. normalsHash[ hash ] = normals.length / 3;
  8109. normals.push( normal.x, normal.y, normal.z );
  8110. return normalsHash[ hash ];
  8111. }
  8112. function getColorIndex( color ) {
  8113. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  8114. if ( colorsHash[ hash ] !== undefined ) {
  8115. return colorsHash[ hash ];
  8116. }
  8117. colorsHash[ hash ] = colors.length;
  8118. colors.push( color.getHex() );
  8119. return colorsHash[ hash ];
  8120. }
  8121. function getUvIndex( uv ) {
  8122. var hash = uv.x.toString() + uv.y.toString();
  8123. if ( uvsHash[ hash ] !== undefined ) {
  8124. return uvsHash[ hash ];
  8125. }
  8126. uvsHash[ hash ] = uvs.length / 2;
  8127. uvs.push( uv.x, uv.y );
  8128. return uvsHash[ hash ];
  8129. }
  8130. data.data = {};
  8131. data.data.vertices = vertices;
  8132. data.data.normals = normals;
  8133. if ( colors.length > 0 ) data.data.colors = colors;
  8134. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  8135. data.data.faces = faces;
  8136. return data;
  8137. },
  8138. clone: function () {
  8139. /*
  8140. // Handle primitives
  8141. var parameters = this.parameters;
  8142. if ( parameters !== undefined ) {
  8143. var values = [];
  8144. for ( var key in parameters ) {
  8145. values.push( parameters[ key ] );
  8146. }
  8147. var geometry = Object.create( this.constructor.prototype );
  8148. this.constructor.apply( geometry, values );
  8149. return geometry;
  8150. }
  8151. return new this.constructor().copy( this );
  8152. */
  8153. return new Geometry().copy( this );
  8154. },
  8155. copy: function ( source ) {
  8156. this.vertices = [];
  8157. this.faces = [];
  8158. this.faceVertexUvs = [ [] ];
  8159. this.colors = [];
  8160. var vertices = source.vertices;
  8161. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  8162. this.vertices.push( vertices[ i ].clone() );
  8163. }
  8164. var colors = source.colors;
  8165. for ( var i = 0, il = colors.length; i < il; i ++ ) {
  8166. this.colors.push( colors[ i ].clone() );
  8167. }
  8168. var faces = source.faces;
  8169. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  8170. this.faces.push( faces[ i ].clone() );
  8171. }
  8172. for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  8173. var faceVertexUvs = source.faceVertexUvs[ i ];
  8174. if ( this.faceVertexUvs[ i ] === undefined ) {
  8175. this.faceVertexUvs[ i ] = [];
  8176. }
  8177. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  8178. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  8179. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  8180. var uv = uvs[ k ];
  8181. uvsCopy.push( uv.clone() );
  8182. }
  8183. this.faceVertexUvs[ i ].push( uvsCopy );
  8184. }
  8185. }
  8186. return this;
  8187. },
  8188. dispose: function () {
  8189. this.dispatchEvent( { type: 'dispose' } );
  8190. }
  8191. } );
  8192. var count = 0;
  8193. function GeometryIdCount() { return count++; }
  8194. /**
  8195. * @author alteredq / http://alteredqualia.com/
  8196. * @author mrdoob / http://mrdoob.com/
  8197. */
  8198. function BufferGeometry() {
  8199. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  8200. this.uuid = _Math.generateUUID();
  8201. this.name = '';
  8202. this.type = 'BufferGeometry';
  8203. this.index = null;
  8204. this.attributes = {};
  8205. this.morphAttributes = {};
  8206. this.groups = [];
  8207. this.boundingBox = null;
  8208. this.boundingSphere = null;
  8209. this.drawRange = { start: 0, count: Infinity };
  8210. }
  8211. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, {
  8212. isBufferGeometry: true,
  8213. getIndex: function () {
  8214. return this.index;
  8215. },
  8216. setIndex: function ( index ) {
  8217. this.index = index;
  8218. },
  8219. addAttribute: function ( name, attribute ) {
  8220. if ( ( attribute && attribute.isBufferAttribute ) === false && ( attribute && attribute.isInterleavedBufferAttribute ) === false ) {
  8221. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  8222. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  8223. return;
  8224. }
  8225. if ( name === 'index' ) {
  8226. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  8227. this.setIndex( attribute );
  8228. return;
  8229. }
  8230. this.attributes[ name ] = attribute;
  8231. return this;
  8232. },
  8233. getAttribute: function ( name ) {
  8234. return this.attributes[ name ];
  8235. },
  8236. removeAttribute: function ( name ) {
  8237. delete this.attributes[ name ];
  8238. return this;
  8239. },
  8240. addGroup: function ( start, count, materialIndex ) {
  8241. this.groups.push( {
  8242. start: start,
  8243. count: count,
  8244. materialIndex: materialIndex !== undefined ? materialIndex : 0
  8245. } );
  8246. },
  8247. clearGroups: function () {
  8248. this.groups = [];
  8249. },
  8250. setDrawRange: function ( start, count ) {
  8251. this.drawRange.start = start;
  8252. this.drawRange.count = count;
  8253. },
  8254. applyMatrix: function ( matrix ) {
  8255. var position = this.attributes.position;
  8256. if ( position !== undefined ) {
  8257. matrix.applyToVector3Array( position.array );
  8258. position.needsUpdate = true;
  8259. }
  8260. var normal = this.attributes.normal;
  8261. if ( normal !== undefined ) {
  8262. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8263. normalMatrix.applyToVector3Array( normal.array );
  8264. normal.needsUpdate = true;
  8265. }
  8266. if ( this.boundingBox !== null ) {
  8267. this.computeBoundingBox();
  8268. }
  8269. if ( this.boundingSphere !== null ) {
  8270. this.computeBoundingSphere();
  8271. }
  8272. return this;
  8273. },
  8274. rotateX: function () {
  8275. // rotate geometry around world x-axis
  8276. var m1;
  8277. return function rotateX( angle ) {
  8278. if ( m1 === undefined ) m1 = new Matrix4();
  8279. m1.makeRotationX( angle );
  8280. this.applyMatrix( m1 );
  8281. return this;
  8282. };
  8283. }(),
  8284. rotateY: function () {
  8285. // rotate geometry around world y-axis
  8286. var m1;
  8287. return function rotateY( angle ) {
  8288. if ( m1 === undefined ) m1 = new Matrix4();
  8289. m1.makeRotationY( angle );
  8290. this.applyMatrix( m1 );
  8291. return this;
  8292. };
  8293. }(),
  8294. rotateZ: function () {
  8295. // rotate geometry around world z-axis
  8296. var m1;
  8297. return function rotateZ( angle ) {
  8298. if ( m1 === undefined ) m1 = new Matrix4();
  8299. m1.makeRotationZ( angle );
  8300. this.applyMatrix( m1 );
  8301. return this;
  8302. };
  8303. }(),
  8304. translate: function () {
  8305. // translate geometry
  8306. var m1;
  8307. return function translate( x, y, z ) {
  8308. if ( m1 === undefined ) m1 = new Matrix4();
  8309. m1.makeTranslation( x, y, z );
  8310. this.applyMatrix( m1 );
  8311. return this;
  8312. };
  8313. }(),
  8314. scale: function () {
  8315. // scale geometry
  8316. var m1;
  8317. return function scale( x, y, z ) {
  8318. if ( m1 === undefined ) m1 = new Matrix4();
  8319. m1.makeScale( x, y, z );
  8320. this.applyMatrix( m1 );
  8321. return this;
  8322. };
  8323. }(),
  8324. lookAt: function () {
  8325. var obj;
  8326. return function lookAt( vector ) {
  8327. if ( obj === undefined ) obj = new Object3D();
  8328. obj.lookAt( vector );
  8329. obj.updateMatrix();
  8330. this.applyMatrix( obj.matrix );
  8331. };
  8332. }(),
  8333. center: function () {
  8334. this.computeBoundingBox();
  8335. var offset = this.boundingBox.getCenter().negate();
  8336. this.translate( offset.x, offset.y, offset.z );
  8337. return offset;
  8338. },
  8339. setFromObject: function ( object ) {
  8340. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  8341. var geometry = object.geometry;
  8342. if ( object.isPoints || object.isLine ) {
  8343. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  8344. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  8345. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  8346. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  8347. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  8348. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  8349. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  8350. }
  8351. if ( geometry.boundingSphere !== null ) {
  8352. this.boundingSphere = geometry.boundingSphere.clone();
  8353. }
  8354. if ( geometry.boundingBox !== null ) {
  8355. this.boundingBox = geometry.boundingBox.clone();
  8356. }
  8357. } else if ( object.isMesh ) {
  8358. if ( geometry && geometry.isGeometry ) {
  8359. this.fromGeometry( geometry );
  8360. }
  8361. }
  8362. return this;
  8363. },
  8364. updateFromObject: function ( object ) {
  8365. var geometry = object.geometry;
  8366. if ( object.isMesh ) {
  8367. var direct = geometry.__directGeometry;
  8368. if ( geometry.elementsNeedUpdate === true ) {
  8369. direct = undefined;
  8370. geometry.elementsNeedUpdate = false;
  8371. }
  8372. if ( direct === undefined ) {
  8373. return this.fromGeometry( geometry );
  8374. }
  8375. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  8376. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  8377. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  8378. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  8379. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  8380. geometry.verticesNeedUpdate = false;
  8381. geometry.normalsNeedUpdate = false;
  8382. geometry.colorsNeedUpdate = false;
  8383. geometry.uvsNeedUpdate = false;
  8384. geometry.groupsNeedUpdate = false;
  8385. geometry = direct;
  8386. }
  8387. var attribute;
  8388. if ( geometry.verticesNeedUpdate === true ) {
  8389. attribute = this.attributes.position;
  8390. if ( attribute !== undefined ) {
  8391. attribute.copyVector3sArray( geometry.vertices );
  8392. attribute.needsUpdate = true;
  8393. }
  8394. geometry.verticesNeedUpdate = false;
  8395. }
  8396. if ( geometry.normalsNeedUpdate === true ) {
  8397. attribute = this.attributes.normal;
  8398. if ( attribute !== undefined ) {
  8399. attribute.copyVector3sArray( geometry.normals );
  8400. attribute.needsUpdate = true;
  8401. }
  8402. geometry.normalsNeedUpdate = false;
  8403. }
  8404. if ( geometry.colorsNeedUpdate === true ) {
  8405. attribute = this.attributes.color;
  8406. if ( attribute !== undefined ) {
  8407. attribute.copyColorsArray( geometry.colors );
  8408. attribute.needsUpdate = true;
  8409. }
  8410. geometry.colorsNeedUpdate = false;
  8411. }
  8412. if ( geometry.uvsNeedUpdate ) {
  8413. attribute = this.attributes.uv;
  8414. if ( attribute !== undefined ) {
  8415. attribute.copyVector2sArray( geometry.uvs );
  8416. attribute.needsUpdate = true;
  8417. }
  8418. geometry.uvsNeedUpdate = false;
  8419. }
  8420. if ( geometry.lineDistancesNeedUpdate ) {
  8421. attribute = this.attributes.lineDistance;
  8422. if ( attribute !== undefined ) {
  8423. attribute.copyArray( geometry.lineDistances );
  8424. attribute.needsUpdate = true;
  8425. }
  8426. geometry.lineDistancesNeedUpdate = false;
  8427. }
  8428. if ( geometry.groupsNeedUpdate ) {
  8429. geometry.computeGroups( object.geometry );
  8430. this.groups = geometry.groups;
  8431. geometry.groupsNeedUpdate = false;
  8432. }
  8433. return this;
  8434. },
  8435. fromGeometry: function ( geometry ) {
  8436. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  8437. return this.fromDirectGeometry( geometry.__directGeometry );
  8438. },
  8439. fromDirectGeometry: function ( geometry ) {
  8440. var positions = new Float32Array( geometry.vertices.length * 3 );
  8441. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  8442. if ( geometry.normals.length > 0 ) {
  8443. var normals = new Float32Array( geometry.normals.length * 3 );
  8444. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  8445. }
  8446. if ( geometry.colors.length > 0 ) {
  8447. var colors = new Float32Array( geometry.colors.length * 3 );
  8448. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  8449. }
  8450. if ( geometry.uvs.length > 0 ) {
  8451. var uvs = new Float32Array( geometry.uvs.length * 2 );
  8452. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  8453. }
  8454. if ( geometry.uvs2.length > 0 ) {
  8455. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  8456. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  8457. }
  8458. if ( geometry.indices.length > 0 ) {
  8459. var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array;
  8460. var indices = new TypeArray( geometry.indices.length * 3 );
  8461. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  8462. }
  8463. // groups
  8464. this.groups = geometry.groups;
  8465. // morphs
  8466. for ( var name in geometry.morphTargets ) {
  8467. var array = [];
  8468. var morphTargets = geometry.morphTargets[ name ];
  8469. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  8470. var morphTarget = morphTargets[ i ];
  8471. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  8472. array.push( attribute.copyVector3sArray( morphTarget ) );
  8473. }
  8474. this.morphAttributes[ name ] = array;
  8475. }
  8476. // skinning
  8477. if ( geometry.skinIndices.length > 0 ) {
  8478. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  8479. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  8480. }
  8481. if ( geometry.skinWeights.length > 0 ) {
  8482. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  8483. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  8484. }
  8485. //
  8486. if ( geometry.boundingSphere !== null ) {
  8487. this.boundingSphere = geometry.boundingSphere.clone();
  8488. }
  8489. if ( geometry.boundingBox !== null ) {
  8490. this.boundingBox = geometry.boundingBox.clone();
  8491. }
  8492. return this;
  8493. },
  8494. computeBoundingBox: function () {
  8495. if ( this.boundingBox === null ) {
  8496. this.boundingBox = new Box3();
  8497. }
  8498. var positions = this.attributes.position.array;
  8499. if ( positions !== undefined ) {
  8500. this.boundingBox.setFromArray( positions );
  8501. } else {
  8502. this.boundingBox.makeEmpty();
  8503. }
  8504. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  8505. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  8506. }
  8507. },
  8508. computeBoundingSphere: function () {
  8509. var box = new Box3();
  8510. var vector = new Vector3();
  8511. return function computeBoundingSphere() {
  8512. if ( this.boundingSphere === null ) {
  8513. this.boundingSphere = new Sphere();
  8514. }
  8515. var positions = this.attributes.position;
  8516. if ( positions ) {
  8517. var array = positions.array;
  8518. var center = this.boundingSphere.center;
  8519. box.setFromArray( array );
  8520. box.getCenter( center );
  8521. // hoping to find a boundingSphere with a radius smaller than the
  8522. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  8523. var maxRadiusSq = 0;
  8524. for ( var i = 0, il = array.length; i < il; i += 3 ) {
  8525. vector.fromArray( array, i );
  8526. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  8527. }
  8528. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  8529. if ( isNaN( this.boundingSphere.radius ) ) {
  8530. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  8531. }
  8532. }
  8533. };
  8534. }(),
  8535. computeFaceNormals: function () {
  8536. // backwards compatibility
  8537. },
  8538. computeVertexNormals: function () {
  8539. var index = this.index;
  8540. var attributes = this.attributes;
  8541. var groups = this.groups;
  8542. if ( attributes.position ) {
  8543. var positions = attributes.position.array;
  8544. if ( attributes.normal === undefined ) {
  8545. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  8546. } else {
  8547. // reset existing normals to zero
  8548. var array = attributes.normal.array;
  8549. for ( var i = 0, il = array.length; i < il; i ++ ) {
  8550. array[ i ] = 0;
  8551. }
  8552. }
  8553. var normals = attributes.normal.array;
  8554. var vA, vB, vC;
  8555. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  8556. var cb = new Vector3(), ab = new Vector3();
  8557. // indexed elements
  8558. if ( index ) {
  8559. var indices = index.array;
  8560. if ( groups.length === 0 ) {
  8561. this.addGroup( 0, indices.length );
  8562. }
  8563. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  8564. var group = groups[ j ];
  8565. var start = group.start;
  8566. var count = group.count;
  8567. for ( var i = start, il = start + count; i < il; i += 3 ) {
  8568. vA = indices[ i + 0 ] * 3;
  8569. vB = indices[ i + 1 ] * 3;
  8570. vC = indices[ i + 2 ] * 3;
  8571. pA.fromArray( positions, vA );
  8572. pB.fromArray( positions, vB );
  8573. pC.fromArray( positions, vC );
  8574. cb.subVectors( pC, pB );
  8575. ab.subVectors( pA, pB );
  8576. cb.cross( ab );
  8577. normals[ vA ] += cb.x;
  8578. normals[ vA + 1 ] += cb.y;
  8579. normals[ vA + 2 ] += cb.z;
  8580. normals[ vB ] += cb.x;
  8581. normals[ vB + 1 ] += cb.y;
  8582. normals[ vB + 2 ] += cb.z;
  8583. normals[ vC ] += cb.x;
  8584. normals[ vC + 1 ] += cb.y;
  8585. normals[ vC + 2 ] += cb.z;
  8586. }
  8587. }
  8588. } else {
  8589. // non-indexed elements (unconnected triangle soup)
  8590. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  8591. pA.fromArray( positions, i );
  8592. pB.fromArray( positions, i + 3 );
  8593. pC.fromArray( positions, i + 6 );
  8594. cb.subVectors( pC, pB );
  8595. ab.subVectors( pA, pB );
  8596. cb.cross( ab );
  8597. normals[ i ] = cb.x;
  8598. normals[ i + 1 ] = cb.y;
  8599. normals[ i + 2 ] = cb.z;
  8600. normals[ i + 3 ] = cb.x;
  8601. normals[ i + 4 ] = cb.y;
  8602. normals[ i + 5 ] = cb.z;
  8603. normals[ i + 6 ] = cb.x;
  8604. normals[ i + 7 ] = cb.y;
  8605. normals[ i + 8 ] = cb.z;
  8606. }
  8607. }
  8608. this.normalizeNormals();
  8609. attributes.normal.needsUpdate = true;
  8610. }
  8611. },
  8612. merge: function ( geometry, offset ) {
  8613. if ( ( geometry && geometry.isBufferGeometry ) === false ) {
  8614. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  8615. return;
  8616. }
  8617. if ( offset === undefined ) offset = 0;
  8618. var attributes = this.attributes;
  8619. for ( var key in attributes ) {
  8620. if ( geometry.attributes[ key ] === undefined ) continue;
  8621. var attribute1 = attributes[ key ];
  8622. var attributeArray1 = attribute1.array;
  8623. var attribute2 = geometry.attributes[ key ];
  8624. var attributeArray2 = attribute2.array;
  8625. var attributeSize = attribute2.itemSize;
  8626. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  8627. attributeArray1[ j ] = attributeArray2[ i ];
  8628. }
  8629. }
  8630. return this;
  8631. },
  8632. normalizeNormals: function () {
  8633. var normals = this.attributes.normal.array;
  8634. var x, y, z, n;
  8635. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  8636. x = normals[ i ];
  8637. y = normals[ i + 1 ];
  8638. z = normals[ i + 2 ];
  8639. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  8640. normals[ i ] *= n;
  8641. normals[ i + 1 ] *= n;
  8642. normals[ i + 2 ] *= n;
  8643. }
  8644. },
  8645. toNonIndexed: function () {
  8646. if ( this.index === null ) {
  8647. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  8648. return this;
  8649. }
  8650. var geometry2 = new BufferGeometry();
  8651. var indices = this.index.array;
  8652. var attributes = this.attributes;
  8653. for ( var name in attributes ) {
  8654. var attribute = attributes[ name ];
  8655. var array = attribute.array;
  8656. var itemSize = attribute.itemSize;
  8657. var array2 = new array.constructor( indices.length * itemSize );
  8658. var index = 0, index2 = 0;
  8659. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  8660. index = indices[ i ] * itemSize;
  8661. for ( var j = 0; j < itemSize; j ++ ) {
  8662. array2[ index2 ++ ] = array[ index ++ ];
  8663. }
  8664. }
  8665. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  8666. }
  8667. return geometry2;
  8668. },
  8669. toJSON: function () {
  8670. var data = {
  8671. metadata: {
  8672. version: 4.4,
  8673. type: 'BufferGeometry',
  8674. generator: 'BufferGeometry.toJSON'
  8675. }
  8676. };
  8677. // standard BufferGeometry serialization
  8678. data.uuid = this.uuid;
  8679. data.type = this.type;
  8680. if ( this.name !== '' ) data.name = this.name;
  8681. if ( this.parameters !== undefined ) {
  8682. var parameters = this.parameters;
  8683. for ( var key in parameters ) {
  8684. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8685. }
  8686. return data;
  8687. }
  8688. data.data = { attributes: {} };
  8689. var index = this.index;
  8690. if ( index !== null ) {
  8691. var array = Array.prototype.slice.call( index.array );
  8692. data.data.index = {
  8693. type: index.array.constructor.name,
  8694. array: array
  8695. };
  8696. }
  8697. var attributes = this.attributes;
  8698. for ( var key in attributes ) {
  8699. var attribute = attributes[ key ];
  8700. var array = Array.prototype.slice.call( attribute.array );
  8701. data.data.attributes[ key ] = {
  8702. itemSize: attribute.itemSize,
  8703. type: attribute.array.constructor.name,
  8704. array: array,
  8705. normalized: attribute.normalized
  8706. };
  8707. }
  8708. var groups = this.groups;
  8709. if ( groups.length > 0 ) {
  8710. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  8711. }
  8712. var boundingSphere = this.boundingSphere;
  8713. if ( boundingSphere !== null ) {
  8714. data.data.boundingSphere = {
  8715. center: boundingSphere.center.toArray(),
  8716. radius: boundingSphere.radius
  8717. };
  8718. }
  8719. return data;
  8720. },
  8721. clone: function () {
  8722. /*
  8723. // Handle primitives
  8724. var parameters = this.parameters;
  8725. if ( parameters !== undefined ) {
  8726. var values = [];
  8727. for ( var key in parameters ) {
  8728. values.push( parameters[ key ] );
  8729. }
  8730. var geometry = Object.create( this.constructor.prototype );
  8731. this.constructor.apply( geometry, values );
  8732. return geometry;
  8733. }
  8734. return new this.constructor().copy( this );
  8735. */
  8736. return new BufferGeometry().copy( this );
  8737. },
  8738. copy: function ( source ) {
  8739. var index = source.index;
  8740. if ( index !== null ) {
  8741. this.setIndex( index.clone() );
  8742. }
  8743. var attributes = source.attributes;
  8744. for ( var name in attributes ) {
  8745. var attribute = attributes[ name ];
  8746. this.addAttribute( name, attribute.clone() );
  8747. }
  8748. var groups = source.groups;
  8749. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  8750. var group = groups[ i ];
  8751. this.addGroup( group.start, group.count, group.materialIndex );
  8752. }
  8753. return this;
  8754. },
  8755. dispose: function () {
  8756. this.dispatchEvent( { type: 'dispose' } );
  8757. }
  8758. } );
  8759. BufferGeometry.MaxIndex = 65535;
  8760. /**
  8761. * @author mrdoob / http://mrdoob.com/
  8762. * @author alteredq / http://alteredqualia.com/
  8763. * @author mikael emtinger / http://gomo.se/
  8764. * @author jonobr1 / http://jonobr1.com/
  8765. */
  8766. function Mesh( geometry, material ) {
  8767. Object3D.call( this );
  8768. this.type = 'Mesh';
  8769. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  8770. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8771. this.drawMode = TrianglesDrawMode;
  8772. this.updateMorphTargets();
  8773. }
  8774. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  8775. constructor: Mesh,
  8776. isMesh: true,
  8777. setDrawMode: function ( value ) {
  8778. this.drawMode = value;
  8779. },
  8780. copy: function ( source ) {
  8781. Object3D.prototype.copy.call( this, source );
  8782. this.drawMode = source.drawMode;
  8783. return this;
  8784. },
  8785. updateMorphTargets: function () {
  8786. var morphTargets = this.geometry.morphTargets;
  8787. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  8788. this.morphTargetInfluences = [];
  8789. this.morphTargetDictionary = {};
  8790. for ( var m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  8791. this.morphTargetInfluences.push( 0 );
  8792. this.morphTargetDictionary[ morphTargets[ m ].name ] = m;
  8793. }
  8794. }
  8795. },
  8796. raycast: ( function () {
  8797. var inverseMatrix = new Matrix4();
  8798. var ray = new Ray();
  8799. var sphere = new Sphere();
  8800. var vA = new Vector3();
  8801. var vB = new Vector3();
  8802. var vC = new Vector3();
  8803. var tempA = new Vector3();
  8804. var tempB = new Vector3();
  8805. var tempC = new Vector3();
  8806. var uvA = new Vector2();
  8807. var uvB = new Vector2();
  8808. var uvC = new Vector2();
  8809. var barycoord = new Vector3();
  8810. var intersectionPoint = new Vector3();
  8811. var intersectionPointWorld = new Vector3();
  8812. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  8813. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  8814. uv1.multiplyScalar( barycoord.x );
  8815. uv2.multiplyScalar( barycoord.y );
  8816. uv3.multiplyScalar( barycoord.z );
  8817. uv1.add( uv2 ).add( uv3 );
  8818. return uv1.clone();
  8819. }
  8820. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  8821. var intersect;
  8822. var material = object.material;
  8823. if ( material.side === BackSide ) {
  8824. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  8825. } else {
  8826. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  8827. }
  8828. if ( intersect === null ) return null;
  8829. intersectionPointWorld.copy( point );
  8830. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  8831. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  8832. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  8833. return {
  8834. distance: distance,
  8835. point: intersectionPointWorld.clone(),
  8836. object: object
  8837. };
  8838. }
  8839. function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) {
  8840. vA.fromArray( positions, a * 3 );
  8841. vB.fromArray( positions, b * 3 );
  8842. vC.fromArray( positions, c * 3 );
  8843. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  8844. if ( intersection ) {
  8845. if ( uvs ) {
  8846. uvA.fromArray( uvs, a * 2 );
  8847. uvB.fromArray( uvs, b * 2 );
  8848. uvC.fromArray( uvs, c * 2 );
  8849. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  8850. }
  8851. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  8852. intersection.faceIndex = a;
  8853. }
  8854. return intersection;
  8855. }
  8856. return function raycast( raycaster, intersects ) {
  8857. var geometry = this.geometry;
  8858. var material = this.material;
  8859. var matrixWorld = this.matrixWorld;
  8860. if ( material === undefined ) return;
  8861. // Checking boundingSphere distance to ray
  8862. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8863. sphere.copy( geometry.boundingSphere );
  8864. sphere.applyMatrix4( matrixWorld );
  8865. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  8866. //
  8867. inverseMatrix.getInverse( matrixWorld );
  8868. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8869. // Check boundingBox before continuing
  8870. if ( geometry.boundingBox !== null ) {
  8871. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  8872. }
  8873. var uvs, intersection;
  8874. if ( geometry.isBufferGeometry ) {
  8875. var a, b, c;
  8876. var index = geometry.index;
  8877. var attributes = geometry.attributes;
  8878. var positions = attributes.position.array;
  8879. if ( attributes.uv !== undefined ) {
  8880. uvs = attributes.uv.array;
  8881. }
  8882. if ( index !== null ) {
  8883. var indices = index.array;
  8884. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  8885. a = indices[ i ];
  8886. b = indices[ i + 1 ];
  8887. c = indices[ i + 2 ];
  8888. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  8889. if ( intersection ) {
  8890. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  8891. intersects.push( intersection );
  8892. }
  8893. }
  8894. } else {
  8895. for ( var i = 0, l = positions.length; i < l; i += 9 ) {
  8896. a = i / 3;
  8897. b = a + 1;
  8898. c = a + 2;
  8899. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  8900. if ( intersection ) {
  8901. intersection.index = a; // triangle number in positions buffer semantics
  8902. intersects.push( intersection );
  8903. }
  8904. }
  8905. }
  8906. } else if ( geometry.isGeometry ) {
  8907. var fvA, fvB, fvC;
  8908. var isFaceMaterial = (material && material.isMultiMaterial);
  8909. var materials = isFaceMaterial === true ? material.materials : null;
  8910. var vertices = geometry.vertices;
  8911. var faces = geometry.faces;
  8912. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  8913. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  8914. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  8915. var face = faces[ f ];
  8916. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  8917. if ( faceMaterial === undefined ) continue;
  8918. fvA = vertices[ face.a ];
  8919. fvB = vertices[ face.b ];
  8920. fvC = vertices[ face.c ];
  8921. if ( faceMaterial.morphTargets === true ) {
  8922. var morphTargets = geometry.morphTargets;
  8923. var morphInfluences = this.morphTargetInfluences;
  8924. vA.set( 0, 0, 0 );
  8925. vB.set( 0, 0, 0 );
  8926. vC.set( 0, 0, 0 );
  8927. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  8928. var influence = morphInfluences[ t ];
  8929. if ( influence === 0 ) continue;
  8930. var targets = morphTargets[ t ].vertices;
  8931. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  8932. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  8933. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  8934. }
  8935. vA.add( fvA );
  8936. vB.add( fvB );
  8937. vC.add( fvC );
  8938. fvA = vA;
  8939. fvB = vB;
  8940. fvC = vC;
  8941. }
  8942. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  8943. if ( intersection ) {
  8944. if ( uvs ) {
  8945. var uvs_f = uvs[ f ];
  8946. uvA.copy( uvs_f[ 0 ] );
  8947. uvB.copy( uvs_f[ 1 ] );
  8948. uvC.copy( uvs_f[ 2 ] );
  8949. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  8950. }
  8951. intersection.face = face;
  8952. intersection.faceIndex = f;
  8953. intersects.push( intersection );
  8954. }
  8955. }
  8956. }
  8957. };
  8958. }() ),
  8959. clone: function () {
  8960. return new this.constructor( this.geometry, this.material ).copy( this );
  8961. }
  8962. } );
  8963. /**
  8964. * @author Mugen87 / https://github.com/Mugen87
  8965. */
  8966. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  8967. BufferGeometry.call( this );
  8968. this.type = 'BoxBufferGeometry';
  8969. this.parameters = {
  8970. width: width,
  8971. height: height,
  8972. depth: depth,
  8973. widthSegments: widthSegments,
  8974. heightSegments: heightSegments,
  8975. depthSegments: depthSegments
  8976. };
  8977. var scope = this;
  8978. // segments
  8979. widthSegments = Math.floor( widthSegments ) || 1;
  8980. heightSegments = Math.floor( heightSegments ) || 1;
  8981. depthSegments = Math.floor( depthSegments ) || 1;
  8982. // these are used to calculate buffer length
  8983. var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments );
  8984. var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments );
  8985. // buffers
  8986. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  8987. var vertices = new Float32Array( vertexCount * 3 );
  8988. var normals = new Float32Array( vertexCount * 3 );
  8989. var uvs = new Float32Array( vertexCount * 2 );
  8990. // offset variables
  8991. var vertexBufferOffset = 0;
  8992. var uvBufferOffset = 0;
  8993. var indexBufferOffset = 0;
  8994. var numberOfVertices = 0;
  8995. // group variables
  8996. var groupStart = 0;
  8997. // build each side of the box geometry
  8998. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  8999. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  9000. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  9001. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  9002. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  9003. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  9004. // build geometry
  9005. this.setIndex( new BufferAttribute( indices, 1 ) );
  9006. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  9007. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  9008. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  9009. // helper functions
  9010. function calculateVertexCount( w, h, d ) {
  9011. var vertices = 0;
  9012. // calculate the amount of vertices for each side (plane)
  9013. vertices += (w + 1) * (h + 1) * 2; // xy
  9014. vertices += (w + 1) * (d + 1) * 2; // xz
  9015. vertices += (d + 1) * (h + 1) * 2; // zy
  9016. return vertices;
  9017. }
  9018. function calculateIndexCount( w, h, d ) {
  9019. var index = 0;
  9020. // calculate the amount of squares for each side
  9021. index += w * h * 2; // xy
  9022. index += w * d * 2; // xz
  9023. index += d * h * 2; // zy
  9024. return index * 6; // two triangles per square => six vertices per square
  9025. }
  9026. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  9027. var segmentWidth = width / gridX;
  9028. var segmentHeight = height / gridY;
  9029. var widthHalf = width / 2;
  9030. var heightHalf = height / 2;
  9031. var depthHalf = depth / 2;
  9032. var gridX1 = gridX + 1;
  9033. var gridY1 = gridY + 1;
  9034. var vertexCounter = 0;
  9035. var groupCount = 0;
  9036. var vector = new Vector3();
  9037. // generate vertices, normals and uvs
  9038. for ( var iy = 0; iy < gridY1; iy ++ ) {
  9039. var y = iy * segmentHeight - heightHalf;
  9040. for ( var ix = 0; ix < gridX1; ix ++ ) {
  9041. var x = ix * segmentWidth - widthHalf;
  9042. // set values to correct vector component
  9043. vector[ u ] = x * udir;
  9044. vector[ v ] = y * vdir;
  9045. vector[ w ] = depthHalf;
  9046. // now apply vector to vertex buffer
  9047. vertices[ vertexBufferOffset ] = vector.x;
  9048. vertices[ vertexBufferOffset + 1 ] = vector.y;
  9049. vertices[ vertexBufferOffset + 2 ] = vector.z;
  9050. // set values to correct vector component
  9051. vector[ u ] = 0;
  9052. vector[ v ] = 0;
  9053. vector[ w ] = depth > 0 ? 1 : - 1;
  9054. // now apply vector to normal buffer
  9055. normals[ vertexBufferOffset ] = vector.x;
  9056. normals[ vertexBufferOffset + 1 ] = vector.y;
  9057. normals[ vertexBufferOffset + 2 ] = vector.z;
  9058. // uvs
  9059. uvs[ uvBufferOffset ] = ix / gridX;
  9060. uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY );
  9061. // update offsets and counters
  9062. vertexBufferOffset += 3;
  9063. uvBufferOffset += 2;
  9064. vertexCounter += 1;
  9065. }
  9066. }
  9067. // 1. you need three indices to draw a single face
  9068. // 2. a single segment consists of two faces
  9069. // 3. so we need to generate six (2*3) indices per segment
  9070. for ( iy = 0; iy < gridY; iy ++ ) {
  9071. for ( ix = 0; ix < gridX; ix ++ ) {
  9072. // indices
  9073. var a = numberOfVertices + ix + gridX1 * iy;
  9074. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  9075. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  9076. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  9077. // face one
  9078. indices[ indexBufferOffset ] = a;
  9079. indices[ indexBufferOffset + 1 ] = b;
  9080. indices[ indexBufferOffset + 2 ] = d;
  9081. // face two
  9082. indices[ indexBufferOffset + 3 ] = b;
  9083. indices[ indexBufferOffset + 4 ] = c;
  9084. indices[ indexBufferOffset + 5 ] = d;
  9085. // update offsets and counters
  9086. indexBufferOffset += 6;
  9087. groupCount += 6;
  9088. }
  9089. }
  9090. // add a group to the geometry. this will ensure multi material support
  9091. scope.addGroup( groupStart, groupCount, materialIndex );
  9092. // calculate new start value for groups
  9093. groupStart += groupCount;
  9094. // update total number of vertices
  9095. numberOfVertices += vertexCounter;
  9096. }
  9097. }
  9098. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  9099. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  9100. /**
  9101. * @author mrdoob / http://mrdoob.com/
  9102. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  9103. */
  9104. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  9105. BufferGeometry.call( this );
  9106. this.type = 'PlaneBufferGeometry';
  9107. this.parameters = {
  9108. width: width,
  9109. height: height,
  9110. widthSegments: widthSegments,
  9111. heightSegments: heightSegments
  9112. };
  9113. var width_half = width / 2;
  9114. var height_half = height / 2;
  9115. var gridX = Math.floor( widthSegments ) || 1;
  9116. var gridY = Math.floor( heightSegments ) || 1;
  9117. var gridX1 = gridX + 1;
  9118. var gridY1 = gridY + 1;
  9119. var segment_width = width / gridX;
  9120. var segment_height = height / gridY;
  9121. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  9122. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  9123. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  9124. var offset = 0;
  9125. var offset2 = 0;
  9126. for ( var iy = 0; iy < gridY1; iy ++ ) {
  9127. var y = iy * segment_height - height_half;
  9128. for ( var ix = 0; ix < gridX1; ix ++ ) {
  9129. var x = ix * segment_width - width_half;
  9130. vertices[ offset ] = x;
  9131. vertices[ offset + 1 ] = - y;
  9132. normals[ offset + 2 ] = 1;
  9133. uvs[ offset2 ] = ix / gridX;
  9134. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  9135. offset += 3;
  9136. offset2 += 2;
  9137. }
  9138. }
  9139. offset = 0;
  9140. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  9141. for ( var iy = 0; iy < gridY; iy ++ ) {
  9142. for ( var ix = 0; ix < gridX; ix ++ ) {
  9143. var a = ix + gridX1 * iy;
  9144. var b = ix + gridX1 * ( iy + 1 );
  9145. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  9146. var d = ( ix + 1 ) + gridX1 * iy;
  9147. indices[ offset ] = a;
  9148. indices[ offset + 1 ] = b;
  9149. indices[ offset + 2 ] = d;
  9150. indices[ offset + 3 ] = b;
  9151. indices[ offset + 4 ] = c;
  9152. indices[ offset + 5 ] = d;
  9153. offset += 6;
  9154. }
  9155. }
  9156. this.setIndex( new BufferAttribute( indices, 1 ) );
  9157. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  9158. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  9159. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  9160. }
  9161. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  9162. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  9163. /**
  9164. * @author mrdoob / http://mrdoob.com/
  9165. * @author mikael emtinger / http://gomo.se/
  9166. * @author WestLangley / http://github.com/WestLangley
  9167. */
  9168. function Camera() {
  9169. Object3D.call( this );
  9170. this.type = 'Camera';
  9171. this.matrixWorldInverse = new Matrix4();
  9172. this.projectionMatrix = new Matrix4();
  9173. }
  9174. Camera.prototype = Object.create( Object3D.prototype );
  9175. Camera.prototype.constructor = Camera;
  9176. Camera.prototype.isCamera = true;
  9177. Camera.prototype.getWorldDirection = function () {
  9178. var quaternion = new Quaternion();
  9179. return function getWorldDirection( optionalTarget ) {
  9180. var result = optionalTarget || new Vector3();
  9181. this.getWorldQuaternion( quaternion );
  9182. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9183. };
  9184. }();
  9185. Camera.prototype.lookAt = function () {
  9186. // This routine does not support cameras with rotated and/or translated parent(s)
  9187. var m1 = new Matrix4();
  9188. return function lookAt( vector ) {
  9189. m1.lookAt( this.position, vector, this.up );
  9190. this.quaternion.setFromRotationMatrix( m1 );
  9191. };
  9192. }();
  9193. Camera.prototype.clone = function () {
  9194. return new this.constructor().copy( this );
  9195. };
  9196. Camera.prototype.copy = function ( source ) {
  9197. Object3D.prototype.copy.call( this, source );
  9198. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9199. this.projectionMatrix.copy( source.projectionMatrix );
  9200. return this;
  9201. };
  9202. /**
  9203. * @author mrdoob / http://mrdoob.com/
  9204. * @author greggman / http://games.greggman.com/
  9205. * @author zz85 / http://www.lab4games.net/zz85/blog
  9206. * @author tschw
  9207. */
  9208. function PerspectiveCamera( fov, aspect, near, far ) {
  9209. Camera.call( this );
  9210. this.type = 'PerspectiveCamera';
  9211. this.fov = fov !== undefined ? fov : 50;
  9212. this.zoom = 1;
  9213. this.near = near !== undefined ? near : 0.1;
  9214. this.far = far !== undefined ? far : 2000;
  9215. this.focus = 10;
  9216. this.aspect = aspect !== undefined ? aspect : 1;
  9217. this.view = null;
  9218. this.filmGauge = 35; // width of the film (default in millimeters)
  9219. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  9220. this.updateProjectionMatrix();
  9221. }
  9222. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9223. constructor: PerspectiveCamera,
  9224. isPerspectiveCamera: true,
  9225. copy: function ( source ) {
  9226. Camera.prototype.copy.call( this, source );
  9227. this.fov = source.fov;
  9228. this.zoom = source.zoom;
  9229. this.near = source.near;
  9230. this.far = source.far;
  9231. this.focus = source.focus;
  9232. this.aspect = source.aspect;
  9233. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9234. this.filmGauge = source.filmGauge;
  9235. this.filmOffset = source.filmOffset;
  9236. return this;
  9237. },
  9238. /**
  9239. * Sets the FOV by focal length in respect to the current .filmGauge.
  9240. *
  9241. * The default film gauge is 35, so that the focal length can be specified for
  9242. * a 35mm (full frame) camera.
  9243. *
  9244. * Values for focal length and film gauge must have the same unit.
  9245. */
  9246. setFocalLength: function ( focalLength ) {
  9247. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  9248. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  9249. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  9250. this.updateProjectionMatrix();
  9251. },
  9252. /**
  9253. * Calculates the focal length from the current .fov and .filmGauge.
  9254. */
  9255. getFocalLength: function () {
  9256. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  9257. return 0.5 * this.getFilmHeight() / vExtentSlope;
  9258. },
  9259. getEffectiveFOV: function () {
  9260. return _Math.RAD2DEG * 2 * Math.atan(
  9261. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  9262. },
  9263. getFilmWidth: function () {
  9264. // film not completely covered in portrait format (aspect < 1)
  9265. return this.filmGauge * Math.min( this.aspect, 1 );
  9266. },
  9267. getFilmHeight: function () {
  9268. // film not completely covered in landscape format (aspect > 1)
  9269. return this.filmGauge / Math.max( this.aspect, 1 );
  9270. },
  9271. /**
  9272. * Sets an offset in a larger frustum. This is useful for multi-window or
  9273. * multi-monitor/multi-machine setups.
  9274. *
  9275. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9276. * the monitors are in grid like this
  9277. *
  9278. * +---+---+---+
  9279. * | A | B | C |
  9280. * +---+---+---+
  9281. * | D | E | F |
  9282. * +---+---+---+
  9283. *
  9284. * then for each monitor you would call it like this
  9285. *
  9286. * var w = 1920;
  9287. * var h = 1080;
  9288. * var fullWidth = w * 3;
  9289. * var fullHeight = h * 2;
  9290. *
  9291. * --A--
  9292. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9293. * --B--
  9294. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9295. * --C--
  9296. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9297. * --D--
  9298. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9299. * --E--
  9300. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9301. * --F--
  9302. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9303. *
  9304. * Note there is no reason monitors have to be the same size or in a grid.
  9305. */
  9306. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  9307. this.aspect = fullWidth / fullHeight;
  9308. this.view = {
  9309. fullWidth: fullWidth,
  9310. fullHeight: fullHeight,
  9311. offsetX: x,
  9312. offsetY: y,
  9313. width: width,
  9314. height: height
  9315. };
  9316. this.updateProjectionMatrix();
  9317. },
  9318. clearViewOffset: function() {
  9319. this.view = null;
  9320. this.updateProjectionMatrix();
  9321. },
  9322. updateProjectionMatrix: function () {
  9323. var near = this.near,
  9324. top = near * Math.tan(
  9325. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  9326. height = 2 * top,
  9327. width = this.aspect * height,
  9328. left = - 0.5 * width,
  9329. view = this.view;
  9330. if ( view !== null ) {
  9331. var fullWidth = view.fullWidth,
  9332. fullHeight = view.fullHeight;
  9333. left += view.offsetX * width / fullWidth;
  9334. top -= view.offsetY * height / fullHeight;
  9335. width *= view.width / fullWidth;
  9336. height *= view.height / fullHeight;
  9337. }
  9338. var skew = this.filmOffset;
  9339. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  9340. this.projectionMatrix.makeFrustum(
  9341. left, left + width, top - height, top, near, this.far );
  9342. },
  9343. toJSON: function ( meta ) {
  9344. var data = Object3D.prototype.toJSON.call( this, meta );
  9345. data.object.fov = this.fov;
  9346. data.object.zoom = this.zoom;
  9347. data.object.near = this.near;
  9348. data.object.far = this.far;
  9349. data.object.focus = this.focus;
  9350. data.object.aspect = this.aspect;
  9351. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9352. data.object.filmGauge = this.filmGauge;
  9353. data.object.filmOffset = this.filmOffset;
  9354. return data;
  9355. }
  9356. } );
  9357. /**
  9358. * @author alteredq / http://alteredqualia.com/
  9359. * @author arose / http://github.com/arose
  9360. */
  9361. function OrthographicCamera( left, right, top, bottom, near, far ) {
  9362. Camera.call( this );
  9363. this.type = 'OrthographicCamera';
  9364. this.zoom = 1;
  9365. this.view = null;
  9366. this.left = left;
  9367. this.right = right;
  9368. this.top = top;
  9369. this.bottom = bottom;
  9370. this.near = ( near !== undefined ) ? near : 0.1;
  9371. this.far = ( far !== undefined ) ? far : 2000;
  9372. this.updateProjectionMatrix();
  9373. }
  9374. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9375. constructor: OrthographicCamera,
  9376. isOrthographicCamera: true,
  9377. copy: function ( source ) {
  9378. Camera.prototype.copy.call( this, source );
  9379. this.left = source.left;
  9380. this.right = source.right;
  9381. this.top = source.top;
  9382. this.bottom = source.bottom;
  9383. this.near = source.near;
  9384. this.far = source.far;
  9385. this.zoom = source.zoom;
  9386. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9387. return this;
  9388. },
  9389. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  9390. this.view = {
  9391. fullWidth: fullWidth,
  9392. fullHeight: fullHeight,
  9393. offsetX: x,
  9394. offsetY: y,
  9395. width: width,
  9396. height: height
  9397. };
  9398. this.updateProjectionMatrix();
  9399. },
  9400. clearViewOffset: function() {
  9401. this.view = null;
  9402. this.updateProjectionMatrix();
  9403. },
  9404. updateProjectionMatrix: function () {
  9405. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9406. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9407. var cx = ( this.right + this.left ) / 2;
  9408. var cy = ( this.top + this.bottom ) / 2;
  9409. var left = cx - dx;
  9410. var right = cx + dx;
  9411. var top = cy + dy;
  9412. var bottom = cy - dy;
  9413. if ( this.view !== null ) {
  9414. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  9415. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  9416. var scaleW = ( this.right - this.left ) / this.view.width;
  9417. var scaleH = ( this.top - this.bottom ) / this.view.height;
  9418. left += scaleW * ( this.view.offsetX / zoomW );
  9419. right = left + scaleW * ( this.view.width / zoomW );
  9420. top -= scaleH * ( this.view.offsetY / zoomH );
  9421. bottom = top - scaleH * ( this.view.height / zoomH );
  9422. }
  9423. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9424. },
  9425. toJSON: function ( meta ) {
  9426. var data = Object3D.prototype.toJSON.call( this, meta );
  9427. data.object.zoom = this.zoom;
  9428. data.object.left = this.left;
  9429. data.object.right = this.right;
  9430. data.object.top = this.top;
  9431. data.object.bottom = this.bottom;
  9432. data.object.near = this.near;
  9433. data.object.far = this.far;
  9434. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9435. return data;
  9436. }
  9437. } );
  9438. /**
  9439. * @author mrdoob / http://mrdoob.com/
  9440. */
  9441. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  9442. var mode;
  9443. function setMode( value ) {
  9444. mode = value;
  9445. }
  9446. var type, size;
  9447. function setIndex( index ) {
  9448. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  9449. type = gl.UNSIGNED_INT;
  9450. size = 4;
  9451. } else {
  9452. type = gl.UNSIGNED_SHORT;
  9453. size = 2;
  9454. }
  9455. }
  9456. function render( start, count ) {
  9457. gl.drawElements( mode, count, type, start * size );
  9458. infoRender.calls ++;
  9459. infoRender.vertices += count;
  9460. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9461. }
  9462. function renderInstances( geometry, start, count ) {
  9463. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9464. if ( extension === null ) {
  9465. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9466. return;
  9467. }
  9468. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  9469. infoRender.calls ++;
  9470. infoRender.vertices += count * geometry.maxInstancedCount;
  9471. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9472. }
  9473. return {
  9474. setMode: setMode,
  9475. setIndex: setIndex,
  9476. render: render,
  9477. renderInstances: renderInstances
  9478. };
  9479. }
  9480. /**
  9481. * @author mrdoob / http://mrdoob.com/
  9482. */
  9483. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  9484. var mode;
  9485. function setMode( value ) {
  9486. mode = value;
  9487. }
  9488. function render( start, count ) {
  9489. gl.drawArrays( mode, start, count );
  9490. infoRender.calls ++;
  9491. infoRender.vertices += count;
  9492. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9493. }
  9494. function renderInstances( geometry ) {
  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. var position = geometry.attributes.position;
  9501. var count = 0;
  9502. if ( position.isInterleavedBufferAttribute ) {
  9503. count = position.data.count;
  9504. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  9505. } else {
  9506. count = position.count;
  9507. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  9508. }
  9509. infoRender.calls ++;
  9510. infoRender.vertices += count * geometry.maxInstancedCount;
  9511. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9512. }
  9513. return {
  9514. setMode: setMode,
  9515. render: render,
  9516. renderInstances: renderInstances
  9517. };
  9518. }
  9519. /**
  9520. * @author mrdoob / http://mrdoob.com/
  9521. */
  9522. function WebGLLights() {
  9523. var lights = {};
  9524. return {
  9525. get: function ( light ) {
  9526. if ( lights[ light.id ] !== undefined ) {
  9527. return lights[ light.id ];
  9528. }
  9529. var uniforms;
  9530. switch ( light.type ) {
  9531. case 'DirectionalLight':
  9532. uniforms = {
  9533. direction: new Vector3(),
  9534. color: new Color(),
  9535. shadow: false,
  9536. shadowBias: 0,
  9537. shadowRadius: 1,
  9538. shadowMapSize: new Vector2()
  9539. };
  9540. break;
  9541. case 'SpotLight':
  9542. uniforms = {
  9543. position: new Vector3(),
  9544. direction: new Vector3(),
  9545. color: new Color(),
  9546. distance: 0,
  9547. coneCos: 0,
  9548. penumbraCos: 0,
  9549. decay: 0,
  9550. shadow: false,
  9551. shadowBias: 0,
  9552. shadowRadius: 1,
  9553. shadowMapSize: new Vector2()
  9554. };
  9555. break;
  9556. case 'PointLight':
  9557. uniforms = {
  9558. position: new Vector3(),
  9559. color: new Color(),
  9560. distance: 0,
  9561. decay: 0,
  9562. shadow: false,
  9563. shadowBias: 0,
  9564. shadowRadius: 1,
  9565. shadowMapSize: new Vector2()
  9566. };
  9567. break;
  9568. case 'HemisphereLight':
  9569. uniforms = {
  9570. direction: new Vector3(),
  9571. skyColor: new Color(),
  9572. groundColor: new Color()
  9573. };
  9574. break;
  9575. case 'RectAreaLight':
  9576. uniforms = {
  9577. color: new Color(),
  9578. position: new Vector3(),
  9579. halfWidth: new Vector3(),
  9580. halfHeight: new Vector3()
  9581. // TODO (abelnation): set RectAreaLight shadow uniforms
  9582. };
  9583. break;
  9584. }
  9585. lights[ light.id ] = uniforms;
  9586. return uniforms;
  9587. }
  9588. };
  9589. }
  9590. /**
  9591. * @author mrdoob / http://mrdoob.com/
  9592. */
  9593. function addLineNumbers( string ) {
  9594. var lines = string.split( '\n' );
  9595. for ( var i = 0; i < lines.length; i ++ ) {
  9596. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  9597. }
  9598. return lines.join( '\n' );
  9599. }
  9600. function WebGLShader( gl, type, string ) {
  9601. var shader = gl.createShader( type );
  9602. gl.shaderSource( shader, string );
  9603. gl.compileShader( shader );
  9604. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  9605. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  9606. }
  9607. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  9608. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  9609. }
  9610. // --enable-privileged-webgl-extension
  9611. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  9612. return shader;
  9613. }
  9614. /**
  9615. * @author mrdoob / http://mrdoob.com/
  9616. */
  9617. var programIdCount = 0;
  9618. function getEncodingComponents( encoding ) {
  9619. switch ( encoding ) {
  9620. case LinearEncoding:
  9621. return [ 'Linear','( value )' ];
  9622. case sRGBEncoding:
  9623. return [ 'sRGB','( value )' ];
  9624. case RGBEEncoding:
  9625. return [ 'RGBE','( value )' ];
  9626. case RGBM7Encoding:
  9627. return [ 'RGBM','( value, 7.0 )' ];
  9628. case RGBM16Encoding:
  9629. return [ 'RGBM','( value, 16.0 )' ];
  9630. case RGBDEncoding:
  9631. return [ 'RGBD','( value, 256.0 )' ];
  9632. case GammaEncoding:
  9633. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  9634. default:
  9635. throw new Error( 'unsupported encoding: ' + encoding );
  9636. }
  9637. }
  9638. function getTexelDecodingFunction( functionName, encoding ) {
  9639. var components = getEncodingComponents( encoding );
  9640. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  9641. }
  9642. function getTexelEncodingFunction( functionName, encoding ) {
  9643. var components = getEncodingComponents( encoding );
  9644. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  9645. }
  9646. function getToneMappingFunction( functionName, toneMapping ) {
  9647. var toneMappingName;
  9648. switch ( toneMapping ) {
  9649. case LinearToneMapping:
  9650. toneMappingName = "Linear";
  9651. break;
  9652. case ReinhardToneMapping:
  9653. toneMappingName = "Reinhard";
  9654. break;
  9655. case Uncharted2ToneMapping:
  9656. toneMappingName = "Uncharted2";
  9657. break;
  9658. case CineonToneMapping:
  9659. toneMappingName = "OptimizedCineon";
  9660. break;
  9661. default:
  9662. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  9663. }
  9664. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  9665. }
  9666. function generateExtensions( extensions, parameters, rendererExtensions ) {
  9667. extensions = extensions || {};
  9668. var chunks = [
  9669. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  9670. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  9671. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  9672. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '',
  9673. ];
  9674. return chunks.filter( filterEmptyLine ).join( '\n' );
  9675. }
  9676. function generateDefines( defines ) {
  9677. var chunks = [];
  9678. for ( var name in defines ) {
  9679. var value = defines[ name ];
  9680. if ( value === false ) continue;
  9681. chunks.push( '#define ' + name + ' ' + value );
  9682. }
  9683. return chunks.join( '\n' );
  9684. }
  9685. function fetchAttributeLocations( gl, program, identifiers ) {
  9686. var attributes = {};
  9687. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  9688. for ( var i = 0; i < n; i ++ ) {
  9689. var info = gl.getActiveAttrib( program, i );
  9690. var name = info.name;
  9691. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  9692. attributes[ name ] = gl.getAttribLocation( program, name );
  9693. }
  9694. return attributes;
  9695. }
  9696. function filterEmptyLine( string ) {
  9697. return string !== '';
  9698. }
  9699. function replaceLightNums( string, parameters ) {
  9700. return string
  9701. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  9702. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  9703. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  9704. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  9705. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  9706. }
  9707. function parseIncludes( string ) {
  9708. var pattern = /#include +<([\w\d.]+)>/g;
  9709. function replace( match, include ) {
  9710. var replace = ShaderChunk[ include ];
  9711. if ( replace === undefined ) {
  9712. throw new Error( 'Can not resolve #include <' + include + '>' );
  9713. }
  9714. return parseIncludes( replace );
  9715. }
  9716. return string.replace( pattern, replace );
  9717. }
  9718. function unrollLoops( string ) {
  9719. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  9720. function replace( match, start, end, snippet ) {
  9721. var unroll = '';
  9722. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  9723. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  9724. }
  9725. return unroll;
  9726. }
  9727. return string.replace( pattern, replace );
  9728. }
  9729. function WebGLProgram( renderer, code, material, parameters ) {
  9730. var gl = renderer.context;
  9731. var extensions = material.extensions;
  9732. var defines = material.defines;
  9733. var vertexShader = material.__webglShader.vertexShader;
  9734. var fragmentShader = material.__webglShader.fragmentShader;
  9735. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  9736. if ( parameters.shadowMapType === PCFShadowMap ) {
  9737. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  9738. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  9739. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  9740. }
  9741. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  9742. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  9743. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  9744. if ( parameters.envMap ) {
  9745. switch ( material.envMap.mapping ) {
  9746. case CubeReflectionMapping:
  9747. case CubeRefractionMapping:
  9748. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  9749. break;
  9750. case CubeUVReflectionMapping:
  9751. case CubeUVRefractionMapping:
  9752. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  9753. break;
  9754. case EquirectangularReflectionMapping:
  9755. case EquirectangularRefractionMapping:
  9756. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  9757. break;
  9758. case SphericalReflectionMapping:
  9759. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  9760. break;
  9761. }
  9762. switch ( material.envMap.mapping ) {
  9763. case CubeRefractionMapping:
  9764. case EquirectangularRefractionMapping:
  9765. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  9766. break;
  9767. }
  9768. switch ( material.combine ) {
  9769. case MultiplyOperation:
  9770. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  9771. break;
  9772. case MixOperation:
  9773. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  9774. break;
  9775. case AddOperation:
  9776. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  9777. break;
  9778. }
  9779. }
  9780. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  9781. // console.log( 'building new program ' );
  9782. //
  9783. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  9784. var customDefines = generateDefines( defines );
  9785. //
  9786. var program = gl.createProgram();
  9787. var prefixVertex, prefixFragment;
  9788. if ( material.isRawShaderMaterial ) {
  9789. prefixVertex = [
  9790. customDefines,
  9791. '\n'
  9792. ].filter( filterEmptyLine ).join( '\n' );
  9793. prefixFragment = [
  9794. customExtensions,
  9795. customDefines,
  9796. '\n'
  9797. ].filter( filterEmptyLine ).join( '\n' );
  9798. } else {
  9799. prefixVertex = [
  9800. 'precision ' + parameters.precision + ' float;',
  9801. 'precision ' + parameters.precision + ' int;',
  9802. '#define SHADER_NAME ' + material.__webglShader.name,
  9803. customDefines,
  9804. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  9805. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  9806. '#define MAX_BONES ' + parameters.maxBones,
  9807. parameters.map ? '#define USE_MAP' : '',
  9808. parameters.envMap ? '#define USE_ENVMAP' : '',
  9809. parameters.envMap ? '#define ' + envMapModeDefine : '',
  9810. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  9811. parameters.aoMap ? '#define USE_AOMAP' : '',
  9812. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  9813. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  9814. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  9815. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  9816. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  9817. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  9818. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  9819. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  9820. parameters.vertexColors ? '#define USE_COLOR' : '',
  9821. parameters.flatShading ? '#define FLAT_SHADED' : '',
  9822. parameters.skinning ? '#define USE_SKINNING' : '',
  9823. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  9824. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  9825. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  9826. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  9827. parameters.flipSided ? '#define FLIP_SIDED' : '',
  9828. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  9829. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  9830. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  9831. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  9832. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  9833. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  9834. 'uniform mat4 modelMatrix;',
  9835. 'uniform mat4 modelViewMatrix;',
  9836. 'uniform mat4 projectionMatrix;',
  9837. 'uniform mat4 viewMatrix;',
  9838. 'uniform mat3 normalMatrix;',
  9839. 'uniform vec3 cameraPosition;',
  9840. 'attribute vec3 position;',
  9841. 'attribute vec3 normal;',
  9842. 'attribute vec2 uv;',
  9843. '#ifdef USE_COLOR',
  9844. ' attribute vec3 color;',
  9845. '#endif',
  9846. '#ifdef USE_MORPHTARGETS',
  9847. ' attribute vec3 morphTarget0;',
  9848. ' attribute vec3 morphTarget1;',
  9849. ' attribute vec3 morphTarget2;',
  9850. ' attribute vec3 morphTarget3;',
  9851. ' #ifdef USE_MORPHNORMALS',
  9852. ' attribute vec3 morphNormal0;',
  9853. ' attribute vec3 morphNormal1;',
  9854. ' attribute vec3 morphNormal2;',
  9855. ' attribute vec3 morphNormal3;',
  9856. ' #else',
  9857. ' attribute vec3 morphTarget4;',
  9858. ' attribute vec3 morphTarget5;',
  9859. ' attribute vec3 morphTarget6;',
  9860. ' attribute vec3 morphTarget7;',
  9861. ' #endif',
  9862. '#endif',
  9863. '#ifdef USE_SKINNING',
  9864. ' attribute vec4 skinIndex;',
  9865. ' attribute vec4 skinWeight;',
  9866. '#endif',
  9867. '\n'
  9868. ].filter( filterEmptyLine ).join( '\n' );
  9869. prefixFragment = [
  9870. customExtensions,
  9871. 'precision ' + parameters.precision + ' float;',
  9872. 'precision ' + parameters.precision + ' int;',
  9873. '#define SHADER_NAME ' + material.__webglShader.name,
  9874. customDefines,
  9875. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  9876. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  9877. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  9878. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  9879. parameters.map ? '#define USE_MAP' : '',
  9880. parameters.envMap ? '#define USE_ENVMAP' : '',
  9881. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  9882. parameters.envMap ? '#define ' + envMapModeDefine : '',
  9883. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  9884. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  9885. parameters.aoMap ? '#define USE_AOMAP' : '',
  9886. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  9887. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  9888. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  9889. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  9890. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  9891. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  9892. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  9893. parameters.vertexColors ? '#define USE_COLOR' : '',
  9894. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  9895. parameters.flatShading ? '#define FLAT_SHADED' : '',
  9896. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  9897. parameters.flipSided ? '#define FLIP_SIDED' : '',
  9898. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  9899. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  9900. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  9901. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  9902. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  9903. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  9904. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  9905. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  9906. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  9907. 'uniform mat4 viewMatrix;',
  9908. 'uniform vec3 cameraPosition;',
  9909. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  9910. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  9911. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  9912. ( 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
  9913. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  9914. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  9915. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  9916. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  9917. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  9918. '\n'
  9919. ].filter( filterEmptyLine ).join( '\n' );
  9920. }
  9921. vertexShader = parseIncludes( vertexShader, parameters );
  9922. vertexShader = replaceLightNums( vertexShader, parameters );
  9923. fragmentShader = parseIncludes( fragmentShader, parameters );
  9924. fragmentShader = replaceLightNums( fragmentShader, parameters );
  9925. if ( ! material.isShaderMaterial ) {
  9926. vertexShader = unrollLoops( vertexShader );
  9927. fragmentShader = unrollLoops( fragmentShader );
  9928. }
  9929. var vertexGlsl = prefixVertex + vertexShader;
  9930. var fragmentGlsl = prefixFragment + fragmentShader;
  9931. // console.log( '*VERTEX*', vertexGlsl );
  9932. // console.log( '*FRAGMENT*', fragmentGlsl );
  9933. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  9934. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  9935. gl.attachShader( program, glVertexShader );
  9936. gl.attachShader( program, glFragmentShader );
  9937. // Force a particular attribute to index 0.
  9938. if ( material.index0AttributeName !== undefined ) {
  9939. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  9940. } else if ( parameters.morphTargets === true ) {
  9941. // programs with morphTargets displace position out of attribute 0
  9942. gl.bindAttribLocation( program, 0, 'position' );
  9943. }
  9944. gl.linkProgram( program );
  9945. var programLog = gl.getProgramInfoLog( program );
  9946. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  9947. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  9948. var runnable = true;
  9949. var haveDiagnostics = true;
  9950. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  9951. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  9952. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  9953. runnable = false;
  9954. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  9955. } else if ( programLog !== '' ) {
  9956. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  9957. } else if ( vertexLog === '' || fragmentLog === '' ) {
  9958. haveDiagnostics = false;
  9959. }
  9960. if ( haveDiagnostics ) {
  9961. this.diagnostics = {
  9962. runnable: runnable,
  9963. material: material,
  9964. programLog: programLog,
  9965. vertexShader: {
  9966. log: vertexLog,
  9967. prefix: prefixVertex
  9968. },
  9969. fragmentShader: {
  9970. log: fragmentLog,
  9971. prefix: prefixFragment
  9972. }
  9973. };
  9974. }
  9975. // clean up
  9976. gl.deleteShader( glVertexShader );
  9977. gl.deleteShader( glFragmentShader );
  9978. // set up caching for uniform locations
  9979. var cachedUniforms;
  9980. this.getUniforms = function() {
  9981. if ( cachedUniforms === undefined ) {
  9982. cachedUniforms =
  9983. new WebGLUniforms( gl, program, renderer );
  9984. }
  9985. return cachedUniforms;
  9986. };
  9987. // set up caching for attribute locations
  9988. var cachedAttributes;
  9989. this.getAttributes = function() {
  9990. if ( cachedAttributes === undefined ) {
  9991. cachedAttributes = fetchAttributeLocations( gl, program );
  9992. }
  9993. return cachedAttributes;
  9994. };
  9995. // free resource
  9996. this.destroy = function() {
  9997. gl.deleteProgram( program );
  9998. this.program = undefined;
  9999. };
  10000. // DEPRECATED
  10001. Object.defineProperties( this, {
  10002. uniforms: {
  10003. get: function() {
  10004. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  10005. return this.getUniforms();
  10006. }
  10007. },
  10008. attributes: {
  10009. get: function() {
  10010. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  10011. return this.getAttributes();
  10012. }
  10013. }
  10014. } );
  10015. //
  10016. this.id = programIdCount ++;
  10017. this.code = code;
  10018. this.usedTimes = 1;
  10019. this.program = program;
  10020. this.vertexShader = glVertexShader;
  10021. this.fragmentShader = glFragmentShader;
  10022. return this;
  10023. }
  10024. /**
  10025. * @author mrdoob / http://mrdoob.com/
  10026. */
  10027. function WebGLPrograms( renderer, capabilities ) {
  10028. var programs = [];
  10029. var shaderIDs = {
  10030. MeshDepthMaterial: 'depth',
  10031. MeshNormalMaterial: 'normal',
  10032. MeshBasicMaterial: 'basic',
  10033. MeshLambertMaterial: 'lambert',
  10034. MeshPhongMaterial: 'phong',
  10035. MeshToonMaterial: 'phong',
  10036. MeshStandardMaterial: 'physical',
  10037. MeshPhysicalMaterial: 'physical',
  10038. LineBasicMaterial: 'basic',
  10039. LineDashedMaterial: 'dashed',
  10040. PointsMaterial: 'points'
  10041. };
  10042. var parameterNames = [
  10043. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  10044. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  10045. "roughnessMap", "metalnessMap", "gradientMap",
  10046. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  10047. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  10048. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  10049. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  10050. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  10051. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  10052. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking"
  10053. ];
  10054. function allocateBones( object ) {
  10055. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  10056. return 1024;
  10057. } else {
  10058. // default for when object is not specified
  10059. // ( for example when prebuilding shader to be used with multiple objects )
  10060. //
  10061. // - leave some extra space for other uniforms
  10062. // - limit here is ANGLE's 254 max uniform vectors
  10063. // (up to 54 should be safe)
  10064. var nVertexUniforms = capabilities.maxVertexUniforms;
  10065. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  10066. var maxBones = nVertexMatrices;
  10067. if ( object !== undefined && (object && object.isSkinnedMesh) ) {
  10068. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  10069. if ( maxBones < object.skeleton.bones.length ) {
  10070. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  10071. }
  10072. }
  10073. return maxBones;
  10074. }
  10075. }
  10076. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  10077. var encoding;
  10078. if ( ! map ) {
  10079. encoding = LinearEncoding;
  10080. } else if ( map.isTexture ) {
  10081. encoding = map.encoding;
  10082. } else if ( map.isWebGLRenderTarget ) {
  10083. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  10084. encoding = map.texture.encoding;
  10085. }
  10086. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  10087. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  10088. encoding = GammaEncoding;
  10089. }
  10090. return encoding;
  10091. }
  10092. this.getParameters = function ( material, lights, fog, nClipPlanes, nClipIntersection, object ) {
  10093. var shaderID = shaderIDs[ material.type ];
  10094. // heuristics to create shader parameters according to lights in the scene
  10095. // (not to blow over maxLights budget)
  10096. var maxBones = allocateBones( object );
  10097. var precision = renderer.getPrecision();
  10098. if ( material.precision !== null ) {
  10099. precision = capabilities.getMaxPrecision( material.precision );
  10100. if ( precision !== material.precision ) {
  10101. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  10102. }
  10103. }
  10104. var currentRenderTarget = renderer.getCurrentRenderTarget();
  10105. var parameters = {
  10106. shaderID: shaderID,
  10107. precision: precision,
  10108. supportsVertexTextures: capabilities.vertexTextures,
  10109. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  10110. map: !! material.map,
  10111. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  10112. envMap: !! material.envMap,
  10113. envMapMode: material.envMap && material.envMap.mapping,
  10114. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  10115. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  10116. lightMap: !! material.lightMap,
  10117. aoMap: !! material.aoMap,
  10118. emissiveMap: !! material.emissiveMap,
  10119. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  10120. bumpMap: !! material.bumpMap,
  10121. normalMap: !! material.normalMap,
  10122. displacementMap: !! material.displacementMap,
  10123. roughnessMap: !! material.roughnessMap,
  10124. metalnessMap: !! material.metalnessMap,
  10125. specularMap: !! material.specularMap,
  10126. alphaMap: !! material.alphaMap,
  10127. gradientMap: !! material.gradientMap,
  10128. combine: material.combine,
  10129. vertexColors: material.vertexColors,
  10130. fog: !! fog,
  10131. useFog: material.fog,
  10132. fogExp: (fog && fog.isFogExp2),
  10133. flatShading: material.shading === FlatShading,
  10134. sizeAttenuation: material.sizeAttenuation,
  10135. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  10136. skinning: material.skinning,
  10137. maxBones: maxBones,
  10138. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  10139. morphTargets: material.morphTargets,
  10140. morphNormals: material.morphNormals,
  10141. maxMorphTargets: renderer.maxMorphTargets,
  10142. maxMorphNormals: renderer.maxMorphNormals,
  10143. numDirLights: lights.directional.length,
  10144. numPointLights: lights.point.length,
  10145. numSpotLights: lights.spot.length,
  10146. numRectAreaLights: lights.rectArea.length,
  10147. numHemiLights: lights.hemi.length,
  10148. numClippingPlanes: nClipPlanes,
  10149. numClipIntersection: nClipIntersection,
  10150. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  10151. shadowMapType: renderer.shadowMap.type,
  10152. toneMapping: renderer.toneMapping,
  10153. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10154. premultipliedAlpha: material.premultipliedAlpha,
  10155. alphaTest: material.alphaTest,
  10156. doubleSided: material.side === DoubleSide,
  10157. flipSided: material.side === BackSide,
  10158. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  10159. };
  10160. return parameters;
  10161. };
  10162. this.getProgramCode = function ( material, parameters ) {
  10163. var array = [];
  10164. if ( parameters.shaderID ) {
  10165. array.push( parameters.shaderID );
  10166. } else {
  10167. array.push( material.fragmentShader );
  10168. array.push( material.vertexShader );
  10169. }
  10170. if ( material.defines !== undefined ) {
  10171. for ( var name in material.defines ) {
  10172. array.push( name );
  10173. array.push( material.defines[ name ] );
  10174. }
  10175. }
  10176. for ( var i = 0; i < parameterNames.length; i ++ ) {
  10177. array.push( parameters[ parameterNames[ i ] ] );
  10178. }
  10179. return array.join();
  10180. };
  10181. this.acquireProgram = function ( material, parameters, code ) {
  10182. var program;
  10183. // Check if code has been already compiled
  10184. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  10185. var programInfo = programs[ p ];
  10186. if ( programInfo.code === code ) {
  10187. program = programInfo;
  10188. ++ program.usedTimes;
  10189. break;
  10190. }
  10191. }
  10192. if ( program === undefined ) {
  10193. program = new WebGLProgram( renderer, code, material, parameters );
  10194. programs.push( program );
  10195. }
  10196. return program;
  10197. };
  10198. this.releaseProgram = function( program ) {
  10199. if ( -- program.usedTimes === 0 ) {
  10200. // Remove from unordered set
  10201. var i = programs.indexOf( program );
  10202. programs[ i ] = programs[ programs.length - 1 ];
  10203. programs.pop();
  10204. // Free WebGL resources
  10205. program.destroy();
  10206. }
  10207. };
  10208. // Exposed for resource monitoring & error feedback via renderer.info:
  10209. this.programs = programs;
  10210. }
  10211. /**
  10212. * @author mrdoob / http://mrdoob.com/
  10213. */
  10214. function WebGLGeometries( gl, properties, info ) {
  10215. var geometries = {};
  10216. function onGeometryDispose( event ) {
  10217. var geometry = event.target;
  10218. var buffergeometry = geometries[ geometry.id ];
  10219. if ( buffergeometry.index !== null ) {
  10220. deleteAttribute( buffergeometry.index );
  10221. }
  10222. deleteAttributes( buffergeometry.attributes );
  10223. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10224. delete geometries[ geometry.id ];
  10225. // TODO
  10226. var property = properties.get( geometry );
  10227. if ( property.wireframe ) {
  10228. deleteAttribute( property.wireframe );
  10229. }
  10230. properties.delete( geometry );
  10231. var bufferproperty = properties.get( buffergeometry );
  10232. if ( bufferproperty.wireframe ) {
  10233. deleteAttribute( bufferproperty.wireframe );
  10234. }
  10235. properties.delete( buffergeometry );
  10236. //
  10237. info.memory.geometries --;
  10238. }
  10239. function getAttributeBuffer( attribute ) {
  10240. if ( attribute.isInterleavedBufferAttribute ) {
  10241. return properties.get( attribute.data ).__webglBuffer;
  10242. }
  10243. return properties.get( attribute ).__webglBuffer;
  10244. }
  10245. function deleteAttribute( attribute ) {
  10246. var buffer = getAttributeBuffer( attribute );
  10247. if ( buffer !== undefined ) {
  10248. gl.deleteBuffer( buffer );
  10249. removeAttributeBuffer( attribute );
  10250. }
  10251. }
  10252. function deleteAttributes( attributes ) {
  10253. for ( var name in attributes ) {
  10254. deleteAttribute( attributes[ name ] );
  10255. }
  10256. }
  10257. function removeAttributeBuffer( attribute ) {
  10258. if ( attribute.isInterleavedBufferAttribute ) {
  10259. properties.delete( attribute.data );
  10260. } else {
  10261. properties.delete( attribute );
  10262. }
  10263. }
  10264. return {
  10265. get: function ( object ) {
  10266. var geometry = object.geometry;
  10267. if ( geometries[ geometry.id ] !== undefined ) {
  10268. return geometries[ geometry.id ];
  10269. }
  10270. geometry.addEventListener( 'dispose', onGeometryDispose );
  10271. var buffergeometry;
  10272. if ( geometry.isBufferGeometry ) {
  10273. buffergeometry = geometry;
  10274. } else if ( geometry.isGeometry ) {
  10275. if ( geometry._bufferGeometry === undefined ) {
  10276. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  10277. }
  10278. buffergeometry = geometry._bufferGeometry;
  10279. }
  10280. geometries[ geometry.id ] = buffergeometry;
  10281. info.memory.geometries ++;
  10282. return buffergeometry;
  10283. }
  10284. };
  10285. }
  10286. /**
  10287. * @author mrdoob / http://mrdoob.com/
  10288. */
  10289. function WebGLObjects( gl, properties, info ) {
  10290. var geometries = new WebGLGeometries( gl, properties, info );
  10291. //
  10292. function update( object ) {
  10293. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  10294. var geometry = geometries.get( object );
  10295. if ( object.geometry.isGeometry ) {
  10296. geometry.updateFromObject( object );
  10297. }
  10298. var index = geometry.index;
  10299. var attributes = geometry.attributes;
  10300. if ( index !== null ) {
  10301. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  10302. }
  10303. for ( var name in attributes ) {
  10304. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  10305. }
  10306. // morph targets
  10307. var morphAttributes = geometry.morphAttributes;
  10308. for ( var name in morphAttributes ) {
  10309. var array = morphAttributes[ name ];
  10310. for ( var i = 0, l = array.length; i < l; i ++ ) {
  10311. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  10312. }
  10313. }
  10314. return geometry;
  10315. }
  10316. function updateAttribute( attribute, bufferType ) {
  10317. var data = ( attribute.isInterleavedBufferAttribute ) ? attribute.data : attribute;
  10318. var attributeProperties = properties.get( data );
  10319. if ( attributeProperties.__webglBuffer === undefined ) {
  10320. createBuffer( attributeProperties, data, bufferType );
  10321. } else if ( attributeProperties.version !== data.version ) {
  10322. updateBuffer( attributeProperties, data, bufferType );
  10323. }
  10324. }
  10325. function createBuffer( attributeProperties, data, bufferType ) {
  10326. attributeProperties.__webglBuffer = gl.createBuffer();
  10327. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  10328. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  10329. gl.bufferData( bufferType, data.array, usage );
  10330. var type = gl.FLOAT;
  10331. var array = data.array;
  10332. if ( array instanceof Float32Array ) {
  10333. type = gl.FLOAT;
  10334. } else if ( array instanceof Float64Array ) {
  10335. console.warn( "Unsupported data buffer format: Float64Array" );
  10336. } else if ( array instanceof Uint16Array ) {
  10337. type = gl.UNSIGNED_SHORT;
  10338. } else if ( array instanceof Int16Array ) {
  10339. type = gl.SHORT;
  10340. } else if ( array instanceof Uint32Array ) {
  10341. type = gl.UNSIGNED_INT;
  10342. } else if ( array instanceof Int32Array ) {
  10343. type = gl.INT;
  10344. } else if ( array instanceof Int8Array ) {
  10345. type = gl.BYTE;
  10346. } else if ( array instanceof Uint8Array ) {
  10347. type = gl.UNSIGNED_BYTE;
  10348. }
  10349. attributeProperties.bytesPerElement = array.BYTES_PER_ELEMENT;
  10350. attributeProperties.type = type;
  10351. attributeProperties.version = data.version;
  10352. data.onUploadCallback();
  10353. }
  10354. function updateBuffer( attributeProperties, data, bufferType ) {
  10355. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  10356. if ( data.dynamic === false ) {
  10357. gl.bufferData( bufferType, data.array, gl.STATIC_DRAW );
  10358. } else if ( data.updateRange.count === - 1 ) {
  10359. // Not using update ranges
  10360. gl.bufferSubData( bufferType, 0, data.array );
  10361. } else if ( data.updateRange.count === 0 ) {
  10362. 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.' );
  10363. } else {
  10364. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  10365. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  10366. data.updateRange.count = 0; // reset range
  10367. }
  10368. attributeProperties.version = data.version;
  10369. }
  10370. function getAttributeBuffer( attribute ) {
  10371. if ( attribute.isInterleavedBufferAttribute ) {
  10372. return properties.get( attribute.data ).__webglBuffer;
  10373. }
  10374. return properties.get( attribute ).__webglBuffer;
  10375. }
  10376. function getAttributeProperties( attribute ) {
  10377. if ( attribute.isInterleavedBufferAttribute ) {
  10378. return properties.get( attribute.data );
  10379. }
  10380. return properties.get( attribute );
  10381. }
  10382. function getWireframeAttribute( geometry ) {
  10383. var property = properties.get( geometry );
  10384. if ( property.wireframe !== undefined ) {
  10385. return property.wireframe;
  10386. }
  10387. var indices = [];
  10388. var index = geometry.index;
  10389. var attributes = geometry.attributes;
  10390. var position = attributes.position;
  10391. // console.time( 'wireframe' );
  10392. if ( index !== null ) {
  10393. var edges = {};
  10394. var array = index.array;
  10395. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  10396. var a = array[ i + 0 ];
  10397. var b = array[ i + 1 ];
  10398. var c = array[ i + 2 ];
  10399. indices.push( a, b, b, c, c, a );
  10400. }
  10401. } else {
  10402. var array = attributes.position.array;
  10403. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10404. var a = i + 0;
  10405. var b = i + 1;
  10406. var c = i + 2;
  10407. indices.push( a, b, b, c, c, a );
  10408. }
  10409. }
  10410. // console.timeEnd( 'wireframe' );
  10411. var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array;
  10412. var attribute = new BufferAttribute( new TypeArray( indices ), 1 );
  10413. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  10414. property.wireframe = attribute;
  10415. return attribute;
  10416. }
  10417. return {
  10418. getAttributeBuffer: getAttributeBuffer,
  10419. getAttributeProperties: getAttributeProperties,
  10420. getWireframeAttribute: getWireframeAttribute,
  10421. update: update
  10422. };
  10423. }
  10424. /**
  10425. * @author mrdoob / http://mrdoob.com/
  10426. */
  10427. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) {
  10428. var _infoMemory = info.memory;
  10429. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  10430. //
  10431. function clampToMaxSize( image, maxSize ) {
  10432. if ( image.width > maxSize || image.height > maxSize ) {
  10433. // Warning: Scaling through the canvas will only work with images that use
  10434. // premultiplied alpha.
  10435. var scale = maxSize / Math.max( image.width, image.height );
  10436. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10437. canvas.width = Math.floor( image.width * scale );
  10438. canvas.height = Math.floor( image.height * scale );
  10439. var context = canvas.getContext( '2d' );
  10440. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  10441. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10442. return canvas;
  10443. }
  10444. return image;
  10445. }
  10446. function isPowerOfTwo( image ) {
  10447. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  10448. }
  10449. function makePowerOfTwo( image ) {
  10450. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  10451. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10452. canvas.width = _Math.nearestPowerOfTwo( image.width );
  10453. canvas.height = _Math.nearestPowerOfTwo( image.height );
  10454. var context = canvas.getContext( '2d' );
  10455. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  10456. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10457. return canvas;
  10458. }
  10459. return image;
  10460. }
  10461. function textureNeedsPowerOfTwo( texture ) {
  10462. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) return true;
  10463. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) return true;
  10464. return false;
  10465. }
  10466. // Fallback filters for non-power-of-2 textures
  10467. function filterFallback( f ) {
  10468. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  10469. return _gl.NEAREST;
  10470. }
  10471. return _gl.LINEAR;
  10472. }
  10473. //
  10474. function onTextureDispose( event ) {
  10475. var texture = event.target;
  10476. texture.removeEventListener( 'dispose', onTextureDispose );
  10477. deallocateTexture( texture );
  10478. _infoMemory.textures --;
  10479. }
  10480. function onRenderTargetDispose( event ) {
  10481. var renderTarget = event.target;
  10482. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10483. deallocateRenderTarget( renderTarget );
  10484. _infoMemory.textures --;
  10485. }
  10486. //
  10487. function deallocateTexture( texture ) {
  10488. var textureProperties = properties.get( texture );
  10489. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  10490. // cube texture
  10491. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  10492. } else {
  10493. // 2D texture
  10494. if ( textureProperties.__webglInit === undefined ) return;
  10495. _gl.deleteTexture( textureProperties.__webglTexture );
  10496. }
  10497. // remove all webgl properties
  10498. properties.delete( texture );
  10499. }
  10500. function deallocateRenderTarget( renderTarget ) {
  10501. var renderTargetProperties = properties.get( renderTarget );
  10502. var textureProperties = properties.get( renderTarget.texture );
  10503. if ( ! renderTarget ) return;
  10504. if ( textureProperties.__webglTexture !== undefined ) {
  10505. _gl.deleteTexture( textureProperties.__webglTexture );
  10506. }
  10507. if ( renderTarget.depthTexture ) {
  10508. renderTarget.depthTexture.dispose();
  10509. }
  10510. if ( renderTarget.isWebGLRenderTargetCube ) {
  10511. for ( var i = 0; i < 6; i ++ ) {
  10512. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  10513. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  10514. }
  10515. } else {
  10516. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  10517. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  10518. }
  10519. properties.delete( renderTarget.texture );
  10520. properties.delete( renderTarget );
  10521. }
  10522. //
  10523. function setTexture2D( texture, slot ) {
  10524. var textureProperties = properties.get( texture );
  10525. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10526. var image = texture.image;
  10527. if ( image === undefined ) {
  10528. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  10529. } else if ( image.complete === false ) {
  10530. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  10531. } else {
  10532. uploadTexture( textureProperties, texture, slot );
  10533. return;
  10534. }
  10535. }
  10536. state.activeTexture( _gl.TEXTURE0 + slot );
  10537. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10538. }
  10539. function setTextureCube( texture, slot ) {
  10540. var textureProperties = properties.get( texture );
  10541. if ( texture.image.length === 6 ) {
  10542. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10543. if ( ! textureProperties.__image__webglTextureCube ) {
  10544. texture.addEventListener( 'dispose', onTextureDispose );
  10545. textureProperties.__image__webglTextureCube = _gl.createTexture();
  10546. _infoMemory.textures ++;
  10547. }
  10548. state.activeTexture( _gl.TEXTURE0 + slot );
  10549. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10550. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10551. var isCompressed = (texture && texture.isCompressedTexture);
  10552. var isDataTexture = (texture.image[ 0 ] && texture.image[ 0 ].isDataTexture);
  10553. var cubeImage = [];
  10554. for ( var i = 0; i < 6; i ++ ) {
  10555. if ( ! isCompressed && ! isDataTexture ) {
  10556. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  10557. } else {
  10558. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  10559. }
  10560. }
  10561. var image = cubeImage[ 0 ],
  10562. isPowerOfTwoImage = isPowerOfTwo( image ),
  10563. glFormat = paramThreeToGL( texture.format ),
  10564. glType = paramThreeToGL( texture.type );
  10565. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  10566. for ( var i = 0; i < 6; i ++ ) {
  10567. if ( ! isCompressed ) {
  10568. if ( isDataTexture ) {
  10569. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  10570. } else {
  10571. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  10572. }
  10573. } else {
  10574. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  10575. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  10576. mipmap = mipmaps[ j ];
  10577. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10578. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10579. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10580. } else {
  10581. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" );
  10582. }
  10583. } else {
  10584. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10585. }
  10586. }
  10587. }
  10588. }
  10589. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  10590. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  10591. }
  10592. textureProperties.__version = texture.version;
  10593. if ( texture.onUpdate ) texture.onUpdate( texture );
  10594. } else {
  10595. state.activeTexture( _gl.TEXTURE0 + slot );
  10596. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10597. }
  10598. }
  10599. }
  10600. function setTextureCubeDynamic( texture, slot ) {
  10601. state.activeTexture( _gl.TEXTURE0 + slot );
  10602. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  10603. }
  10604. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  10605. var extension;
  10606. if ( isPowerOfTwoImage ) {
  10607. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  10608. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  10609. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  10610. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  10611. } else {
  10612. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  10613. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  10614. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  10615. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  10616. }
  10617. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  10618. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  10619. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  10620. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  10621. }
  10622. }
  10623. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  10624. if ( extension ) {
  10625. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  10626. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  10627. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  10628. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  10629. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  10630. }
  10631. }
  10632. }
  10633. function uploadTexture( textureProperties, texture, slot ) {
  10634. if ( textureProperties.__webglInit === undefined ) {
  10635. textureProperties.__webglInit = true;
  10636. texture.addEventListener( 'dispose', onTextureDispose );
  10637. textureProperties.__webglTexture = _gl.createTexture();
  10638. _infoMemory.textures ++;
  10639. }
  10640. state.activeTexture( _gl.TEXTURE0 + slot );
  10641. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10642. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10643. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  10644. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  10645. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  10646. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  10647. image = makePowerOfTwo( image );
  10648. }
  10649. var isPowerOfTwoImage = isPowerOfTwo( image ),
  10650. glFormat = paramThreeToGL( texture.format ),
  10651. glType = paramThreeToGL( texture.type );
  10652. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  10653. var mipmap, mipmaps = texture.mipmaps;
  10654. if ( texture.isDepthTexture ) {
  10655. // populate depth texture with dummy data
  10656. var internalFormat = _gl.DEPTH_COMPONENT;
  10657. if ( texture.type === FloatType ) {
  10658. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  10659. internalFormat = _gl.DEPTH_COMPONENT32F;
  10660. } else if ( _isWebGL2 ) {
  10661. // WebGL 2.0 requires signed internalformat for glTexImage2D
  10662. internalFormat = _gl.DEPTH_COMPONENT16;
  10663. }
  10664. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  10665. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  10666. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  10667. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10668. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  10669. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  10670. texture.type = UnsignedShortType;
  10671. glType = paramThreeToGL( texture.type );
  10672. }
  10673. }
  10674. // Depth stencil textures need the DEPTH_STENCIL internal format
  10675. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10676. if ( texture.format === DepthStencilFormat ) {
  10677. internalFormat = _gl.DEPTH_STENCIL;
  10678. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  10679. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  10680. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10681. if ( texture.type !== UnsignedInt248Type ) {
  10682. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  10683. texture.type = UnsignedInt248Type;
  10684. glType = paramThreeToGL( texture.type );
  10685. }
  10686. }
  10687. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  10688. } else if ( texture.isDataTexture ) {
  10689. // use manually created mipmaps if available
  10690. // if there are no manual mipmaps
  10691. // set 0 level mipmap and then use GL to generate other mipmap levels
  10692. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10693. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10694. mipmap = mipmaps[ i ];
  10695. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10696. }
  10697. texture.generateMipmaps = false;
  10698. } else {
  10699. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  10700. }
  10701. } else if ( texture.isCompressedTexture ) {
  10702. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10703. mipmap = mipmaps[ i ];
  10704. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10705. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10706. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10707. } else {
  10708. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  10709. }
  10710. } else {
  10711. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10712. }
  10713. }
  10714. } else {
  10715. // regular Texture (image, video, canvas)
  10716. // use manually created mipmaps if available
  10717. // if there are no manual mipmaps
  10718. // set 0 level mipmap and then use GL to generate other mipmap levels
  10719. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10720. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10721. mipmap = mipmaps[ i ];
  10722. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  10723. }
  10724. texture.generateMipmaps = false;
  10725. } else {
  10726. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  10727. }
  10728. }
  10729. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  10730. textureProperties.__version = texture.version;
  10731. if ( texture.onUpdate ) texture.onUpdate( texture );
  10732. }
  10733. // Render targets
  10734. // Setup storage for target texture and bind it to correct framebuffer
  10735. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  10736. var glFormat = paramThreeToGL( renderTarget.texture.format );
  10737. var glType = paramThreeToGL( renderTarget.texture.type );
  10738. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  10739. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10740. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  10741. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  10742. }
  10743. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  10744. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  10745. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  10746. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  10747. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  10748. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10749. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  10750. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  10751. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10752. } else {
  10753. // FIXME: We don't support !depth !stencil
  10754. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  10755. }
  10756. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  10757. }
  10758. // Setup resources for a Depth Texture for a FBO (needs an extension)
  10759. function setupDepthTexture( framebuffer, renderTarget ) {
  10760. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  10761. if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');
  10762. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10763. if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  10764. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  10765. }
  10766. // upload an empty depth texture with framebuffer size
  10767. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  10768. renderTarget.depthTexture.image.width !== renderTarget.width ||
  10769. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  10770. renderTarget.depthTexture.image.width = renderTarget.width;
  10771. renderTarget.depthTexture.image.height = renderTarget.height;
  10772. renderTarget.depthTexture.needsUpdate = true;
  10773. }
  10774. setTexture2D( renderTarget.depthTexture, 0 );
  10775. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  10776. if ( renderTarget.depthTexture.format === DepthFormat ) {
  10777. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  10778. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  10779. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  10780. } else {
  10781. throw new Error('Unknown depthTexture format')
  10782. }
  10783. }
  10784. // Setup GL resources for a non-texture depth buffer
  10785. function setupDepthRenderbuffer( renderTarget ) {
  10786. var renderTargetProperties = properties.get( renderTarget );
  10787. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  10788. if ( renderTarget.depthTexture ) {
  10789. if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
  10790. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  10791. } else {
  10792. if ( isCube ) {
  10793. renderTargetProperties.__webglDepthbuffer = [];
  10794. for ( var i = 0; i < 6; i ++ ) {
  10795. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  10796. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  10797. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  10798. }
  10799. } else {
  10800. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  10801. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  10802. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  10803. }
  10804. }
  10805. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  10806. }
  10807. // Set up GL resources for the render target
  10808. function setupRenderTarget( renderTarget ) {
  10809. var renderTargetProperties = properties.get( renderTarget );
  10810. var textureProperties = properties.get( renderTarget.texture );
  10811. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  10812. textureProperties.__webglTexture = _gl.createTexture();
  10813. _infoMemory.textures ++;
  10814. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  10815. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  10816. // Setup framebuffer
  10817. if ( isCube ) {
  10818. renderTargetProperties.__webglFramebuffer = [];
  10819. for ( var i = 0; i < 6; i ++ ) {
  10820. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  10821. }
  10822. } else {
  10823. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  10824. }
  10825. // Setup color buffer
  10826. if ( isCube ) {
  10827. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  10828. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  10829. for ( var i = 0; i < 6; i ++ ) {
  10830. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  10831. }
  10832. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  10833. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  10834. } else {
  10835. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10836. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  10837. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  10838. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  10839. state.bindTexture( _gl.TEXTURE_2D, null );
  10840. }
  10841. // Setup depth and stencil buffers
  10842. if ( renderTarget.depthBuffer ) {
  10843. setupDepthRenderbuffer( renderTarget );
  10844. }
  10845. }
  10846. function updateRenderTargetMipmap( renderTarget ) {
  10847. var texture = renderTarget.texture;
  10848. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  10849. texture.minFilter !== NearestFilter &&
  10850. texture.minFilter !== LinearFilter ) {
  10851. var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  10852. var webglTexture = properties.get( texture ).__webglTexture;
  10853. state.bindTexture( target, webglTexture );
  10854. _gl.generateMipmap( target );
  10855. state.bindTexture( target, null );
  10856. }
  10857. }
  10858. this.setTexture2D = setTexture2D;
  10859. this.setTextureCube = setTextureCube;
  10860. this.setTextureCubeDynamic = setTextureCubeDynamic;
  10861. this.setupRenderTarget = setupRenderTarget;
  10862. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  10863. }
  10864. /**
  10865. * @author fordacious / fordacious.github.io
  10866. */
  10867. function WebGLProperties() {
  10868. var properties = {};
  10869. return {
  10870. get: function ( object ) {
  10871. var uuid = object.uuid;
  10872. var map = properties[ uuid ];
  10873. if ( map === undefined ) {
  10874. map = {};
  10875. properties[ uuid ] = map;
  10876. }
  10877. return map;
  10878. },
  10879. delete: function ( object ) {
  10880. delete properties[ object.uuid ];
  10881. },
  10882. clear: function () {
  10883. properties = {};
  10884. }
  10885. };
  10886. }
  10887. /**
  10888. * @author mrdoob / http://mrdoob.com/
  10889. */
  10890. function WebGLState( gl, extensions, paramThreeToGL ) {
  10891. function ColorBuffer() {
  10892. var locked = false;
  10893. var color = new Vector4();
  10894. var currentColorMask = null;
  10895. var currentColorClear = new Vector4();
  10896. return {
  10897. setMask: function ( colorMask ) {
  10898. if ( currentColorMask !== colorMask && ! locked ) {
  10899. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  10900. currentColorMask = colorMask;
  10901. }
  10902. },
  10903. setLocked: function ( lock ) {
  10904. locked = lock;
  10905. },
  10906. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  10907. if ( premultipliedAlpha === true ) {
  10908. r *= a; g *= a; b *= a;
  10909. }
  10910. color.set( r, g, b, a );
  10911. if ( currentColorClear.equals( color ) === false ) {
  10912. gl.clearColor( r, g, b, a );
  10913. currentColorClear.copy( color );
  10914. }
  10915. },
  10916. reset: function () {
  10917. locked = false;
  10918. currentColorMask = null;
  10919. currentColorClear.set( 0, 0, 0, 1 );
  10920. }
  10921. };
  10922. }
  10923. function DepthBuffer() {
  10924. var locked = false;
  10925. var currentDepthMask = null;
  10926. var currentDepthFunc = null;
  10927. var currentDepthClear = null;
  10928. return {
  10929. setTest: function ( depthTest ) {
  10930. if ( depthTest ) {
  10931. enable( gl.DEPTH_TEST );
  10932. } else {
  10933. disable( gl.DEPTH_TEST );
  10934. }
  10935. },
  10936. setMask: function ( depthMask ) {
  10937. if ( currentDepthMask !== depthMask && ! locked ) {
  10938. gl.depthMask( depthMask );
  10939. currentDepthMask = depthMask;
  10940. }
  10941. },
  10942. setFunc: function ( depthFunc ) {
  10943. if ( currentDepthFunc !== depthFunc ) {
  10944. if ( depthFunc ) {
  10945. switch ( depthFunc ) {
  10946. case NeverDepth:
  10947. gl.depthFunc( gl.NEVER );
  10948. break;
  10949. case AlwaysDepth:
  10950. gl.depthFunc( gl.ALWAYS );
  10951. break;
  10952. case LessDepth:
  10953. gl.depthFunc( gl.LESS );
  10954. break;
  10955. case LessEqualDepth:
  10956. gl.depthFunc( gl.LEQUAL );
  10957. break;
  10958. case EqualDepth:
  10959. gl.depthFunc( gl.EQUAL );
  10960. break;
  10961. case GreaterEqualDepth:
  10962. gl.depthFunc( gl.GEQUAL );
  10963. break;
  10964. case GreaterDepth:
  10965. gl.depthFunc( gl.GREATER );
  10966. break;
  10967. case NotEqualDepth:
  10968. gl.depthFunc( gl.NOTEQUAL );
  10969. break;
  10970. default:
  10971. gl.depthFunc( gl.LEQUAL );
  10972. }
  10973. } else {
  10974. gl.depthFunc( gl.LEQUAL );
  10975. }
  10976. currentDepthFunc = depthFunc;
  10977. }
  10978. },
  10979. setLocked: function ( lock ) {
  10980. locked = lock;
  10981. },
  10982. setClear: function ( depth ) {
  10983. if ( currentDepthClear !== depth ) {
  10984. gl.clearDepth( depth );
  10985. currentDepthClear = depth;
  10986. }
  10987. },
  10988. reset: function () {
  10989. locked = false;
  10990. currentDepthMask = null;
  10991. currentDepthFunc = null;
  10992. currentDepthClear = null;
  10993. }
  10994. };
  10995. }
  10996. function StencilBuffer() {
  10997. var locked = false;
  10998. var currentStencilMask = null;
  10999. var currentStencilFunc = null;
  11000. var currentStencilRef = null;
  11001. var currentStencilFuncMask = null;
  11002. var currentStencilFail = null;
  11003. var currentStencilZFail = null;
  11004. var currentStencilZPass = null;
  11005. var currentStencilClear = null;
  11006. return {
  11007. setTest: function ( stencilTest ) {
  11008. if ( stencilTest ) {
  11009. enable( gl.STENCIL_TEST );
  11010. } else {
  11011. disable( gl.STENCIL_TEST );
  11012. }
  11013. },
  11014. setMask: function ( stencilMask ) {
  11015. if ( currentStencilMask !== stencilMask && ! locked ) {
  11016. gl.stencilMask( stencilMask );
  11017. currentStencilMask = stencilMask;
  11018. }
  11019. },
  11020. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  11021. if ( currentStencilFunc !== stencilFunc ||
  11022. currentStencilRef !== stencilRef ||
  11023. currentStencilFuncMask !== stencilMask ) {
  11024. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  11025. currentStencilFunc = stencilFunc;
  11026. currentStencilRef = stencilRef;
  11027. currentStencilFuncMask = stencilMask;
  11028. }
  11029. },
  11030. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  11031. if ( currentStencilFail !== stencilFail ||
  11032. currentStencilZFail !== stencilZFail ||
  11033. currentStencilZPass !== stencilZPass ) {
  11034. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  11035. currentStencilFail = stencilFail;
  11036. currentStencilZFail = stencilZFail;
  11037. currentStencilZPass = stencilZPass;
  11038. }
  11039. },
  11040. setLocked: function ( lock ) {
  11041. locked = lock;
  11042. },
  11043. setClear: function ( stencil ) {
  11044. if ( currentStencilClear !== stencil ) {
  11045. gl.clearStencil( stencil );
  11046. currentStencilClear = stencil;
  11047. }
  11048. },
  11049. reset: function () {
  11050. locked = false;
  11051. currentStencilMask = null;
  11052. currentStencilFunc = null;
  11053. currentStencilRef = null;
  11054. currentStencilFuncMask = null;
  11055. currentStencilFail = null;
  11056. currentStencilZFail = null;
  11057. currentStencilZPass = null;
  11058. currentStencilClear = null;
  11059. }
  11060. };
  11061. }
  11062. //
  11063. var colorBuffer = new ColorBuffer();
  11064. var depthBuffer = new DepthBuffer();
  11065. var stencilBuffer = new StencilBuffer();
  11066. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11067. var newAttributes = new Uint8Array( maxVertexAttributes );
  11068. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  11069. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  11070. var capabilities = {};
  11071. var compressedTextureFormats = null;
  11072. var currentBlending = null;
  11073. var currentBlendEquation = null;
  11074. var currentBlendSrc = null;
  11075. var currentBlendDst = null;
  11076. var currentBlendEquationAlpha = null;
  11077. var currentBlendSrcAlpha = null;
  11078. var currentBlendDstAlpha = null;
  11079. var currentPremultipledAlpha = false;
  11080. var currentFlipSided = null;
  11081. var currentCullFace = null;
  11082. var currentLineWidth = null;
  11083. var currentPolygonOffsetFactor = null;
  11084. var currentPolygonOffsetUnits = null;
  11085. var currentScissorTest = null;
  11086. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  11087. var currentTextureSlot = null;
  11088. var currentBoundTextures = {};
  11089. var currentScissor = new Vector4();
  11090. var currentViewport = new Vector4();
  11091. function createTexture( type, target, count ) {
  11092. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  11093. var texture = gl.createTexture();
  11094. gl.bindTexture( type, texture );
  11095. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  11096. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  11097. for ( var i = 0; i < count; i ++ ) {
  11098. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  11099. }
  11100. return texture;
  11101. }
  11102. var emptyTextures = {};
  11103. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  11104. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  11105. //
  11106. function init() {
  11107. colorBuffer.setClear( 0, 0, 0, 1 );
  11108. depthBuffer.setClear( 1 );
  11109. stencilBuffer.setClear( 0 );
  11110. enable( gl.DEPTH_TEST );
  11111. setDepthFunc( LessEqualDepth );
  11112. setFlipSided( false );
  11113. setCullFace( CullFaceBack );
  11114. enable( gl.CULL_FACE );
  11115. enable( gl.BLEND );
  11116. setBlending( NormalBlending );
  11117. }
  11118. function initAttributes() {
  11119. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  11120. newAttributes[ i ] = 0;
  11121. }
  11122. }
  11123. function enableAttribute( attribute ) {
  11124. newAttributes[ attribute ] = 1;
  11125. if ( enabledAttributes[ attribute ] === 0 ) {
  11126. gl.enableVertexAttribArray( attribute );
  11127. enabledAttributes[ attribute ] = 1;
  11128. }
  11129. if ( attributeDivisors[ attribute ] !== 0 ) {
  11130. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11131. extension.vertexAttribDivisorANGLE( attribute, 0 );
  11132. attributeDivisors[ attribute ] = 0;
  11133. }
  11134. }
  11135. function enableAttributeAndDivisor( attribute, meshPerAttribute, extension ) {
  11136. newAttributes[ attribute ] = 1;
  11137. if ( enabledAttributes[ attribute ] === 0 ) {
  11138. gl.enableVertexAttribArray( attribute );
  11139. enabledAttributes[ attribute ] = 1;
  11140. }
  11141. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  11142. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  11143. attributeDivisors[ attribute ] = meshPerAttribute;
  11144. }
  11145. }
  11146. function disableUnusedAttributes() {
  11147. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  11148. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  11149. gl.disableVertexAttribArray( i );
  11150. enabledAttributes[ i ] = 0;
  11151. }
  11152. }
  11153. }
  11154. function enable( id ) {
  11155. if ( capabilities[ id ] !== true ) {
  11156. gl.enable( id );
  11157. capabilities[ id ] = true;
  11158. }
  11159. }
  11160. function disable( id ) {
  11161. if ( capabilities[ id ] !== false ) {
  11162. gl.disable( id );
  11163. capabilities[ id ] = false;
  11164. }
  11165. }
  11166. function getCompressedTextureFormats() {
  11167. if ( compressedTextureFormats === null ) {
  11168. compressedTextureFormats = [];
  11169. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  11170. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  11171. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  11172. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  11173. for ( var i = 0; i < formats.length; i ++ ) {
  11174. compressedTextureFormats.push( formats[ i ] );
  11175. }
  11176. }
  11177. }
  11178. return compressedTextureFormats;
  11179. }
  11180. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11181. if ( blending !== NoBlending ) {
  11182. enable( gl.BLEND );
  11183. } else {
  11184. disable( gl.BLEND );
  11185. }
  11186. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  11187. if ( blending === AdditiveBlending ) {
  11188. if ( premultipliedAlpha ) {
  11189. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11190. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  11191. } else {
  11192. gl.blendEquation( gl.FUNC_ADD );
  11193. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  11194. }
  11195. } else if ( blending === SubtractiveBlending ) {
  11196. if ( premultipliedAlpha ) {
  11197. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11198. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  11199. } else {
  11200. gl.blendEquation( gl.FUNC_ADD );
  11201. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  11202. }
  11203. } else if ( blending === MultiplyBlending ) {
  11204. if ( premultipliedAlpha ) {
  11205. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11206. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  11207. } else {
  11208. gl.blendEquation( gl.FUNC_ADD );
  11209. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  11210. }
  11211. } else {
  11212. if ( premultipliedAlpha ) {
  11213. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11214. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11215. } else {
  11216. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11217. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11218. }
  11219. }
  11220. currentBlending = blending;
  11221. currentPremultipledAlpha = premultipliedAlpha;
  11222. }
  11223. if ( blending === CustomBlending ) {
  11224. blendEquationAlpha = blendEquationAlpha || blendEquation;
  11225. blendSrcAlpha = blendSrcAlpha || blendSrc;
  11226. blendDstAlpha = blendDstAlpha || blendDst;
  11227. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  11228. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  11229. currentBlendEquation = blendEquation;
  11230. currentBlendEquationAlpha = blendEquationAlpha;
  11231. }
  11232. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  11233. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  11234. currentBlendSrc = blendSrc;
  11235. currentBlendDst = blendDst;
  11236. currentBlendSrcAlpha = blendSrcAlpha;
  11237. currentBlendDstAlpha = blendDstAlpha;
  11238. }
  11239. } else {
  11240. currentBlendEquation = null;
  11241. currentBlendSrc = null;
  11242. currentBlendDst = null;
  11243. currentBlendEquationAlpha = null;
  11244. currentBlendSrcAlpha = null;
  11245. currentBlendDstAlpha = null;
  11246. }
  11247. }
  11248. // TODO Deprecate
  11249. function setColorWrite( colorWrite ) {
  11250. colorBuffer.setMask( colorWrite );
  11251. }
  11252. function setDepthTest( depthTest ) {
  11253. depthBuffer.setTest( depthTest );
  11254. }
  11255. function setDepthWrite( depthWrite ) {
  11256. depthBuffer.setMask( depthWrite );
  11257. }
  11258. function setDepthFunc( depthFunc ) {
  11259. depthBuffer.setFunc( depthFunc );
  11260. }
  11261. function setStencilTest( stencilTest ) {
  11262. stencilBuffer.setTest( stencilTest );
  11263. }
  11264. function setStencilWrite( stencilWrite ) {
  11265. stencilBuffer.setMask( stencilWrite );
  11266. }
  11267. function setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  11268. stencilBuffer.setFunc( stencilFunc, stencilRef, stencilMask );
  11269. }
  11270. function setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  11271. stencilBuffer.setOp( stencilFail, stencilZFail, stencilZPass );
  11272. }
  11273. //
  11274. function setFlipSided( flipSided ) {
  11275. if ( currentFlipSided !== flipSided ) {
  11276. if ( flipSided ) {
  11277. gl.frontFace( gl.CW );
  11278. } else {
  11279. gl.frontFace( gl.CCW );
  11280. }
  11281. currentFlipSided = flipSided;
  11282. }
  11283. }
  11284. function setCullFace( cullFace ) {
  11285. if ( cullFace !== CullFaceNone ) {
  11286. enable( gl.CULL_FACE );
  11287. if ( cullFace !== currentCullFace ) {
  11288. if ( cullFace === CullFaceBack ) {
  11289. gl.cullFace( gl.BACK );
  11290. } else if ( cullFace === CullFaceFront ) {
  11291. gl.cullFace( gl.FRONT );
  11292. } else {
  11293. gl.cullFace( gl.FRONT_AND_BACK );
  11294. }
  11295. }
  11296. } else {
  11297. disable( gl.CULL_FACE );
  11298. }
  11299. currentCullFace = cullFace;
  11300. }
  11301. function setLineWidth( width ) {
  11302. if ( width !== currentLineWidth ) {
  11303. gl.lineWidth( width );
  11304. currentLineWidth = width;
  11305. }
  11306. }
  11307. function setPolygonOffset( polygonOffset, factor, units ) {
  11308. if ( polygonOffset ) {
  11309. enable( gl.POLYGON_OFFSET_FILL );
  11310. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  11311. gl.polygonOffset( factor, units );
  11312. currentPolygonOffsetFactor = factor;
  11313. currentPolygonOffsetUnits = units;
  11314. }
  11315. } else {
  11316. disable( gl.POLYGON_OFFSET_FILL );
  11317. }
  11318. }
  11319. function getScissorTest() {
  11320. return currentScissorTest;
  11321. }
  11322. function setScissorTest( scissorTest ) {
  11323. currentScissorTest = scissorTest;
  11324. if ( scissorTest ) {
  11325. enable( gl.SCISSOR_TEST );
  11326. } else {
  11327. disable( gl.SCISSOR_TEST );
  11328. }
  11329. }
  11330. // texture
  11331. function activeTexture( webglSlot ) {
  11332. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  11333. if ( currentTextureSlot !== webglSlot ) {
  11334. gl.activeTexture( webglSlot );
  11335. currentTextureSlot = webglSlot;
  11336. }
  11337. }
  11338. function bindTexture( webglType, webglTexture ) {
  11339. if ( currentTextureSlot === null ) {
  11340. activeTexture();
  11341. }
  11342. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  11343. if ( boundTexture === undefined ) {
  11344. boundTexture = { type: undefined, texture: undefined };
  11345. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  11346. }
  11347. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  11348. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  11349. boundTexture.type = webglType;
  11350. boundTexture.texture = webglTexture;
  11351. }
  11352. }
  11353. function compressedTexImage2D() {
  11354. try {
  11355. gl.compressedTexImage2D.apply( gl, arguments );
  11356. } catch ( error ) {
  11357. console.error( error );
  11358. }
  11359. }
  11360. function texImage2D() {
  11361. try {
  11362. gl.texImage2D.apply( gl, arguments );
  11363. } catch ( error ) {
  11364. console.error( error );
  11365. }
  11366. }
  11367. //
  11368. function scissor( scissor ) {
  11369. if ( currentScissor.equals( scissor ) === false ) {
  11370. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  11371. currentScissor.copy( scissor );
  11372. }
  11373. }
  11374. function viewport( viewport ) {
  11375. if ( currentViewport.equals( viewport ) === false ) {
  11376. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  11377. currentViewport.copy( viewport );
  11378. }
  11379. }
  11380. //
  11381. function reset() {
  11382. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  11383. if ( enabledAttributes[ i ] === 1 ) {
  11384. gl.disableVertexAttribArray( i );
  11385. enabledAttributes[ i ] = 0;
  11386. }
  11387. }
  11388. capabilities = {};
  11389. compressedTextureFormats = null;
  11390. currentTextureSlot = null;
  11391. currentBoundTextures = {};
  11392. currentBlending = null;
  11393. currentFlipSided = null;
  11394. currentCullFace = null;
  11395. colorBuffer.reset();
  11396. depthBuffer.reset();
  11397. stencilBuffer.reset();
  11398. }
  11399. return {
  11400. buffers: {
  11401. color: colorBuffer,
  11402. depth: depthBuffer,
  11403. stencil: stencilBuffer
  11404. },
  11405. init: init,
  11406. initAttributes: initAttributes,
  11407. enableAttribute: enableAttribute,
  11408. enableAttributeAndDivisor: enableAttributeAndDivisor,
  11409. disableUnusedAttributes: disableUnusedAttributes,
  11410. enable: enable,
  11411. disable: disable,
  11412. getCompressedTextureFormats: getCompressedTextureFormats,
  11413. setBlending: setBlending,
  11414. setColorWrite: setColorWrite,
  11415. setDepthTest: setDepthTest,
  11416. setDepthWrite: setDepthWrite,
  11417. setDepthFunc: setDepthFunc,
  11418. setStencilTest: setStencilTest,
  11419. setStencilWrite: setStencilWrite,
  11420. setStencilFunc: setStencilFunc,
  11421. setStencilOp: setStencilOp,
  11422. setFlipSided: setFlipSided,
  11423. setCullFace: setCullFace,
  11424. setLineWidth: setLineWidth,
  11425. setPolygonOffset: setPolygonOffset,
  11426. getScissorTest: getScissorTest,
  11427. setScissorTest: setScissorTest,
  11428. activeTexture: activeTexture,
  11429. bindTexture: bindTexture,
  11430. compressedTexImage2D: compressedTexImage2D,
  11431. texImage2D: texImage2D,
  11432. scissor: scissor,
  11433. viewport: viewport,
  11434. reset: reset
  11435. };
  11436. }
  11437. /**
  11438. * @author mrdoob / http://mrdoob.com/
  11439. */
  11440. function WebGLCapabilities( gl, extensions, parameters ) {
  11441. var maxAnisotropy;
  11442. function getMaxAnisotropy() {
  11443. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  11444. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  11445. if ( extension !== null ) {
  11446. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  11447. } else {
  11448. maxAnisotropy = 0;
  11449. }
  11450. return maxAnisotropy;
  11451. }
  11452. function getMaxPrecision( precision ) {
  11453. if ( precision === 'highp' ) {
  11454. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  11455. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  11456. return 'highp';
  11457. }
  11458. precision = 'mediump';
  11459. }
  11460. if ( precision === 'mediump' ) {
  11461. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  11462. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  11463. return 'mediump';
  11464. }
  11465. }
  11466. return 'lowp';
  11467. }
  11468. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  11469. var maxPrecision = getMaxPrecision( precision );
  11470. if ( maxPrecision !== precision ) {
  11471. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  11472. precision = maxPrecision;
  11473. }
  11474. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  11475. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  11476. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11477. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  11478. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11479. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11480. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  11481. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  11482. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  11483. var vertexTextures = maxVertexTextures > 0;
  11484. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  11485. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  11486. return {
  11487. getMaxAnisotropy: getMaxAnisotropy,
  11488. getMaxPrecision: getMaxPrecision,
  11489. precision: precision,
  11490. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11491. maxTextures: maxTextures,
  11492. maxVertexTextures: maxVertexTextures,
  11493. maxTextureSize: maxTextureSize,
  11494. maxCubemapSize: maxCubemapSize,
  11495. maxAttributes: maxAttributes,
  11496. maxVertexUniforms: maxVertexUniforms,
  11497. maxVaryings: maxVaryings,
  11498. maxFragmentUniforms: maxFragmentUniforms,
  11499. vertexTextures: vertexTextures,
  11500. floatFragmentTextures: floatFragmentTextures,
  11501. floatVertexTextures: floatVertexTextures
  11502. };
  11503. }
  11504. /**
  11505. * @author mrdoob / http://mrdoob.com/
  11506. */
  11507. function WebGLExtensions( gl ) {
  11508. var extensions = {};
  11509. return {
  11510. get: function ( name ) {
  11511. if ( extensions[ name ] !== undefined ) {
  11512. return extensions[ name ];
  11513. }
  11514. var extension;
  11515. switch ( name ) {
  11516. case 'WEBGL_depth_texture':
  11517. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  11518. break;
  11519. case 'EXT_texture_filter_anisotropic':
  11520. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  11521. break;
  11522. case 'WEBGL_compressed_texture_s3tc':
  11523. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  11524. break;
  11525. case 'WEBGL_compressed_texture_pvrtc':
  11526. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  11527. break;
  11528. case 'WEBGL_compressed_texture_etc1':
  11529. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  11530. break;
  11531. default:
  11532. extension = gl.getExtension( name );
  11533. }
  11534. if ( extension === null ) {
  11535. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  11536. }
  11537. extensions[ name ] = extension;
  11538. return extension;
  11539. }
  11540. };
  11541. }
  11542. /**
  11543. * @author tschw
  11544. */
  11545. function WebGLClipping() {
  11546. var scope = this,
  11547. globalState = null,
  11548. numGlobalPlanes = 0,
  11549. localClippingEnabled = false,
  11550. renderingShadows = false,
  11551. plane = new Plane(),
  11552. viewNormalMatrix = new Matrix3(),
  11553. uniform = { value: null, needsUpdate: false };
  11554. this.uniform = uniform;
  11555. this.numPlanes = 0;
  11556. this.numIntersection = 0;
  11557. this.init = function( planes, enableLocalClipping, camera ) {
  11558. var enabled =
  11559. planes.length !== 0 ||
  11560. enableLocalClipping ||
  11561. // enable state of previous frame - the clipping code has to
  11562. // run another frame in order to reset the state:
  11563. numGlobalPlanes !== 0 ||
  11564. localClippingEnabled;
  11565. localClippingEnabled = enableLocalClipping;
  11566. globalState = projectPlanes( planes, camera, 0 );
  11567. numGlobalPlanes = planes.length;
  11568. return enabled;
  11569. };
  11570. this.beginShadows = function() {
  11571. renderingShadows = true;
  11572. projectPlanes( null );
  11573. };
  11574. this.endShadows = function() {
  11575. renderingShadows = false;
  11576. resetGlobalState();
  11577. };
  11578. this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  11579. if ( ! localClippingEnabled ||
  11580. planes === null || planes.length === 0 ||
  11581. renderingShadows && ! clipShadows ) {
  11582. // there's no local clipping
  11583. if ( renderingShadows ) {
  11584. // there's no global clipping
  11585. projectPlanes( null );
  11586. } else {
  11587. resetGlobalState();
  11588. }
  11589. } else {
  11590. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  11591. lGlobal = nGlobal * 4,
  11592. dstArray = cache.clippingState || null;
  11593. uniform.value = dstArray; // ensure unique state
  11594. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  11595. for ( var i = 0; i !== lGlobal; ++ i ) {
  11596. dstArray[ i ] = globalState[ i ];
  11597. }
  11598. cache.clippingState = dstArray;
  11599. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  11600. this.numPlanes += nGlobal;
  11601. }
  11602. };
  11603. function resetGlobalState() {
  11604. if ( uniform.value !== globalState ) {
  11605. uniform.value = globalState;
  11606. uniform.needsUpdate = numGlobalPlanes > 0;
  11607. }
  11608. scope.numPlanes = numGlobalPlanes;
  11609. scope.numIntersection = 0;
  11610. }
  11611. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  11612. var nPlanes = planes !== null ? planes.length : 0,
  11613. dstArray = null;
  11614. if ( nPlanes !== 0 ) {
  11615. dstArray = uniform.value;
  11616. if ( skipTransform !== true || dstArray === null ) {
  11617. var flatSize = dstOffset + nPlanes * 4,
  11618. viewMatrix = camera.matrixWorldInverse;
  11619. viewNormalMatrix.getNormalMatrix( viewMatrix );
  11620. if ( dstArray === null || dstArray.length < flatSize ) {
  11621. dstArray = new Float32Array( flatSize );
  11622. }
  11623. for ( var i = 0, i4 = dstOffset;
  11624. i !== nPlanes; ++ i, i4 += 4 ) {
  11625. plane.copy( planes[ i ] ).
  11626. applyMatrix4( viewMatrix, viewNormalMatrix );
  11627. plane.normal.toArray( dstArray, i4 );
  11628. dstArray[ i4 + 3 ] = plane.constant;
  11629. }
  11630. }
  11631. uniform.value = dstArray;
  11632. uniform.needsUpdate = true;
  11633. }
  11634. scope.numPlanes = nPlanes;
  11635. return dstArray;
  11636. }
  11637. }
  11638. /**
  11639. * @author supereggbert / http://www.paulbrunt.co.uk/
  11640. * @author mrdoob / http://mrdoob.com/
  11641. * @author alteredq / http://alteredqualia.com/
  11642. * @author szimek / https://github.com/szimek/
  11643. * @author tschw
  11644. */
  11645. function WebGLRenderer( parameters ) {
  11646. console.log( 'THREE.WebGLRenderer', REVISION );
  11647. parameters = parameters || {};
  11648. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  11649. _context = parameters.context !== undefined ? parameters.context : null,
  11650. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11651. _depth = parameters.depth !== undefined ? parameters.depth : true,
  11652. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11653. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11654. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11655. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  11656. var lights = [];
  11657. var opaqueObjects = [];
  11658. var opaqueObjectsLastIndex = - 1;
  11659. var transparentObjects = [];
  11660. var transparentObjectsLastIndex = - 1;
  11661. var morphInfluences = new Float32Array( 8 );
  11662. var sprites = [];
  11663. var lensFlares = [];
  11664. // public properties
  11665. this.domElement = _canvas;
  11666. this.context = null;
  11667. // clearing
  11668. this.autoClear = true;
  11669. this.autoClearColor = true;
  11670. this.autoClearDepth = true;
  11671. this.autoClearStencil = true;
  11672. // scene graph
  11673. this.sortObjects = true;
  11674. // user-defined clipping
  11675. this.clippingPlanes = [];
  11676. this.localClippingEnabled = false;
  11677. // physically based shading
  11678. this.gammaFactor = 2.0; // for backwards compatibility
  11679. this.gammaInput = false;
  11680. this.gammaOutput = false;
  11681. // physical lights
  11682. this.physicallyCorrectLights = false;
  11683. // tone mapping
  11684. this.toneMapping = LinearToneMapping;
  11685. this.toneMappingExposure = 1.0;
  11686. this.toneMappingWhitePoint = 1.0;
  11687. // morphs
  11688. this.maxMorphTargets = 8;
  11689. this.maxMorphNormals = 4;
  11690. // internal properties
  11691. var _this = this,
  11692. // internal state cache
  11693. _currentProgram = null,
  11694. _currentRenderTarget = null,
  11695. _currentFramebuffer = null,
  11696. _currentMaterialId = - 1,
  11697. _currentGeometryProgram = '',
  11698. _currentCamera = null,
  11699. _currentScissor = new Vector4(),
  11700. _currentScissorTest = null,
  11701. _currentViewport = new Vector4(),
  11702. //
  11703. _usedTextureUnits = 0,
  11704. //
  11705. _clearColor = new Color( 0x000000 ),
  11706. _clearAlpha = 0,
  11707. _width = _canvas.width,
  11708. _height = _canvas.height,
  11709. _pixelRatio = 1,
  11710. _scissor = new Vector4( 0, 0, _width, _height ),
  11711. _scissorTest = false,
  11712. _viewport = new Vector4( 0, 0, _width, _height ),
  11713. // frustum
  11714. _frustum = new Frustum(),
  11715. // clipping
  11716. _clipping = new WebGLClipping(),
  11717. _clippingEnabled = false,
  11718. _localClippingEnabled = false,
  11719. _sphere = new Sphere(),
  11720. // camera matrices cache
  11721. _projScreenMatrix = new Matrix4(),
  11722. _vector3 = new Vector3(),
  11723. _matrix4 = new Matrix4(),
  11724. _matrix42 = new Matrix4(),
  11725. // light arrays cache
  11726. _lights = {
  11727. hash: '',
  11728. ambient: [ 0, 0, 0 ],
  11729. directional: [],
  11730. directionalShadowMap: [],
  11731. directionalShadowMatrix: [],
  11732. spot: [],
  11733. spotShadowMap: [],
  11734. spotShadowMatrix: [],
  11735. rectArea: [],
  11736. point: [],
  11737. pointShadowMap: [],
  11738. pointShadowMatrix: [],
  11739. hemi: [],
  11740. shadows: []
  11741. },
  11742. // info
  11743. _infoRender = {
  11744. calls: 0,
  11745. vertices: 0,
  11746. faces: 0,
  11747. points: 0
  11748. };
  11749. this.info = {
  11750. render: _infoRender,
  11751. memory: {
  11752. geometries: 0,
  11753. textures: 0
  11754. },
  11755. programs: null
  11756. };
  11757. // initialize
  11758. var _gl;
  11759. try {
  11760. var attributes = {
  11761. alpha: _alpha,
  11762. depth: _depth,
  11763. stencil: _stencil,
  11764. antialias: _antialias,
  11765. premultipliedAlpha: _premultipliedAlpha,
  11766. preserveDrawingBuffer: _preserveDrawingBuffer
  11767. };
  11768. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  11769. if ( _gl === null ) {
  11770. if ( _canvas.getContext( 'webgl' ) !== null ) {
  11771. throw 'Error creating WebGL context with your selected attributes.';
  11772. } else {
  11773. throw 'Error creating WebGL context.';
  11774. }
  11775. }
  11776. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  11777. if ( _gl.getShaderPrecisionFormat === undefined ) {
  11778. _gl.getShaderPrecisionFormat = function () {
  11779. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  11780. };
  11781. }
  11782. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  11783. } catch ( error ) {
  11784. console.error( 'THREE.WebGLRenderer: ' + error );
  11785. }
  11786. var extensions = new WebGLExtensions( _gl );
  11787. extensions.get( 'WEBGL_depth_texture' );
  11788. extensions.get( 'OES_texture_float' );
  11789. extensions.get( 'OES_texture_float_linear' );
  11790. extensions.get( 'OES_texture_half_float' );
  11791. extensions.get( 'OES_texture_half_float_linear' );
  11792. extensions.get( 'OES_standard_derivatives' );
  11793. extensions.get( 'ANGLE_instanced_arrays' );
  11794. if ( extensions.get( 'OES_element_index_uint' ) ) {
  11795. BufferGeometry.MaxIndex = 4294967296;
  11796. }
  11797. var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  11798. var state = new WebGLState( _gl, extensions, paramThreeToGL );
  11799. var properties = new WebGLProperties();
  11800. var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info );
  11801. var objects = new WebGLObjects( _gl, properties, this.info );
  11802. var programCache = new WebGLPrograms( this, capabilities );
  11803. var lightCache = new WebGLLights();
  11804. this.info.programs = programCache.programs;
  11805. var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  11806. var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  11807. //
  11808. var backgroundCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  11809. var backgroundCamera2 = new PerspectiveCamera();
  11810. var backgroundPlaneMesh = new Mesh(
  11811. new PlaneBufferGeometry( 2, 2 ),
  11812. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  11813. );
  11814. var backgroundBoxShader = ShaderLib[ 'cube' ];
  11815. var backgroundBoxMesh = new Mesh(
  11816. new BoxBufferGeometry( 5, 5, 5 ),
  11817. new ShaderMaterial( {
  11818. uniforms: backgroundBoxShader.uniforms,
  11819. vertexShader: backgroundBoxShader.vertexShader,
  11820. fragmentShader: backgroundBoxShader.fragmentShader,
  11821. side: BackSide,
  11822. depthTest: false,
  11823. depthWrite: false,
  11824. fog: false
  11825. } )
  11826. );
  11827. //
  11828. function getTargetPixelRatio() {
  11829. return _currentRenderTarget === null ? _pixelRatio : 1;
  11830. }
  11831. function setDefaultGLState() {
  11832. state.init();
  11833. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  11834. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  11835. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  11836. }
  11837. function resetGLState() {
  11838. _currentProgram = null;
  11839. _currentCamera = null;
  11840. _currentGeometryProgram = '';
  11841. _currentMaterialId = - 1;
  11842. state.reset();
  11843. }
  11844. setDefaultGLState();
  11845. this.context = _gl;
  11846. this.capabilities = capabilities;
  11847. this.extensions = extensions;
  11848. this.properties = properties;
  11849. this.state = state;
  11850. // shadow map
  11851. var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
  11852. this.shadowMap = shadowMap;
  11853. // Plugins
  11854. var spritePlugin = new SpritePlugin( this, sprites );
  11855. var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
  11856. // API
  11857. this.getContext = function () {
  11858. return _gl;
  11859. };
  11860. this.getContextAttributes = function () {
  11861. return _gl.getContextAttributes();
  11862. };
  11863. this.forceContextLoss = function () {
  11864. extensions.get( 'WEBGL_lose_context' ).loseContext();
  11865. };
  11866. this.getMaxAnisotropy = function () {
  11867. return capabilities.getMaxAnisotropy();
  11868. };
  11869. this.getPrecision = function () {
  11870. return capabilities.precision;
  11871. };
  11872. this.getPixelRatio = function () {
  11873. return _pixelRatio;
  11874. };
  11875. this.setPixelRatio = function ( value ) {
  11876. if ( value === undefined ) return;
  11877. _pixelRatio = value;
  11878. this.setSize( _viewport.z, _viewport.w, false );
  11879. };
  11880. this.getSize = function () {
  11881. return {
  11882. width: _width,
  11883. height: _height
  11884. };
  11885. };
  11886. this.setSize = function ( width, height, updateStyle ) {
  11887. _width = width;
  11888. _height = height;
  11889. _canvas.width = width * _pixelRatio;
  11890. _canvas.height = height * _pixelRatio;
  11891. if ( updateStyle !== false ) {
  11892. _canvas.style.width = width + 'px';
  11893. _canvas.style.height = height + 'px';
  11894. }
  11895. this.setViewport( 0, 0, width, height );
  11896. };
  11897. this.setViewport = function ( x, y, width, height ) {
  11898. state.viewport( _viewport.set( x, y, width, height ) );
  11899. };
  11900. this.setScissor = function ( x, y, width, height ) {
  11901. state.scissor( _scissor.set( x, y, width, height ) );
  11902. };
  11903. this.setScissorTest = function ( boolean ) {
  11904. state.setScissorTest( _scissorTest = boolean );
  11905. };
  11906. // Clearing
  11907. this.getClearColor = function () {
  11908. return _clearColor;
  11909. };
  11910. this.setClearColor = function ( color, alpha ) {
  11911. _clearColor.set( color );
  11912. _clearAlpha = alpha !== undefined ? alpha : 1;
  11913. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  11914. };
  11915. this.getClearAlpha = function () {
  11916. return _clearAlpha;
  11917. };
  11918. this.setClearAlpha = function ( alpha ) {
  11919. _clearAlpha = alpha;
  11920. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  11921. };
  11922. this.clear = function ( color, depth, stencil ) {
  11923. var bits = 0;
  11924. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11925. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11926. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11927. _gl.clear( bits );
  11928. };
  11929. this.clearColor = function () {
  11930. this.clear( true, false, false );
  11931. };
  11932. this.clearDepth = function () {
  11933. this.clear( false, true, false );
  11934. };
  11935. this.clearStencil = function () {
  11936. this.clear( false, false, true );
  11937. };
  11938. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11939. this.setRenderTarget( renderTarget );
  11940. this.clear( color, depth, stencil );
  11941. };
  11942. // Reset
  11943. this.resetGLState = resetGLState;
  11944. this.dispose = function() {
  11945. transparentObjects = [];
  11946. transparentObjectsLastIndex = -1;
  11947. opaqueObjects = [];
  11948. opaqueObjectsLastIndex = -1;
  11949. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  11950. };
  11951. // Events
  11952. function onContextLost( event ) {
  11953. event.preventDefault();
  11954. resetGLState();
  11955. setDefaultGLState();
  11956. properties.clear();
  11957. }
  11958. function onMaterialDispose( event ) {
  11959. var material = event.target;
  11960. material.removeEventListener( 'dispose', onMaterialDispose );
  11961. deallocateMaterial( material );
  11962. }
  11963. // Buffer deallocation
  11964. function deallocateMaterial( material ) {
  11965. releaseMaterialProgramReference( material );
  11966. properties.delete( material );
  11967. }
  11968. function releaseMaterialProgramReference( material ) {
  11969. var programInfo = properties.get( material ).program;
  11970. material.program = undefined;
  11971. if ( programInfo !== undefined ) {
  11972. programCache.releaseProgram( programInfo );
  11973. }
  11974. }
  11975. // Buffer rendering
  11976. this.renderBufferImmediate = function ( object, program, material ) {
  11977. state.initAttributes();
  11978. var buffers = properties.get( object );
  11979. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  11980. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  11981. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  11982. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  11983. var attributes = program.getAttributes();
  11984. if ( object.hasPositions ) {
  11985. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  11986. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11987. state.enableAttribute( attributes.position );
  11988. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11989. }
  11990. if ( object.hasNormals ) {
  11991. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  11992. if ( ! material.isMeshPhongMaterial &&
  11993. ! material.isMeshStandardMaterial &&
  11994. material.shading === FlatShading ) {
  11995. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  11996. var array = object.normalArray;
  11997. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  11998. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  11999. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  12000. array[ i + 0 ] = nx;
  12001. array[ i + 1 ] = ny;
  12002. array[ i + 2 ] = nz;
  12003. array[ i + 3 ] = nx;
  12004. array[ i + 4 ] = ny;
  12005. array[ i + 5 ] = nz;
  12006. array[ i + 6 ] = nx;
  12007. array[ i + 7 ] = ny;
  12008. array[ i + 8 ] = nz;
  12009. }
  12010. }
  12011. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12012. state.enableAttribute( attributes.normal );
  12013. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12014. }
  12015. if ( object.hasUvs && material.map ) {
  12016. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  12017. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12018. state.enableAttribute( attributes.uv );
  12019. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12020. }
  12021. if ( object.hasColors && material.vertexColors !== NoColors ) {
  12022. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  12023. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12024. state.enableAttribute( attributes.color );
  12025. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12026. }
  12027. state.disableUnusedAttributes();
  12028. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12029. object.count = 0;
  12030. };
  12031. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  12032. setMaterial( material );
  12033. var program = setProgram( camera, fog, material, object );
  12034. var updateBuffers = false;
  12035. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  12036. if ( geometryProgram !== _currentGeometryProgram ) {
  12037. _currentGeometryProgram = geometryProgram;
  12038. updateBuffers = true;
  12039. }
  12040. // morph targets
  12041. var morphTargetInfluences = object.morphTargetInfluences;
  12042. if ( morphTargetInfluences !== undefined ) {
  12043. var activeInfluences = [];
  12044. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  12045. var influence = morphTargetInfluences[ i ];
  12046. activeInfluences.push( [ influence, i ] );
  12047. }
  12048. activeInfluences.sort( absNumericalSort );
  12049. if ( activeInfluences.length > 8 ) {
  12050. activeInfluences.length = 8;
  12051. }
  12052. var morphAttributes = geometry.morphAttributes;
  12053. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  12054. var influence = activeInfluences[ i ];
  12055. morphInfluences[ i ] = influence[ 0 ];
  12056. if ( influence[ 0 ] !== 0 ) {
  12057. var index = influence[ 1 ];
  12058. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  12059. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  12060. } else {
  12061. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  12062. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  12063. }
  12064. }
  12065. for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) {
  12066. morphInfluences[ i ] = 0.0;
  12067. }
  12068. program.getUniforms().setValue(
  12069. _gl, 'morphTargetInfluences', morphInfluences );
  12070. updateBuffers = true;
  12071. }
  12072. //
  12073. var index = geometry.index;
  12074. var position = geometry.attributes.position;
  12075. var rangeFactor = 1;
  12076. if ( material.wireframe === true ) {
  12077. index = objects.getWireframeAttribute( geometry );
  12078. rangeFactor = 2;
  12079. }
  12080. var renderer;
  12081. if ( index !== null ) {
  12082. renderer = indexedBufferRenderer;
  12083. renderer.setIndex( index );
  12084. } else {
  12085. renderer = bufferRenderer;
  12086. }
  12087. if ( updateBuffers ) {
  12088. setupVertexAttributes( material, program, geometry );
  12089. if ( index !== null ) {
  12090. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  12091. }
  12092. }
  12093. //
  12094. var dataCount = 0;
  12095. if ( index !== null ) {
  12096. dataCount = index.count;
  12097. } else if ( position !== undefined ) {
  12098. dataCount = position.count;
  12099. }
  12100. var rangeStart = geometry.drawRange.start * rangeFactor;
  12101. var rangeCount = geometry.drawRange.count * rangeFactor;
  12102. var groupStart = group !== null ? group.start * rangeFactor : 0;
  12103. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  12104. var drawStart = Math.max( rangeStart, groupStart );
  12105. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  12106. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  12107. if ( drawCount === 0 ) return;
  12108. //
  12109. if ( object.isMesh ) {
  12110. if ( material.wireframe === true ) {
  12111. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  12112. renderer.setMode( _gl.LINES );
  12113. } else {
  12114. switch ( object.drawMode ) {
  12115. case TrianglesDrawMode:
  12116. renderer.setMode( _gl.TRIANGLES );
  12117. break;
  12118. case TriangleStripDrawMode:
  12119. renderer.setMode( _gl.TRIANGLE_STRIP );
  12120. break;
  12121. case TriangleFanDrawMode:
  12122. renderer.setMode( _gl.TRIANGLE_FAN );
  12123. break;
  12124. }
  12125. }
  12126. } else if ( object.isLine ) {
  12127. var lineWidth = material.linewidth;
  12128. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  12129. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  12130. if ( object.isLineSegments ) {
  12131. renderer.setMode( _gl.LINES );
  12132. } else {
  12133. renderer.setMode( _gl.LINE_STRIP );
  12134. }
  12135. } else if ( object.isPoints ) {
  12136. renderer.setMode( _gl.POINTS );
  12137. }
  12138. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12139. if ( geometry.maxInstancedCount > 0 ) {
  12140. renderer.renderInstances( geometry, drawStart, drawCount );
  12141. }
  12142. } else {
  12143. renderer.render( drawStart, drawCount );
  12144. }
  12145. };
  12146. function setupVertexAttributes( material, program, geometry, startIndex ) {
  12147. var extension;
  12148. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12149. extension = extensions.get( 'ANGLE_instanced_arrays' );
  12150. if ( extension === null ) {
  12151. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12152. return;
  12153. }
  12154. }
  12155. if ( startIndex === undefined ) startIndex = 0;
  12156. state.initAttributes();
  12157. var geometryAttributes = geometry.attributes;
  12158. var programAttributes = program.getAttributes();
  12159. var materialDefaultAttributeValues = material.defaultAttributeValues;
  12160. for ( var name in programAttributes ) {
  12161. var programAttribute = programAttributes[ name ];
  12162. if ( programAttribute >= 0 ) {
  12163. var geometryAttribute = geometryAttributes[ name ];
  12164. if ( geometryAttribute !== undefined ) {
  12165. var normalized = geometryAttribute.normalized;
  12166. var size = geometryAttribute.itemSize;
  12167. var attributeProperties = objects.getAttributeProperties( geometryAttribute );
  12168. var buffer = attributeProperties.__webglBuffer;
  12169. var type = attributeProperties.type;
  12170. var bytesPerElement = attributeProperties.bytesPerElement;
  12171. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  12172. var data = geometryAttribute.data;
  12173. var stride = data.stride;
  12174. var offset = geometryAttribute.offset;
  12175. if ( data && data.isInstancedInterleavedBuffer ) {
  12176. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  12177. if ( geometry.maxInstancedCount === undefined ) {
  12178. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  12179. }
  12180. } else {
  12181. state.enableAttribute( programAttribute );
  12182. }
  12183. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12184. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  12185. } else {
  12186. if ( geometryAttribute.isInstancedBufferAttribute ) {
  12187. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  12188. if ( geometry.maxInstancedCount === undefined ) {
  12189. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  12190. }
  12191. } else {
  12192. state.enableAttribute( programAttribute );
  12193. }
  12194. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12195. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  12196. }
  12197. } else if ( materialDefaultAttributeValues !== undefined ) {
  12198. var value = materialDefaultAttributeValues[ name ];
  12199. if ( value !== undefined ) {
  12200. switch ( value.length ) {
  12201. case 2:
  12202. _gl.vertexAttrib2fv( programAttribute, value );
  12203. break;
  12204. case 3:
  12205. _gl.vertexAttrib3fv( programAttribute, value );
  12206. break;
  12207. case 4:
  12208. _gl.vertexAttrib4fv( programAttribute, value );
  12209. break;
  12210. default:
  12211. _gl.vertexAttrib1fv( programAttribute, value );
  12212. }
  12213. }
  12214. }
  12215. }
  12216. }
  12217. state.disableUnusedAttributes();
  12218. }
  12219. // Sorting
  12220. function absNumericalSort( a, b ) {
  12221. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  12222. }
  12223. function painterSortStable( a, b ) {
  12224. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12225. return a.object.renderOrder - b.object.renderOrder;
  12226. } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) {
  12227. return a.material.program.id - b.material.program.id;
  12228. } else if ( a.material.id !== b.material.id ) {
  12229. return a.material.id - b.material.id;
  12230. } else if ( a.z !== b.z ) {
  12231. return a.z - b.z;
  12232. } else {
  12233. return a.id - b.id;
  12234. }
  12235. }
  12236. function reversePainterSortStable( a, b ) {
  12237. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12238. return a.object.renderOrder - b.object.renderOrder;
  12239. } if ( a.z !== b.z ) {
  12240. return b.z - a.z;
  12241. } else {
  12242. return a.id - b.id;
  12243. }
  12244. }
  12245. // Rendering
  12246. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12247. if ( camera !== undefined && camera.isCamera !== true ) {
  12248. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12249. return;
  12250. }
  12251. // reset caching for this frame
  12252. _currentGeometryProgram = '';
  12253. _currentMaterialId = - 1;
  12254. _currentCamera = null;
  12255. // update scene graph
  12256. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12257. // update camera matrices and frustum
  12258. if ( camera.parent === null ) camera.updateMatrixWorld();
  12259. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12260. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12261. _frustum.setFromMatrix( _projScreenMatrix );
  12262. lights.length = 0;
  12263. opaqueObjectsLastIndex = - 1;
  12264. transparentObjectsLastIndex = - 1;
  12265. sprites.length = 0;
  12266. lensFlares.length = 0;
  12267. _localClippingEnabled = this.localClippingEnabled;
  12268. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  12269. projectObject( scene, camera );
  12270. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  12271. transparentObjects.length = transparentObjectsLastIndex + 1;
  12272. if ( _this.sortObjects === true ) {
  12273. opaqueObjects.sort( painterSortStable );
  12274. transparentObjects.sort( reversePainterSortStable );
  12275. }
  12276. //
  12277. if ( _clippingEnabled ) _clipping.beginShadows();
  12278. setupShadows( lights );
  12279. shadowMap.render( scene, camera );
  12280. setupLights( lights, camera );
  12281. if ( _clippingEnabled ) _clipping.endShadows();
  12282. //
  12283. _infoRender.calls = 0;
  12284. _infoRender.vertices = 0;
  12285. _infoRender.faces = 0;
  12286. _infoRender.points = 0;
  12287. if ( renderTarget === undefined ) {
  12288. renderTarget = null;
  12289. }
  12290. this.setRenderTarget( renderTarget );
  12291. //
  12292. var background = scene.background;
  12293. if ( background === null ) {
  12294. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  12295. } else if ( background && background.isColor ) {
  12296. state.buffers.color.setClear( background.r, background.g, background.b, 1, _premultipliedAlpha );
  12297. forceClear = true;
  12298. }
  12299. if ( this.autoClear || forceClear ) {
  12300. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12301. }
  12302. if ( background && background.isCubeTexture ) {
  12303. backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix );
  12304. backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld );
  12305. backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld );
  12306. backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
  12307. backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
  12308. objects.update( backgroundBoxMesh );
  12309. _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
  12310. } else if ( background && background.isTexture ) {
  12311. backgroundPlaneMesh.material.map = background;
  12312. objects.update( backgroundPlaneMesh );
  12313. _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
  12314. }
  12315. //
  12316. if ( scene.overrideMaterial ) {
  12317. var overrideMaterial = scene.overrideMaterial;
  12318. renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  12319. renderObjects( transparentObjects, scene, camera, overrideMaterial );
  12320. } else {
  12321. // opaque pass (front-to-back order)
  12322. state.setBlending( NoBlending );
  12323. renderObjects( opaqueObjects, scene, camera );
  12324. // transparent pass (back-to-front order)
  12325. renderObjects( transparentObjects, scene, camera );
  12326. }
  12327. // custom render plugins (post pass)
  12328. spritePlugin.render( scene, camera );
  12329. lensFlarePlugin.render( scene, camera, _currentViewport );
  12330. // Generate mipmap if we're using any kind of mipmap filtering
  12331. if ( renderTarget ) {
  12332. textures.updateRenderTargetMipmap( renderTarget );
  12333. }
  12334. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12335. state.setDepthTest( true );
  12336. state.setDepthWrite( true );
  12337. state.setColorWrite( true );
  12338. // _gl.finish();
  12339. };
  12340. function pushRenderItem( object, geometry, material, z, group ) {
  12341. var array, index;
  12342. // allocate the next position in the appropriate array
  12343. if ( material.transparent ) {
  12344. array = transparentObjects;
  12345. index = ++ transparentObjectsLastIndex;
  12346. } else {
  12347. array = opaqueObjects;
  12348. index = ++ opaqueObjectsLastIndex;
  12349. }
  12350. // recycle existing render item or grow the array
  12351. var renderItem = array[ index ];
  12352. if ( renderItem !== undefined ) {
  12353. renderItem.id = object.id;
  12354. renderItem.object = object;
  12355. renderItem.geometry = geometry;
  12356. renderItem.material = material;
  12357. renderItem.z = _vector3.z;
  12358. renderItem.group = group;
  12359. } else {
  12360. renderItem = {
  12361. id: object.id,
  12362. object: object,
  12363. geometry: geometry,
  12364. material: material,
  12365. z: _vector3.z,
  12366. group: group
  12367. };
  12368. // assert( index === array.length );
  12369. array.push( renderItem );
  12370. }
  12371. }
  12372. // TODO Duplicated code (Frustum)
  12373. function isObjectViewable( object ) {
  12374. var geometry = object.geometry;
  12375. if ( geometry.boundingSphere === null )
  12376. geometry.computeBoundingSphere();
  12377. _sphere.copy( geometry.boundingSphere ).
  12378. applyMatrix4( object.matrixWorld );
  12379. return isSphereViewable( _sphere );
  12380. }
  12381. function isSpriteViewable( sprite ) {
  12382. _sphere.center.set( 0, 0, 0 );
  12383. _sphere.radius = 0.7071067811865476;
  12384. _sphere.applyMatrix4( sprite.matrixWorld );
  12385. return isSphereViewable( _sphere );
  12386. }
  12387. function isSphereViewable( sphere ) {
  12388. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  12389. var numPlanes = _clipping.numPlanes;
  12390. if ( numPlanes === 0 ) return true;
  12391. var planes = _this.clippingPlanes,
  12392. center = sphere.center,
  12393. negRad = - sphere.radius,
  12394. i = 0;
  12395. do {
  12396. // out when deeper than radius in the negative halfspace
  12397. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  12398. } while ( ++ i !== numPlanes );
  12399. return true;
  12400. }
  12401. function projectObject( object, camera ) {
  12402. if ( object.visible === false ) return;
  12403. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  12404. if ( visible ) {
  12405. if ( object.isLight ) {
  12406. lights.push( object );
  12407. } else if ( object.isSprite ) {
  12408. if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) {
  12409. sprites.push( object );
  12410. }
  12411. } else if ( object.isLensFlare ) {
  12412. lensFlares.push( object );
  12413. } else if ( object.isImmediateRenderObject ) {
  12414. if ( _this.sortObjects === true ) {
  12415. _vector3.setFromMatrixPosition( object.matrixWorld );
  12416. _vector3.applyProjection( _projScreenMatrix );
  12417. }
  12418. pushRenderItem( object, null, object.material, _vector3.z, null );
  12419. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  12420. if ( object.isSkinnedMesh ) {
  12421. object.skeleton.update();
  12422. }
  12423. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  12424. var material = object.material;
  12425. if ( material.visible === true ) {
  12426. if ( _this.sortObjects === true ) {
  12427. _vector3.setFromMatrixPosition( object.matrixWorld );
  12428. _vector3.applyProjection( _projScreenMatrix );
  12429. }
  12430. var geometry = objects.update( object );
  12431. if ( material.isMultiMaterial ) {
  12432. var groups = geometry.groups;
  12433. var materials = material.materials;
  12434. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  12435. var group = groups[ i ];
  12436. var groupMaterial = materials[ group.materialIndex ];
  12437. if ( groupMaterial.visible === true ) {
  12438. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  12439. }
  12440. }
  12441. } else {
  12442. pushRenderItem( object, geometry, material, _vector3.z, null );
  12443. }
  12444. }
  12445. }
  12446. }
  12447. }
  12448. var children = object.children;
  12449. for ( var i = 0, l = children.length; i < l; i ++ ) {
  12450. projectObject( children[ i ], camera );
  12451. }
  12452. }
  12453. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  12454. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12455. var renderItem = renderList[ i ];
  12456. var object = renderItem.object;
  12457. var geometry = renderItem.geometry;
  12458. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  12459. var group = renderItem.group;
  12460. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  12461. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  12462. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  12463. if ( object.isImmediateRenderObject ) {
  12464. setMaterial( material );
  12465. var program = setProgram( camera, scene.fog, material, object );
  12466. _currentGeometryProgram = '';
  12467. object.render( function ( object ) {
  12468. _this.renderBufferImmediate( object, program, material );
  12469. } );
  12470. } else {
  12471. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  12472. }
  12473. object.onAfterRender( _this, scene, camera, geometry, material, group );
  12474. }
  12475. }
  12476. function initMaterial( material, fog, object ) {
  12477. var materialProperties = properties.get( material );
  12478. var parameters = programCache.getParameters(
  12479. material, _lights, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  12480. var code = programCache.getProgramCode( material, parameters );
  12481. var program = materialProperties.program;
  12482. var programChange = true;
  12483. if ( program === undefined ) {
  12484. // new material
  12485. material.addEventListener( 'dispose', onMaterialDispose );
  12486. } else if ( program.code !== code ) {
  12487. // changed glsl or parameters
  12488. releaseMaterialProgramReference( material );
  12489. } else if ( parameters.shaderID !== undefined ) {
  12490. // same glsl and uniform list
  12491. return;
  12492. } else {
  12493. // only rebuild uniform list
  12494. programChange = false;
  12495. }
  12496. if ( programChange ) {
  12497. if ( parameters.shaderID ) {
  12498. var shader = ShaderLib[ parameters.shaderID ];
  12499. materialProperties.__webglShader = {
  12500. name: material.type,
  12501. uniforms: Object.assign( {}, shader.uniforms ),
  12502. vertexShader: shader.vertexShader,
  12503. fragmentShader: shader.fragmentShader
  12504. };
  12505. } else {
  12506. materialProperties.__webglShader = {
  12507. name: material.type,
  12508. uniforms: material.uniforms,
  12509. vertexShader: material.vertexShader,
  12510. fragmentShader: material.fragmentShader
  12511. };
  12512. }
  12513. material.__webglShader = materialProperties.__webglShader;
  12514. program = programCache.acquireProgram( material, parameters, code );
  12515. materialProperties.program = program;
  12516. material.program = program;
  12517. }
  12518. var attributes = program.getAttributes();
  12519. if ( material.morphTargets ) {
  12520. material.numSupportedMorphTargets = 0;
  12521. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  12522. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  12523. material.numSupportedMorphTargets ++;
  12524. }
  12525. }
  12526. }
  12527. if ( material.morphNormals ) {
  12528. material.numSupportedMorphNormals = 0;
  12529. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  12530. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  12531. material.numSupportedMorphNormals ++;
  12532. }
  12533. }
  12534. }
  12535. var uniforms = materialProperties.__webglShader.uniforms;
  12536. if ( ! material.isShaderMaterial &&
  12537. ! material.isRawShaderMaterial ||
  12538. material.clipping === true ) {
  12539. materialProperties.numClippingPlanes = _clipping.numPlanes;
  12540. materialProperties.numIntersection = _clipping.numIntersection;
  12541. uniforms.clippingPlanes = _clipping.uniform;
  12542. }
  12543. materialProperties.fog = fog;
  12544. // store the light setup it was created for
  12545. materialProperties.lightsHash = _lights.hash;
  12546. if ( material.lights ) {
  12547. // wire up the material to this renderer's lighting state
  12548. uniforms.ambientLightColor.value = _lights.ambient;
  12549. uniforms.directionalLights.value = _lights.directional;
  12550. uniforms.spotLights.value = _lights.spot;
  12551. uniforms.rectAreaLights.value = _lights.rectArea;
  12552. uniforms.pointLights.value = _lights.point;
  12553. uniforms.hemisphereLights.value = _lights.hemi;
  12554. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  12555. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  12556. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  12557. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  12558. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  12559. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  12560. // TODO (abelnation): add area lights shadow info to uniforms
  12561. }
  12562. var progUniforms = materialProperties.program.getUniforms(),
  12563. uniformsList =
  12564. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  12565. materialProperties.uniformsList = uniformsList;
  12566. }
  12567. function setMaterial( material ) {
  12568. material.side === DoubleSide
  12569. ? state.disable( _gl.CULL_FACE )
  12570. : state.enable( _gl.CULL_FACE );
  12571. state.setFlipSided( material.side === BackSide );
  12572. material.transparent === true
  12573. ? state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  12574. : state.setBlending( NoBlending );
  12575. state.setDepthFunc( material.depthFunc );
  12576. state.setDepthTest( material.depthTest );
  12577. state.setDepthWrite( material.depthWrite );
  12578. state.setColorWrite( material.colorWrite );
  12579. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12580. }
  12581. function setProgram( camera, fog, material, object ) {
  12582. _usedTextureUnits = 0;
  12583. var materialProperties = properties.get( material );
  12584. if ( _clippingEnabled ) {
  12585. if ( _localClippingEnabled || camera !== _currentCamera ) {
  12586. var useCache =
  12587. camera === _currentCamera &&
  12588. material.id === _currentMaterialId;
  12589. // we might want to call this function with some ClippingGroup
  12590. // object instead of the material, once it becomes feasible
  12591. // (#8465, #8379)
  12592. _clipping.setState(
  12593. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  12594. camera, materialProperties, useCache );
  12595. }
  12596. }
  12597. if ( material.needsUpdate === false ) {
  12598. if ( materialProperties.program === undefined ) {
  12599. material.needsUpdate = true;
  12600. } else if ( material.fog && materialProperties.fog !== fog ) {
  12601. material.needsUpdate = true;
  12602. } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) {
  12603. material.needsUpdate = true;
  12604. } else if ( materialProperties.numClippingPlanes !== undefined &&
  12605. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  12606. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  12607. material.needsUpdate = true;
  12608. }
  12609. }
  12610. if ( material.needsUpdate ) {
  12611. initMaterial( material, fog, object );
  12612. material.needsUpdate = false;
  12613. }
  12614. var refreshProgram = false;
  12615. var refreshMaterial = false;
  12616. var refreshLights = false;
  12617. var program = materialProperties.program,
  12618. p_uniforms = program.getUniforms(),
  12619. m_uniforms = materialProperties.__webglShader.uniforms;
  12620. if ( program.id !== _currentProgram ) {
  12621. _gl.useProgram( program.program );
  12622. _currentProgram = program.id;
  12623. refreshProgram = true;
  12624. refreshMaterial = true;
  12625. refreshLights = true;
  12626. }
  12627. if ( material.id !== _currentMaterialId ) {
  12628. _currentMaterialId = material.id;
  12629. refreshMaterial = true;
  12630. }
  12631. if ( refreshProgram || camera !== _currentCamera ) {
  12632. p_uniforms.set( _gl, camera, 'projectionMatrix' );
  12633. if ( capabilities.logarithmicDepthBuffer ) {
  12634. p_uniforms.setValue( _gl, 'logDepthBufFC',
  12635. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  12636. }
  12637. if ( camera !== _currentCamera ) {
  12638. _currentCamera = camera;
  12639. // lighting uniforms depend on the camera so enforce an update
  12640. // now, in case this material supports lights - or later, when
  12641. // the next material that does gets activated:
  12642. refreshMaterial = true; // set to true on material change
  12643. refreshLights = true; // remains set until update done
  12644. }
  12645. // load material specific uniforms
  12646. // (shader material also gets them for the sake of genericity)
  12647. if ( material.isShaderMaterial ||
  12648. material.isMeshPhongMaterial ||
  12649. material.isMeshStandardMaterial ||
  12650. material.envMap ) {
  12651. var uCamPos = p_uniforms.map.cameraPosition;
  12652. if ( uCamPos !== undefined ) {
  12653. uCamPos.setValue( _gl,
  12654. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  12655. }
  12656. }
  12657. if ( material.isMeshPhongMaterial ||
  12658. material.isMeshLambertMaterial ||
  12659. material.isMeshBasicMaterial ||
  12660. material.isMeshStandardMaterial ||
  12661. material.isShaderMaterial ||
  12662. material.skinning ) {
  12663. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  12664. }
  12665. p_uniforms.set( _gl, _this, 'toneMappingExposure' );
  12666. p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
  12667. }
  12668. // skinning uniforms must be set even if material didn't change
  12669. // auto-setting of texture unit for bone texture must go before other textures
  12670. // not sure why, but otherwise weird things happen
  12671. if ( material.skinning ) {
  12672. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  12673. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  12674. var skeleton = object.skeleton;
  12675. if ( skeleton ) {
  12676. if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
  12677. p_uniforms.set( _gl, skeleton, 'boneTexture' );
  12678. p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
  12679. p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
  12680. } else {
  12681. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  12682. }
  12683. }
  12684. }
  12685. if ( refreshMaterial ) {
  12686. if ( material.lights ) {
  12687. // the current material requires lighting info
  12688. // note: all lighting uniforms are always set correctly
  12689. // they simply reference the renderer's state for their
  12690. // values
  12691. //
  12692. // use the current material's .needsUpdate flags to set
  12693. // the GL state when required
  12694. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  12695. }
  12696. // refresh uniforms common to several materials
  12697. if ( fog && material.fog ) {
  12698. refreshUniformsFog( m_uniforms, fog );
  12699. }
  12700. if ( material.isMeshBasicMaterial ||
  12701. material.isMeshLambertMaterial ||
  12702. material.isMeshPhongMaterial ||
  12703. material.isMeshStandardMaterial ||
  12704. material.isMeshDepthMaterial ) {
  12705. refreshUniformsCommon( m_uniforms, material );
  12706. }
  12707. // refresh single material specific uniforms
  12708. if ( material.isLineBasicMaterial ) {
  12709. refreshUniformsLine( m_uniforms, material );
  12710. } else if ( material.isLineDashedMaterial ) {
  12711. refreshUniformsLine( m_uniforms, material );
  12712. refreshUniformsDash( m_uniforms, material );
  12713. } else if ( material.isPointsMaterial ) {
  12714. refreshUniformsPoints( m_uniforms, material );
  12715. } else if ( material.isMeshLambertMaterial ) {
  12716. refreshUniformsLambert( m_uniforms, material );
  12717. } else if ( material.isMeshToonMaterial ) {
  12718. refreshUniformsToon( m_uniforms, material );
  12719. } else if ( material.isMeshPhongMaterial ) {
  12720. refreshUniformsPhong( m_uniforms, material );
  12721. } else if ( material.isMeshPhysicalMaterial ) {
  12722. refreshUniformsPhysical( m_uniforms, material );
  12723. } else if ( material.isMeshStandardMaterial ) {
  12724. refreshUniformsStandard( m_uniforms, material );
  12725. } else if ( material.isMeshDepthMaterial ) {
  12726. if ( material.displacementMap ) {
  12727. m_uniforms.displacementMap.value = material.displacementMap;
  12728. m_uniforms.displacementScale.value = material.displacementScale;
  12729. m_uniforms.displacementBias.value = material.displacementBias;
  12730. }
  12731. } else if ( material.isMeshNormalMaterial ) {
  12732. m_uniforms.opacity.value = material.opacity;
  12733. }
  12734. WebGLUniforms.upload(
  12735. _gl, materialProperties.uniformsList, m_uniforms, _this );
  12736. }
  12737. // common matrices
  12738. p_uniforms.set( _gl, object, 'modelViewMatrix' );
  12739. p_uniforms.set( _gl, object, 'normalMatrix' );
  12740. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  12741. return program;
  12742. }
  12743. // Uniforms (refresh uniforms objects)
  12744. function refreshUniformsCommon( uniforms, material ) {
  12745. uniforms.opacity.value = material.opacity;
  12746. uniforms.diffuse.value = material.color;
  12747. if ( material.emissive ) {
  12748. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  12749. }
  12750. uniforms.map.value = material.map;
  12751. uniforms.specularMap.value = material.specularMap;
  12752. uniforms.alphaMap.value = material.alphaMap;
  12753. if ( material.lightMap ) {
  12754. uniforms.lightMap.value = material.lightMap;
  12755. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12756. }
  12757. if ( material.aoMap ) {
  12758. uniforms.aoMap.value = material.aoMap;
  12759. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  12760. }
  12761. // uv repeat and offset setting priorities
  12762. // 1. color map
  12763. // 2. specular map
  12764. // 3. normal map
  12765. // 4. bump map
  12766. // 5. alpha map
  12767. // 6. emissive map
  12768. var uvScaleMap;
  12769. if ( material.map ) {
  12770. uvScaleMap = material.map;
  12771. } else if ( material.specularMap ) {
  12772. uvScaleMap = material.specularMap;
  12773. } else if ( material.displacementMap ) {
  12774. uvScaleMap = material.displacementMap;
  12775. } else if ( material.normalMap ) {
  12776. uvScaleMap = material.normalMap;
  12777. } else if ( material.bumpMap ) {
  12778. uvScaleMap = material.bumpMap;
  12779. } else if ( material.roughnessMap ) {
  12780. uvScaleMap = material.roughnessMap;
  12781. } else if ( material.metalnessMap ) {
  12782. uvScaleMap = material.metalnessMap;
  12783. } else if ( material.alphaMap ) {
  12784. uvScaleMap = material.alphaMap;
  12785. } else if ( material.emissiveMap ) {
  12786. uvScaleMap = material.emissiveMap;
  12787. }
  12788. if ( uvScaleMap !== undefined ) {
  12789. // backwards compatibility
  12790. if ( uvScaleMap.isWebGLRenderTarget ) {
  12791. uvScaleMap = uvScaleMap.texture;
  12792. }
  12793. var offset = uvScaleMap.offset;
  12794. var repeat = uvScaleMap.repeat;
  12795. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12796. }
  12797. uniforms.envMap.value = material.envMap;
  12798. // don't flip CubeTexture envMaps, flip everything else:
  12799. // WebGLRenderTargetCube will be flipped for backwards compatibility
  12800. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  12801. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  12802. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  12803. uniforms.reflectivity.value = material.reflectivity;
  12804. uniforms.refractionRatio.value = material.refractionRatio;
  12805. }
  12806. function refreshUniformsLine( uniforms, material ) {
  12807. uniforms.diffuse.value = material.color;
  12808. uniforms.opacity.value = material.opacity;
  12809. }
  12810. function refreshUniformsDash( uniforms, material ) {
  12811. uniforms.dashSize.value = material.dashSize;
  12812. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12813. uniforms.scale.value = material.scale;
  12814. }
  12815. function refreshUniformsPoints( uniforms, material ) {
  12816. uniforms.diffuse.value = material.color;
  12817. uniforms.opacity.value = material.opacity;
  12818. uniforms.size.value = material.size * _pixelRatio;
  12819. uniforms.scale.value = _height * 0.5;
  12820. uniforms.map.value = material.map;
  12821. if ( material.map !== null ) {
  12822. var offset = material.map.offset;
  12823. var repeat = material.map.repeat;
  12824. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12825. }
  12826. }
  12827. function refreshUniformsFog( uniforms, fog ) {
  12828. uniforms.fogColor.value = fog.color;
  12829. if ( fog.isFog ) {
  12830. uniforms.fogNear.value = fog.near;
  12831. uniforms.fogFar.value = fog.far;
  12832. } else if ( fog.isFogExp2 ) {
  12833. uniforms.fogDensity.value = fog.density;
  12834. }
  12835. }
  12836. function refreshUniformsLambert( uniforms, material ) {
  12837. if ( material.emissiveMap ) {
  12838. uniforms.emissiveMap.value = material.emissiveMap;
  12839. }
  12840. }
  12841. function refreshUniformsPhong( uniforms, material ) {
  12842. uniforms.specular.value = material.specular;
  12843. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  12844. if ( material.emissiveMap ) {
  12845. uniforms.emissiveMap.value = material.emissiveMap;
  12846. }
  12847. if ( material.bumpMap ) {
  12848. uniforms.bumpMap.value = material.bumpMap;
  12849. uniforms.bumpScale.value = material.bumpScale;
  12850. }
  12851. if ( material.normalMap ) {
  12852. uniforms.normalMap.value = material.normalMap;
  12853. uniforms.normalScale.value.copy( material.normalScale );
  12854. }
  12855. if ( material.displacementMap ) {
  12856. uniforms.displacementMap.value = material.displacementMap;
  12857. uniforms.displacementScale.value = material.displacementScale;
  12858. uniforms.displacementBias.value = material.displacementBias;
  12859. }
  12860. }
  12861. function refreshUniformsToon( uniforms, material ) {
  12862. refreshUniformsPhong( uniforms, material );
  12863. if ( material.gradientMap ) {
  12864. uniforms.gradientMap.value = material.gradientMap;
  12865. }
  12866. }
  12867. function refreshUniformsStandard( uniforms, material ) {
  12868. uniforms.roughness.value = material.roughness;
  12869. uniforms.metalness.value = material.metalness;
  12870. if ( material.roughnessMap ) {
  12871. uniforms.roughnessMap.value = material.roughnessMap;
  12872. }
  12873. if ( material.metalnessMap ) {
  12874. uniforms.metalnessMap.value = material.metalnessMap;
  12875. }
  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. if ( material.envMap ) {
  12893. //uniforms.envMap.value = material.envMap; // part of uniforms common
  12894. uniforms.envMapIntensity.value = material.envMapIntensity;
  12895. }
  12896. }
  12897. function refreshUniformsPhysical( uniforms, material ) {
  12898. uniforms.clearCoat.value = material.clearCoat;
  12899. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  12900. refreshUniformsStandard( uniforms, material );
  12901. }
  12902. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  12903. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  12904. uniforms.ambientLightColor.needsUpdate = value;
  12905. uniforms.directionalLights.needsUpdate = value;
  12906. uniforms.pointLights.needsUpdate = value;
  12907. uniforms.spotLights.needsUpdate = value;
  12908. uniforms.rectAreaLights.needsUpdate = value;
  12909. uniforms.hemisphereLights.needsUpdate = value;
  12910. }
  12911. // Lighting
  12912. function setupShadows( lights ) {
  12913. var lightShadowsLength = 0;
  12914. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  12915. var light = lights[ i ];
  12916. if ( light.castShadow ) {
  12917. _lights.shadows[ lightShadowsLength ++ ] = light;
  12918. }
  12919. }
  12920. _lights.shadows.length = lightShadowsLength;
  12921. }
  12922. function setupLights( lights, camera ) {
  12923. var l, ll, light,
  12924. r = 0, g = 0, b = 0,
  12925. color,
  12926. intensity,
  12927. distance,
  12928. shadowMap,
  12929. viewMatrix = camera.matrixWorldInverse,
  12930. directionalLength = 0,
  12931. pointLength = 0,
  12932. spotLength = 0,
  12933. rectAreaLength = 0,
  12934. hemiLength = 0;
  12935. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12936. light = lights[ l ];
  12937. color = light.color;
  12938. intensity = light.intensity;
  12939. distance = light.distance;
  12940. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12941. if ( light.isAmbientLight ) {
  12942. r += color.r * intensity;
  12943. g += color.g * intensity;
  12944. b += color.b * intensity;
  12945. } else if ( light.isDirectionalLight ) {
  12946. var uniforms = lightCache.get( light );
  12947. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  12948. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12949. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  12950. uniforms.direction.sub( _vector3 );
  12951. uniforms.direction.transformDirection( viewMatrix );
  12952. uniforms.shadow = light.castShadow;
  12953. if ( light.castShadow ) {
  12954. uniforms.shadowBias = light.shadow.bias;
  12955. uniforms.shadowRadius = light.shadow.radius;
  12956. uniforms.shadowMapSize = light.shadow.mapSize;
  12957. }
  12958. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  12959. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12960. _lights.directional[ directionalLength ++ ] = uniforms;
  12961. } else if ( light.isSpotLight ) {
  12962. var uniforms = lightCache.get( light );
  12963. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12964. uniforms.position.applyMatrix4( viewMatrix );
  12965. uniforms.color.copy( color ).multiplyScalar( intensity );
  12966. uniforms.distance = distance;
  12967. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12968. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  12969. uniforms.direction.sub( _vector3 );
  12970. uniforms.direction.transformDirection( viewMatrix );
  12971. uniforms.coneCos = Math.cos( light.angle );
  12972. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12973. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  12974. uniforms.shadow = light.castShadow;
  12975. if ( light.castShadow ) {
  12976. uniforms.shadowBias = light.shadow.bias;
  12977. uniforms.shadowRadius = light.shadow.radius;
  12978. uniforms.shadowMapSize = light.shadow.mapSize;
  12979. }
  12980. _lights.spotShadowMap[ spotLength ] = shadowMap;
  12981. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  12982. _lights.spot[ spotLength ++ ] = uniforms;
  12983. } else if ( light.isRectAreaLight ) {
  12984. var uniforms = lightCache.get( light );
  12985. // (a) intensity controls irradiance of entire light
  12986. uniforms.color
  12987. .copy( color )
  12988. .multiplyScalar( intensity / ( light.width * light.height ) );
  12989. // (b) intensity controls the radiance per light area
  12990. // uniforms.color.copy( color ).multiplyScalar( intensity );
  12991. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12992. uniforms.position.applyMatrix4( viewMatrix );
  12993. // extract local rotation of light to derive width/height half vectors
  12994. _matrix42.identity();
  12995. _matrix4.copy( light.matrixWorld );
  12996. _matrix4.premultiply( viewMatrix );
  12997. _matrix42.extractRotation( _matrix4 );
  12998. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12999. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13000. uniforms.halfWidth.applyMatrix4( _matrix42 );
  13001. uniforms.halfHeight.applyMatrix4( _matrix42 );
  13002. // TODO (abelnation): RectAreaLight distance?
  13003. // uniforms.distance = distance;
  13004. _lights.rectArea[ rectAreaLength ++ ] = uniforms;
  13005. } else if ( light.isPointLight ) {
  13006. var uniforms = lightCache.get( light );
  13007. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13008. uniforms.position.applyMatrix4( viewMatrix );
  13009. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13010. uniforms.distance = light.distance;
  13011. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  13012. uniforms.shadow = light.castShadow;
  13013. if ( light.castShadow ) {
  13014. uniforms.shadowBias = light.shadow.bias;
  13015. uniforms.shadowRadius = light.shadow.radius;
  13016. uniforms.shadowMapSize = light.shadow.mapSize;
  13017. }
  13018. _lights.pointShadowMap[ pointLength ] = shadowMap;
  13019. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  13020. _lights.pointShadowMatrix[ pointLength ] = new Matrix4();
  13021. }
  13022. // for point lights we set the shadow matrix to be a translation-only matrix
  13023. // equal to inverse of the light's position
  13024. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  13025. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  13026. _lights.point[ pointLength ++ ] = uniforms;
  13027. } else if ( light.isHemisphereLight ) {
  13028. var uniforms = lightCache.get( light );
  13029. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13030. uniforms.direction.transformDirection( viewMatrix );
  13031. uniforms.direction.normalize();
  13032. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  13033. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  13034. _lights.hemi[ hemiLength ++ ] = uniforms;
  13035. }
  13036. }
  13037. _lights.ambient[ 0 ] = r;
  13038. _lights.ambient[ 1 ] = g;
  13039. _lights.ambient[ 2 ] = b;
  13040. _lights.directional.length = directionalLength;
  13041. _lights.spot.length = spotLength;
  13042. _lights.rectArea.length = rectAreaLength;
  13043. _lights.point.length = pointLength;
  13044. _lights.hemi.length = hemiLength;
  13045. // TODO (sam-g-steel) why aren't we using join
  13046. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + _lights.shadows.length;
  13047. }
  13048. // GL state setting
  13049. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13050. state.setCullFace( cullFace );
  13051. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  13052. };
  13053. // Textures
  13054. function allocTextureUnit() {
  13055. var textureUnit = _usedTextureUnits;
  13056. if ( textureUnit >= capabilities.maxTextures ) {
  13057. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  13058. }
  13059. _usedTextureUnits += 1;
  13060. return textureUnit;
  13061. }
  13062. this.allocTextureUnit = allocTextureUnit;
  13063. // this.setTexture2D = setTexture2D;
  13064. this.setTexture2D = ( function() {
  13065. var warned = false;
  13066. // backwards compatibility: peel texture.texture
  13067. return function setTexture2D( texture, slot ) {
  13068. if ( texture && texture.isWebGLRenderTarget ) {
  13069. if ( ! warned ) {
  13070. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  13071. warned = true;
  13072. }
  13073. texture = texture.texture;
  13074. }
  13075. textures.setTexture2D( texture, slot );
  13076. };
  13077. }() );
  13078. this.setTexture = ( function() {
  13079. var warned = false;
  13080. return function setTexture( texture, slot ) {
  13081. if ( ! warned ) {
  13082. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  13083. warned = true;
  13084. }
  13085. textures.setTexture2D( texture, slot );
  13086. };
  13087. }() );
  13088. this.setTextureCube = ( function() {
  13089. var warned = false;
  13090. return function setTextureCube( texture, slot ) {
  13091. // backwards compatibility: peel texture.texture
  13092. if ( texture && texture.isWebGLRenderTargetCube ) {
  13093. if ( ! warned ) {
  13094. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  13095. warned = true;
  13096. }
  13097. texture = texture.texture;
  13098. }
  13099. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  13100. // TODO: unify these code paths
  13101. if ( ( texture && texture.isCubeTexture ) ||
  13102. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  13103. // CompressedTexture can have Array in image :/
  13104. // this function alone should take care of cube textures
  13105. textures.setTextureCube( texture, slot );
  13106. } else {
  13107. // assumed: texture property of THREE.WebGLRenderTargetCube
  13108. textures.setTextureCubeDynamic( texture, slot );
  13109. }
  13110. };
  13111. }() );
  13112. this.getCurrentRenderTarget = function() {
  13113. return _currentRenderTarget;
  13114. };
  13115. this.setRenderTarget = function ( renderTarget ) {
  13116. _currentRenderTarget = renderTarget;
  13117. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  13118. textures.setupRenderTarget( renderTarget );
  13119. }
  13120. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  13121. var framebuffer;
  13122. if ( renderTarget ) {
  13123. var renderTargetProperties = properties.get( renderTarget );
  13124. if ( isCube ) {
  13125. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13126. } else {
  13127. framebuffer = renderTargetProperties.__webglFramebuffer;
  13128. }
  13129. _currentScissor.copy( renderTarget.scissor );
  13130. _currentScissorTest = renderTarget.scissorTest;
  13131. _currentViewport.copy( renderTarget.viewport );
  13132. } else {
  13133. framebuffer = null;
  13134. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  13135. _currentScissorTest = _scissorTest;
  13136. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  13137. }
  13138. if ( _currentFramebuffer !== framebuffer ) {
  13139. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13140. _currentFramebuffer = framebuffer;
  13141. }
  13142. state.scissor( _currentScissor );
  13143. state.setScissorTest( _currentScissorTest );
  13144. state.viewport( _currentViewport );
  13145. if ( isCube ) {
  13146. var textureProperties = properties.get( renderTarget.texture );
  13147. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  13148. }
  13149. };
  13150. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  13151. if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
  13152. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  13153. return;
  13154. }
  13155. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  13156. if ( framebuffer ) {
  13157. var restore = false;
  13158. if ( framebuffer !== _currentFramebuffer ) {
  13159. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13160. restore = true;
  13161. }
  13162. try {
  13163. var texture = renderTarget.texture;
  13164. var textureFormat = texture.format;
  13165. var textureType = texture.type;
  13166. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  13167. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  13168. return;
  13169. }
  13170. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  13171. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  13172. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  13173. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  13174. return;
  13175. }
  13176. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13177. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  13178. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  13179. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  13180. }
  13181. } else {
  13182. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13183. }
  13184. } finally {
  13185. if ( restore ) {
  13186. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13187. }
  13188. }
  13189. }
  13190. };
  13191. // Map three.js constants to WebGL constants
  13192. function paramThreeToGL( p ) {
  13193. var extension;
  13194. if ( p === RepeatWrapping ) return _gl.REPEAT;
  13195. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13196. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13197. if ( p === NearestFilter ) return _gl.NEAREST;
  13198. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13199. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13200. if ( p === LinearFilter ) return _gl.LINEAR;
  13201. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13202. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13203. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13204. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13205. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13206. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13207. if ( p === ByteType ) return _gl.BYTE;
  13208. if ( p === ShortType ) return _gl.SHORT;
  13209. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13210. if ( p === IntType ) return _gl.INT;
  13211. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  13212. if ( p === FloatType ) return _gl.FLOAT;
  13213. if ( p === HalfFloatType ) {
  13214. extension = extensions.get( 'OES_texture_half_float' );
  13215. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  13216. }
  13217. if ( p === AlphaFormat ) return _gl.ALPHA;
  13218. if ( p === RGBFormat ) return _gl.RGB;
  13219. if ( p === RGBAFormat ) return _gl.RGBA;
  13220. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  13221. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13222. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  13223. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  13224. if ( p === AddEquation ) return _gl.FUNC_ADD;
  13225. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13226. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13227. if ( p === ZeroFactor ) return _gl.ZERO;
  13228. if ( p === OneFactor ) return _gl.ONE;
  13229. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  13230. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13231. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13232. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13233. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  13234. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13235. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  13236. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13237. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13238. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  13239. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  13240. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13241. if ( extension !== null ) {
  13242. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13243. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13244. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13245. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13246. }
  13247. }
  13248. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  13249. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  13250. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13251. if ( extension !== null ) {
  13252. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13253. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13254. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13255. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13256. }
  13257. }
  13258. if ( p === RGB_ETC1_Format ) {
  13259. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13260. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13261. }
  13262. if ( p === MinEquation || p === MaxEquation ) {
  13263. extension = extensions.get( 'EXT_blend_minmax' );
  13264. if ( extension !== null ) {
  13265. if ( p === MinEquation ) return extension.MIN_EXT;
  13266. if ( p === MaxEquation ) return extension.MAX_EXT;
  13267. }
  13268. }
  13269. if ( p === UnsignedInt248Type ) {
  13270. extension = extensions.get( 'WEBGL_depth_texture' );
  13271. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  13272. }
  13273. return 0;
  13274. }
  13275. }
  13276. /**
  13277. * @author mrdoob / http://mrdoob.com/
  13278. * @author alteredq / http://alteredqualia.com/
  13279. */
  13280. function FogExp2 ( color, density ) {
  13281. this.name = '';
  13282. this.color = new Color( color );
  13283. this.density = ( density !== undefined ) ? density : 0.00025;
  13284. }
  13285. FogExp2.prototype.isFogExp2 = true;
  13286. FogExp2.prototype.clone = function () {
  13287. return new FogExp2( this.color.getHex(), this.density );
  13288. };
  13289. FogExp2.prototype.toJSON = function ( meta ) {
  13290. return {
  13291. type: 'FogExp2',
  13292. color: this.color.getHex(),
  13293. density: this.density
  13294. };
  13295. };
  13296. /**
  13297. * @author mrdoob / http://mrdoob.com/
  13298. * @author alteredq / http://alteredqualia.com/
  13299. */
  13300. function Fog ( color, near, far ) {
  13301. this.name = '';
  13302. this.color = new Color( color );
  13303. this.near = ( near !== undefined ) ? near : 1;
  13304. this.far = ( far !== undefined ) ? far : 1000;
  13305. }
  13306. Fog.prototype.isFog = true;
  13307. Fog.prototype.clone = function () {
  13308. return new Fog( this.color.getHex(), this.near, this.far );
  13309. };
  13310. Fog.prototype.toJSON = function ( meta ) {
  13311. return {
  13312. type: 'Fog',
  13313. color: this.color.getHex(),
  13314. near: this.near,
  13315. far: this.far
  13316. };
  13317. };
  13318. /**
  13319. * @author mrdoob / http://mrdoob.com/
  13320. */
  13321. function Scene () {
  13322. Object3D.call( this );
  13323. this.type = 'Scene';
  13324. this.background = null;
  13325. this.fog = null;
  13326. this.overrideMaterial = null;
  13327. this.autoUpdate = true; // checked by the renderer
  13328. }
  13329. Scene.prototype = Object.create( Object3D.prototype );
  13330. Scene.prototype.constructor = Scene;
  13331. Scene.prototype.copy = function ( source, recursive ) {
  13332. Object3D.prototype.copy.call( this, source, recursive );
  13333. if ( source.background !== null ) this.background = source.background.clone();
  13334. if ( source.fog !== null ) this.fog = source.fog.clone();
  13335. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13336. this.autoUpdate = source.autoUpdate;
  13337. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13338. return this;
  13339. };
  13340. Scene.prototype.toJSON = function ( meta ) {
  13341. var data = Object3D.prototype.toJSON.call( this, meta );
  13342. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  13343. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13344. return data;
  13345. };
  13346. /**
  13347. * @author mikael emtinger / http://gomo.se/
  13348. * @author alteredq / http://alteredqualia.com/
  13349. */
  13350. function LensFlare( texture, size, distance, blending, color ) {
  13351. Object3D.call( this );
  13352. this.lensFlares = [];
  13353. this.positionScreen = new Vector3();
  13354. this.customUpdateCallback = undefined;
  13355. if ( texture !== undefined ) {
  13356. this.add( texture, size, distance, blending, color );
  13357. }
  13358. }
  13359. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13360. constructor: LensFlare,
  13361. isLensFlare: true,
  13362. copy: function ( source ) {
  13363. Object3D.prototype.copy.call( this, source );
  13364. this.positionScreen.copy( source.positionScreen );
  13365. this.customUpdateCallback = source.customUpdateCallback;
  13366. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13367. this.lensFlares.push( source.lensFlares[ i ] );
  13368. }
  13369. return this;
  13370. },
  13371. add: function ( texture, size, distance, blending, color, opacity ) {
  13372. if ( size === undefined ) size = - 1;
  13373. if ( distance === undefined ) distance = 0;
  13374. if ( opacity === undefined ) opacity = 1;
  13375. if ( color === undefined ) color = new Color( 0xffffff );
  13376. if ( blending === undefined ) blending = NormalBlending;
  13377. distance = Math.min( distance, Math.max( 0, distance ) );
  13378. this.lensFlares.push( {
  13379. texture: texture, // THREE.Texture
  13380. size: size, // size in pixels (-1 = use texture.width)
  13381. distance: distance, // distance (0-1) from light source (0=at light source)
  13382. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13383. scale: 1, // scale
  13384. rotation: 0, // rotation
  13385. opacity: opacity, // opacity
  13386. color: color, // color
  13387. blending: blending // blending
  13388. } );
  13389. },
  13390. /*
  13391. * Update lens flares update positions on all flares based on the screen position
  13392. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13393. */
  13394. updateLensFlares: function () {
  13395. var f, fl = this.lensFlares.length;
  13396. var flare;
  13397. var vecX = - this.positionScreen.x * 2;
  13398. var vecY = - this.positionScreen.y * 2;
  13399. for ( f = 0; f < fl; f ++ ) {
  13400. flare = this.lensFlares[ f ];
  13401. flare.x = this.positionScreen.x + vecX * flare.distance;
  13402. flare.y = this.positionScreen.y + vecY * flare.distance;
  13403. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13404. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13405. }
  13406. }
  13407. } );
  13408. /**
  13409. * @author alteredq / http://alteredqualia.com/
  13410. *
  13411. * parameters = {
  13412. * color: <hex>,
  13413. * opacity: <float>,
  13414. * map: new THREE.Texture( <Image> ),
  13415. *
  13416. * uvOffset: new THREE.Vector2(),
  13417. * uvScale: new THREE.Vector2()
  13418. * }
  13419. */
  13420. function SpriteMaterial( parameters ) {
  13421. Material.call( this );
  13422. this.type = 'SpriteMaterial';
  13423. this.color = new Color( 0xffffff );
  13424. this.map = null;
  13425. this.rotation = 0;
  13426. this.fog = false;
  13427. this.lights = false;
  13428. this.setValues( parameters );
  13429. }
  13430. SpriteMaterial.prototype = Object.create( Material.prototype );
  13431. SpriteMaterial.prototype.constructor = SpriteMaterial;
  13432. SpriteMaterial.prototype.copy = function ( source ) {
  13433. Material.prototype.copy.call( this, source );
  13434. this.color.copy( source.color );
  13435. this.map = source.map;
  13436. this.rotation = source.rotation;
  13437. return this;
  13438. };
  13439. /**
  13440. * @author mikael emtinger / http://gomo.se/
  13441. * @author alteredq / http://alteredqualia.com/
  13442. */
  13443. function Sprite( material ) {
  13444. Object3D.call( this );
  13445. this.type = 'Sprite';
  13446. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  13447. }
  13448. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13449. constructor: Sprite,
  13450. isSprite: true,
  13451. raycast: ( function () {
  13452. var matrixPosition = new Vector3();
  13453. return function raycast( raycaster, intersects ) {
  13454. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13455. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  13456. var guessSizeSq = this.scale.x * this.scale.y / 4;
  13457. if ( distanceSq > guessSizeSq ) {
  13458. return;
  13459. }
  13460. intersects.push( {
  13461. distance: Math.sqrt( distanceSq ),
  13462. point: this.position,
  13463. face: null,
  13464. object: this
  13465. } );
  13466. };
  13467. }() ),
  13468. clone: function () {
  13469. return new this.constructor( this.material ).copy( this );
  13470. }
  13471. } );
  13472. /**
  13473. * @author mikael emtinger / http://gomo.se/
  13474. * @author alteredq / http://alteredqualia.com/
  13475. * @author mrdoob / http://mrdoob.com/
  13476. */
  13477. function LOD() {
  13478. Object3D.call( this );
  13479. this.type = 'LOD';
  13480. Object.defineProperties( this, {
  13481. levels: {
  13482. enumerable: true,
  13483. value: []
  13484. }
  13485. } );
  13486. }
  13487. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13488. constructor: LOD,
  13489. copy: function ( source ) {
  13490. Object3D.prototype.copy.call( this, source, false );
  13491. var levels = source.levels;
  13492. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13493. var level = levels[ i ];
  13494. this.addLevel( level.object.clone(), level.distance );
  13495. }
  13496. return this;
  13497. },
  13498. addLevel: function ( object, distance ) {
  13499. if ( distance === undefined ) distance = 0;
  13500. distance = Math.abs( distance );
  13501. var levels = this.levels;
  13502. for ( var l = 0; l < levels.length; l ++ ) {
  13503. if ( distance < levels[ l ].distance ) {
  13504. break;
  13505. }
  13506. }
  13507. levels.splice( l, 0, { distance: distance, object: object } );
  13508. this.add( object );
  13509. },
  13510. getObjectForDistance: function ( distance ) {
  13511. var levels = this.levels;
  13512. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13513. if ( distance < levels[ i ].distance ) {
  13514. break;
  13515. }
  13516. }
  13517. return levels[ i - 1 ].object;
  13518. },
  13519. raycast: ( function () {
  13520. var matrixPosition = new Vector3();
  13521. return function raycast( raycaster, intersects ) {
  13522. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13523. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13524. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13525. };
  13526. }() ),
  13527. update: function () {
  13528. var v1 = new Vector3();
  13529. var v2 = new Vector3();
  13530. return function update( camera ) {
  13531. var levels = this.levels;
  13532. if ( levels.length > 1 ) {
  13533. v1.setFromMatrixPosition( camera.matrixWorld );
  13534. v2.setFromMatrixPosition( this.matrixWorld );
  13535. var distance = v1.distanceTo( v2 );
  13536. levels[ 0 ].object.visible = true;
  13537. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13538. if ( distance >= levels[ i ].distance ) {
  13539. levels[ i - 1 ].object.visible = false;
  13540. levels[ i ].object.visible = true;
  13541. } else {
  13542. break;
  13543. }
  13544. }
  13545. for ( ; i < l; i ++ ) {
  13546. levels[ i ].object.visible = false;
  13547. }
  13548. }
  13549. };
  13550. }(),
  13551. toJSON: function ( meta ) {
  13552. var data = Object3D.prototype.toJSON.call( this, meta );
  13553. data.object.levels = [];
  13554. var levels = this.levels;
  13555. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13556. var level = levels[ i ];
  13557. data.object.levels.push( {
  13558. object: level.object.uuid,
  13559. distance: level.distance
  13560. } );
  13561. }
  13562. return data;
  13563. }
  13564. } );
  13565. /**
  13566. * @author mikael emtinger / http://gomo.se/
  13567. * @author alteredq / http://alteredqualia.com/
  13568. * @author michael guerrero / http://realitymeltdown.com
  13569. * @author ikerr / http://verold.com
  13570. */
  13571. function Skeleton( bones, boneInverses, useVertexTexture ) {
  13572. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  13573. this.identityMatrix = new Matrix4();
  13574. // copy the bone array
  13575. bones = bones || [];
  13576. this.bones = bones.slice( 0 );
  13577. // create a bone texture or an array of floats
  13578. if ( this.useVertexTexture ) {
  13579. // layout (1 matrix = 4 pixels)
  13580. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13581. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13582. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13583. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13584. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13585. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  13586. size = _Math.nextPowerOfTwo( Math.ceil( size ) );
  13587. size = Math.max( size, 4 );
  13588. this.boneTextureWidth = size;
  13589. this.boneTextureHeight = size;
  13590. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  13591. this.boneTexture = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType );
  13592. } else {
  13593. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  13594. }
  13595. // use the supplied bone inverses or calculate the inverses
  13596. if ( boneInverses === undefined ) {
  13597. this.calculateInverses();
  13598. } else {
  13599. if ( this.bones.length === boneInverses.length ) {
  13600. this.boneInverses = boneInverses.slice( 0 );
  13601. } else {
  13602. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  13603. this.boneInverses = [];
  13604. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13605. this.boneInverses.push( new Matrix4() );
  13606. }
  13607. }
  13608. }
  13609. }
  13610. Object.assign( Skeleton.prototype, {
  13611. calculateInverses: function () {
  13612. this.boneInverses = [];
  13613. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13614. var inverse = new Matrix4();
  13615. if ( this.bones[ b ] ) {
  13616. inverse.getInverse( this.bones[ b ].matrixWorld );
  13617. }
  13618. this.boneInverses.push( inverse );
  13619. }
  13620. },
  13621. pose: function () {
  13622. var bone;
  13623. // recover the bind-time world matrices
  13624. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13625. bone = this.bones[ b ];
  13626. if ( bone ) {
  13627. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  13628. }
  13629. }
  13630. // compute the local matrices, positions, rotations and scales
  13631. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13632. bone = this.bones[ b ];
  13633. if ( bone ) {
  13634. if ( bone.parent && bone.parent.isBone ) {
  13635. bone.matrix.getInverse( bone.parent.matrixWorld );
  13636. bone.matrix.multiply( bone.matrixWorld );
  13637. } else {
  13638. bone.matrix.copy( bone.matrixWorld );
  13639. }
  13640. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  13641. }
  13642. }
  13643. },
  13644. update: ( function () {
  13645. var offsetMatrix = new Matrix4();
  13646. return function update() {
  13647. // flatten bone matrices to array
  13648. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13649. // compute the offset between the current and the original transform
  13650. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  13651. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  13652. offsetMatrix.toArray( this.boneMatrices, b * 16 );
  13653. }
  13654. if ( this.useVertexTexture ) {
  13655. this.boneTexture.needsUpdate = true;
  13656. }
  13657. };
  13658. } )(),
  13659. clone: function () {
  13660. return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  13661. }
  13662. } );
  13663. /**
  13664. * @author mikael emtinger / http://gomo.se/
  13665. * @author alteredq / http://alteredqualia.com/
  13666. * @author ikerr / http://verold.com
  13667. */
  13668. function Bone() {
  13669. Object3D.call( this );
  13670. this.type = 'Bone';
  13671. }
  13672. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13673. constructor: Bone,
  13674. isBone: true
  13675. } );
  13676. /**
  13677. * @author mikael emtinger / http://gomo.se/
  13678. * @author alteredq / http://alteredqualia.com/
  13679. * @author ikerr / http://verold.com
  13680. */
  13681. function SkinnedMesh( geometry, material, useVertexTexture ) {
  13682. Mesh.call( this, geometry, material );
  13683. this.type = 'SkinnedMesh';
  13684. this.bindMode = "attached";
  13685. this.bindMatrix = new Matrix4();
  13686. this.bindMatrixInverse = new Matrix4();
  13687. // init bones
  13688. // TODO: remove bone creation as there is no reason (other than
  13689. // convenience) for THREE.SkinnedMesh to do this.
  13690. var bones = [];
  13691. if ( this.geometry && this.geometry.bones !== undefined ) {
  13692. var bone, gbone;
  13693. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13694. gbone = this.geometry.bones[ b ];
  13695. bone = new Bone();
  13696. bones.push( bone );
  13697. bone.name = gbone.name;
  13698. bone.position.fromArray( gbone.pos );
  13699. bone.quaternion.fromArray( gbone.rotq );
  13700. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  13701. }
  13702. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13703. gbone = this.geometry.bones[ b ];
  13704. if ( gbone.parent !== - 1 && gbone.parent !== null &&
  13705. bones[ gbone.parent ] !== undefined ) {
  13706. bones[ gbone.parent ].add( bones[ b ] );
  13707. } else {
  13708. this.add( bones[ b ] );
  13709. }
  13710. }
  13711. }
  13712. this.normalizeSkinWeights();
  13713. this.updateMatrixWorld( true );
  13714. this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  13715. }
  13716. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  13717. constructor: SkinnedMesh,
  13718. isSkinnedMesh: true,
  13719. bind: function( skeleton, bindMatrix ) {
  13720. this.skeleton = skeleton;
  13721. if ( bindMatrix === undefined ) {
  13722. this.updateMatrixWorld( true );
  13723. this.skeleton.calculateInverses();
  13724. bindMatrix = this.matrixWorld;
  13725. }
  13726. this.bindMatrix.copy( bindMatrix );
  13727. this.bindMatrixInverse.getInverse( bindMatrix );
  13728. },
  13729. pose: function () {
  13730. this.skeleton.pose();
  13731. },
  13732. normalizeSkinWeights: function () {
  13733. if ( this.geometry && this.geometry.isGeometry ) {
  13734. for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  13735. var sw = this.geometry.skinWeights[ i ];
  13736. var scale = 1.0 / sw.lengthManhattan();
  13737. if ( scale !== Infinity ) {
  13738. sw.multiplyScalar( scale );
  13739. } else {
  13740. sw.set( 1, 0, 0, 0 ); // do something reasonable
  13741. }
  13742. }
  13743. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  13744. var vec = new Vector4();
  13745. var skinWeight = this.geometry.attributes.skinWeight;
  13746. for ( var i = 0; i < skinWeight.count; i ++ ) {
  13747. vec.x = skinWeight.getX( i );
  13748. vec.y = skinWeight.getY( i );
  13749. vec.z = skinWeight.getZ( i );
  13750. vec.w = skinWeight.getW( i );
  13751. var scale = 1.0 / vec.lengthManhattan();
  13752. if ( scale !== Infinity ) {
  13753. vec.multiplyScalar( scale );
  13754. } else {
  13755. vec.set( 1, 0, 0, 0 ); // do something reasonable
  13756. }
  13757. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  13758. }
  13759. }
  13760. },
  13761. updateMatrixWorld: function( force ) {
  13762. Mesh.prototype.updateMatrixWorld.call( this, true );
  13763. if ( this.bindMode === "attached" ) {
  13764. this.bindMatrixInverse.getInverse( this.matrixWorld );
  13765. } else if ( this.bindMode === "detached" ) {
  13766. this.bindMatrixInverse.getInverse( this.bindMatrix );
  13767. } else {
  13768. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  13769. }
  13770. },
  13771. clone: function() {
  13772. return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this );
  13773. }
  13774. } );
  13775. /**
  13776. * @author mrdoob / http://mrdoob.com/
  13777. * @author alteredq / http://alteredqualia.com/
  13778. *
  13779. * parameters = {
  13780. * color: <hex>,
  13781. * opacity: <float>,
  13782. *
  13783. * linewidth: <float>,
  13784. * linecap: "round",
  13785. * linejoin: "round"
  13786. * }
  13787. */
  13788. function LineBasicMaterial( parameters ) {
  13789. Material.call( this );
  13790. this.type = 'LineBasicMaterial';
  13791. this.color = new Color( 0xffffff );
  13792. this.linewidth = 1;
  13793. this.linecap = 'round';
  13794. this.linejoin = 'round';
  13795. this.lights = false;
  13796. this.setValues( parameters );
  13797. }
  13798. LineBasicMaterial.prototype = Object.create( Material.prototype );
  13799. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  13800. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  13801. LineBasicMaterial.prototype.copy = function ( source ) {
  13802. Material.prototype.copy.call( this, source );
  13803. this.color.copy( source.color );
  13804. this.linewidth = source.linewidth;
  13805. this.linecap = source.linecap;
  13806. this.linejoin = source.linejoin;
  13807. return this;
  13808. };
  13809. /**
  13810. * @author mrdoob / http://mrdoob.com/
  13811. */
  13812. function Line( geometry, material, mode ) {
  13813. if ( mode === 1 ) {
  13814. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  13815. return new LineSegments( geometry, material );
  13816. }
  13817. Object3D.call( this );
  13818. this.type = 'Line';
  13819. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13820. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  13821. }
  13822. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13823. constructor: Line,
  13824. isLine: true,
  13825. raycast: ( function () {
  13826. var inverseMatrix = new Matrix4();
  13827. var ray = new Ray();
  13828. var sphere = new Sphere();
  13829. return function raycast( raycaster, intersects ) {
  13830. var precision = raycaster.linePrecision;
  13831. var precisionSq = precision * precision;
  13832. var geometry = this.geometry;
  13833. var matrixWorld = this.matrixWorld;
  13834. // Checking boundingSphere distance to ray
  13835. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13836. sphere.copy( geometry.boundingSphere );
  13837. sphere.applyMatrix4( matrixWorld );
  13838. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13839. //
  13840. inverseMatrix.getInverse( matrixWorld );
  13841. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13842. var vStart = new Vector3();
  13843. var vEnd = new Vector3();
  13844. var interSegment = new Vector3();
  13845. var interRay = new Vector3();
  13846. var step = (this && this.isLineSegments) ? 2 : 1;
  13847. if ( geometry.isBufferGeometry ) {
  13848. var index = geometry.index;
  13849. var attributes = geometry.attributes;
  13850. var positions = attributes.position.array;
  13851. if ( index !== null ) {
  13852. var indices = index.array;
  13853. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  13854. var a = indices[ i ];
  13855. var b = indices[ i + 1 ];
  13856. vStart.fromArray( positions, a * 3 );
  13857. vEnd.fromArray( positions, b * 3 );
  13858. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13859. if ( distSq > precisionSq ) continue;
  13860. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13861. var distance = raycaster.ray.origin.distanceTo( interRay );
  13862. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13863. intersects.push( {
  13864. distance: distance,
  13865. // What do we want? intersection point on the ray or on the segment??
  13866. // point: raycaster.ray.at( distance ),
  13867. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13868. index: i,
  13869. face: null,
  13870. faceIndex: null,
  13871. object: this
  13872. } );
  13873. }
  13874. } else {
  13875. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  13876. vStart.fromArray( positions, 3 * i );
  13877. vEnd.fromArray( positions, 3 * i + 3 );
  13878. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13879. if ( distSq > precisionSq ) continue;
  13880. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13881. var distance = raycaster.ray.origin.distanceTo( interRay );
  13882. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13883. intersects.push( {
  13884. distance: distance,
  13885. // What do we want? intersection point on the ray or on the segment??
  13886. // point: raycaster.ray.at( distance ),
  13887. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13888. index: i,
  13889. face: null,
  13890. faceIndex: null,
  13891. object: this
  13892. } );
  13893. }
  13894. }
  13895. } else if ( geometry.isGeometry ) {
  13896. var vertices = geometry.vertices;
  13897. var nbVertices = vertices.length;
  13898. for ( var i = 0; i < nbVertices - 1; i += step ) {
  13899. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  13900. if ( distSq > precisionSq ) continue;
  13901. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13902. var distance = raycaster.ray.origin.distanceTo( interRay );
  13903. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13904. intersects.push( {
  13905. distance: distance,
  13906. // What do we want? intersection point on the ray or on the segment??
  13907. // point: raycaster.ray.at( distance ),
  13908. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13909. index: i,
  13910. face: null,
  13911. faceIndex: null,
  13912. object: this
  13913. } );
  13914. }
  13915. }
  13916. };
  13917. }() ),
  13918. clone: function () {
  13919. return new this.constructor( this.geometry, this.material ).copy( this );
  13920. }
  13921. } );
  13922. /**
  13923. * @author mrdoob / http://mrdoob.com/
  13924. */
  13925. function LineSegments( geometry, material ) {
  13926. Line.call( this, geometry, material );
  13927. this.type = 'LineSegments';
  13928. }
  13929. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  13930. constructor: LineSegments,
  13931. isLineSegments: true
  13932. } );
  13933. /**
  13934. * @author mrdoob / http://mrdoob.com/
  13935. * @author alteredq / http://alteredqualia.com/
  13936. *
  13937. * parameters = {
  13938. * color: <hex>,
  13939. * opacity: <float>,
  13940. * map: new THREE.Texture( <Image> ),
  13941. *
  13942. * size: <float>,
  13943. * sizeAttenuation: <bool>
  13944. * }
  13945. */
  13946. function PointsMaterial( parameters ) {
  13947. Material.call( this );
  13948. this.type = 'PointsMaterial';
  13949. this.color = new Color( 0xffffff );
  13950. this.map = null;
  13951. this.size = 1;
  13952. this.sizeAttenuation = true;
  13953. this.lights = false;
  13954. this.setValues( parameters );
  13955. }
  13956. PointsMaterial.prototype = Object.create( Material.prototype );
  13957. PointsMaterial.prototype.constructor = PointsMaterial;
  13958. PointsMaterial.prototype.isPointsMaterial = true;
  13959. PointsMaterial.prototype.copy = function ( source ) {
  13960. Material.prototype.copy.call( this, source );
  13961. this.color.copy( source.color );
  13962. this.map = source.map;
  13963. this.size = source.size;
  13964. this.sizeAttenuation = source.sizeAttenuation;
  13965. return this;
  13966. };
  13967. /**
  13968. * @author alteredq / http://alteredqualia.com/
  13969. */
  13970. function Points( geometry, material ) {
  13971. Object3D.call( this );
  13972. this.type = 'Points';
  13973. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13974. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  13975. }
  13976. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13977. constructor: Points,
  13978. isPoints: true,
  13979. raycast: ( function () {
  13980. var inverseMatrix = new Matrix4();
  13981. var ray = new Ray();
  13982. var sphere = new Sphere();
  13983. return function raycast( raycaster, intersects ) {
  13984. var object = this;
  13985. var geometry = this.geometry;
  13986. var matrixWorld = this.matrixWorld;
  13987. var threshold = raycaster.params.Points.threshold;
  13988. // Checking boundingSphere distance to ray
  13989. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13990. sphere.copy( geometry.boundingSphere );
  13991. sphere.applyMatrix4( matrixWorld );
  13992. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13993. //
  13994. inverseMatrix.getInverse( matrixWorld );
  13995. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13996. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  13997. var localThresholdSq = localThreshold * localThreshold;
  13998. var position = new Vector3();
  13999. function testPoint( point, index ) {
  14000. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  14001. if ( rayPointDistanceSq < localThresholdSq ) {
  14002. var intersectPoint = ray.closestPointToPoint( point );
  14003. intersectPoint.applyMatrix4( matrixWorld );
  14004. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  14005. if ( distance < raycaster.near || distance > raycaster.far ) return;
  14006. intersects.push( {
  14007. distance: distance,
  14008. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  14009. point: intersectPoint.clone(),
  14010. index: index,
  14011. face: null,
  14012. object: object
  14013. } );
  14014. }
  14015. }
  14016. if ( geometry.isBufferGeometry ) {
  14017. var index = geometry.index;
  14018. var attributes = geometry.attributes;
  14019. var positions = attributes.position.array;
  14020. if ( index !== null ) {
  14021. var indices = index.array;
  14022. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  14023. var a = indices[ i ];
  14024. position.fromArray( positions, a * 3 );
  14025. testPoint( position, a );
  14026. }
  14027. } else {
  14028. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  14029. position.fromArray( positions, i * 3 );
  14030. testPoint( position, i );
  14031. }
  14032. }
  14033. } else {
  14034. var vertices = geometry.vertices;
  14035. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  14036. testPoint( vertices[ i ], i );
  14037. }
  14038. }
  14039. };
  14040. }() ),
  14041. clone: function () {
  14042. return new this.constructor( this.geometry, this.material ).copy( this );
  14043. }
  14044. } );
  14045. /**
  14046. * @author mrdoob / http://mrdoob.com/
  14047. */
  14048. function Group() {
  14049. Object3D.call( this );
  14050. this.type = 'Group';
  14051. }
  14052. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14053. constructor: Group
  14054. } );
  14055. /**
  14056. * @author mrdoob / http://mrdoob.com/
  14057. */
  14058. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14059. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14060. this.generateMipmaps = false;
  14061. var scope = this;
  14062. function update() {
  14063. requestAnimationFrame( update );
  14064. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  14065. scope.needsUpdate = true;
  14066. }
  14067. }
  14068. update();
  14069. }
  14070. VideoTexture.prototype = Object.create( Texture.prototype );
  14071. VideoTexture.prototype.constructor = VideoTexture;
  14072. /**
  14073. * @author alteredq / http://alteredqualia.com/
  14074. */
  14075. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  14076. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  14077. this.image = { width: width, height: height };
  14078. this.mipmaps = mipmaps;
  14079. // no flipping for cube textures
  14080. // (also flipping doesn't work for compressed textures )
  14081. this.flipY = false;
  14082. // can't generate mipmaps for compressed textures
  14083. // mips must be embedded in DDS files
  14084. this.generateMipmaps = false;
  14085. }
  14086. CompressedTexture.prototype = Object.create( Texture.prototype );
  14087. CompressedTexture.prototype.constructor = CompressedTexture;
  14088. CompressedTexture.prototype.isCompressedTexture = true;
  14089. /**
  14090. * @author mrdoob / http://mrdoob.com/
  14091. */
  14092. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14093. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14094. this.needsUpdate = true;
  14095. }
  14096. CanvasTexture.prototype = Object.create( Texture.prototype );
  14097. CanvasTexture.prototype.constructor = CanvasTexture;
  14098. /**
  14099. * @author Matt DesLauriers / @mattdesl
  14100. * @author atix / arthursilber.de
  14101. */
  14102. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  14103. format = format !== undefined ? format : DepthFormat;
  14104. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  14105. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' )
  14106. }
  14107. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  14108. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  14109. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14110. this.image = { width: width, height: height };
  14111. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14112. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14113. this.flipY = false;
  14114. this.generateMipmaps = false;
  14115. }
  14116. DepthTexture.prototype = Object.create( Texture.prototype );
  14117. DepthTexture.prototype.constructor = DepthTexture;
  14118. DepthTexture.prototype.isDepthTexture = true;
  14119. /**
  14120. * @author mrdoob / http://mrdoob.com/
  14121. */
  14122. function WireframeGeometry( geometry ) {
  14123. BufferGeometry.call( this );
  14124. var edge = [ 0, 0 ], hash = {};
  14125. function sortFunction( a, b ) {
  14126. return a - b;
  14127. }
  14128. var keys = [ 'a', 'b', 'c' ];
  14129. if ( geometry && geometry.isGeometry ) {
  14130. var vertices = geometry.vertices;
  14131. var faces = geometry.faces;
  14132. var numEdges = 0;
  14133. // allocate maximal size
  14134. var edges = new Uint32Array( 6 * faces.length );
  14135. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  14136. var face = faces[ i ];
  14137. for ( var j = 0; j < 3; j ++ ) {
  14138. edge[ 0 ] = face[ keys[ j ] ];
  14139. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  14140. edge.sort( sortFunction );
  14141. var key = edge.toString();
  14142. if ( hash[ key ] === undefined ) {
  14143. edges[ 2 * numEdges ] = edge[ 0 ];
  14144. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  14145. hash[ key ] = true;
  14146. numEdges ++;
  14147. }
  14148. }
  14149. }
  14150. var coords = new Float32Array( numEdges * 2 * 3 );
  14151. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  14152. for ( var j = 0; j < 2; j ++ ) {
  14153. var vertex = vertices[ edges [ 2 * i + j ] ];
  14154. var index = 6 * i + 3 * j;
  14155. coords[ index + 0 ] = vertex.x;
  14156. coords[ index + 1 ] = vertex.y;
  14157. coords[ index + 2 ] = vertex.z;
  14158. }
  14159. }
  14160. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  14161. } else if ( geometry && geometry.isBufferGeometry ) {
  14162. if ( geometry.index !== null ) {
  14163. // Indexed BufferGeometry
  14164. var indices = geometry.index.array;
  14165. var vertices = geometry.attributes.position;
  14166. var groups = geometry.groups;
  14167. var numEdges = 0;
  14168. if ( groups.length === 0 ) {
  14169. geometry.addGroup( 0, indices.length );
  14170. }
  14171. // allocate maximal size
  14172. var edges = new Uint32Array( 2 * indices.length );
  14173. for ( var o = 0, ol = groups.length; o < ol; ++ o ) {
  14174. var group = groups[ o ];
  14175. var start = group.start;
  14176. var count = group.count;
  14177. for ( var i = start, il = start + count; i < il; i += 3 ) {
  14178. for ( var j = 0; j < 3; j ++ ) {
  14179. edge[ 0 ] = indices[ i + j ];
  14180. edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
  14181. edge.sort( sortFunction );
  14182. var key = edge.toString();
  14183. if ( hash[ key ] === undefined ) {
  14184. edges[ 2 * numEdges ] = edge[ 0 ];
  14185. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  14186. hash[ key ] = true;
  14187. numEdges ++;
  14188. }
  14189. }
  14190. }
  14191. }
  14192. var coords = new Float32Array( numEdges * 2 * 3 );
  14193. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  14194. for ( var j = 0; j < 2; j ++ ) {
  14195. var index = 6 * i + 3 * j;
  14196. var index2 = edges[ 2 * i + j ];
  14197. coords[ index + 0 ] = vertices.getX( index2 );
  14198. coords[ index + 1 ] = vertices.getY( index2 );
  14199. coords[ index + 2 ] = vertices.getZ( index2 );
  14200. }
  14201. }
  14202. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  14203. } else {
  14204. // non-indexed BufferGeometry
  14205. var vertices = geometry.attributes.position.array;
  14206. var numEdges = vertices.length / 3;
  14207. var numTris = numEdges / 3;
  14208. var coords = new Float32Array( numEdges * 2 * 3 );
  14209. for ( var i = 0, l = numTris; i < l; i ++ ) {
  14210. for ( var j = 0; j < 3; j ++ ) {
  14211. var index = 18 * i + 6 * j;
  14212. var index1 = 9 * i + 3 * j;
  14213. coords[ index + 0 ] = vertices[ index1 ];
  14214. coords[ index + 1 ] = vertices[ index1 + 1 ];
  14215. coords[ index + 2 ] = vertices[ index1 + 2 ];
  14216. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  14217. coords[ index + 3 ] = vertices[ index2 ];
  14218. coords[ index + 4 ] = vertices[ index2 + 1 ];
  14219. coords[ index + 5 ] = vertices[ index2 + 2 ];
  14220. }
  14221. }
  14222. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  14223. }
  14224. }
  14225. }
  14226. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  14227. WireframeGeometry.prototype.constructor = WireframeGeometry;
  14228. /**
  14229. * @author Mugen87 / https://github.com/Mugen87
  14230. *
  14231. * Parametric Surfaces Geometry
  14232. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  14233. */
  14234. function ParametricBufferGeometry( func, slices, stacks ) {
  14235. BufferGeometry.call( this );
  14236. this.type = 'ParametricBufferGeometry';
  14237. this.parameters = {
  14238. func: func,
  14239. slices: slices,
  14240. stacks: stacks
  14241. };
  14242. // generate vertices and uvs
  14243. var vertices = [];
  14244. var uvs = [];
  14245. var i, j, p;
  14246. var u, v;
  14247. var sliceCount = slices + 1;
  14248. for ( i = 0; i <= stacks; i ++ ) {
  14249. v = i / stacks;
  14250. for ( j = 0; j <= slices; j ++ ) {
  14251. u = j / slices;
  14252. p = func( u, v );
  14253. vertices.push( p.x, p.y, p.z );
  14254. uvs.push( u, v );
  14255. }
  14256. }
  14257. // generate indices
  14258. var indices = [];
  14259. var a, b, c, d;
  14260. for ( i = 0; i < stacks; i ++ ) {
  14261. for ( j = 0; j < slices; j ++ ) {
  14262. a = i * sliceCount + j;
  14263. b = i * sliceCount + j + 1;
  14264. c = ( i + 1 ) * sliceCount + j + 1;
  14265. d = ( i + 1 ) * sliceCount + j;
  14266. // faces one and two
  14267. indices.push( a, b, d );
  14268. indices.push( b, c, d );
  14269. }
  14270. }
  14271. // build geometry
  14272. this.setIndex( new ( indices.length > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  14273. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14274. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14275. // generate normals
  14276. this.computeVertexNormals();
  14277. }
  14278. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14279. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  14280. /**
  14281. * @author zz85 / https://github.com/zz85
  14282. *
  14283. * Parametric Surfaces Geometry
  14284. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  14285. */
  14286. function ParametricGeometry( func, slices, stacks ) {
  14287. Geometry.call( this );
  14288. this.type = 'ParametricGeometry';
  14289. this.parameters = {
  14290. func: func,
  14291. slices: slices,
  14292. stacks: stacks
  14293. };
  14294. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  14295. this.mergeVertices();
  14296. }
  14297. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  14298. ParametricGeometry.prototype.constructor = ParametricGeometry;
  14299. /**
  14300. * @author Mugen87 / https://github.com/Mugen87
  14301. */
  14302. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  14303. BufferGeometry.call( this );
  14304. this.type = 'PolyhedronBufferGeometry';
  14305. this.parameters = {
  14306. vertices: vertices,
  14307. indices: indices,
  14308. radius: radius,
  14309. detail: detail
  14310. };
  14311. radius = radius || 1;
  14312. detail = detail || 0;
  14313. // default buffer data
  14314. var vertexBuffer = [];
  14315. var uvBuffer = [];
  14316. // the subdivision creates the vertex buffer data
  14317. subdivide( detail );
  14318. // all vertices should lie on a conceptual sphere with a given radius
  14319. appplyRadius( radius );
  14320. // finally, create the uv data
  14321. generateUVs();
  14322. // build non-indexed geometry
  14323. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  14324. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  14325. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  14326. this.normalizeNormals();
  14327. this.boundingSphere = new Sphere( new Vector3(), radius );
  14328. // helper functions
  14329. function subdivide( detail ) {
  14330. var a = new Vector3();
  14331. var b = new Vector3();
  14332. var c = new Vector3();
  14333. // iterate over all faces and apply a subdivison with the given detail value
  14334. for ( var i = 0; i < indices.length; i += 3 ) {
  14335. // get the vertices of the face
  14336. getVertexByIndex( indices[ i + 0 ], a );
  14337. getVertexByIndex( indices[ i + 1 ], b );
  14338. getVertexByIndex( indices[ i + 2 ], c );
  14339. // perform subdivision
  14340. subdivideFace( a, b, c, detail );
  14341. }
  14342. }
  14343. function subdivideFace( a, b, c, detail ) {
  14344. var cols = Math.pow( 2, detail );
  14345. // we use this multidimensional array as a data structure for creating the subdivision
  14346. var v = [];
  14347. var i, j;
  14348. // construct all of the vertices for this subdivision
  14349. for ( i = 0 ; i <= cols; i ++ ) {
  14350. v[ i ] = [];
  14351. var aj = a.clone().lerp( c, i / cols );
  14352. var bj = b.clone().lerp( c, i / cols );
  14353. var rows = cols - i;
  14354. for ( j = 0; j <= rows; j ++ ) {
  14355. if ( j === 0 && i === cols ) {
  14356. v[ i ][ j ] = aj;
  14357. } else {
  14358. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  14359. }
  14360. }
  14361. }
  14362. // construct all of the faces
  14363. for ( i = 0; i < cols ; i ++ ) {
  14364. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  14365. var k = Math.floor( j / 2 );
  14366. if ( j % 2 === 0 ) {
  14367. pushVertex( v[ i ][ k + 1 ] );
  14368. pushVertex( v[ i + 1 ][ k ] );
  14369. pushVertex( v[ i ][ k ] );
  14370. } else {
  14371. pushVertex( v[ i ][ k + 1 ] );
  14372. pushVertex( v[ i + 1 ][ k + 1 ] );
  14373. pushVertex( v[ i + 1 ][ k ] );
  14374. }
  14375. }
  14376. }
  14377. }
  14378. function appplyRadius( radius ) {
  14379. var vertex = new Vector3();
  14380. // iterate over the entire buffer and apply the radius to each vertex
  14381. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14382. vertex.x = vertexBuffer[ i + 0 ];
  14383. vertex.y = vertexBuffer[ i + 1 ];
  14384. vertex.z = vertexBuffer[ i + 2 ];
  14385. vertex.normalize().multiplyScalar( radius );
  14386. vertexBuffer[ i + 0 ] = vertex.x;
  14387. vertexBuffer[ i + 1 ] = vertex.y;
  14388. vertexBuffer[ i + 2 ] = vertex.z;
  14389. }
  14390. }
  14391. function generateUVs() {
  14392. var vertex = new Vector3();
  14393. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14394. vertex.x = vertexBuffer[ i + 0 ];
  14395. vertex.y = vertexBuffer[ i + 1 ];
  14396. vertex.z = vertexBuffer[ i + 2 ];
  14397. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  14398. var v = inclination( vertex ) / Math.PI + 0.5;
  14399. uvBuffer.push( u, 1 - v );
  14400. }
  14401. correctUVs();
  14402. correctSeam();
  14403. }
  14404. function correctSeam() {
  14405. // handle case when face straddles the seam, see #3269
  14406. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  14407. // uv data of a single face
  14408. var x0 = uvBuffer[ i + 0 ];
  14409. var x1 = uvBuffer[ i + 2 ];
  14410. var x2 = uvBuffer[ i + 4 ];
  14411. var max = Math.max( x0, x1, x2 );
  14412. var min = Math.min( x0, x1, x2 );
  14413. // 0.9 is somewhat arbitrary
  14414. if ( max > 0.9 && min < 0.1 ) {
  14415. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  14416. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  14417. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  14418. }
  14419. }
  14420. }
  14421. function pushVertex( vertex ) {
  14422. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  14423. }
  14424. function getVertexByIndex( index, vertex ) {
  14425. var stride = index * 3;
  14426. vertex.x = vertices[ stride + 0 ];
  14427. vertex.y = vertices[ stride + 1 ];
  14428. vertex.z = vertices[ stride + 2 ];
  14429. }
  14430. function correctUVs() {
  14431. var a = new Vector3();
  14432. var b = new Vector3();
  14433. var c = new Vector3();
  14434. var centroid = new Vector3();
  14435. var uvA = new Vector2();
  14436. var uvB = new Vector2();
  14437. var uvC = new Vector2();
  14438. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  14439. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  14440. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  14441. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  14442. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  14443. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  14444. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  14445. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  14446. var azi = azimuth( centroid );
  14447. correctUV( uvA, j + 0, a, azi );
  14448. correctUV( uvB, j + 2, b, azi );
  14449. correctUV( uvC, j + 4, c, azi );
  14450. }
  14451. }
  14452. function correctUV( uv, stride, vector, azimuth ) {
  14453. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  14454. uvBuffer[ stride ] = uv.x - 1;
  14455. }
  14456. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  14457. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  14458. }
  14459. }
  14460. // Angle around the Y axis, counter-clockwise when looking from above.
  14461. function azimuth( vector ) {
  14462. return Math.atan2( vector.z, - vector.x );
  14463. }
  14464. // Angle above the XZ plane.
  14465. function inclination( vector ) {
  14466. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  14467. }
  14468. }
  14469. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14470. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  14471. /**
  14472. * @author Mugen87 / https://github.com/Mugen87
  14473. */
  14474. function TetrahedronBufferGeometry( radius, detail ) {
  14475. var vertices = [
  14476. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  14477. ];
  14478. var indices = [
  14479. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  14480. ];
  14481. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14482. this.type = 'TetrahedronBufferGeometry';
  14483. this.parameters = {
  14484. radius: radius,
  14485. detail: detail
  14486. };
  14487. }
  14488. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14489. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  14490. /**
  14491. * @author timothypratley / https://github.com/timothypratley
  14492. */
  14493. function TetrahedronGeometry( radius, detail ) {
  14494. Geometry.call( this );
  14495. this.type = 'TetrahedronGeometry';
  14496. this.parameters = {
  14497. radius: radius,
  14498. detail: detail
  14499. };
  14500. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  14501. this.mergeVertices();
  14502. }
  14503. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  14504. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  14505. /**
  14506. * @author Mugen87 / https://github.com/Mugen87
  14507. */
  14508. function OctahedronBufferGeometry( radius,detail ) {
  14509. var vertices = [
  14510. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  14511. ];
  14512. var indices = [
  14513. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  14514. ];
  14515. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14516. this.type = 'OctahedronBufferGeometry';
  14517. this.parameters = {
  14518. radius: radius,
  14519. detail: detail
  14520. };
  14521. }
  14522. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14523. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  14524. /**
  14525. * @author timothypratley / https://github.com/timothypratley
  14526. */
  14527. function OctahedronGeometry( radius, detail ) {
  14528. Geometry.call( this );
  14529. this.type = 'OctahedronGeometry';
  14530. this.parameters = {
  14531. radius: radius,
  14532. detail: detail
  14533. };
  14534. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  14535. this.mergeVertices();
  14536. }
  14537. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  14538. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  14539. /**
  14540. * @author Mugen87 / https://github.com/Mugen87
  14541. */
  14542. function IcosahedronBufferGeometry( radius, detail ) {
  14543. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  14544. var vertices = [
  14545. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  14546. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  14547. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  14548. ];
  14549. var indices = [
  14550. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  14551. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  14552. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  14553. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  14554. ];
  14555. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14556. this.type = 'IcosahedronBufferGeometry';
  14557. this.parameters = {
  14558. radius: radius,
  14559. detail: detail
  14560. };
  14561. }
  14562. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14563. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  14564. /**
  14565. * @author timothypratley / https://github.com/timothypratley
  14566. */
  14567. function IcosahedronGeometry( radius, detail ) {
  14568. Geometry.call( this );
  14569. this.type = 'IcosahedronGeometry';
  14570. this.parameters = {
  14571. radius: radius,
  14572. detail: detail
  14573. };
  14574. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  14575. this.mergeVertices();
  14576. }
  14577. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  14578. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  14579. /**
  14580. * @author Mugen87 / https://github.com/Mugen87
  14581. */
  14582. function DodecahedronBufferGeometry( radius, detail ) {
  14583. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  14584. var r = 1 / t;
  14585. var vertices = [
  14586. // (±1, ±1, ±1)
  14587. - 1, - 1, - 1, - 1, - 1, 1,
  14588. - 1, 1, - 1, - 1, 1, 1,
  14589. 1, - 1, - 1, 1, - 1, 1,
  14590. 1, 1, - 1, 1, 1, 1,
  14591. // (0, ±1/φ, ±φ)
  14592. 0, - r, - t, 0, - r, t,
  14593. 0, r, - t, 0, r, t,
  14594. // (±1/φ, ±φ, 0)
  14595. - r, - t, 0, - r, t, 0,
  14596. r, - t, 0, r, t, 0,
  14597. // (±φ, 0, ±1/φ)
  14598. - t, 0, - r, t, 0, - r,
  14599. - t, 0, r, t, 0, r
  14600. ];
  14601. var indices = [
  14602. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  14603. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  14604. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  14605. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  14606. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  14607. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  14608. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  14609. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  14610. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  14611. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  14612. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  14613. 1, 12, 14, 1, 14, 5, 1, 5, 9
  14614. ];
  14615. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14616. this.type = 'DodecahedronBufferGeometry';
  14617. this.parameters = {
  14618. radius: radius,
  14619. detail: detail
  14620. };
  14621. }
  14622. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14623. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  14624. /**
  14625. * @author Abe Pazos / https://hamoid.com
  14626. */
  14627. function DodecahedronGeometry( radius, detail ) {
  14628. Geometry.call( this );
  14629. this.type = 'DodecahedronGeometry';
  14630. this.parameters = {
  14631. radius: radius,
  14632. detail: detail
  14633. };
  14634. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  14635. this.mergeVertices();
  14636. }
  14637. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  14638. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  14639. /**
  14640. * @author clockworkgeek / https://github.com/clockworkgeek
  14641. * @author timothypratley / https://github.com/timothypratley
  14642. * @author WestLangley / http://github.com/WestLangley
  14643. */
  14644. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  14645. Geometry.call( this );
  14646. this.type = 'PolyhedronGeometry';
  14647. this.parameters = {
  14648. vertices: vertices,
  14649. indices: indices,
  14650. radius: radius,
  14651. detail: detail
  14652. };
  14653. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  14654. this.mergeVertices();
  14655. }
  14656. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  14657. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  14658. /**
  14659. * @author Mugen87 / https://github.com/Mugen87
  14660. *
  14661. * Creates a tube which extrudes along a 3d spline.
  14662. *
  14663. */
  14664. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  14665. BufferGeometry.call( this );
  14666. this.type = 'TubeBufferGeometry';
  14667. this.parameters = {
  14668. path: path,
  14669. tubularSegments: tubularSegments,
  14670. radius: radius,
  14671. radialSegments: radialSegments,
  14672. closed: closed
  14673. };
  14674. tubularSegments = tubularSegments || 64;
  14675. radius = radius || 1;
  14676. radialSegments = radialSegments || 8;
  14677. closed = closed || false;
  14678. var frames = path.computeFrenetFrames( tubularSegments, closed );
  14679. // expose internals
  14680. this.tangents = frames.tangents;
  14681. this.normals = frames.normals;
  14682. this.binormals = frames.binormals;
  14683. // helper variables
  14684. var vertex = new Vector3();
  14685. var normal = new Vector3();
  14686. var uv = new Vector2();
  14687. var i, j;
  14688. // buffer
  14689. var vertices = [];
  14690. var normals = [];
  14691. var uvs = [];
  14692. var indices = [];
  14693. // create buffer data
  14694. generateBufferData();
  14695. // build geometry
  14696. this.setIndex( new ( indices.length > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  14697. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14698. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  14699. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14700. // functions
  14701. function generateBufferData() {
  14702. for ( i = 0; i < tubularSegments; i ++ ) {
  14703. generateSegment( i );
  14704. }
  14705. // if the geometry is not closed, generate the last row of vertices and normals
  14706. // at the regular position on the given path
  14707. //
  14708. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  14709. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  14710. // uvs are generated in a separate function.
  14711. // this makes it easy compute correct values for closed geometries
  14712. generateUVs();
  14713. // finally create faces
  14714. generateIndices();
  14715. }
  14716. function generateSegment( i ) {
  14717. // we use getPointAt to sample evenly distributed points from the given path
  14718. var P = path.getPointAt( i / tubularSegments );
  14719. // retrieve corresponding normal and binormal
  14720. var N = frames.normals[ i ];
  14721. var B = frames.binormals[ i ];
  14722. // generate normals and vertices for the current segment
  14723. for ( j = 0; j <= radialSegments; j ++ ) {
  14724. var v = j / radialSegments * Math.PI * 2;
  14725. var sin = Math.sin( v );
  14726. var cos = - Math.cos( v );
  14727. // normal
  14728. normal.x = ( cos * N.x + sin * B.x );
  14729. normal.y = ( cos * N.y + sin * B.y );
  14730. normal.z = ( cos * N.z + sin * B.z );
  14731. normal.normalize();
  14732. normals.push( normal.x, normal.y, normal.z );
  14733. // vertex
  14734. vertex.x = P.x + radius * normal.x;
  14735. vertex.y = P.y + radius * normal.y;
  14736. vertex.z = P.z + radius * normal.z;
  14737. vertices.push( vertex.x, vertex.y, vertex.z );
  14738. }
  14739. }
  14740. function generateIndices() {
  14741. for ( j = 1; j <= tubularSegments; j ++ ) {
  14742. for ( i = 1; i <= radialSegments; i ++ ) {
  14743. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  14744. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  14745. var c = ( radialSegments + 1 ) * j + i;
  14746. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  14747. // faces
  14748. indices.push( a, b, d );
  14749. indices.push( b, c, d );
  14750. }
  14751. }
  14752. }
  14753. function generateUVs() {
  14754. for ( i = 0; i <= tubularSegments; i ++ ) {
  14755. for ( j = 0; j <= radialSegments; j ++ ) {
  14756. uv.x = i / tubularSegments;
  14757. uv.y = j / radialSegments;
  14758. uvs.push( uv.x, uv.y );
  14759. }
  14760. }
  14761. }
  14762. }
  14763. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14764. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  14765. /**
  14766. * @author oosmoxiecode / https://github.com/oosmoxiecode
  14767. * @author WestLangley / https://github.com/WestLangley
  14768. * @author zz85 / https://github.com/zz85
  14769. * @author miningold / https://github.com/miningold
  14770. * @author jonobr1 / https://github.com/jonobr1
  14771. *
  14772. * Creates a tube which extrudes along a 3d spline.
  14773. */
  14774. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  14775. Geometry.call( this );
  14776. this.type = 'TubeGeometry';
  14777. this.parameters = {
  14778. path: path,
  14779. tubularSegments: tubularSegments,
  14780. radius: radius,
  14781. radialSegments: radialSegments,
  14782. closed: closed
  14783. };
  14784. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  14785. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  14786. // expose internals
  14787. this.tangents = bufferGeometry.tangents;
  14788. this.normals = bufferGeometry.normals;
  14789. this.binormals = bufferGeometry.binormals;
  14790. // create geometry
  14791. this.fromBufferGeometry( bufferGeometry );
  14792. this.mergeVertices();
  14793. }
  14794. TubeGeometry.prototype = Object.create( Geometry.prototype );
  14795. TubeGeometry.prototype.constructor = TubeGeometry;
  14796. /**
  14797. * @author Mugen87 / https://github.com/Mugen87
  14798. *
  14799. * see: http://www.blackpawn.com/texts/pqtorus/
  14800. */
  14801. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  14802. BufferGeometry.call( this );
  14803. this.type = 'TorusKnotBufferGeometry';
  14804. this.parameters = {
  14805. radius: radius,
  14806. tube: tube,
  14807. tubularSegments: tubularSegments,
  14808. radialSegments: radialSegments,
  14809. p: p,
  14810. q: q
  14811. };
  14812. radius = radius || 100;
  14813. tube = tube || 40;
  14814. tubularSegments = Math.floor( tubularSegments ) || 64;
  14815. radialSegments = Math.floor( radialSegments ) || 8;
  14816. p = p || 2;
  14817. q = q || 3;
  14818. // used to calculate buffer length
  14819. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  14820. var indexCount = radialSegments * tubularSegments * 2 * 3;
  14821. // buffers
  14822. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  14823. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  14824. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  14825. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  14826. // helper variables
  14827. var i, j, index = 0, indexOffset = 0;
  14828. var vertex = new Vector3();
  14829. var normal = new Vector3();
  14830. var uv = new Vector2();
  14831. var P1 = new Vector3();
  14832. var P2 = new Vector3();
  14833. var B = new Vector3();
  14834. var T = new Vector3();
  14835. var N = new Vector3();
  14836. // generate vertices, normals and uvs
  14837. for ( i = 0; i <= tubularSegments; ++ i ) {
  14838. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  14839. var u = i / tubularSegments * p * Math.PI * 2;
  14840. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  14841. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  14842. calculatePositionOnCurve( u, p, q, radius, P1 );
  14843. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  14844. // calculate orthonormal basis
  14845. T.subVectors( P2, P1 );
  14846. N.addVectors( P2, P1 );
  14847. B.crossVectors( T, N );
  14848. N.crossVectors( B, T );
  14849. // normalize B, N. T can be ignored, we don't use it
  14850. B.normalize();
  14851. N.normalize();
  14852. for ( j = 0; j <= radialSegments; ++ j ) {
  14853. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  14854. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  14855. var v = j / radialSegments * Math.PI * 2;
  14856. var cx = - tube * Math.cos( v );
  14857. var cy = tube * Math.sin( v );
  14858. // now calculate the final vertex position.
  14859. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  14860. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  14861. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  14862. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  14863. // vertex
  14864. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  14865. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  14866. normal.subVectors( vertex, P1 ).normalize();
  14867. normals.setXYZ( index, normal.x, normal.y, normal.z );
  14868. // uv
  14869. uv.x = i / tubularSegments;
  14870. uv.y = j / radialSegments;
  14871. uvs.setXY( index, uv.x, uv.y );
  14872. // increase index
  14873. index ++;
  14874. }
  14875. }
  14876. // generate indices
  14877. for ( j = 1; j <= tubularSegments; j ++ ) {
  14878. for ( i = 1; i <= radialSegments; i ++ ) {
  14879. // indices
  14880. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  14881. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  14882. var c = ( radialSegments + 1 ) * j + i;
  14883. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  14884. // face one
  14885. indices.setX( indexOffset, a ); indexOffset++;
  14886. indices.setX( indexOffset, b ); indexOffset++;
  14887. indices.setX( indexOffset, d ); indexOffset++;
  14888. // face two
  14889. indices.setX( indexOffset, b ); indexOffset++;
  14890. indices.setX( indexOffset, c ); indexOffset++;
  14891. indices.setX( indexOffset, d ); indexOffset++;
  14892. }
  14893. }
  14894. // build geometry
  14895. this.setIndex( indices );
  14896. this.addAttribute( 'position', vertices );
  14897. this.addAttribute( 'normal', normals );
  14898. this.addAttribute( 'uv', uvs );
  14899. // this function calculates the current position on the torus curve
  14900. function calculatePositionOnCurve( u, p, q, radius, position ) {
  14901. var cu = Math.cos( u );
  14902. var su = Math.sin( u );
  14903. var quOverP = q / p * u;
  14904. var cs = Math.cos( quOverP );
  14905. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  14906. position.y = radius * ( 2 + cs ) * su * 0.5;
  14907. position.z = radius * Math.sin( quOverP ) * 0.5;
  14908. }
  14909. }
  14910. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14911. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  14912. /**
  14913. * @author oosmoxiecode
  14914. */
  14915. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  14916. Geometry.call( this );
  14917. this.type = 'TorusKnotGeometry';
  14918. this.parameters = {
  14919. radius: radius,
  14920. tube: tube,
  14921. tubularSegments: tubularSegments,
  14922. radialSegments: radialSegments,
  14923. p: p,
  14924. q: q
  14925. };
  14926. if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  14927. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  14928. this.mergeVertices();
  14929. }
  14930. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  14931. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  14932. /**
  14933. * @author Mugen87 / https://github.com/Mugen87
  14934. */
  14935. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  14936. BufferGeometry.call( this );
  14937. this.type = 'TorusBufferGeometry';
  14938. this.parameters = {
  14939. radius: radius,
  14940. tube: tube,
  14941. radialSegments: radialSegments,
  14942. tubularSegments: tubularSegments,
  14943. arc: arc
  14944. };
  14945. radius = radius || 100;
  14946. tube = tube || 40;
  14947. radialSegments = Math.floor( radialSegments ) || 8;
  14948. tubularSegments = Math.floor( tubularSegments ) || 6;
  14949. arc = arc || Math.PI * 2;
  14950. // used to calculate buffer length
  14951. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  14952. var indexCount = radialSegments * tubularSegments * 2 * 3;
  14953. // buffers
  14954. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  14955. var vertices = new Float32Array( vertexCount * 3 );
  14956. var normals = new Float32Array( vertexCount * 3 );
  14957. var uvs = new Float32Array( vertexCount * 2 );
  14958. // offset variables
  14959. var vertexBufferOffset = 0;
  14960. var uvBufferOffset = 0;
  14961. var indexBufferOffset = 0;
  14962. // helper variables
  14963. var center = new Vector3();
  14964. var vertex = new Vector3();
  14965. var normal = new Vector3();
  14966. var j, i;
  14967. // generate vertices, normals and uvs
  14968. for ( j = 0; j <= radialSegments; j ++ ) {
  14969. for ( i = 0; i <= tubularSegments; i ++ ) {
  14970. var u = i / tubularSegments * arc;
  14971. var v = j / radialSegments * Math.PI * 2;
  14972. // vertex
  14973. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  14974. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  14975. vertex.z = tube * Math.sin( v );
  14976. vertices[ vertexBufferOffset ] = vertex.x;
  14977. vertices[ vertexBufferOffset + 1 ] = vertex.y;
  14978. vertices[ vertexBufferOffset + 2 ] = vertex.z;
  14979. // this vector is used to calculate the normal
  14980. center.x = radius * Math.cos( u );
  14981. center.y = radius * Math.sin( u );
  14982. // normal
  14983. normal.subVectors( vertex, center ).normalize();
  14984. normals[ vertexBufferOffset ] = normal.x;
  14985. normals[ vertexBufferOffset + 1 ] = normal.y;
  14986. normals[ vertexBufferOffset + 2 ] = normal.z;
  14987. // uv
  14988. uvs[ uvBufferOffset ] = i / tubularSegments;
  14989. uvs[ uvBufferOffset + 1 ] = j / radialSegments;
  14990. // update offsets
  14991. vertexBufferOffset += 3;
  14992. uvBufferOffset += 2;
  14993. }
  14994. }
  14995. // generate indices
  14996. for ( j = 1; j <= radialSegments; j ++ ) {
  14997. for ( i = 1; i <= tubularSegments; i ++ ) {
  14998. // indices
  14999. var a = ( tubularSegments + 1 ) * j + i - 1;
  15000. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  15001. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  15002. var d = ( tubularSegments + 1 ) * j + i;
  15003. // face one
  15004. indices[ indexBufferOffset ] = a;
  15005. indices[ indexBufferOffset + 1 ] = b;
  15006. indices[ indexBufferOffset + 2 ] = d;
  15007. // face two
  15008. indices[ indexBufferOffset + 3 ] = b;
  15009. indices[ indexBufferOffset + 4 ] = c;
  15010. indices[ indexBufferOffset + 5 ] = d;
  15011. // update offset
  15012. indexBufferOffset += 6;
  15013. }
  15014. }
  15015. // build geometry
  15016. this.setIndex( new BufferAttribute( indices, 1 ) );
  15017. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  15018. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  15019. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  15020. }
  15021. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15022. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  15023. /**
  15024. * @author oosmoxiecode
  15025. * @author mrdoob / http://mrdoob.com/
  15026. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  15027. */
  15028. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15029. Geometry.call( this );
  15030. this.type = 'TorusGeometry';
  15031. this.parameters = {
  15032. radius: radius,
  15033. tube: tube,
  15034. radialSegments: radialSegments,
  15035. tubularSegments: tubularSegments,
  15036. arc: arc
  15037. };
  15038. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  15039. }
  15040. TorusGeometry.prototype = Object.create( Geometry.prototype );
  15041. TorusGeometry.prototype.constructor = TorusGeometry;
  15042. /**
  15043. * @author zz85 / http://www.lab4games.net/zz85/blog
  15044. */
  15045. var ShapeUtils = {
  15046. // calculate area of the contour polygon
  15047. area: function ( contour ) {
  15048. var n = contour.length;
  15049. var a = 0.0;
  15050. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  15051. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15052. }
  15053. return a * 0.5;
  15054. },
  15055. triangulate: ( function () {
  15056. /**
  15057. * This code is a quick port of code written in C++ which was submitted to
  15058. * flipcode.com by John W. Ratcliff // July 22, 2000
  15059. * See original code and more information here:
  15060. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15061. *
  15062. * ported to actionscript by Zevan Rosser
  15063. * www.actionsnippet.com
  15064. *
  15065. * ported to javascript by Joshua Koo
  15066. * http://www.lab4games.net/zz85/blog
  15067. *
  15068. */
  15069. function snip( contour, u, v, w, n, verts ) {
  15070. var p;
  15071. var ax, ay, bx, by;
  15072. var cx, cy, px, py;
  15073. ax = contour[ verts[ u ] ].x;
  15074. ay = contour[ verts[ u ] ].y;
  15075. bx = contour[ verts[ v ] ].x;
  15076. by = contour[ verts[ v ] ].y;
  15077. cx = contour[ verts[ w ] ].x;
  15078. cy = contour[ verts[ w ] ].y;
  15079. if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false;
  15080. var aX, aY, bX, bY, cX, cY;
  15081. var apx, apy, bpx, bpy, cpx, cpy;
  15082. var cCROSSap, bCROSScp, aCROSSbp;
  15083. aX = cx - bx; aY = cy - by;
  15084. bX = ax - cx; bY = ay - cy;
  15085. cX = bx - ax; cY = by - ay;
  15086. for ( p = 0; p < n; p ++ ) {
  15087. px = contour[ verts[ p ] ].x;
  15088. py = contour[ verts[ p ] ].y;
  15089. if ( ( ( px === ax ) && ( py === ay ) ) ||
  15090. ( ( px === bx ) && ( py === by ) ) ||
  15091. ( ( px === cx ) && ( py === cy ) ) ) continue;
  15092. apx = px - ax; apy = py - ay;
  15093. bpx = px - bx; bpy = py - by;
  15094. cpx = px - cx; cpy = py - cy;
  15095. // see if p is inside triangle abc
  15096. aCROSSbp = aX * bpy - aY * bpx;
  15097. cCROSSap = cX * apy - cY * apx;
  15098. bCROSScp = bX * cpy - bY * cpx;
  15099. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  15100. }
  15101. return true;
  15102. }
  15103. // takes in an contour array and returns
  15104. return function triangulate( contour, indices ) {
  15105. var n = contour.length;
  15106. if ( n < 3 ) return null;
  15107. var result = [],
  15108. verts = [],
  15109. vertIndices = [];
  15110. /* we want a counter-clockwise polygon in verts */
  15111. var u, v, w;
  15112. if ( ShapeUtils.area( contour ) > 0.0 ) {
  15113. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  15114. } else {
  15115. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  15116. }
  15117. var nv = n;
  15118. /* remove nv - 2 vertices, creating 1 triangle every time */
  15119. var count = 2 * nv; /* error detection */
  15120. for ( v = nv - 1; nv > 2; ) {
  15121. /* if we loop, it is probably a non-simple polygon */
  15122. if ( ( count -- ) <= 0 ) {
  15123. //** Triangulate: ERROR - probable bad polygon!
  15124. //throw ( "Warning, unable to triangulate polygon!" );
  15125. //return null;
  15126. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15127. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  15128. if ( indices ) return vertIndices;
  15129. return result;
  15130. }
  15131. /* three consecutive vertices in current polygon, <u,v,w> */
  15132. u = v; if ( nv <= u ) u = 0; /* previous */
  15133. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15134. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15135. if ( snip( contour, u, v, w, nv, verts ) ) {
  15136. var a, b, c, s, t;
  15137. /* true names of the vertices */
  15138. a = verts[ u ];
  15139. b = verts[ v ];
  15140. c = verts[ w ];
  15141. /* output Triangle */
  15142. result.push( [ contour[ a ],
  15143. contour[ b ],
  15144. contour[ c ] ] );
  15145. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15146. /* remove v from the remaining polygon */
  15147. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  15148. verts[ s ] = verts[ t ];
  15149. }
  15150. nv --;
  15151. /* reset error detection counter */
  15152. count = 2 * nv;
  15153. }
  15154. }
  15155. if ( indices ) return vertIndices;
  15156. return result;
  15157. }
  15158. } )(),
  15159. triangulateShape: function ( contour, holes ) {
  15160. function removeDupEndPts(points) {
  15161. var l = points.length;
  15162. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  15163. points.pop();
  15164. }
  15165. }
  15166. removeDupEndPts( contour );
  15167. holes.forEach( removeDupEndPts );
  15168. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  15169. // inOtherPt needs to be collinear to the inSegment
  15170. if ( inSegPt1.x !== inSegPt2.x ) {
  15171. if ( inSegPt1.x < inSegPt2.x ) {
  15172. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  15173. } else {
  15174. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  15175. }
  15176. } else {
  15177. if ( inSegPt1.y < inSegPt2.y ) {
  15178. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  15179. } else {
  15180. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  15181. }
  15182. }
  15183. }
  15184. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  15185. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  15186. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  15187. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  15188. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  15189. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  15190. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  15191. if ( Math.abs( limit ) > Number.EPSILON ) {
  15192. // not parallel
  15193. var perpSeg2;
  15194. if ( limit > 0 ) {
  15195. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  15196. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15197. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  15198. } else {
  15199. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  15200. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15201. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  15202. }
  15203. // i.e. to reduce rounding errors
  15204. // intersection at endpoint of segment#1?
  15205. if ( perpSeg2 === 0 ) {
  15206. if ( ( inExcludeAdjacentSegs ) &&
  15207. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15208. return [ inSeg1Pt1 ];
  15209. }
  15210. if ( perpSeg2 === limit ) {
  15211. if ( ( inExcludeAdjacentSegs ) &&
  15212. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15213. return [ inSeg1Pt2 ];
  15214. }
  15215. // intersection at endpoint of segment#2?
  15216. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  15217. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  15218. // return real intersection point
  15219. var factorSeg1 = perpSeg2 / limit;
  15220. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  15221. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  15222. } else {
  15223. // parallel or collinear
  15224. if ( ( perpSeg1 !== 0 ) ||
  15225. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  15226. // they are collinear or degenerate
  15227. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  15228. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  15229. // both segments are points
  15230. if ( seg1Pt && seg2Pt ) {
  15231. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  15232. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  15233. return [ inSeg1Pt1 ]; // they are the same point
  15234. }
  15235. // segment#1 is a single point
  15236. if ( seg1Pt ) {
  15237. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  15238. return [ inSeg1Pt1 ];
  15239. }
  15240. // segment#2 is a single point
  15241. if ( seg2Pt ) {
  15242. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  15243. return [ inSeg2Pt1 ];
  15244. }
  15245. // they are collinear segments, which might overlap
  15246. var seg1min, seg1max, seg1minVal, seg1maxVal;
  15247. var seg2min, seg2max, seg2minVal, seg2maxVal;
  15248. if ( seg1dx !== 0 ) {
  15249. // the segments are NOT on a vertical line
  15250. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  15251. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  15252. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  15253. } else {
  15254. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  15255. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  15256. }
  15257. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  15258. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  15259. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  15260. } else {
  15261. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  15262. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  15263. }
  15264. } else {
  15265. // the segments are on a vertical line
  15266. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  15267. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  15268. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  15269. } else {
  15270. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  15271. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  15272. }
  15273. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  15274. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  15275. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  15276. } else {
  15277. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  15278. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  15279. }
  15280. }
  15281. if ( seg1minVal <= seg2minVal ) {
  15282. if ( seg1maxVal < seg2minVal ) return [];
  15283. if ( seg1maxVal === seg2minVal ) {
  15284. if ( inExcludeAdjacentSegs ) return [];
  15285. return [ seg2min ];
  15286. }
  15287. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  15288. return [ seg2min, seg2max ];
  15289. } else {
  15290. if ( seg1minVal > seg2maxVal ) return [];
  15291. if ( seg1minVal === seg2maxVal ) {
  15292. if ( inExcludeAdjacentSegs ) return [];
  15293. return [ seg1min ];
  15294. }
  15295. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  15296. return [ seg1min, seg2max ];
  15297. }
  15298. }
  15299. }
  15300. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  15301. // The order of legs is important
  15302. // translation of all points, so that Vertex is at (0,0)
  15303. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  15304. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  15305. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  15306. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  15307. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  15308. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  15309. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  15310. // angle != 180 deg.
  15311. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  15312. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  15313. if ( from2toAngle > 0 ) {
  15314. // main angle < 180 deg.
  15315. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  15316. } else {
  15317. // main angle > 180 deg.
  15318. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  15319. }
  15320. } else {
  15321. // angle == 180 deg.
  15322. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  15323. return ( from2otherAngle > 0 );
  15324. }
  15325. }
  15326. function removeHoles( contour, holes ) {
  15327. var shape = contour.concat(); // work on this shape
  15328. var hole;
  15329. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  15330. // Check if hole point lies within angle around shape point
  15331. var lastShapeIdx = shape.length - 1;
  15332. var prevShapeIdx = inShapeIdx - 1;
  15333. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  15334. var nextShapeIdx = inShapeIdx + 1;
  15335. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  15336. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  15337. if ( ! insideAngle ) {
  15338. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  15339. return false;
  15340. }
  15341. // Check if shape point lies within angle around hole point
  15342. var lastHoleIdx = hole.length - 1;
  15343. var prevHoleIdx = inHoleIdx - 1;
  15344. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  15345. var nextHoleIdx = inHoleIdx + 1;
  15346. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  15347. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  15348. if ( ! insideAngle ) {
  15349. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  15350. return false;
  15351. }
  15352. return true;
  15353. }
  15354. function intersectsShapeEdge( inShapePt, inHolePt ) {
  15355. // checks for intersections with shape edges
  15356. var sIdx, nextIdx, intersection;
  15357. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  15358. nextIdx = sIdx + 1; nextIdx %= shape.length;
  15359. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  15360. if ( intersection.length > 0 ) return true;
  15361. }
  15362. return false;
  15363. }
  15364. var indepHoles = [];
  15365. function intersectsHoleEdge( inShapePt, inHolePt ) {
  15366. // checks for intersections with hole edges
  15367. var ihIdx, chkHole,
  15368. hIdx, nextIdx, intersection;
  15369. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  15370. chkHole = holes[ indepHoles[ ihIdx ]];
  15371. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  15372. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  15373. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  15374. if ( intersection.length > 0 ) return true;
  15375. }
  15376. }
  15377. return false;
  15378. }
  15379. var holeIndex, shapeIndex,
  15380. shapePt, holePt,
  15381. holeIdx, cutKey, failedCuts = [],
  15382. tmpShape1, tmpShape2,
  15383. tmpHole1, tmpHole2;
  15384. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15385. indepHoles.push( h );
  15386. }
  15387. var minShapeIndex = 0;
  15388. var counter = indepHoles.length * 2;
  15389. while ( indepHoles.length > 0 ) {
  15390. counter --;
  15391. if ( counter < 0 ) {
  15392. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  15393. break;
  15394. }
  15395. // search for shape-vertex and hole-vertex,
  15396. // which can be connected without intersections
  15397. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  15398. shapePt = shape[ shapeIndex ];
  15399. holeIndex = - 1;
  15400. // search for hole which can be reached without intersections
  15401. for ( var h = 0; h < indepHoles.length; h ++ ) {
  15402. holeIdx = indepHoles[ h ];
  15403. // prevent multiple checks
  15404. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  15405. if ( failedCuts[ cutKey ] !== undefined ) continue;
  15406. hole = holes[ holeIdx ];
  15407. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  15408. holePt = hole[ h2 ];
  15409. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  15410. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  15411. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  15412. holeIndex = h2;
  15413. indepHoles.splice( h, 1 );
  15414. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  15415. tmpShape2 = shape.slice( shapeIndex );
  15416. tmpHole1 = hole.slice( holeIndex );
  15417. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  15418. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  15419. minShapeIndex = shapeIndex;
  15420. // Debug only, to show the selected cuts
  15421. // glob_CutLines.push( [ shapePt, holePt ] );
  15422. break;
  15423. }
  15424. if ( holeIndex >= 0 ) break; // hole-vertex found
  15425. failedCuts[ cutKey ] = true; // remember failure
  15426. }
  15427. if ( holeIndex >= 0 ) break; // hole-vertex found
  15428. }
  15429. }
  15430. return shape; /* shape with no holes */
  15431. }
  15432. var i, il, f, face,
  15433. key, index,
  15434. allPointsMap = {};
  15435. // 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.
  15436. var allpoints = contour.concat();
  15437. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15438. Array.prototype.push.apply( allpoints, holes[ h ] );
  15439. }
  15440. //console.log( "allpoints",allpoints, allpoints.length );
  15441. // prepare all points map
  15442. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  15443. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  15444. if ( allPointsMap[ key ] !== undefined ) {
  15445. console.warn( "THREE.ShapeUtils: Duplicate point", key, i );
  15446. }
  15447. allPointsMap[ key ] = i;
  15448. }
  15449. // remove holes by cutting paths to holes and adding them to the shape
  15450. var shapeWithoutHoles = removeHoles( contour, holes );
  15451. var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  15452. //console.log( "triangles",triangles, triangles.length );
  15453. // check all face vertices against all points map
  15454. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  15455. face = triangles[ i ];
  15456. for ( f = 0; f < 3; f ++ ) {
  15457. key = face[ f ].x + ":" + face[ f ].y;
  15458. index = allPointsMap[ key ];
  15459. if ( index !== undefined ) {
  15460. face[ f ] = index;
  15461. }
  15462. }
  15463. }
  15464. return triangles.concat();
  15465. },
  15466. isClockWise: function ( pts ) {
  15467. return ShapeUtils.area( pts ) < 0;
  15468. },
  15469. // Bezier Curves formulas obtained from
  15470. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  15471. // Quad Bezier Functions
  15472. b2: ( function () {
  15473. function b2p0( t, p ) {
  15474. var k = 1 - t;
  15475. return k * k * p;
  15476. }
  15477. function b2p1( t, p ) {
  15478. return 2 * ( 1 - t ) * t * p;
  15479. }
  15480. function b2p2( t, p ) {
  15481. return t * t * p;
  15482. }
  15483. return function b2( t, p0, p1, p2 ) {
  15484. return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 );
  15485. };
  15486. } )(),
  15487. // Cubic Bezier Functions
  15488. b3: ( function () {
  15489. function b3p0( t, p ) {
  15490. var k = 1 - t;
  15491. return k * k * k * p;
  15492. }
  15493. function b3p1( t, p ) {
  15494. var k = 1 - t;
  15495. return 3 * k * k * t * p;
  15496. }
  15497. function b3p2( t, p ) {
  15498. var k = 1 - t;
  15499. return 3 * k * t * t * p;
  15500. }
  15501. function b3p3( t, p ) {
  15502. return t * t * t * p;
  15503. }
  15504. return function b3( t, p0, p1, p2, p3 ) {
  15505. return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 );
  15506. };
  15507. } )()
  15508. };
  15509. /**
  15510. * @author zz85 / http://www.lab4games.net/zz85/blog
  15511. *
  15512. * Creates extruded geometry from a path shape.
  15513. *
  15514. * parameters = {
  15515. *
  15516. * curveSegments: <int>, // number of points on the curves
  15517. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  15518. * amount: <int>, // Depth to extrude the shape
  15519. *
  15520. * bevelEnabled: <bool>, // turn on bevel
  15521. * bevelThickness: <float>, // how deep into the original shape bevel goes
  15522. * bevelSize: <float>, // how far from shape outline is bevel
  15523. * bevelSegments: <int>, // number of bevel layers
  15524. *
  15525. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  15526. * frames: <Object> // containing arrays of tangents, normals, binormals
  15527. *
  15528. * uvGenerator: <Object> // object that provides UV generator functions
  15529. *
  15530. * }
  15531. **/
  15532. function ExtrudeGeometry( shapes, options ) {
  15533. if ( typeof( shapes ) === "undefined" ) {
  15534. shapes = [];
  15535. return;
  15536. }
  15537. Geometry.call( this );
  15538. this.type = 'ExtrudeGeometry';
  15539. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  15540. this.addShapeList( shapes, options );
  15541. this.computeFaceNormals();
  15542. // can't really use automatic vertex normals
  15543. // as then front and back sides get smoothed too
  15544. // should do separate smoothing just for sides
  15545. //this.computeVertexNormals();
  15546. //console.log( "took", ( Date.now() - startTime ) );
  15547. }
  15548. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  15549. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  15550. ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  15551. var sl = shapes.length;
  15552. for ( var s = 0; s < sl; s ++ ) {
  15553. var shape = shapes[ s ];
  15554. this.addShape( shape, options );
  15555. }
  15556. };
  15557. ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  15558. var amount = options.amount !== undefined ? options.amount : 100;
  15559. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  15560. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  15561. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  15562. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  15563. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  15564. var steps = options.steps !== undefined ? options.steps : 1;
  15565. var extrudePath = options.extrudePath;
  15566. var extrudePts, extrudeByPath = false;
  15567. // Use default WorldUVGenerator if no UV generators are specified.
  15568. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  15569. var splineTube, binormal, normal, position2;
  15570. if ( extrudePath ) {
  15571. extrudePts = extrudePath.getSpacedPoints( steps );
  15572. extrudeByPath = true;
  15573. bevelEnabled = false; // bevels not supported for path extrusion
  15574. // SETUP TNB variables
  15575. // TODO1 - have a .isClosed in spline?
  15576. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  15577. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  15578. binormal = new Vector3();
  15579. normal = new Vector3();
  15580. position2 = new Vector3();
  15581. }
  15582. // Safeguards if bevels are not enabled
  15583. if ( ! bevelEnabled ) {
  15584. bevelSegments = 0;
  15585. bevelThickness = 0;
  15586. bevelSize = 0;
  15587. }
  15588. // Variables initialization
  15589. var ahole, h, hl; // looping of holes
  15590. var scope = this;
  15591. var shapesOffset = this.vertices.length;
  15592. var shapePoints = shape.extractPoints( curveSegments );
  15593. var vertices = shapePoints.shape;
  15594. var holes = shapePoints.holes;
  15595. var reverse = ! ShapeUtils.isClockWise( vertices );
  15596. if ( reverse ) {
  15597. vertices = vertices.reverse();
  15598. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  15599. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15600. ahole = holes[ h ];
  15601. if ( ShapeUtils.isClockWise( ahole ) ) {
  15602. holes[ h ] = ahole.reverse();
  15603. }
  15604. }
  15605. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  15606. }
  15607. var faces = ShapeUtils.triangulateShape( vertices, holes );
  15608. /* Vertices */
  15609. var contour = vertices; // vertices has all points but contour has only points of circumference
  15610. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15611. ahole = holes[ h ];
  15612. vertices = vertices.concat( ahole );
  15613. }
  15614. function scalePt2( pt, vec, size ) {
  15615. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  15616. return vec.clone().multiplyScalar( size ).add( pt );
  15617. }
  15618. var b, bs, t, z,
  15619. vert, vlen = vertices.length,
  15620. face, flen = faces.length;
  15621. // Find directions for point movement
  15622. function getBevelVec( inPt, inPrev, inNext ) {
  15623. // computes for inPt the corresponding point inPt' on a new contour
  15624. // shifted by 1 unit (length of normalized vector) to the left
  15625. // if we walk along contour clockwise, this new contour is outside the old one
  15626. //
  15627. // inPt' is the intersection of the two lines parallel to the two
  15628. // adjacent edges of inPt at a distance of 1 unit on the left side.
  15629. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  15630. // good reading for geometry algorithms (here: line-line intersection)
  15631. // http://geomalgorithms.com/a05-_intersect-1.html
  15632. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  15633. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  15634. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  15635. // check for collinear edges
  15636. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  15637. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  15638. // not collinear
  15639. // length of vectors for normalizing
  15640. var v_prev_len = Math.sqrt( v_prev_lensq );
  15641. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  15642. // shift adjacent points by unit vectors to the left
  15643. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  15644. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  15645. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  15646. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  15647. // scaling factor for v_prev to intersection point
  15648. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  15649. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  15650. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  15651. // vector from inPt to intersection point
  15652. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  15653. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  15654. // Don't normalize!, otherwise sharp corners become ugly
  15655. // but prevent crazy spikes
  15656. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  15657. if ( v_trans_lensq <= 2 ) {
  15658. return new Vector2( v_trans_x, v_trans_y );
  15659. } else {
  15660. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  15661. }
  15662. } else {
  15663. // handle special case of collinear edges
  15664. var direction_eq = false; // assumes: opposite
  15665. if ( v_prev_x > Number.EPSILON ) {
  15666. if ( v_next_x > Number.EPSILON ) {
  15667. direction_eq = true;
  15668. }
  15669. } else {
  15670. if ( v_prev_x < - Number.EPSILON ) {
  15671. if ( v_next_x < - Number.EPSILON ) {
  15672. direction_eq = true;
  15673. }
  15674. } else {
  15675. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  15676. direction_eq = true;
  15677. }
  15678. }
  15679. }
  15680. if ( direction_eq ) {
  15681. // console.log("Warning: lines are a straight sequence");
  15682. v_trans_x = - v_prev_y;
  15683. v_trans_y = v_prev_x;
  15684. shrink_by = Math.sqrt( v_prev_lensq );
  15685. } else {
  15686. // console.log("Warning: lines are a straight spike");
  15687. v_trans_x = v_prev_x;
  15688. v_trans_y = v_prev_y;
  15689. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  15690. }
  15691. }
  15692. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  15693. }
  15694. var contourMovements = [];
  15695. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  15696. if ( j === il ) j = 0;
  15697. if ( k === il ) k = 0;
  15698. // (j)---(i)---(k)
  15699. // console.log('i,j,k', i, j , k)
  15700. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  15701. }
  15702. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  15703. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15704. ahole = holes[ h ];
  15705. oneHoleMovements = [];
  15706. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  15707. if ( j === il ) j = 0;
  15708. if ( k === il ) k = 0;
  15709. // (j)---(i)---(k)
  15710. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  15711. }
  15712. holesMovements.push( oneHoleMovements );
  15713. verticesMovements = verticesMovements.concat( oneHoleMovements );
  15714. }
  15715. // Loop bevelSegments, 1 for the front, 1 for the back
  15716. for ( b = 0; b < bevelSegments; b ++ ) {
  15717. //for ( b = bevelSegments; b > 0; b -- ) {
  15718. t = b / bevelSegments;
  15719. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  15720. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  15721. // contract shape
  15722. for ( i = 0, il = contour.length; i < il; i ++ ) {
  15723. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  15724. v( vert.x, vert.y, - z );
  15725. }
  15726. // expand holes
  15727. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15728. ahole = holes[ h ];
  15729. oneHoleMovements = holesMovements[ h ];
  15730. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  15731. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  15732. v( vert.x, vert.y, - z );
  15733. }
  15734. }
  15735. }
  15736. bs = bevelSize;
  15737. // Back facing vertices
  15738. for ( i = 0; i < vlen; i ++ ) {
  15739. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  15740. if ( ! extrudeByPath ) {
  15741. v( vert.x, vert.y, 0 );
  15742. } else {
  15743. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  15744. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  15745. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  15746. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  15747. v( position2.x, position2.y, position2.z );
  15748. }
  15749. }
  15750. // Add stepped vertices...
  15751. // Including front facing vertices
  15752. var s;
  15753. for ( s = 1; s <= steps; s ++ ) {
  15754. for ( i = 0; i < vlen; i ++ ) {
  15755. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  15756. if ( ! extrudeByPath ) {
  15757. v( vert.x, vert.y, amount / steps * s );
  15758. } else {
  15759. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  15760. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  15761. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  15762. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  15763. v( position2.x, position2.y, position2.z );
  15764. }
  15765. }
  15766. }
  15767. // Add bevel segments planes
  15768. //for ( b = 1; b <= bevelSegments; b ++ ) {
  15769. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  15770. t = b / bevelSegments;
  15771. z = bevelThickness * Math.cos ( t * Math.PI / 2 );
  15772. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  15773. // contract shape
  15774. for ( i = 0, il = contour.length; i < il; i ++ ) {
  15775. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  15776. v( vert.x, vert.y, amount + z );
  15777. }
  15778. // expand holes
  15779. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15780. ahole = holes[ h ];
  15781. oneHoleMovements = holesMovements[ h ];
  15782. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  15783. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  15784. if ( ! extrudeByPath ) {
  15785. v( vert.x, vert.y, amount + z );
  15786. } else {
  15787. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  15788. }
  15789. }
  15790. }
  15791. }
  15792. /* Faces */
  15793. // Top and bottom faces
  15794. buildLidFaces();
  15795. // Sides faces
  15796. buildSideFaces();
  15797. ///// Internal functions
  15798. function buildLidFaces() {
  15799. if ( bevelEnabled ) {
  15800. var layer = 0; // steps + 1
  15801. var offset = vlen * layer;
  15802. // Bottom faces
  15803. for ( i = 0; i < flen; i ++ ) {
  15804. face = faces[ i ];
  15805. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  15806. }
  15807. layer = steps + bevelSegments * 2;
  15808. offset = vlen * layer;
  15809. // Top faces
  15810. for ( i = 0; i < flen; i ++ ) {
  15811. face = faces[ i ];
  15812. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  15813. }
  15814. } else {
  15815. // Bottom faces
  15816. for ( i = 0; i < flen; i ++ ) {
  15817. face = faces[ i ];
  15818. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  15819. }
  15820. // Top faces
  15821. for ( i = 0; i < flen; i ++ ) {
  15822. face = faces[ i ];
  15823. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  15824. }
  15825. }
  15826. }
  15827. // Create faces for the z-sides of the shape
  15828. function buildSideFaces() {
  15829. var layeroffset = 0;
  15830. sidewalls( contour, layeroffset );
  15831. layeroffset += contour.length;
  15832. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15833. ahole = holes[ h ];
  15834. sidewalls( ahole, layeroffset );
  15835. //, true
  15836. layeroffset += ahole.length;
  15837. }
  15838. }
  15839. function sidewalls( contour, layeroffset ) {
  15840. var j, k;
  15841. i = contour.length;
  15842. while ( -- i >= 0 ) {
  15843. j = i;
  15844. k = i - 1;
  15845. if ( k < 0 ) k = contour.length - 1;
  15846. //console.log('b', i,j, i-1, k,vertices.length);
  15847. var s = 0, sl = steps + bevelSegments * 2;
  15848. for ( s = 0; s < sl; s ++ ) {
  15849. var slen1 = vlen * s;
  15850. var slen2 = vlen * ( s + 1 );
  15851. var a = layeroffset + j + slen1,
  15852. b = layeroffset + k + slen1,
  15853. c = layeroffset + k + slen2,
  15854. d = layeroffset + j + slen2;
  15855. f4( a, b, c, d, contour, s, sl, j, k );
  15856. }
  15857. }
  15858. }
  15859. function v( x, y, z ) {
  15860. scope.vertices.push( new Vector3( x, y, z ) );
  15861. }
  15862. function f3( a, b, c ) {
  15863. a += shapesOffset;
  15864. b += shapesOffset;
  15865. c += shapesOffset;
  15866. scope.faces.push( new Face3( a, b, c, null, null, 0 ) );
  15867. var uvs = uvgen.generateTopUV( scope, a, b, c );
  15868. scope.faceVertexUvs[ 0 ].push( uvs );
  15869. }
  15870. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  15871. a += shapesOffset;
  15872. b += shapesOffset;
  15873. c += shapesOffset;
  15874. d += shapesOffset;
  15875. scope.faces.push( new Face3( a, b, d, null, null, 1 ) );
  15876. scope.faces.push( new Face3( b, c, d, null, null, 1 ) );
  15877. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  15878. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  15879. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  15880. }
  15881. };
  15882. ExtrudeGeometry.WorldUVGenerator = {
  15883. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  15884. var vertices = geometry.vertices;
  15885. var a = vertices[ indexA ];
  15886. var b = vertices[ indexB ];
  15887. var c = vertices[ indexC ];
  15888. return [
  15889. new Vector2( a.x, a.y ),
  15890. new Vector2( b.x, b.y ),
  15891. new Vector2( c.x, c.y )
  15892. ];
  15893. },
  15894. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  15895. var vertices = geometry.vertices;
  15896. var a = vertices[ indexA ];
  15897. var b = vertices[ indexB ];
  15898. var c = vertices[ indexC ];
  15899. var d = vertices[ indexD ];
  15900. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  15901. return [
  15902. new Vector2( a.x, 1 - a.z ),
  15903. new Vector2( b.x, 1 - b.z ),
  15904. new Vector2( c.x, 1 - c.z ),
  15905. new Vector2( d.x, 1 - d.z )
  15906. ];
  15907. } else {
  15908. return [
  15909. new Vector2( a.y, 1 - a.z ),
  15910. new Vector2( b.y, 1 - b.z ),
  15911. new Vector2( c.y, 1 - c.z ),
  15912. new Vector2( d.y, 1 - d.z )
  15913. ];
  15914. }
  15915. }
  15916. };
  15917. /**
  15918. * @author zz85 / http://www.lab4games.net/zz85/blog
  15919. * @author alteredq / http://alteredqualia.com/
  15920. *
  15921. * Text = 3D Text
  15922. *
  15923. * parameters = {
  15924. * font: <THREE.Font>, // font
  15925. *
  15926. * size: <float>, // size of the text
  15927. * height: <float>, // thickness to extrude text
  15928. * curveSegments: <int>, // number of points on the curves
  15929. *
  15930. * bevelEnabled: <bool>, // turn on bevel
  15931. * bevelThickness: <float>, // how deep into text bevel goes
  15932. * bevelSize: <float> // how far from text outline is bevel
  15933. * }
  15934. */
  15935. function TextGeometry( text, parameters ) {
  15936. parameters = parameters || {};
  15937. var font = parameters.font;
  15938. if ( (font && font.isFont) === false ) {
  15939. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  15940. return new Geometry();
  15941. }
  15942. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  15943. // translate parameters to ExtrudeGeometry API
  15944. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  15945. // defaults
  15946. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  15947. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  15948. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  15949. ExtrudeGeometry.call( this, shapes, parameters );
  15950. this.type = 'TextGeometry';
  15951. }
  15952. TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype );
  15953. TextGeometry.prototype.constructor = TextGeometry;
  15954. /**
  15955. * @author benaadams / https://twitter.com/ben_a_adams
  15956. * based on THREE.SphereGeometry
  15957. */
  15958. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  15959. BufferGeometry.call( this );
  15960. this.type = 'SphereBufferGeometry';
  15961. this.parameters = {
  15962. radius: radius,
  15963. widthSegments: widthSegments,
  15964. heightSegments: heightSegments,
  15965. phiStart: phiStart,
  15966. phiLength: phiLength,
  15967. thetaStart: thetaStart,
  15968. thetaLength: thetaLength
  15969. };
  15970. radius = radius || 50;
  15971. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  15972. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  15973. phiStart = phiStart !== undefined ? phiStart : 0;
  15974. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  15975. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  15976. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  15977. var thetaEnd = thetaStart + thetaLength;
  15978. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  15979. var positions = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  15980. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  15981. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  15982. var index = 0, vertices = [], normal = new Vector3();
  15983. for ( var y = 0; y <= heightSegments; y ++ ) {
  15984. var verticesRow = [];
  15985. var v = y / heightSegments;
  15986. for ( var x = 0; x <= widthSegments; x ++ ) {
  15987. var u = x / widthSegments;
  15988. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  15989. var py = radius * Math.cos( thetaStart + v * thetaLength );
  15990. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  15991. normal.set( px, py, pz ).normalize();
  15992. positions.setXYZ( index, px, py, pz );
  15993. normals.setXYZ( index, normal.x, normal.y, normal.z );
  15994. uvs.setXY( index, u, 1 - v );
  15995. verticesRow.push( index );
  15996. index ++;
  15997. }
  15998. vertices.push( verticesRow );
  15999. }
  16000. var indices = [];
  16001. for ( var y = 0; y < heightSegments; y ++ ) {
  16002. for ( var x = 0; x < widthSegments; x ++ ) {
  16003. var v1 = vertices[ y ][ x + 1 ];
  16004. var v2 = vertices[ y ][ x ];
  16005. var v3 = vertices[ y + 1 ][ x ];
  16006. var v4 = vertices[ y + 1 ][ x + 1 ];
  16007. if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 );
  16008. if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 );
  16009. }
  16010. }
  16011. this.setIndex( new ( positions.count > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  16012. this.addAttribute( 'position', positions );
  16013. this.addAttribute( 'normal', normals );
  16014. this.addAttribute( 'uv', uvs );
  16015. this.boundingSphere = new Sphere( new Vector3(), radius );
  16016. }
  16017. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16018. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  16019. /**
  16020. * @author mrdoob / http://mrdoob.com/
  16021. */
  16022. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16023. Geometry.call( this );
  16024. this.type = 'SphereGeometry';
  16025. this.parameters = {
  16026. radius: radius,
  16027. widthSegments: widthSegments,
  16028. heightSegments: heightSegments,
  16029. phiStart: phiStart,
  16030. phiLength: phiLength,
  16031. thetaStart: thetaStart,
  16032. thetaLength: thetaLength
  16033. };
  16034. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  16035. }
  16036. SphereGeometry.prototype = Object.create( Geometry.prototype );
  16037. SphereGeometry.prototype.constructor = SphereGeometry;
  16038. /**
  16039. * @author Mugen87 / https://github.com/Mugen87
  16040. */
  16041. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16042. BufferGeometry.call( this );
  16043. this.type = 'RingBufferGeometry';
  16044. this.parameters = {
  16045. innerRadius: innerRadius,
  16046. outerRadius: outerRadius,
  16047. thetaSegments: thetaSegments,
  16048. phiSegments: phiSegments,
  16049. thetaStart: thetaStart,
  16050. thetaLength: thetaLength
  16051. };
  16052. innerRadius = innerRadius || 20;
  16053. outerRadius = outerRadius || 50;
  16054. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16055. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16056. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  16057. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  16058. // these are used to calculate buffer length
  16059. var vertexCount = ( thetaSegments + 1 ) * ( phiSegments + 1 );
  16060. var indexCount = thetaSegments * phiSegments * 2 * 3;
  16061. // buffers
  16062. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  16063. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16064. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16065. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  16066. // some helper variables
  16067. var index = 0, indexOffset = 0, segment;
  16068. var radius = innerRadius;
  16069. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  16070. var vertex = new Vector3();
  16071. var uv = new Vector2();
  16072. var j, i;
  16073. // generate vertices, normals and uvs
  16074. // values are generate from the inside of the ring to the outside
  16075. for ( j = 0; j <= phiSegments; j ++ ) {
  16076. for ( i = 0; i <= thetaSegments; i ++ ) {
  16077. segment = thetaStart + i / thetaSegments * thetaLength;
  16078. // vertex
  16079. vertex.x = radius * Math.cos( segment );
  16080. vertex.y = radius * Math.sin( segment );
  16081. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  16082. // normal
  16083. normals.setXYZ( index, 0, 0, 1 );
  16084. // uv
  16085. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  16086. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  16087. uvs.setXY( index, uv.x, uv.y );
  16088. // increase index
  16089. index++;
  16090. }
  16091. // increase the radius for next row of vertices
  16092. radius += radiusStep;
  16093. }
  16094. // generate indices
  16095. for ( j = 0; j < phiSegments; j ++ ) {
  16096. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  16097. for ( i = 0; i < thetaSegments; i ++ ) {
  16098. segment = i + thetaSegmentLevel;
  16099. // indices
  16100. var a = segment;
  16101. var b = segment + thetaSegments + 1;
  16102. var c = segment + thetaSegments + 2;
  16103. var d = segment + 1;
  16104. // face one
  16105. indices.setX( indexOffset, a ); indexOffset++;
  16106. indices.setX( indexOffset, b ); indexOffset++;
  16107. indices.setX( indexOffset, c ); indexOffset++;
  16108. // face two
  16109. indices.setX( indexOffset, a ); indexOffset++;
  16110. indices.setX( indexOffset, c ); indexOffset++;
  16111. indices.setX( indexOffset, d ); indexOffset++;
  16112. }
  16113. }
  16114. // build geometry
  16115. this.setIndex( indices );
  16116. this.addAttribute( 'position', vertices );
  16117. this.addAttribute( 'normal', normals );
  16118. this.addAttribute( 'uv', uvs );
  16119. }
  16120. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16121. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  16122. /**
  16123. * @author Kaleb Murphy
  16124. */
  16125. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16126. Geometry.call( this );
  16127. this.type = 'RingGeometry';
  16128. this.parameters = {
  16129. innerRadius: innerRadius,
  16130. outerRadius: outerRadius,
  16131. thetaSegments: thetaSegments,
  16132. phiSegments: phiSegments,
  16133. thetaStart: thetaStart,
  16134. thetaLength: thetaLength
  16135. };
  16136. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  16137. }
  16138. RingGeometry.prototype = Object.create( Geometry.prototype );
  16139. RingGeometry.prototype.constructor = RingGeometry;
  16140. /**
  16141. * @author mrdoob / http://mrdoob.com/
  16142. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  16143. */
  16144. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  16145. Geometry.call( this );
  16146. this.type = 'PlaneGeometry';
  16147. this.parameters = {
  16148. width: width,
  16149. height: height,
  16150. widthSegments: widthSegments,
  16151. heightSegments: heightSegments
  16152. };
  16153. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  16154. }
  16155. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  16156. PlaneGeometry.prototype.constructor = PlaneGeometry;
  16157. /**
  16158. * @author Mugen87 / https://github.com/Mugen87
  16159. */
  16160. // points - to create a closed torus, one must use a set of points
  16161. // like so: [ a, b, c, d, a ], see first is the same as last.
  16162. // segments - the number of circumference segments to create
  16163. // phiStart - the starting radian
  16164. // phiLength - the radian (0 to 2PI) range of the lathed section
  16165. // 2PI is a closed lathe, less than 2PI is a portion.
  16166. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  16167. BufferGeometry.call( this );
  16168. this.type = 'LatheBufferGeometry';
  16169. this.parameters = {
  16170. points: points,
  16171. segments: segments,
  16172. phiStart: phiStart,
  16173. phiLength: phiLength
  16174. };
  16175. segments = Math.floor( segments ) || 12;
  16176. phiStart = phiStart || 0;
  16177. phiLength = phiLength || Math.PI * 2;
  16178. // clamp phiLength so it's in range of [ 0, 2PI ]
  16179. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  16180. // these are used to calculate buffer length
  16181. var vertexCount = ( segments + 1 ) * points.length;
  16182. var indexCount = segments * points.length * 2 * 3;
  16183. // buffers
  16184. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  16185. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16186. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  16187. // helper variables
  16188. var index = 0, indexOffset = 0, base;
  16189. var inverseSegments = 1.0 / segments;
  16190. var vertex = new Vector3();
  16191. var uv = new Vector2();
  16192. var i, j;
  16193. // generate vertices and uvs
  16194. for ( i = 0; i <= segments; i ++ ) {
  16195. var phi = phiStart + i * inverseSegments * phiLength;
  16196. var sin = Math.sin( phi );
  16197. var cos = Math.cos( phi );
  16198. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  16199. // vertex
  16200. vertex.x = points[ j ].x * sin;
  16201. vertex.y = points[ j ].y;
  16202. vertex.z = points[ j ].x * cos;
  16203. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  16204. // uv
  16205. uv.x = i / segments;
  16206. uv.y = j / ( points.length - 1 );
  16207. uvs.setXY( index, uv.x, uv.y );
  16208. // increase index
  16209. index ++;
  16210. }
  16211. }
  16212. // generate indices
  16213. for ( i = 0; i < segments; i ++ ) {
  16214. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  16215. base = j + i * points.length;
  16216. // indices
  16217. var a = base;
  16218. var b = base + points.length;
  16219. var c = base + points.length + 1;
  16220. var d = base + 1;
  16221. // face one
  16222. indices.setX( indexOffset, a ); indexOffset++;
  16223. indices.setX( indexOffset, b ); indexOffset++;
  16224. indices.setX( indexOffset, d ); indexOffset++;
  16225. // face two
  16226. indices.setX( indexOffset, b ); indexOffset++;
  16227. indices.setX( indexOffset, c ); indexOffset++;
  16228. indices.setX( indexOffset, d ); indexOffset++;
  16229. }
  16230. }
  16231. // build geometry
  16232. this.setIndex( indices );
  16233. this.addAttribute( 'position', vertices );
  16234. this.addAttribute( 'uv', uvs );
  16235. // generate normals
  16236. this.computeVertexNormals();
  16237. // if the geometry is closed, we need to average the normals along the seam.
  16238. // because the corresponding vertices are identical (but still have different UVs).
  16239. if( phiLength === Math.PI * 2 ) {
  16240. var normals = this.attributes.normal.array;
  16241. var n1 = new Vector3();
  16242. var n2 = new Vector3();
  16243. var n = new Vector3();
  16244. // this is the buffer offset for the last line of vertices
  16245. base = segments * points.length * 3;
  16246. for( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  16247. // select the normal of the vertex in the first line
  16248. n1.x = normals[ j + 0 ];
  16249. n1.y = normals[ j + 1 ];
  16250. n1.z = normals[ j + 2 ];
  16251. // select the normal of the vertex in the last line
  16252. n2.x = normals[ base + j + 0 ];
  16253. n2.y = normals[ base + j + 1 ];
  16254. n2.z = normals[ base + j + 2 ];
  16255. // average normals
  16256. n.addVectors( n1, n2 ).normalize();
  16257. // assign the new values to both normals
  16258. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  16259. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  16260. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  16261. } // next row
  16262. }
  16263. }
  16264. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16265. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  16266. /**
  16267. * @author astrodud / http://astrodud.isgreat.org/
  16268. * @author zz85 / https://github.com/zz85
  16269. * @author bhouston / http://clara.io
  16270. */
  16271. // points - to create a closed torus, one must use a set of points
  16272. // like so: [ a, b, c, d, a ], see first is the same as last.
  16273. // segments - the number of circumference segments to create
  16274. // phiStart - the starting radian
  16275. // phiLength - the radian (0 to 2PI) range of the lathed section
  16276. // 2PI is a closed lathe, less than 2PI is a portion.
  16277. function LatheGeometry( points, segments, phiStart, phiLength ) {
  16278. Geometry.call( this );
  16279. this.type = 'LatheGeometry';
  16280. this.parameters = {
  16281. points: points,
  16282. segments: segments,
  16283. phiStart: phiStart,
  16284. phiLength: phiLength
  16285. };
  16286. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  16287. this.mergeVertices();
  16288. }
  16289. LatheGeometry.prototype = Object.create( Geometry.prototype );
  16290. LatheGeometry.prototype.constructor = LatheGeometry;
  16291. /**
  16292. * @author Mugen87 / https://github.com/Mugen87
  16293. *
  16294. * Creates a one-sided polygonal geometry from one or more shapes.
  16295. *
  16296. **/
  16297. function ShapeBufferGeometry( shapes, curveSegments ) {
  16298. BufferGeometry.call( this );
  16299. this.type = 'ShapeBufferGeometry';
  16300. this.parameters = {
  16301. shapes: shapes,
  16302. curveSegments: curveSegments
  16303. };
  16304. curveSegments = curveSegments || 12;
  16305. var vertices = [];
  16306. var normals = [];
  16307. var uvs = [];
  16308. var indices = [];
  16309. var groupStart = 0;
  16310. var groupCount = 0;
  16311. // allow single and array values for "shapes" parameter
  16312. if ( Array.isArray( shapes ) === false ) {
  16313. addShape( shapes );
  16314. } else {
  16315. for ( var i = 0; i < shapes.length; i++ ) {
  16316. addShape( shapes[ i ] );
  16317. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  16318. groupStart += groupCount;
  16319. groupCount = 0;
  16320. }
  16321. }
  16322. // build geometry
  16323. this.setIndex( new ( indices.length > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  16324. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16325. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16326. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16327. // helper functions
  16328. function addShape( shape ) {
  16329. var i, l, shapeHole;
  16330. var indexOffset = vertices.length / 3;
  16331. var points = shape.extractPoints( curveSegments );
  16332. var shapeVertices = points.shape;
  16333. var shapeHoles = points.holes;
  16334. // check direction of vertices
  16335. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  16336. shapeVertices = shapeVertices.reverse();
  16337. // also check if holes are in the opposite direction
  16338. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16339. shapeHole = shapeHoles[ i ];
  16340. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  16341. shapeHoles[ i ] = shapeHole.reverse();
  16342. }
  16343. }
  16344. }
  16345. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  16346. // join vertices of inner and outer paths to a single array
  16347. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16348. shapeHole = shapeHoles[ i ];
  16349. shapeVertices = shapeVertices.concat( shapeHole );
  16350. }
  16351. // vertices, normals, uvs
  16352. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  16353. var vertex = shapeVertices[ i ];
  16354. vertices.push( vertex.x, vertex.y, 0 );
  16355. normals.push( 0, 0, 1 );
  16356. uvs.push( vertex.x, vertex.y ); // world uvs
  16357. }
  16358. // incides
  16359. for ( i = 0, l = faces.length; i < l; i ++ ) {
  16360. var face = faces[ i ];
  16361. var a = face[ 0 ] + indexOffset;
  16362. var b = face[ 1 ] + indexOffset;
  16363. var c = face[ 2 ] + indexOffset;
  16364. indices.push( a, b, c );
  16365. groupCount += 3;
  16366. }
  16367. }
  16368. }
  16369. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16370. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  16371. /**
  16372. * @author jonobr1 / http://jonobr1.com
  16373. *
  16374. * Creates a one-sided polygonal geometry from a path shape.
  16375. *
  16376. **/
  16377. function ShapeGeometry( shapes, curveSegments ) {
  16378. Geometry.call( this );
  16379. this.type = 'ShapeGeometry';
  16380. if ( typeof curveSegments === 'object' ) {
  16381. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  16382. curveSegments = curveSegments.curveSegments;
  16383. }
  16384. this.parameters = {
  16385. shapes: shapes,
  16386. curveSegments: curveSegments
  16387. };
  16388. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  16389. this.mergeVertices();
  16390. }
  16391. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  16392. ShapeGeometry.prototype.constructor = ShapeGeometry;
  16393. /**
  16394. * @author WestLangley / http://github.com/WestLangley
  16395. */
  16396. function EdgesGeometry( geometry, thresholdAngle ) {
  16397. BufferGeometry.call( this );
  16398. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  16399. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  16400. var edge = [ 0, 0 ], hash = {};
  16401. function sortFunction( a, b ) {
  16402. return a - b;
  16403. }
  16404. var keys = [ 'a', 'b', 'c' ];
  16405. var geometry2;
  16406. if ( geometry.isBufferGeometry ) {
  16407. geometry2 = new Geometry();
  16408. geometry2.fromBufferGeometry( geometry );
  16409. } else {
  16410. geometry2 = geometry.clone();
  16411. }
  16412. geometry2.mergeVertices();
  16413. geometry2.computeFaceNormals();
  16414. var vertices = geometry2.vertices;
  16415. var faces = geometry2.faces;
  16416. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  16417. var face = faces[ i ];
  16418. for ( var j = 0; j < 3; j ++ ) {
  16419. edge[ 0 ] = face[ keys[ j ] ];
  16420. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  16421. edge.sort( sortFunction );
  16422. var key = edge.toString();
  16423. if ( hash[ key ] === undefined ) {
  16424. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  16425. } else {
  16426. hash[ key ].face2 = i;
  16427. }
  16428. }
  16429. }
  16430. var coords = [];
  16431. for ( var key in hash ) {
  16432. var h = hash[ key ];
  16433. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  16434. var vertex = vertices[ h.vert1 ];
  16435. coords.push( vertex.x );
  16436. coords.push( vertex.y );
  16437. coords.push( vertex.z );
  16438. vertex = vertices[ h.vert2 ];
  16439. coords.push( vertex.x );
  16440. coords.push( vertex.y );
  16441. coords.push( vertex.z );
  16442. }
  16443. }
  16444. this.addAttribute( 'position', new BufferAttribute( new Float32Array( coords ), 3 ) );
  16445. }
  16446. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  16447. EdgesGeometry.prototype.constructor = EdgesGeometry;
  16448. /**
  16449. * @author Mugen87 / https://github.com/Mugen87
  16450. */
  16451. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16452. BufferGeometry.call( this );
  16453. this.type = 'CylinderBufferGeometry';
  16454. this.parameters = {
  16455. radiusTop: radiusTop,
  16456. radiusBottom: radiusBottom,
  16457. height: height,
  16458. radialSegments: radialSegments,
  16459. heightSegments: heightSegments,
  16460. openEnded: openEnded,
  16461. thetaStart: thetaStart,
  16462. thetaLength: thetaLength
  16463. };
  16464. var scope = this;
  16465. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  16466. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  16467. height = height !== undefined ? height : 100;
  16468. radialSegments = Math.floor( radialSegments ) || 8;
  16469. heightSegments = Math.floor( heightSegments ) || 1;
  16470. openEnded = openEnded !== undefined ? openEnded : false;
  16471. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  16472. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  16473. // used to calculate buffer length
  16474. var nbCap = 0;
  16475. if ( openEnded === false ) {
  16476. if ( radiusTop > 0 ) nbCap ++;
  16477. if ( radiusBottom > 0 ) nbCap ++;
  16478. }
  16479. var vertexCount = calculateVertexCount();
  16480. var indexCount = calculateIndexCount();
  16481. // buffers
  16482. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 );
  16483. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16484. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16485. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  16486. // helper variables
  16487. var index = 0,
  16488. indexOffset = 0,
  16489. indexArray = [],
  16490. halfHeight = height / 2;
  16491. // group variables
  16492. var groupStart = 0;
  16493. // generate geometry
  16494. generateTorso();
  16495. if ( openEnded === false ) {
  16496. if ( radiusTop > 0 ) generateCap( true );
  16497. if ( radiusBottom > 0 ) generateCap( false );
  16498. }
  16499. // build geometry
  16500. this.setIndex( indices );
  16501. this.addAttribute( 'position', vertices );
  16502. this.addAttribute( 'normal', normals );
  16503. this.addAttribute( 'uv', uvs );
  16504. // helper functions
  16505. function calculateVertexCount() {
  16506. var count = ( radialSegments + 1 ) * ( heightSegments + 1 );
  16507. if ( openEnded === false ) {
  16508. count += ( ( radialSegments + 1 ) * nbCap ) + ( radialSegments * nbCap );
  16509. }
  16510. return count;
  16511. }
  16512. function calculateIndexCount() {
  16513. var count = radialSegments * heightSegments * 2 * 3;
  16514. if ( openEnded === false ) {
  16515. count += radialSegments * nbCap * 3;
  16516. }
  16517. return count;
  16518. }
  16519. function generateTorso() {
  16520. var x, y;
  16521. var normal = new Vector3();
  16522. var vertex = new Vector3();
  16523. var groupCount = 0;
  16524. // this will be used to calculate the normal
  16525. var slope = ( radiusBottom - radiusTop ) / height;
  16526. // generate vertices, normals and uvs
  16527. for ( y = 0; y <= heightSegments; y ++ ) {
  16528. var indexRow = [];
  16529. var v = y / heightSegments;
  16530. // calculate the radius of the current row
  16531. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  16532. for ( x = 0; x <= radialSegments; x ++ ) {
  16533. var u = x / radialSegments;
  16534. var theta = u * thetaLength + thetaStart;
  16535. var sinTheta = Math.sin( theta );
  16536. var cosTheta = Math.cos( theta );
  16537. // vertex
  16538. vertex.x = radius * sinTheta;
  16539. vertex.y = - v * height + halfHeight;
  16540. vertex.z = radius * cosTheta;
  16541. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  16542. // normal
  16543. normal.set( sinTheta, slope, cosTheta ).normalize();
  16544. normals.setXYZ( index, normal.x, normal.y, normal.z );
  16545. // uv
  16546. uvs.setXY( index, u, 1 - v );
  16547. // save index of vertex in respective row
  16548. indexRow.push( index );
  16549. // increase index
  16550. index ++;
  16551. }
  16552. // now save vertices of the row in our index array
  16553. indexArray.push( indexRow );
  16554. }
  16555. // generate indices
  16556. for ( x = 0; x < radialSegments; x ++ ) {
  16557. for ( y = 0; y < heightSegments; y ++ ) {
  16558. // we use the index array to access the correct indices
  16559. var i1 = indexArray[ y ][ x ];
  16560. var i2 = indexArray[ y + 1 ][ x ];
  16561. var i3 = indexArray[ y + 1 ][ x + 1 ];
  16562. var i4 = indexArray[ y ][ x + 1 ];
  16563. // face one
  16564. indices.setX( indexOffset, i1 ); indexOffset ++;
  16565. indices.setX( indexOffset, i2 ); indexOffset ++;
  16566. indices.setX( indexOffset, i4 ); indexOffset ++;
  16567. // face two
  16568. indices.setX( indexOffset, i2 ); indexOffset ++;
  16569. indices.setX( indexOffset, i3 ); indexOffset ++;
  16570. indices.setX( indexOffset, i4 ); indexOffset ++;
  16571. // update counters
  16572. groupCount += 6;
  16573. }
  16574. }
  16575. // add a group to the geometry. this will ensure multi material support
  16576. scope.addGroup( groupStart, groupCount, 0 );
  16577. // calculate new start value for groups
  16578. groupStart += groupCount;
  16579. }
  16580. function generateCap( top ) {
  16581. var x, centerIndexStart, centerIndexEnd;
  16582. var uv = new Vector2();
  16583. var vertex = new Vector3();
  16584. var groupCount = 0;
  16585. var radius = ( top === true ) ? radiusTop : radiusBottom;
  16586. var sign = ( top === true ) ? 1 : - 1;
  16587. // save the index of the first center vertex
  16588. centerIndexStart = index;
  16589. // first we generate the center vertex data of the cap.
  16590. // because the geometry needs one set of uvs per face,
  16591. // we must generate a center vertex per face/segment
  16592. for ( x = 1; x <= radialSegments; x ++ ) {
  16593. // vertex
  16594. vertices.setXYZ( index, 0, halfHeight * sign, 0 );
  16595. // normal
  16596. normals.setXYZ( index, 0, sign, 0 );
  16597. // uv
  16598. uv.x = 0.5;
  16599. uv.y = 0.5;
  16600. uvs.setXY( index, uv.x, uv.y );
  16601. // increase index
  16602. index ++;
  16603. }
  16604. // save the index of the last center vertex
  16605. centerIndexEnd = index;
  16606. // now we generate the surrounding vertices, normals and uvs
  16607. for ( x = 0; x <= radialSegments; x ++ ) {
  16608. var u = x / radialSegments;
  16609. var theta = u * thetaLength + thetaStart;
  16610. var cosTheta = Math.cos( theta );
  16611. var sinTheta = Math.sin( theta );
  16612. // vertex
  16613. vertex.x = radius * sinTheta;
  16614. vertex.y = halfHeight * sign;
  16615. vertex.z = radius * cosTheta;
  16616. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  16617. // normal
  16618. normals.setXYZ( index, 0, sign, 0 );
  16619. // uv
  16620. uv.x = ( cosTheta * 0.5 ) + 0.5;
  16621. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  16622. uvs.setXY( index, uv.x, uv.y );
  16623. // increase index
  16624. index ++;
  16625. }
  16626. // generate indices
  16627. for ( x = 0; x < radialSegments; x ++ ) {
  16628. var c = centerIndexStart + x;
  16629. var i = centerIndexEnd + x;
  16630. if ( top === true ) {
  16631. // face top
  16632. indices.setX( indexOffset, i ); indexOffset ++;
  16633. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  16634. indices.setX( indexOffset, c ); indexOffset ++;
  16635. } else {
  16636. // face bottom
  16637. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  16638. indices.setX( indexOffset, i ); indexOffset ++;
  16639. indices.setX( indexOffset, c ); indexOffset ++;
  16640. }
  16641. // update counters
  16642. groupCount += 3;
  16643. }
  16644. // add a group to the geometry. this will ensure multi material support
  16645. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  16646. // calculate new start value for groups
  16647. groupStart += groupCount;
  16648. }
  16649. }
  16650. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16651. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  16652. /**
  16653. * @author mrdoob / http://mrdoob.com/
  16654. */
  16655. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16656. Geometry.call( this );
  16657. this.type = 'CylinderGeometry';
  16658. this.parameters = {
  16659. radiusTop: radiusTop,
  16660. radiusBottom: radiusBottom,
  16661. height: height,
  16662. radialSegments: radialSegments,
  16663. heightSegments: heightSegments,
  16664. openEnded: openEnded,
  16665. thetaStart: thetaStart,
  16666. thetaLength: thetaLength
  16667. };
  16668. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  16669. this.mergeVertices();
  16670. }
  16671. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  16672. CylinderGeometry.prototype.constructor = CylinderGeometry;
  16673. /**
  16674. * @author abelnation / http://github.com/abelnation
  16675. */
  16676. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16677. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  16678. this.type = 'ConeGeometry';
  16679. this.parameters = {
  16680. radius: radius,
  16681. height: height,
  16682. radialSegments: radialSegments,
  16683. heightSegments: heightSegments,
  16684. openEnded: openEnded,
  16685. thetaStart: thetaStart,
  16686. thetaLength: thetaLength
  16687. };
  16688. }
  16689. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  16690. ConeGeometry.prototype.constructor = ConeGeometry;
  16691. /**
  16692. * @author: abelnation / http://github.com/abelnation
  16693. */
  16694. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16695. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  16696. this.type = 'ConeBufferGeometry';
  16697. this.parameters = {
  16698. radius: radius,
  16699. height: height,
  16700. radialSegments: radialSegments,
  16701. heightSegments: heightSegments,
  16702. openEnded: openEnded,
  16703. thetaStart: thetaStart,
  16704. thetaLength: thetaLength
  16705. };
  16706. }
  16707. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  16708. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  16709. /**
  16710. * @author benaadams / https://twitter.com/ben_a_adams
  16711. */
  16712. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  16713. BufferGeometry.call( this );
  16714. this.type = 'CircleBufferGeometry';
  16715. this.parameters = {
  16716. radius: radius,
  16717. segments: segments,
  16718. thetaStart: thetaStart,
  16719. thetaLength: thetaLength
  16720. };
  16721. radius = radius || 50;
  16722. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  16723. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16724. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16725. var vertices = segments + 2;
  16726. var positions = new Float32Array( vertices * 3 );
  16727. var normals = new Float32Array( vertices * 3 );
  16728. var uvs = new Float32Array( vertices * 2 );
  16729. // center data is already zero, but need to set a few extras
  16730. normals[ 2 ] = 1.0;
  16731. uvs[ 0 ] = 0.5;
  16732. uvs[ 1 ] = 0.5;
  16733. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) {
  16734. var segment = thetaStart + s / segments * thetaLength;
  16735. positions[ i ] = radius * Math.cos( segment );
  16736. positions[ i + 1 ] = radius * Math.sin( segment );
  16737. normals[ i + 2 ] = 1; // normal z
  16738. uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2;
  16739. uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2;
  16740. }
  16741. var indices = [];
  16742. for ( var i = 1; i <= segments; i ++ ) {
  16743. indices.push( i, i + 1, 0 );
  16744. }
  16745. this.setIndex( new BufferAttribute( new Uint16Array( indices ), 1 ) );
  16746. this.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  16747. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  16748. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  16749. this.boundingSphere = new Sphere( new Vector3(), radius );
  16750. }
  16751. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16752. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  16753. /**
  16754. * @author hughes
  16755. */
  16756. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  16757. Geometry.call( this );
  16758. this.type = 'CircleGeometry';
  16759. this.parameters = {
  16760. radius: radius,
  16761. segments: segments,
  16762. thetaStart: thetaStart,
  16763. thetaLength: thetaLength
  16764. };
  16765. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  16766. }
  16767. CircleGeometry.prototype = Object.create( Geometry.prototype );
  16768. CircleGeometry.prototype.constructor = CircleGeometry;
  16769. /**
  16770. * @author mrdoob / http://mrdoob.com/
  16771. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  16772. */
  16773. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  16774. Geometry.call( this );
  16775. this.type = 'BoxGeometry';
  16776. this.parameters = {
  16777. width: width,
  16778. height: height,
  16779. depth: depth,
  16780. widthSegments: widthSegments,
  16781. heightSegments: heightSegments,
  16782. depthSegments: depthSegments
  16783. };
  16784. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  16785. this.mergeVertices();
  16786. }
  16787. BoxGeometry.prototype = Object.create( Geometry.prototype );
  16788. BoxGeometry.prototype.constructor = BoxGeometry;
  16789. var Geometries = Object.freeze({
  16790. WireframeGeometry: WireframeGeometry,
  16791. ParametricGeometry: ParametricGeometry,
  16792. ParametricBufferGeometry: ParametricBufferGeometry,
  16793. TetrahedronGeometry: TetrahedronGeometry,
  16794. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  16795. OctahedronGeometry: OctahedronGeometry,
  16796. OctahedronBufferGeometry: OctahedronBufferGeometry,
  16797. IcosahedronGeometry: IcosahedronGeometry,
  16798. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  16799. DodecahedronGeometry: DodecahedronGeometry,
  16800. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  16801. PolyhedronGeometry: PolyhedronGeometry,
  16802. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  16803. TubeGeometry: TubeGeometry,
  16804. TubeBufferGeometry: TubeBufferGeometry,
  16805. TorusKnotGeometry: TorusKnotGeometry,
  16806. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  16807. TorusGeometry: TorusGeometry,
  16808. TorusBufferGeometry: TorusBufferGeometry,
  16809. TextGeometry: TextGeometry,
  16810. SphereBufferGeometry: SphereBufferGeometry,
  16811. SphereGeometry: SphereGeometry,
  16812. RingGeometry: RingGeometry,
  16813. RingBufferGeometry: RingBufferGeometry,
  16814. PlaneBufferGeometry: PlaneBufferGeometry,
  16815. PlaneGeometry: PlaneGeometry,
  16816. LatheGeometry: LatheGeometry,
  16817. LatheBufferGeometry: LatheBufferGeometry,
  16818. ShapeGeometry: ShapeGeometry,
  16819. ShapeBufferGeometry: ShapeBufferGeometry,
  16820. ExtrudeGeometry: ExtrudeGeometry,
  16821. EdgesGeometry: EdgesGeometry,
  16822. ConeGeometry: ConeGeometry,
  16823. ConeBufferGeometry: ConeBufferGeometry,
  16824. CylinderGeometry: CylinderGeometry,
  16825. CylinderBufferGeometry: CylinderBufferGeometry,
  16826. CircleBufferGeometry: CircleBufferGeometry,
  16827. CircleGeometry: CircleGeometry,
  16828. BoxBufferGeometry: BoxBufferGeometry,
  16829. BoxGeometry: BoxGeometry
  16830. });
  16831. /**
  16832. * @author mrdoob / http://mrdoob.com/
  16833. */
  16834. function ShadowMaterial() {
  16835. ShaderMaterial.call( this, {
  16836. uniforms: Object.assign( {},
  16837. UniformsLib.lights,
  16838. {
  16839. opacity: { value: 1.0 }
  16840. }
  16841. ),
  16842. vertexShader: ShaderChunk[ 'shadow_vert' ],
  16843. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  16844. } );
  16845. this.lights = true;
  16846. this.transparent = true;
  16847. Object.defineProperties( this, {
  16848. opacity: {
  16849. enumerable: true,
  16850. get: function () {
  16851. return this.uniforms.opacity.value;
  16852. },
  16853. set: function ( value ) {
  16854. this.uniforms.opacity.value = value;
  16855. }
  16856. }
  16857. } );
  16858. }
  16859. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  16860. ShadowMaterial.prototype.constructor = ShadowMaterial;
  16861. ShadowMaterial.prototype.isShadowMaterial = true;
  16862. /**
  16863. * @author mrdoob / http://mrdoob.com/
  16864. */
  16865. function RawShaderMaterial( parameters ) {
  16866. ShaderMaterial.call( this, parameters );
  16867. this.type = 'RawShaderMaterial';
  16868. }
  16869. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  16870. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  16871. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  16872. /**
  16873. * @author mrdoob / http://mrdoob.com/
  16874. */
  16875. function MultiMaterial( materials ) {
  16876. this.uuid = _Math.generateUUID();
  16877. this.type = 'MultiMaterial';
  16878. this.materials = materials instanceof Array ? materials : [];
  16879. this.visible = true;
  16880. }
  16881. MultiMaterial.prototype = {
  16882. constructor: MultiMaterial,
  16883. isMultiMaterial: true,
  16884. toJSON: function ( meta ) {
  16885. var output = {
  16886. metadata: {
  16887. version: 4.2,
  16888. type: 'material',
  16889. generator: 'MaterialExporter'
  16890. },
  16891. uuid: this.uuid,
  16892. type: this.type,
  16893. materials: []
  16894. };
  16895. var materials = this.materials;
  16896. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16897. var material = materials[ i ].toJSON( meta );
  16898. delete material.metadata;
  16899. output.materials.push( material );
  16900. }
  16901. output.visible = this.visible;
  16902. return output;
  16903. },
  16904. clone: function () {
  16905. var material = new this.constructor();
  16906. for ( var i = 0; i < this.materials.length; i ++ ) {
  16907. material.materials.push( this.materials[ i ].clone() );
  16908. }
  16909. material.visible = this.visible;
  16910. return material;
  16911. }
  16912. };
  16913. /**
  16914. * @author WestLangley / http://github.com/WestLangley
  16915. *
  16916. * parameters = {
  16917. * color: <hex>,
  16918. * roughness: <float>,
  16919. * metalness: <float>,
  16920. * opacity: <float>,
  16921. *
  16922. * map: new THREE.Texture( <Image> ),
  16923. *
  16924. * lightMap: new THREE.Texture( <Image> ),
  16925. * lightMapIntensity: <float>
  16926. *
  16927. * aoMap: new THREE.Texture( <Image> ),
  16928. * aoMapIntensity: <float>
  16929. *
  16930. * emissive: <hex>,
  16931. * emissiveIntensity: <float>
  16932. * emissiveMap: new THREE.Texture( <Image> ),
  16933. *
  16934. * bumpMap: new THREE.Texture( <Image> ),
  16935. * bumpScale: <float>,
  16936. *
  16937. * normalMap: new THREE.Texture( <Image> ),
  16938. * normalScale: <Vector2>,
  16939. *
  16940. * displacementMap: new THREE.Texture( <Image> ),
  16941. * displacementScale: <float>,
  16942. * displacementBias: <float>,
  16943. *
  16944. * roughnessMap: new THREE.Texture( <Image> ),
  16945. *
  16946. * metalnessMap: new THREE.Texture( <Image> ),
  16947. *
  16948. * alphaMap: new THREE.Texture( <Image> ),
  16949. *
  16950. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  16951. * envMapIntensity: <float>
  16952. *
  16953. * refractionRatio: <float>,
  16954. *
  16955. * wireframe: <boolean>,
  16956. * wireframeLinewidth: <float>,
  16957. *
  16958. * skinning: <bool>,
  16959. * morphTargets: <bool>,
  16960. * morphNormals: <bool>
  16961. * }
  16962. */
  16963. function MeshStandardMaterial( parameters ) {
  16964. Material.call( this );
  16965. this.defines = { 'STANDARD': '' };
  16966. this.type = 'MeshStandardMaterial';
  16967. this.color = new Color( 0xffffff ); // diffuse
  16968. this.roughness = 0.5;
  16969. this.metalness = 0.5;
  16970. this.map = null;
  16971. this.lightMap = null;
  16972. this.lightMapIntensity = 1.0;
  16973. this.aoMap = null;
  16974. this.aoMapIntensity = 1.0;
  16975. this.emissive = new Color( 0x000000 );
  16976. this.emissiveIntensity = 1.0;
  16977. this.emissiveMap = null;
  16978. this.bumpMap = null;
  16979. this.bumpScale = 1;
  16980. this.normalMap = null;
  16981. this.normalScale = new Vector2( 1, 1 );
  16982. this.displacementMap = null;
  16983. this.displacementScale = 1;
  16984. this.displacementBias = 0;
  16985. this.roughnessMap = null;
  16986. this.metalnessMap = null;
  16987. this.alphaMap = null;
  16988. this.envMap = null;
  16989. this.envMapIntensity = 1.0;
  16990. this.refractionRatio = 0.98;
  16991. this.wireframe = false;
  16992. this.wireframeLinewidth = 1;
  16993. this.wireframeLinecap = 'round';
  16994. this.wireframeLinejoin = 'round';
  16995. this.skinning = false;
  16996. this.morphTargets = false;
  16997. this.morphNormals = false;
  16998. this.setValues( parameters );
  16999. }
  17000. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  17001. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  17002. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  17003. MeshStandardMaterial.prototype.copy = function ( source ) {
  17004. Material.prototype.copy.call( this, source );
  17005. this.defines = { 'STANDARD': '' };
  17006. this.color.copy( source.color );
  17007. this.roughness = source.roughness;
  17008. this.metalness = source.metalness;
  17009. this.map = source.map;
  17010. this.lightMap = source.lightMap;
  17011. this.lightMapIntensity = source.lightMapIntensity;
  17012. this.aoMap = source.aoMap;
  17013. this.aoMapIntensity = source.aoMapIntensity;
  17014. this.emissive.copy( source.emissive );
  17015. this.emissiveMap = source.emissiveMap;
  17016. this.emissiveIntensity = source.emissiveIntensity;
  17017. this.bumpMap = source.bumpMap;
  17018. this.bumpScale = source.bumpScale;
  17019. this.normalMap = source.normalMap;
  17020. this.normalScale.copy( source.normalScale );
  17021. this.displacementMap = source.displacementMap;
  17022. this.displacementScale = source.displacementScale;
  17023. this.displacementBias = source.displacementBias;
  17024. this.roughnessMap = source.roughnessMap;
  17025. this.metalnessMap = source.metalnessMap;
  17026. this.alphaMap = source.alphaMap;
  17027. this.envMap = source.envMap;
  17028. this.envMapIntensity = source.envMapIntensity;
  17029. this.refractionRatio = source.refractionRatio;
  17030. this.wireframe = source.wireframe;
  17031. this.wireframeLinewidth = source.wireframeLinewidth;
  17032. this.wireframeLinecap = source.wireframeLinecap;
  17033. this.wireframeLinejoin = source.wireframeLinejoin;
  17034. this.skinning = source.skinning;
  17035. this.morphTargets = source.morphTargets;
  17036. this.morphNormals = source.morphNormals;
  17037. return this;
  17038. };
  17039. /**
  17040. * @author WestLangley / http://github.com/WestLangley
  17041. *
  17042. * parameters = {
  17043. * reflectivity: <float>
  17044. * }
  17045. */
  17046. function MeshPhysicalMaterial( parameters ) {
  17047. MeshStandardMaterial.call( this );
  17048. this.defines = { 'PHYSICAL': '' };
  17049. this.type = 'MeshPhysicalMaterial';
  17050. this.reflectivity = 0.5; // maps to F0 = 0.04
  17051. this.clearCoat = 0.0;
  17052. this.clearCoatRoughness = 0.0;
  17053. this.setValues( parameters );
  17054. }
  17055. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  17056. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  17057. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  17058. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  17059. MeshStandardMaterial.prototype.copy.call( this, source );
  17060. this.defines = { 'PHYSICAL': '' };
  17061. this.reflectivity = source.reflectivity;
  17062. this.clearCoat = source.clearCoat;
  17063. this.clearCoatRoughness = source.clearCoatRoughness;
  17064. return this;
  17065. };
  17066. /**
  17067. * @author mrdoob / http://mrdoob.com/
  17068. * @author alteredq / http://alteredqualia.com/
  17069. *
  17070. * parameters = {
  17071. * color: <hex>,
  17072. * specular: <hex>,
  17073. * shininess: <float>,
  17074. * opacity: <float>,
  17075. *
  17076. * map: new THREE.Texture( <Image> ),
  17077. *
  17078. * lightMap: new THREE.Texture( <Image> ),
  17079. * lightMapIntensity: <float>
  17080. *
  17081. * aoMap: new THREE.Texture( <Image> ),
  17082. * aoMapIntensity: <float>
  17083. *
  17084. * emissive: <hex>,
  17085. * emissiveIntensity: <float>
  17086. * emissiveMap: new THREE.Texture( <Image> ),
  17087. *
  17088. * bumpMap: new THREE.Texture( <Image> ),
  17089. * bumpScale: <float>,
  17090. *
  17091. * normalMap: new THREE.Texture( <Image> ),
  17092. * normalScale: <Vector2>,
  17093. *
  17094. * displacementMap: new THREE.Texture( <Image> ),
  17095. * displacementScale: <float>,
  17096. * displacementBias: <float>,
  17097. *
  17098. * specularMap: new THREE.Texture( <Image> ),
  17099. *
  17100. * alphaMap: new THREE.Texture( <Image> ),
  17101. *
  17102. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17103. * combine: THREE.Multiply,
  17104. * reflectivity: <float>,
  17105. * refractionRatio: <float>,
  17106. *
  17107. * wireframe: <boolean>,
  17108. * wireframeLinewidth: <float>,
  17109. *
  17110. * skinning: <bool>,
  17111. * morphTargets: <bool>,
  17112. * morphNormals: <bool>
  17113. * }
  17114. */
  17115. function MeshPhongMaterial( parameters ) {
  17116. Material.call( this );
  17117. this.type = 'MeshPhongMaterial';
  17118. this.color = new Color( 0xffffff ); // diffuse
  17119. this.specular = new Color( 0x111111 );
  17120. this.shininess = 30;
  17121. this.map = null;
  17122. this.lightMap = null;
  17123. this.lightMapIntensity = 1.0;
  17124. this.aoMap = null;
  17125. this.aoMapIntensity = 1.0;
  17126. this.emissive = new Color( 0x000000 );
  17127. this.emissiveIntensity = 1.0;
  17128. this.emissiveMap = null;
  17129. this.bumpMap = null;
  17130. this.bumpScale = 1;
  17131. this.normalMap = null;
  17132. this.normalScale = new Vector2( 1, 1 );
  17133. this.displacementMap = null;
  17134. this.displacementScale = 1;
  17135. this.displacementBias = 0;
  17136. this.specularMap = null;
  17137. this.alphaMap = null;
  17138. this.envMap = null;
  17139. this.combine = MultiplyOperation;
  17140. this.reflectivity = 1;
  17141. this.refractionRatio = 0.98;
  17142. this.wireframe = false;
  17143. this.wireframeLinewidth = 1;
  17144. this.wireframeLinecap = 'round';
  17145. this.wireframeLinejoin = 'round';
  17146. this.skinning = false;
  17147. this.morphTargets = false;
  17148. this.morphNormals = false;
  17149. this.setValues( parameters );
  17150. }
  17151. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  17152. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  17153. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  17154. MeshPhongMaterial.prototype.copy = function ( source ) {
  17155. Material.prototype.copy.call( this, source );
  17156. this.color.copy( source.color );
  17157. this.specular.copy( source.specular );
  17158. this.shininess = source.shininess;
  17159. this.map = source.map;
  17160. this.lightMap = source.lightMap;
  17161. this.lightMapIntensity = source.lightMapIntensity;
  17162. this.aoMap = source.aoMap;
  17163. this.aoMapIntensity = source.aoMapIntensity;
  17164. this.emissive.copy( source.emissive );
  17165. this.emissiveMap = source.emissiveMap;
  17166. this.emissiveIntensity = source.emissiveIntensity;
  17167. this.bumpMap = source.bumpMap;
  17168. this.bumpScale = source.bumpScale;
  17169. this.normalMap = source.normalMap;
  17170. this.normalScale.copy( source.normalScale );
  17171. this.displacementMap = source.displacementMap;
  17172. this.displacementScale = source.displacementScale;
  17173. this.displacementBias = source.displacementBias;
  17174. this.specularMap = source.specularMap;
  17175. this.alphaMap = source.alphaMap;
  17176. this.envMap = source.envMap;
  17177. this.combine = source.combine;
  17178. this.reflectivity = source.reflectivity;
  17179. this.refractionRatio = source.refractionRatio;
  17180. this.wireframe = source.wireframe;
  17181. this.wireframeLinewidth = source.wireframeLinewidth;
  17182. this.wireframeLinecap = source.wireframeLinecap;
  17183. this.wireframeLinejoin = source.wireframeLinejoin;
  17184. this.skinning = source.skinning;
  17185. this.morphTargets = source.morphTargets;
  17186. this.morphNormals = source.morphNormals;
  17187. return this;
  17188. };
  17189. /**
  17190. * @author takahirox / http://github.com/takahirox
  17191. *
  17192. * parameters = {
  17193. * gradientMap: new THREE.Texture( <Image> )
  17194. * }
  17195. */
  17196. function MeshToonMaterial( parameters ) {
  17197. MeshPhongMaterial.call( this );
  17198. this.defines = { 'TOON': '' };
  17199. this.type = 'MeshToonMaterial';
  17200. this.gradientMap = null;
  17201. this.setValues( parameters );
  17202. }
  17203. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  17204. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  17205. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  17206. MeshToonMaterial.prototype.copy = function ( source ) {
  17207. MeshPhongMaterial.prototype.copy.call( this, source );
  17208. this.gradientMap = source.gradientMap;
  17209. return this;
  17210. };
  17211. /**
  17212. * @author mrdoob / http://mrdoob.com/
  17213. *
  17214. * parameters = {
  17215. * opacity: <float>,
  17216. *
  17217. * wireframe: <boolean>,
  17218. * wireframeLinewidth: <float>
  17219. * }
  17220. */
  17221. function MeshNormalMaterial( parameters ) {
  17222. Material.call( this, parameters );
  17223. this.type = 'MeshNormalMaterial';
  17224. this.wireframe = false;
  17225. this.wireframeLinewidth = 1;
  17226. this.fog = false;
  17227. this.lights = false;
  17228. this.morphTargets = false;
  17229. this.setValues( parameters );
  17230. }
  17231. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  17232. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  17233. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  17234. MeshNormalMaterial.prototype.copy = function ( source ) {
  17235. Material.prototype.copy.call( this, source );
  17236. this.wireframe = source.wireframe;
  17237. this.wireframeLinewidth = source.wireframeLinewidth;
  17238. return this;
  17239. };
  17240. /**
  17241. * @author mrdoob / http://mrdoob.com/
  17242. * @author alteredq / http://alteredqualia.com/
  17243. *
  17244. * parameters = {
  17245. * color: <hex>,
  17246. * opacity: <float>,
  17247. *
  17248. * map: new THREE.Texture( <Image> ),
  17249. *
  17250. * lightMap: new THREE.Texture( <Image> ),
  17251. * lightMapIntensity: <float>
  17252. *
  17253. * aoMap: new THREE.Texture( <Image> ),
  17254. * aoMapIntensity: <float>
  17255. *
  17256. * emissive: <hex>,
  17257. * emissiveIntensity: <float>
  17258. * emissiveMap: new THREE.Texture( <Image> ),
  17259. *
  17260. * specularMap: new THREE.Texture( <Image> ),
  17261. *
  17262. * alphaMap: new THREE.Texture( <Image> ),
  17263. *
  17264. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17265. * combine: THREE.Multiply,
  17266. * reflectivity: <float>,
  17267. * refractionRatio: <float>,
  17268. *
  17269. * wireframe: <boolean>,
  17270. * wireframeLinewidth: <float>,
  17271. *
  17272. * skinning: <bool>,
  17273. * morphTargets: <bool>,
  17274. * morphNormals: <bool>
  17275. * }
  17276. */
  17277. function MeshLambertMaterial( parameters ) {
  17278. Material.call( this );
  17279. this.type = 'MeshLambertMaterial';
  17280. this.color = new Color( 0xffffff ); // diffuse
  17281. this.map = null;
  17282. this.lightMap = null;
  17283. this.lightMapIntensity = 1.0;
  17284. this.aoMap = null;
  17285. this.aoMapIntensity = 1.0;
  17286. this.emissive = new Color( 0x000000 );
  17287. this.emissiveIntensity = 1.0;
  17288. this.emissiveMap = null;
  17289. this.specularMap = null;
  17290. this.alphaMap = null;
  17291. this.envMap = null;
  17292. this.combine = MultiplyOperation;
  17293. this.reflectivity = 1;
  17294. this.refractionRatio = 0.98;
  17295. this.wireframe = false;
  17296. this.wireframeLinewidth = 1;
  17297. this.wireframeLinecap = 'round';
  17298. this.wireframeLinejoin = 'round';
  17299. this.skinning = false;
  17300. this.morphTargets = false;
  17301. this.morphNormals = false;
  17302. this.setValues( parameters );
  17303. }
  17304. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  17305. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  17306. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  17307. MeshLambertMaterial.prototype.copy = function ( source ) {
  17308. Material.prototype.copy.call( this, source );
  17309. this.color.copy( source.color );
  17310. this.map = source.map;
  17311. this.lightMap = source.lightMap;
  17312. this.lightMapIntensity = source.lightMapIntensity;
  17313. this.aoMap = source.aoMap;
  17314. this.aoMapIntensity = source.aoMapIntensity;
  17315. this.emissive.copy( source.emissive );
  17316. this.emissiveMap = source.emissiveMap;
  17317. this.emissiveIntensity = source.emissiveIntensity;
  17318. this.specularMap = source.specularMap;
  17319. this.alphaMap = source.alphaMap;
  17320. this.envMap = source.envMap;
  17321. this.combine = source.combine;
  17322. this.reflectivity = source.reflectivity;
  17323. this.refractionRatio = source.refractionRatio;
  17324. this.wireframe = source.wireframe;
  17325. this.wireframeLinewidth = source.wireframeLinewidth;
  17326. this.wireframeLinecap = source.wireframeLinecap;
  17327. this.wireframeLinejoin = source.wireframeLinejoin;
  17328. this.skinning = source.skinning;
  17329. this.morphTargets = source.morphTargets;
  17330. this.morphNormals = source.morphNormals;
  17331. return this;
  17332. };
  17333. /**
  17334. * @author alteredq / http://alteredqualia.com/
  17335. *
  17336. * parameters = {
  17337. * color: <hex>,
  17338. * opacity: <float>,
  17339. *
  17340. * linewidth: <float>,
  17341. *
  17342. * scale: <float>,
  17343. * dashSize: <float>,
  17344. * gapSize: <float>
  17345. * }
  17346. */
  17347. function LineDashedMaterial( parameters ) {
  17348. Material.call( this );
  17349. this.type = 'LineDashedMaterial';
  17350. this.color = new Color( 0xffffff );
  17351. this.linewidth = 1;
  17352. this.scale = 1;
  17353. this.dashSize = 3;
  17354. this.gapSize = 1;
  17355. this.lights = false;
  17356. this.setValues( parameters );
  17357. }
  17358. LineDashedMaterial.prototype = Object.create( Material.prototype );
  17359. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  17360. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  17361. LineDashedMaterial.prototype.copy = function ( source ) {
  17362. Material.prototype.copy.call( this, source );
  17363. this.color.copy( source.color );
  17364. this.linewidth = source.linewidth;
  17365. this.scale = source.scale;
  17366. this.dashSize = source.dashSize;
  17367. this.gapSize = source.gapSize;
  17368. return this;
  17369. };
  17370. var Materials = Object.freeze({
  17371. ShadowMaterial: ShadowMaterial,
  17372. SpriteMaterial: SpriteMaterial,
  17373. RawShaderMaterial: RawShaderMaterial,
  17374. ShaderMaterial: ShaderMaterial,
  17375. PointsMaterial: PointsMaterial,
  17376. MultiMaterial: MultiMaterial,
  17377. MeshPhysicalMaterial: MeshPhysicalMaterial,
  17378. MeshStandardMaterial: MeshStandardMaterial,
  17379. MeshPhongMaterial: MeshPhongMaterial,
  17380. MeshToonMaterial: MeshToonMaterial,
  17381. MeshNormalMaterial: MeshNormalMaterial,
  17382. MeshLambertMaterial: MeshLambertMaterial,
  17383. MeshDepthMaterial: MeshDepthMaterial,
  17384. MeshBasicMaterial: MeshBasicMaterial,
  17385. LineDashedMaterial: LineDashedMaterial,
  17386. LineBasicMaterial: LineBasicMaterial,
  17387. Material: Material
  17388. });
  17389. /**
  17390. * @author mrdoob / http://mrdoob.com/
  17391. */
  17392. var Cache = {
  17393. enabled: false,
  17394. files: {},
  17395. add: function ( key, file ) {
  17396. if ( this.enabled === false ) return;
  17397. // console.log( 'THREE.Cache', 'Adding key:', key );
  17398. this.files[ key ] = file;
  17399. },
  17400. get: function ( key ) {
  17401. if ( this.enabled === false ) return;
  17402. // console.log( 'THREE.Cache', 'Checking key:', key );
  17403. return this.files[ key ];
  17404. },
  17405. remove: function ( key ) {
  17406. delete this.files[ key ];
  17407. },
  17408. clear: function () {
  17409. this.files = {};
  17410. }
  17411. };
  17412. /**
  17413. * @author mrdoob / http://mrdoob.com/
  17414. */
  17415. function LoadingManager( onLoad, onProgress, onError ) {
  17416. var scope = this;
  17417. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  17418. this.onStart = undefined;
  17419. this.onLoad = onLoad;
  17420. this.onProgress = onProgress;
  17421. this.onError = onError;
  17422. this.itemStart = function ( url ) {
  17423. itemsTotal ++;
  17424. if ( isLoading === false ) {
  17425. if ( scope.onStart !== undefined ) {
  17426. scope.onStart( url, itemsLoaded, itemsTotal );
  17427. }
  17428. }
  17429. isLoading = true;
  17430. };
  17431. this.itemEnd = function ( url ) {
  17432. itemsLoaded ++;
  17433. if ( scope.onProgress !== undefined ) {
  17434. scope.onProgress( url, itemsLoaded, itemsTotal );
  17435. }
  17436. if ( itemsLoaded === itemsTotal ) {
  17437. isLoading = false;
  17438. if ( scope.onLoad !== undefined ) {
  17439. scope.onLoad();
  17440. }
  17441. }
  17442. };
  17443. this.itemError = function ( url ) {
  17444. if ( scope.onError !== undefined ) {
  17445. scope.onError( url );
  17446. }
  17447. };
  17448. }
  17449. var DefaultLoadingManager = new LoadingManager();
  17450. /**
  17451. * @author mrdoob / http://mrdoob.com/
  17452. */
  17453. function FileLoader( manager ) {
  17454. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17455. }
  17456. Object.assign( FileLoader.prototype, {
  17457. load: function ( url, onLoad, onProgress, onError ) {
  17458. if ( url === undefined ) url = '';
  17459. if ( this.path !== undefined ) url = this.path + url;
  17460. var scope = this;
  17461. var cached = Cache.get( url );
  17462. if ( cached !== undefined ) {
  17463. scope.manager.itemStart( url );
  17464. setTimeout( function () {
  17465. if ( onLoad ) onLoad( cached );
  17466. scope.manager.itemEnd( url );
  17467. }, 0 );
  17468. return cached;
  17469. }
  17470. // Check for data: URI
  17471. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  17472. var dataUriRegexResult = url.match( dataUriRegex );
  17473. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  17474. if ( dataUriRegexResult ) {
  17475. var mimeType = dataUriRegexResult[ 1 ];
  17476. var isBase64 = !! dataUriRegexResult[ 2 ];
  17477. var data = dataUriRegexResult[ 3 ];
  17478. data = window.decodeURIComponent( data );
  17479. if ( isBase64 ) data = window.atob( data );
  17480. try {
  17481. var response;
  17482. var responseType = ( this.responseType || '' ).toLowerCase();
  17483. switch ( responseType ) {
  17484. case 'arraybuffer':
  17485. case 'blob':
  17486. response = new ArrayBuffer( data.length );
  17487. var view = new Uint8Array( response );
  17488. for ( var i = 0; i < data.length; i ++ ) {
  17489. view[ i ] = data.charCodeAt( i );
  17490. }
  17491. if ( responseType === 'blob' ) {
  17492. response = new Blob( [ response ], { type: mimeType } );
  17493. }
  17494. break;
  17495. case 'document':
  17496. var parser = new DOMParser();
  17497. response = parser.parseFromString( data, mimeType );
  17498. break;
  17499. case 'json':
  17500. response = JSON.parse( data );
  17501. break;
  17502. default: // 'text' or other
  17503. response = data;
  17504. break;
  17505. }
  17506. // Wait for next browser tick
  17507. window.setTimeout( function () {
  17508. if ( onLoad ) onLoad( response );
  17509. scope.manager.itemEnd( url );
  17510. }, 0 );
  17511. } catch ( error ) {
  17512. // Wait for next browser tick
  17513. window.setTimeout( function () {
  17514. if ( onError ) onError( error );
  17515. scope.manager.itemError( url );
  17516. }, 0 );
  17517. }
  17518. } else {
  17519. var request = new XMLHttpRequest();
  17520. request.open( 'GET', url, true );
  17521. request.addEventListener( 'load', function ( event ) {
  17522. var response = event.target.response;
  17523. Cache.add( url, response );
  17524. if ( this.status === 200 ) {
  17525. if ( onLoad ) onLoad( response );
  17526. scope.manager.itemEnd( url );
  17527. } else if ( this.status === 0 ) {
  17528. // Some browsers return HTTP Status 0 when using non-http protocol
  17529. // e.g. 'file://' or 'data://'. Handle as success.
  17530. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  17531. if ( onLoad ) onLoad( response );
  17532. scope.manager.itemEnd( url );
  17533. } else {
  17534. if ( onError ) onError( event );
  17535. scope.manager.itemError( url );
  17536. }
  17537. }, false );
  17538. if ( onProgress !== undefined ) {
  17539. request.addEventListener( 'progress', function ( event ) {
  17540. onProgress( event );
  17541. }, false );
  17542. }
  17543. request.addEventListener( 'error', function ( event ) {
  17544. if ( onError ) onError( event );
  17545. scope.manager.itemError( url );
  17546. }, false );
  17547. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  17548. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  17549. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  17550. request.send( null );
  17551. }
  17552. scope.manager.itemStart( url );
  17553. return request;
  17554. },
  17555. setPath: function ( value ) {
  17556. this.path = value;
  17557. return this;
  17558. },
  17559. setResponseType: function ( value ) {
  17560. this.responseType = value;
  17561. return this;
  17562. },
  17563. setWithCredentials: function ( value ) {
  17564. this.withCredentials = value;
  17565. return this;
  17566. },
  17567. setMimeType: function ( value ) {
  17568. this.mimeType = value;
  17569. return this;
  17570. }
  17571. } );
  17572. /**
  17573. * @author mrdoob / http://mrdoob.com/
  17574. *
  17575. * Abstract Base class to block based textures loader (dds, pvr, ...)
  17576. */
  17577. function CompressedTextureLoader( manager ) {
  17578. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17579. // override in sub classes
  17580. this._parser = null;
  17581. }
  17582. Object.assign( CompressedTextureLoader.prototype, {
  17583. load: function ( url, onLoad, onProgress, onError ) {
  17584. var scope = this;
  17585. var images = [];
  17586. var texture = new CompressedTexture();
  17587. texture.image = images;
  17588. var loader = new FileLoader( this.manager );
  17589. loader.setPath( this.path );
  17590. loader.setResponseType( 'arraybuffer' );
  17591. function loadTexture( i ) {
  17592. loader.load( url[ i ], function ( buffer ) {
  17593. var texDatas = scope._parser( buffer, true );
  17594. images[ i ] = {
  17595. width: texDatas.width,
  17596. height: texDatas.height,
  17597. format: texDatas.format,
  17598. mipmaps: texDatas.mipmaps
  17599. };
  17600. loaded += 1;
  17601. if ( loaded === 6 ) {
  17602. if ( texDatas.mipmapCount === 1 )
  17603. texture.minFilter = LinearFilter;
  17604. texture.format = texDatas.format;
  17605. texture.needsUpdate = true;
  17606. if ( onLoad ) onLoad( texture );
  17607. }
  17608. }, onProgress, onError );
  17609. }
  17610. if ( Array.isArray( url ) ) {
  17611. var loaded = 0;
  17612. for ( var i = 0, il = url.length; i < il; ++ i ) {
  17613. loadTexture( i );
  17614. }
  17615. } else {
  17616. // compressed cubemap texture stored in a single DDS file
  17617. loader.load( url, function ( buffer ) {
  17618. var texDatas = scope._parser( buffer, true );
  17619. if ( texDatas.isCubemap ) {
  17620. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  17621. for ( var f = 0; f < faces; f ++ ) {
  17622. images[ f ] = { mipmaps : [] };
  17623. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  17624. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  17625. images[ f ].format = texDatas.format;
  17626. images[ f ].width = texDatas.width;
  17627. images[ f ].height = texDatas.height;
  17628. }
  17629. }
  17630. } else {
  17631. texture.image.width = texDatas.width;
  17632. texture.image.height = texDatas.height;
  17633. texture.mipmaps = texDatas.mipmaps;
  17634. }
  17635. if ( texDatas.mipmapCount === 1 ) {
  17636. texture.minFilter = LinearFilter;
  17637. }
  17638. texture.format = texDatas.format;
  17639. texture.needsUpdate = true;
  17640. if ( onLoad ) onLoad( texture );
  17641. }, onProgress, onError );
  17642. }
  17643. return texture;
  17644. },
  17645. setPath: function ( value ) {
  17646. this.path = value;
  17647. return this;
  17648. }
  17649. } );
  17650. /**
  17651. * @author Nikos M. / https://github.com/foo123/
  17652. *
  17653. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  17654. */
  17655. var DataTextureLoader = BinaryTextureLoader;
  17656. function BinaryTextureLoader( manager ) {
  17657. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17658. // override in sub classes
  17659. this._parser = null;
  17660. }
  17661. Object.assign( BinaryTextureLoader.prototype, {
  17662. load: function ( url, onLoad, onProgress, onError ) {
  17663. var scope = this;
  17664. var texture = new DataTexture();
  17665. var loader = new FileLoader( this.manager );
  17666. loader.setResponseType( 'arraybuffer' );
  17667. loader.load( url, function ( buffer ) {
  17668. var texData = scope._parser( buffer );
  17669. if ( ! texData ) return;
  17670. if ( undefined !== texData.image ) {
  17671. texture.image = texData.image;
  17672. } else if ( undefined !== texData.data ) {
  17673. texture.image.width = texData.width;
  17674. texture.image.height = texData.height;
  17675. texture.image.data = texData.data;
  17676. }
  17677. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  17678. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  17679. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  17680. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  17681. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  17682. if ( undefined !== texData.format ) {
  17683. texture.format = texData.format;
  17684. }
  17685. if ( undefined !== texData.type ) {
  17686. texture.type = texData.type;
  17687. }
  17688. if ( undefined !== texData.mipmaps ) {
  17689. texture.mipmaps = texData.mipmaps;
  17690. }
  17691. if ( 1 === texData.mipmapCount ) {
  17692. texture.minFilter = LinearFilter;
  17693. }
  17694. texture.needsUpdate = true;
  17695. if ( onLoad ) onLoad( texture, texData );
  17696. }, onProgress, onError );
  17697. return texture;
  17698. }
  17699. } );
  17700. /**
  17701. * @author mrdoob / http://mrdoob.com/
  17702. */
  17703. function ImageLoader( manager ) {
  17704. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17705. }
  17706. Object.assign( ImageLoader.prototype, {
  17707. load: function ( url, onLoad, onProgress, onError ) {
  17708. var scope = this;
  17709. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  17710. image.onload = function () {
  17711. image.onload = null;
  17712. URL.revokeObjectURL( image.src );
  17713. if ( onLoad ) onLoad( image );
  17714. scope.manager.itemEnd( url );
  17715. };
  17716. image.onerror = onError;
  17717. if ( url.indexOf( 'data:' ) === 0 ) {
  17718. image.src = url;
  17719. } else if ( this.crossOrigin !== undefined ) {
  17720. // crossOrigin doesn't work with URL.createObjectURL()?
  17721. image.crossOrigin = this.crossOrigin;
  17722. image.src = url;
  17723. } else {
  17724. var loader = new FileLoader();
  17725. loader.setPath( this.path );
  17726. loader.setResponseType( 'blob' );
  17727. loader.setWithCredentials( this.withCredentials );
  17728. loader.load( url, function ( blob ) {
  17729. image.src = URL.createObjectURL( blob );
  17730. }, onProgress, onError );
  17731. }
  17732. scope.manager.itemStart( url );
  17733. return image;
  17734. },
  17735. setCrossOrigin: function ( value ) {
  17736. this.crossOrigin = value;
  17737. return this;
  17738. },
  17739. setWithCredentials: function ( value ) {
  17740. this.withCredentials = value;
  17741. return this;
  17742. },
  17743. setPath: function ( value ) {
  17744. this.path = value;
  17745. return this;
  17746. }
  17747. } );
  17748. /**
  17749. * @author mrdoob / http://mrdoob.com/
  17750. */
  17751. function CubeTextureLoader( manager ) {
  17752. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17753. }
  17754. Object.assign( CubeTextureLoader.prototype, {
  17755. load: function ( urls, onLoad, onProgress, onError ) {
  17756. var texture = new CubeTexture();
  17757. var loader = new ImageLoader( this.manager );
  17758. loader.setCrossOrigin( this.crossOrigin );
  17759. loader.setPath( this.path );
  17760. var loaded = 0;
  17761. function loadTexture( i ) {
  17762. loader.load( urls[ i ], function ( image ) {
  17763. texture.images[ i ] = image;
  17764. loaded ++;
  17765. if ( loaded === 6 ) {
  17766. texture.needsUpdate = true;
  17767. if ( onLoad ) onLoad( texture );
  17768. }
  17769. }, undefined, onError );
  17770. }
  17771. for ( var i = 0; i < urls.length; ++ i ) {
  17772. loadTexture( i );
  17773. }
  17774. return texture;
  17775. },
  17776. setCrossOrigin: function ( value ) {
  17777. this.crossOrigin = value;
  17778. return this;
  17779. },
  17780. setPath: function ( value ) {
  17781. this.path = value;
  17782. return this;
  17783. }
  17784. } );
  17785. /**
  17786. * @author mrdoob / http://mrdoob.com/
  17787. */
  17788. function TextureLoader( manager ) {
  17789. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17790. }
  17791. Object.assign( TextureLoader.prototype, {
  17792. load: function ( url, onLoad, onProgress, onError ) {
  17793. var texture = new Texture();
  17794. var loader = new ImageLoader( this.manager );
  17795. loader.setCrossOrigin( this.crossOrigin );
  17796. loader.setWithCredentials( this.withCredentials );
  17797. loader.setPath( this.path );
  17798. loader.load( url, function ( image ) {
  17799. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  17800. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  17801. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  17802. texture.image = image;
  17803. texture.needsUpdate = true;
  17804. if ( onLoad !== undefined ) {
  17805. onLoad( texture );
  17806. }
  17807. }, onProgress, onError );
  17808. return texture;
  17809. },
  17810. setCrossOrigin: function ( value ) {
  17811. this.crossOrigin = value;
  17812. return this;
  17813. },
  17814. setWithCredentials: function ( value ) {
  17815. this.withCredentials = value;
  17816. return this;
  17817. },
  17818. setPath: function ( value ) {
  17819. this.path = value;
  17820. return this;
  17821. }
  17822. } );
  17823. /**
  17824. * @author mrdoob / http://mrdoob.com/
  17825. * @author alteredq / http://alteredqualia.com/
  17826. */
  17827. function Light( color, intensity ) {
  17828. Object3D.call( this );
  17829. this.type = 'Light';
  17830. this.color = new Color( color );
  17831. this.intensity = intensity !== undefined ? intensity : 1;
  17832. this.receiveShadow = undefined;
  17833. }
  17834. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  17835. constructor: Light,
  17836. isLight: true,
  17837. copy: function ( source ) {
  17838. Object3D.prototype.copy.call( this, source );
  17839. this.color.copy( source.color );
  17840. this.intensity = source.intensity;
  17841. return this;
  17842. },
  17843. toJSON: function ( meta ) {
  17844. var data = Object3D.prototype.toJSON.call( this, meta );
  17845. data.object.color = this.color.getHex();
  17846. data.object.intensity = this.intensity;
  17847. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  17848. if ( this.distance !== undefined ) data.object.distance = this.distance;
  17849. if ( this.angle !== undefined ) data.object.angle = this.angle;
  17850. if ( this.decay !== undefined ) data.object.decay = this.decay;
  17851. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  17852. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  17853. return data;
  17854. }
  17855. } );
  17856. /**
  17857. * @author alteredq / http://alteredqualia.com/
  17858. */
  17859. function HemisphereLight( skyColor, groundColor, intensity ) {
  17860. Light.call( this, skyColor, intensity );
  17861. this.type = 'HemisphereLight';
  17862. this.castShadow = undefined;
  17863. this.position.copy( Object3D.DefaultUp );
  17864. this.updateMatrix();
  17865. this.groundColor = new Color( groundColor );
  17866. }
  17867. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  17868. constructor: HemisphereLight,
  17869. isHemisphereLight: true,
  17870. copy: function ( source ) {
  17871. Light.prototype.copy.call( this, source );
  17872. this.groundColor.copy( source.groundColor );
  17873. return this;
  17874. }
  17875. } );
  17876. /**
  17877. * @author mrdoob / http://mrdoob.com/
  17878. */
  17879. function LightShadow( camera ) {
  17880. this.camera = camera;
  17881. this.bias = 0;
  17882. this.radius = 1;
  17883. this.mapSize = new Vector2( 512, 512 );
  17884. this.map = null;
  17885. this.matrix = new Matrix4();
  17886. }
  17887. Object.assign( LightShadow.prototype, {
  17888. copy: function ( source ) {
  17889. this.camera = source.camera.clone();
  17890. this.bias = source.bias;
  17891. this.radius = source.radius;
  17892. this.mapSize.copy( source.mapSize );
  17893. return this;
  17894. },
  17895. clone: function () {
  17896. return new this.constructor().copy( this );
  17897. },
  17898. toJSON: function () {
  17899. var object = {};
  17900. if ( this.bias !== 0 ) object.bias = this.bias;
  17901. if ( this.radius !== 1 ) object.radius = this.radius;
  17902. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  17903. object.camera = this.camera.toJSON( false ).object;
  17904. delete object.camera.matrix;
  17905. return object;
  17906. }
  17907. } );
  17908. /**
  17909. * @author mrdoob / http://mrdoob.com/
  17910. */
  17911. function SpotLightShadow() {
  17912. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  17913. }
  17914. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  17915. constructor: SpotLightShadow,
  17916. isSpotLightShadow: true,
  17917. update: function ( light ) {
  17918. var fov = _Math.RAD2DEG * 2 * light.angle;
  17919. var aspect = this.mapSize.width / this.mapSize.height;
  17920. var far = light.distance || 500;
  17921. var camera = this.camera;
  17922. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  17923. camera.fov = fov;
  17924. camera.aspect = aspect;
  17925. camera.far = far;
  17926. camera.updateProjectionMatrix();
  17927. }
  17928. }
  17929. } );
  17930. /**
  17931. * @author alteredq / http://alteredqualia.com/
  17932. */
  17933. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  17934. Light.call( this, color, intensity );
  17935. this.type = 'SpotLight';
  17936. this.position.copy( Object3D.DefaultUp );
  17937. this.updateMatrix();
  17938. this.target = new Object3D();
  17939. Object.defineProperty( this, 'power', {
  17940. get: function () {
  17941. // intensity = power per solid angle.
  17942. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  17943. return this.intensity * Math.PI;
  17944. },
  17945. set: function ( power ) {
  17946. // intensity = power per solid angle.
  17947. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  17948. this.intensity = power / Math.PI;
  17949. }
  17950. } );
  17951. this.distance = ( distance !== undefined ) ? distance : 0;
  17952. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  17953. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  17954. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  17955. this.shadow = new SpotLightShadow();
  17956. }
  17957. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  17958. constructor: SpotLight,
  17959. isSpotLight: true,
  17960. copy: function ( source ) {
  17961. Light.prototype.copy.call( this, source );
  17962. this.distance = source.distance;
  17963. this.angle = source.angle;
  17964. this.penumbra = source.penumbra;
  17965. this.decay = source.decay;
  17966. this.target = source.target.clone();
  17967. this.shadow = source.shadow.clone();
  17968. return this;
  17969. }
  17970. } );
  17971. /**
  17972. * @author mrdoob / http://mrdoob.com/
  17973. */
  17974. function PointLight( color, intensity, distance, decay ) {
  17975. Light.call( this, color, intensity );
  17976. this.type = 'PointLight';
  17977. Object.defineProperty( this, 'power', {
  17978. get: function () {
  17979. // intensity = power per solid angle.
  17980. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  17981. return this.intensity * 4 * Math.PI;
  17982. },
  17983. set: function ( power ) {
  17984. // intensity = power per solid angle.
  17985. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  17986. this.intensity = power / ( 4 * Math.PI );
  17987. }
  17988. } );
  17989. this.distance = ( distance !== undefined ) ? distance : 0;
  17990. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  17991. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  17992. }
  17993. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  17994. constructor: PointLight,
  17995. isPointLight: true,
  17996. copy: function ( source ) {
  17997. Light.prototype.copy.call( this, source );
  17998. this.distance = source.distance;
  17999. this.decay = source.decay;
  18000. this.shadow = source.shadow.clone();
  18001. return this;
  18002. }
  18003. } );
  18004. /**
  18005. * @author mrdoob / http://mrdoob.com/
  18006. */
  18007. function DirectionalLightShadow( light ) {
  18008. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  18009. }
  18010. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18011. constructor: DirectionalLightShadow
  18012. } );
  18013. /**
  18014. * @author mrdoob / http://mrdoob.com/
  18015. * @author alteredq / http://alteredqualia.com/
  18016. */
  18017. function DirectionalLight( color, intensity ) {
  18018. Light.call( this, color, intensity );
  18019. this.type = 'DirectionalLight';
  18020. this.position.copy( Object3D.DefaultUp );
  18021. this.updateMatrix();
  18022. this.target = new Object3D();
  18023. this.shadow = new DirectionalLightShadow();
  18024. }
  18025. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18026. constructor: DirectionalLight,
  18027. isDirectionalLight: true,
  18028. copy: function ( source ) {
  18029. Light.prototype.copy.call( this, source );
  18030. this.target = source.target.clone();
  18031. this.shadow = source.shadow.clone();
  18032. return this;
  18033. }
  18034. } );
  18035. /**
  18036. * @author mrdoob / http://mrdoob.com/
  18037. */
  18038. function AmbientLight( color, intensity ) {
  18039. Light.call( this, color, intensity );
  18040. this.type = 'AmbientLight';
  18041. this.castShadow = undefined;
  18042. }
  18043. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18044. constructor: AmbientLight,
  18045. isAmbientLight: true,
  18046. } );
  18047. /**
  18048. * @author tschw
  18049. * @author Ben Houston / http://clara.io/
  18050. * @author David Sarno / http://lighthaus.us/
  18051. */
  18052. var AnimationUtils = {
  18053. // same as Array.prototype.slice, but also works on typed arrays
  18054. arraySlice: function( array, from, to ) {
  18055. if ( AnimationUtils.isTypedArray( array ) ) {
  18056. return new array.constructor( array.subarray( from, to ) );
  18057. }
  18058. return array.slice( from, to );
  18059. },
  18060. // converts an array to a specific type
  18061. convertArray: function( array, type, forceClone ) {
  18062. if ( ! array || // let 'undefined' and 'null' pass
  18063. ! forceClone && array.constructor === type ) return array;
  18064. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  18065. return new type( array ); // create typed array
  18066. }
  18067. return Array.prototype.slice.call( array ); // create Array
  18068. },
  18069. isTypedArray: function( object ) {
  18070. return ArrayBuffer.isView( object ) &&
  18071. ! ( object instanceof DataView );
  18072. },
  18073. // returns an array by which times and values can be sorted
  18074. getKeyframeOrder: function( times ) {
  18075. function compareTime( i, j ) {
  18076. return times[ i ] - times[ j ];
  18077. }
  18078. var n = times.length;
  18079. var result = new Array( n );
  18080. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  18081. result.sort( compareTime );
  18082. return result;
  18083. },
  18084. // uses the array previously returned by 'getKeyframeOrder' to sort data
  18085. sortedArray: function( values, stride, order ) {
  18086. var nValues = values.length;
  18087. var result = new values.constructor( nValues );
  18088. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  18089. var srcOffset = order[ i ] * stride;
  18090. for ( var j = 0; j !== stride; ++ j ) {
  18091. result[ dstOffset ++ ] = values[ srcOffset + j ];
  18092. }
  18093. }
  18094. return result;
  18095. },
  18096. // function for parsing AOS keyframe formats
  18097. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  18098. var i = 1, key = jsonKeys[ 0 ];
  18099. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  18100. key = jsonKeys[ i ++ ];
  18101. }
  18102. if ( key === undefined ) return; // no data
  18103. var value = key[ valuePropertyName ];
  18104. if ( value === undefined ) return; // no data
  18105. if ( Array.isArray( value ) ) {
  18106. do {
  18107. value = key[ valuePropertyName ];
  18108. if ( value !== undefined ) {
  18109. times.push( key.time );
  18110. values.push.apply( values, value ); // push all elements
  18111. }
  18112. key = jsonKeys[ i ++ ];
  18113. } while ( key !== undefined );
  18114. } else if ( value.toArray !== undefined ) {
  18115. // ...assume THREE.Math-ish
  18116. do {
  18117. value = key[ valuePropertyName ];
  18118. if ( value !== undefined ) {
  18119. times.push( key.time );
  18120. value.toArray( values, values.length );
  18121. }
  18122. key = jsonKeys[ i ++ ];
  18123. } while ( key !== undefined );
  18124. } else {
  18125. // otherwise push as-is
  18126. do {
  18127. value = key[ valuePropertyName ];
  18128. if ( value !== undefined ) {
  18129. times.push( key.time );
  18130. values.push( value );
  18131. }
  18132. key = jsonKeys[ i ++ ];
  18133. } while ( key !== undefined );
  18134. }
  18135. }
  18136. };
  18137. /**
  18138. * Abstract base class of interpolants over parametric samples.
  18139. *
  18140. * The parameter domain is one dimensional, typically the time or a path
  18141. * along a curve defined by the data.
  18142. *
  18143. * The sample values can have any dimensionality and derived classes may
  18144. * apply special interpretations to the data.
  18145. *
  18146. * This class provides the interval seek in a Template Method, deferring
  18147. * the actual interpolation to derived classes.
  18148. *
  18149. * Time complexity is O(1) for linear access crossing at most two points
  18150. * and O(log N) for random access, where N is the number of positions.
  18151. *
  18152. * References:
  18153. *
  18154. * http://www.oodesign.com/template-method-pattern.html
  18155. *
  18156. * @author tschw
  18157. */
  18158. function Interpolant(
  18159. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18160. this.parameterPositions = parameterPositions;
  18161. this._cachedIndex = 0;
  18162. this.resultBuffer = resultBuffer !== undefined ?
  18163. resultBuffer : new sampleValues.constructor( sampleSize );
  18164. this.sampleValues = sampleValues;
  18165. this.valueSize = sampleSize;
  18166. }
  18167. Interpolant.prototype = {
  18168. constructor: Interpolant,
  18169. evaluate: function( t ) {
  18170. var pp = this.parameterPositions,
  18171. i1 = this._cachedIndex,
  18172. t1 = pp[ i1 ],
  18173. t0 = pp[ i1 - 1 ];
  18174. validate_interval: {
  18175. seek: {
  18176. var right;
  18177. linear_scan: {
  18178. //- See http://jsperf.com/comparison-to-undefined/3
  18179. //- slower code:
  18180. //-
  18181. //- if ( t >= t1 || t1 === undefined ) {
  18182. forward_scan: if ( ! ( t < t1 ) ) {
  18183. for ( var giveUpAt = i1 + 2; ;) {
  18184. if ( t1 === undefined ) {
  18185. if ( t < t0 ) break forward_scan;
  18186. // after end
  18187. i1 = pp.length;
  18188. this._cachedIndex = i1;
  18189. return this.afterEnd_( i1 - 1, t, t0 );
  18190. }
  18191. if ( i1 === giveUpAt ) break; // this loop
  18192. t0 = t1;
  18193. t1 = pp[ ++ i1 ];
  18194. if ( t < t1 ) {
  18195. // we have arrived at the sought interval
  18196. break seek;
  18197. }
  18198. }
  18199. // prepare binary search on the right side of the index
  18200. right = pp.length;
  18201. break linear_scan;
  18202. }
  18203. //- slower code:
  18204. //- if ( t < t0 || t0 === undefined ) {
  18205. if ( ! ( t >= t0 ) ) {
  18206. // looping?
  18207. var t1global = pp[ 1 ];
  18208. if ( t < t1global ) {
  18209. i1 = 2; // + 1, using the scan for the details
  18210. t0 = t1global;
  18211. }
  18212. // linear reverse scan
  18213. for ( var giveUpAt = i1 - 2; ;) {
  18214. if ( t0 === undefined ) {
  18215. // before start
  18216. this._cachedIndex = 0;
  18217. return this.beforeStart_( 0, t, t1 );
  18218. }
  18219. if ( i1 === giveUpAt ) break; // this loop
  18220. t1 = t0;
  18221. t0 = pp[ -- i1 - 1 ];
  18222. if ( t >= t0 ) {
  18223. // we have arrived at the sought interval
  18224. break seek;
  18225. }
  18226. }
  18227. // prepare binary search on the left side of the index
  18228. right = i1;
  18229. i1 = 0;
  18230. break linear_scan;
  18231. }
  18232. // the interval is valid
  18233. break validate_interval;
  18234. } // linear scan
  18235. // binary search
  18236. while ( i1 < right ) {
  18237. var mid = ( i1 + right ) >>> 1;
  18238. if ( t < pp[ mid ] ) {
  18239. right = mid;
  18240. } else {
  18241. i1 = mid + 1;
  18242. }
  18243. }
  18244. t1 = pp[ i1 ];
  18245. t0 = pp[ i1 - 1 ];
  18246. // check boundary cases, again
  18247. if ( t0 === undefined ) {
  18248. this._cachedIndex = 0;
  18249. return this.beforeStart_( 0, t, t1 );
  18250. }
  18251. if ( t1 === undefined ) {
  18252. i1 = pp.length;
  18253. this._cachedIndex = i1;
  18254. return this.afterEnd_( i1 - 1, t0, t );
  18255. }
  18256. } // seek
  18257. this._cachedIndex = i1;
  18258. this.intervalChanged_( i1, t0, t1 );
  18259. } // validate_interval
  18260. return this.interpolate_( i1, t0, t, t1 );
  18261. },
  18262. settings: null, // optional, subclass-specific settings structure
  18263. // Note: The indirection allows central control of many interpolants.
  18264. // --- Protected interface
  18265. DefaultSettings_: {},
  18266. getSettings_: function() {
  18267. return this.settings || this.DefaultSettings_;
  18268. },
  18269. copySampleValue_: function( index ) {
  18270. // copies a sample value to the result buffer
  18271. var result = this.resultBuffer,
  18272. values = this.sampleValues,
  18273. stride = this.valueSize,
  18274. offset = index * stride;
  18275. for ( var i = 0; i !== stride; ++ i ) {
  18276. result[ i ] = values[ offset + i ];
  18277. }
  18278. return result;
  18279. },
  18280. // Template methods for derived classes:
  18281. interpolate_: function( i1, t0, t, t1 ) {
  18282. throw new Error( "call to abstract method" );
  18283. // implementations shall return this.resultBuffer
  18284. },
  18285. intervalChanged_: function( i1, t0, t1 ) {
  18286. // empty
  18287. }
  18288. };
  18289. Object.assign( Interpolant.prototype, {
  18290. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  18291. Interpolant.prototype.copySampleValue_,
  18292. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  18293. Interpolant.prototype.copySampleValue_
  18294. } );
  18295. /**
  18296. * Fast and simple cubic spline interpolant.
  18297. *
  18298. * It was derived from a Hermitian construction setting the first derivative
  18299. * at each sample position to the linear slope between neighboring positions
  18300. * over their parameter interval.
  18301. *
  18302. * @author tschw
  18303. */
  18304. function CubicInterpolant(
  18305. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18306. Interpolant.call(
  18307. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18308. this._weightPrev = -0;
  18309. this._offsetPrev = -0;
  18310. this._weightNext = -0;
  18311. this._offsetNext = -0;
  18312. }
  18313. CubicInterpolant.prototype =
  18314. Object.assign( Object.create( Interpolant.prototype ), {
  18315. constructor: CubicInterpolant,
  18316. DefaultSettings_: {
  18317. endingStart: ZeroCurvatureEnding,
  18318. endingEnd: ZeroCurvatureEnding
  18319. },
  18320. intervalChanged_: function( i1, t0, t1 ) {
  18321. var pp = this.parameterPositions,
  18322. iPrev = i1 - 2,
  18323. iNext = i1 + 1,
  18324. tPrev = pp[ iPrev ],
  18325. tNext = pp[ iNext ];
  18326. if ( tPrev === undefined ) {
  18327. switch ( this.getSettings_().endingStart ) {
  18328. case ZeroSlopeEnding:
  18329. // f'(t0) = 0
  18330. iPrev = i1;
  18331. tPrev = 2 * t0 - t1;
  18332. break;
  18333. case WrapAroundEnding:
  18334. // use the other end of the curve
  18335. iPrev = pp.length - 2;
  18336. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  18337. break;
  18338. default: // ZeroCurvatureEnding
  18339. // f''(t0) = 0 a.k.a. Natural Spline
  18340. iPrev = i1;
  18341. tPrev = t1;
  18342. }
  18343. }
  18344. if ( tNext === undefined ) {
  18345. switch ( this.getSettings_().endingEnd ) {
  18346. case ZeroSlopeEnding:
  18347. // f'(tN) = 0
  18348. iNext = i1;
  18349. tNext = 2 * t1 - t0;
  18350. break;
  18351. case WrapAroundEnding:
  18352. // use the other end of the curve
  18353. iNext = 1;
  18354. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  18355. break;
  18356. default: // ZeroCurvatureEnding
  18357. // f''(tN) = 0, a.k.a. Natural Spline
  18358. iNext = i1 - 1;
  18359. tNext = t0;
  18360. }
  18361. }
  18362. var halfDt = ( t1 - t0 ) * 0.5,
  18363. stride = this.valueSize;
  18364. this._weightPrev = halfDt / ( t0 - tPrev );
  18365. this._weightNext = halfDt / ( tNext - t1 );
  18366. this._offsetPrev = iPrev * stride;
  18367. this._offsetNext = iNext * stride;
  18368. },
  18369. interpolate_: function( i1, t0, t, t1 ) {
  18370. var result = this.resultBuffer,
  18371. values = this.sampleValues,
  18372. stride = this.valueSize,
  18373. o1 = i1 * stride, o0 = o1 - stride,
  18374. oP = this._offsetPrev, oN = this._offsetNext,
  18375. wP = this._weightPrev, wN = this._weightNext,
  18376. p = ( t - t0 ) / ( t1 - t0 ),
  18377. pp = p * p,
  18378. ppp = pp * p;
  18379. // evaluate polynomials
  18380. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  18381. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  18382. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  18383. var sN = wN * ppp - wN * pp;
  18384. // combine data linearly
  18385. for ( var i = 0; i !== stride; ++ i ) {
  18386. result[ i ] =
  18387. sP * values[ oP + i ] +
  18388. s0 * values[ o0 + i ] +
  18389. s1 * values[ o1 + i ] +
  18390. sN * values[ oN + i ];
  18391. }
  18392. return result;
  18393. }
  18394. } );
  18395. /**
  18396. * @author tschw
  18397. */
  18398. function LinearInterpolant(
  18399. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18400. Interpolant.call(
  18401. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18402. }
  18403. LinearInterpolant.prototype =
  18404. Object.assign( Object.create( Interpolant.prototype ), {
  18405. constructor: LinearInterpolant,
  18406. interpolate_: function( i1, t0, t, t1 ) {
  18407. var result = this.resultBuffer,
  18408. values = this.sampleValues,
  18409. stride = this.valueSize,
  18410. offset1 = i1 * stride,
  18411. offset0 = offset1 - stride,
  18412. weight1 = ( t - t0 ) / ( t1 - t0 ),
  18413. weight0 = 1 - weight1;
  18414. for ( var i = 0; i !== stride; ++ i ) {
  18415. result[ i ] =
  18416. values[ offset0 + i ] * weight0 +
  18417. values[ offset1 + i ] * weight1;
  18418. }
  18419. return result;
  18420. }
  18421. } );
  18422. /**
  18423. *
  18424. * Interpolant that evaluates to the sample value at the position preceeding
  18425. * the parameter.
  18426. *
  18427. * @author tschw
  18428. */
  18429. function DiscreteInterpolant(
  18430. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18431. Interpolant.call(
  18432. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18433. }
  18434. DiscreteInterpolant.prototype =
  18435. Object.assign( Object.create( Interpolant.prototype ), {
  18436. constructor: DiscreteInterpolant,
  18437. interpolate_: function( i1, t0, t, t1 ) {
  18438. return this.copySampleValue_( i1 - 1 );
  18439. }
  18440. } );
  18441. var KeyframeTrackPrototype;
  18442. KeyframeTrackPrototype = {
  18443. TimeBufferType: Float32Array,
  18444. ValueBufferType: Float32Array,
  18445. DefaultInterpolation: InterpolateLinear,
  18446. InterpolantFactoryMethodDiscrete: function( result ) {
  18447. return new DiscreteInterpolant(
  18448. this.times, this.values, this.getValueSize(), result );
  18449. },
  18450. InterpolantFactoryMethodLinear: function( result ) {
  18451. return new LinearInterpolant(
  18452. this.times, this.values, this.getValueSize(), result );
  18453. },
  18454. InterpolantFactoryMethodSmooth: function( result ) {
  18455. return new CubicInterpolant(
  18456. this.times, this.values, this.getValueSize(), result );
  18457. },
  18458. setInterpolation: function( interpolation ) {
  18459. var factoryMethod;
  18460. switch ( interpolation ) {
  18461. case InterpolateDiscrete:
  18462. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  18463. break;
  18464. case InterpolateLinear:
  18465. factoryMethod = this.InterpolantFactoryMethodLinear;
  18466. break;
  18467. case InterpolateSmooth:
  18468. factoryMethod = this.InterpolantFactoryMethodSmooth;
  18469. break;
  18470. }
  18471. if ( factoryMethod === undefined ) {
  18472. var message = "unsupported interpolation for " +
  18473. this.ValueTypeName + " keyframe track named " + this.name;
  18474. if ( this.createInterpolant === undefined ) {
  18475. // fall back to default, unless the default itself is messed up
  18476. if ( interpolation !== this.DefaultInterpolation ) {
  18477. this.setInterpolation( this.DefaultInterpolation );
  18478. } else {
  18479. throw new Error( message ); // fatal, in this case
  18480. }
  18481. }
  18482. console.warn( message );
  18483. return;
  18484. }
  18485. this.createInterpolant = factoryMethod;
  18486. },
  18487. getInterpolation: function() {
  18488. switch ( this.createInterpolant ) {
  18489. case this.InterpolantFactoryMethodDiscrete:
  18490. return InterpolateDiscrete;
  18491. case this.InterpolantFactoryMethodLinear:
  18492. return InterpolateLinear;
  18493. case this.InterpolantFactoryMethodSmooth:
  18494. return InterpolateSmooth;
  18495. }
  18496. },
  18497. getValueSize: function() {
  18498. return this.values.length / this.times.length;
  18499. },
  18500. // move all keyframes either forwards or backwards in time
  18501. shift: function( timeOffset ) {
  18502. if( timeOffset !== 0.0 ) {
  18503. var times = this.times;
  18504. for( var i = 0, n = times.length; i !== n; ++ i ) {
  18505. times[ i ] += timeOffset;
  18506. }
  18507. }
  18508. return this;
  18509. },
  18510. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  18511. scale: function( timeScale ) {
  18512. if( timeScale !== 1.0 ) {
  18513. var times = this.times;
  18514. for( var i = 0, n = times.length; i !== n; ++ i ) {
  18515. times[ i ] *= timeScale;
  18516. }
  18517. }
  18518. return this;
  18519. },
  18520. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  18521. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  18522. trim: function( startTime, endTime ) {
  18523. var times = this.times,
  18524. nKeys = times.length,
  18525. from = 0,
  18526. to = nKeys - 1;
  18527. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  18528. while ( to !== -1 && times[ to ] > endTime ) -- to;
  18529. ++ to; // inclusive -> exclusive bound
  18530. if( from !== 0 || to !== nKeys ) {
  18531. // empty tracks are forbidden, so keep at least one keyframe
  18532. if ( from >= to ) to = Math.max( to , 1 ), from = to - 1;
  18533. var stride = this.getValueSize();
  18534. this.times = AnimationUtils.arraySlice( times, from, to );
  18535. this.values = AnimationUtils.
  18536. arraySlice( this.values, from * stride, to * stride );
  18537. }
  18538. return this;
  18539. },
  18540. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  18541. validate: function() {
  18542. var valid = true;
  18543. var valueSize = this.getValueSize();
  18544. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  18545. console.error( "invalid value size in track", this );
  18546. valid = false;
  18547. }
  18548. var times = this.times,
  18549. values = this.values,
  18550. nKeys = times.length;
  18551. if( nKeys === 0 ) {
  18552. console.error( "track is empty", this );
  18553. valid = false;
  18554. }
  18555. var prevTime = null;
  18556. for( var i = 0; i !== nKeys; i ++ ) {
  18557. var currTime = times[ i ];
  18558. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  18559. console.error( "time is not a valid number", this, i, currTime );
  18560. valid = false;
  18561. break;
  18562. }
  18563. if( prevTime !== null && prevTime > currTime ) {
  18564. console.error( "out of order keys", this, i, currTime, prevTime );
  18565. valid = false;
  18566. break;
  18567. }
  18568. prevTime = currTime;
  18569. }
  18570. if ( values !== undefined ) {
  18571. if ( AnimationUtils.isTypedArray( values ) ) {
  18572. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  18573. var value = values[ i ];
  18574. if ( isNaN( value ) ) {
  18575. console.error( "value is not a valid number", this, i, value );
  18576. valid = false;
  18577. break;
  18578. }
  18579. }
  18580. }
  18581. }
  18582. return valid;
  18583. },
  18584. // removes equivalent sequential keys as common in morph target sequences
  18585. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  18586. optimize: function() {
  18587. var times = this.times,
  18588. values = this.values,
  18589. stride = this.getValueSize(),
  18590. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  18591. writeIndex = 1,
  18592. lastIndex = times.length - 1;
  18593. for( var i = 1; i < lastIndex; ++ i ) {
  18594. var keep = false;
  18595. var time = times[ i ];
  18596. var timeNext = times[ i + 1 ];
  18597. // remove adjacent keyframes scheduled at the same time
  18598. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  18599. if ( ! smoothInterpolation ) {
  18600. // remove unnecessary keyframes same as their neighbors
  18601. var offset = i * stride,
  18602. offsetP = offset - stride,
  18603. offsetN = offset + stride;
  18604. for ( var j = 0; j !== stride; ++ j ) {
  18605. var value = values[ offset + j ];
  18606. if ( value !== values[ offsetP + j ] ||
  18607. value !== values[ offsetN + j ] ) {
  18608. keep = true;
  18609. break;
  18610. }
  18611. }
  18612. } else keep = true;
  18613. }
  18614. // in-place compaction
  18615. if ( keep ) {
  18616. if ( i !== writeIndex ) {
  18617. times[ writeIndex ] = times[ i ];
  18618. var readOffset = i * stride,
  18619. writeOffset = writeIndex * stride;
  18620. for ( var j = 0; j !== stride; ++ j )
  18621. values[ writeOffset + j ] = values[ readOffset + j ];
  18622. }
  18623. ++ writeIndex;
  18624. }
  18625. }
  18626. // flush last keyframe (compaction looks ahead)
  18627. if ( lastIndex > 0 ) {
  18628. times[ writeIndex ] = times[ lastIndex ];
  18629. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j )
  18630. values[ writeOffset + j ] = values[ readOffset + j ];
  18631. ++ writeIndex;
  18632. }
  18633. if ( writeIndex !== times.length ) {
  18634. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  18635. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  18636. }
  18637. return this;
  18638. }
  18639. };
  18640. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  18641. if( name === undefined ) throw new Error( "track name is undefined" );
  18642. if( times === undefined || times.length === 0 ) {
  18643. throw new Error( "no keyframes in track named " + name );
  18644. }
  18645. this.name = name;
  18646. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  18647. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  18648. this.setInterpolation( interpolation || this.DefaultInterpolation );
  18649. this.validate();
  18650. this.optimize();
  18651. }
  18652. /**
  18653. *
  18654. * A Track of vectored keyframe values.
  18655. *
  18656. *
  18657. * @author Ben Houston / http://clara.io/
  18658. * @author David Sarno / http://lighthaus.us/
  18659. * @author tschw
  18660. */
  18661. function VectorKeyframeTrack( name, times, values, interpolation ) {
  18662. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18663. }
  18664. VectorKeyframeTrack.prototype =
  18665. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18666. constructor: VectorKeyframeTrack,
  18667. ValueTypeName: 'vector'
  18668. // ValueBufferType is inherited
  18669. // DefaultInterpolation is inherited
  18670. } );
  18671. /**
  18672. * Spherical linear unit quaternion interpolant.
  18673. *
  18674. * @author tschw
  18675. */
  18676. function QuaternionLinearInterpolant(
  18677. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18678. Interpolant.call(
  18679. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18680. }
  18681. QuaternionLinearInterpolant.prototype =
  18682. Object.assign( Object.create( Interpolant.prototype ), {
  18683. constructor: QuaternionLinearInterpolant,
  18684. interpolate_: function( i1, t0, t, t1 ) {
  18685. var result = this.resultBuffer,
  18686. values = this.sampleValues,
  18687. stride = this.valueSize,
  18688. offset = i1 * stride,
  18689. alpha = ( t - t0 ) / ( t1 - t0 );
  18690. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  18691. Quaternion.slerpFlat( result, 0,
  18692. values, offset - stride, values, offset, alpha );
  18693. }
  18694. return result;
  18695. }
  18696. } );
  18697. /**
  18698. *
  18699. * A Track of quaternion keyframe values.
  18700. *
  18701. * @author Ben Houston / http://clara.io/
  18702. * @author David Sarno / http://lighthaus.us/
  18703. * @author tschw
  18704. */
  18705. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  18706. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18707. }
  18708. QuaternionKeyframeTrack.prototype =
  18709. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18710. constructor: QuaternionKeyframeTrack,
  18711. ValueTypeName: 'quaternion',
  18712. // ValueBufferType is inherited
  18713. DefaultInterpolation: InterpolateLinear,
  18714. InterpolantFactoryMethodLinear: function( result ) {
  18715. return new QuaternionLinearInterpolant(
  18716. this.times, this.values, this.getValueSize(), result );
  18717. },
  18718. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  18719. } );
  18720. /**
  18721. *
  18722. * A Track of numeric keyframe values.
  18723. *
  18724. * @author Ben Houston / http://clara.io/
  18725. * @author David Sarno / http://lighthaus.us/
  18726. * @author tschw
  18727. */
  18728. function NumberKeyframeTrack( name, times, values, interpolation ) {
  18729. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18730. }
  18731. NumberKeyframeTrack.prototype =
  18732. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18733. constructor: NumberKeyframeTrack,
  18734. ValueTypeName: 'number',
  18735. // ValueBufferType is inherited
  18736. // DefaultInterpolation is inherited
  18737. } );
  18738. /**
  18739. *
  18740. * A Track that interpolates Strings
  18741. *
  18742. *
  18743. * @author Ben Houston / http://clara.io/
  18744. * @author David Sarno / http://lighthaus.us/
  18745. * @author tschw
  18746. */
  18747. function StringKeyframeTrack( name, times, values, interpolation ) {
  18748. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18749. }
  18750. StringKeyframeTrack.prototype =
  18751. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18752. constructor: StringKeyframeTrack,
  18753. ValueTypeName: 'string',
  18754. ValueBufferType: Array,
  18755. DefaultInterpolation: InterpolateDiscrete,
  18756. InterpolantFactoryMethodLinear: undefined,
  18757. InterpolantFactoryMethodSmooth: undefined
  18758. } );
  18759. /**
  18760. *
  18761. * A Track of Boolean keyframe values.
  18762. *
  18763. *
  18764. * @author Ben Houston / http://clara.io/
  18765. * @author David Sarno / http://lighthaus.us/
  18766. * @author tschw
  18767. */
  18768. function BooleanKeyframeTrack( name, times, values ) {
  18769. KeyframeTrackConstructor.call( this, name, times, values );
  18770. }
  18771. BooleanKeyframeTrack.prototype =
  18772. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18773. constructor: BooleanKeyframeTrack,
  18774. ValueTypeName: 'bool',
  18775. ValueBufferType: Array,
  18776. DefaultInterpolation: InterpolateDiscrete,
  18777. InterpolantFactoryMethodLinear: undefined,
  18778. InterpolantFactoryMethodSmooth: undefined
  18779. // Note: Actually this track could have a optimized / compressed
  18780. // representation of a single value and a custom interpolant that
  18781. // computes "firstValue ^ isOdd( index )".
  18782. } );
  18783. /**
  18784. *
  18785. * A Track of keyframe values that represent color.
  18786. *
  18787. *
  18788. * @author Ben Houston / http://clara.io/
  18789. * @author David Sarno / http://lighthaus.us/
  18790. * @author tschw
  18791. */
  18792. function ColorKeyframeTrack( name, times, values, interpolation ) {
  18793. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18794. }
  18795. ColorKeyframeTrack.prototype =
  18796. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18797. constructor: ColorKeyframeTrack,
  18798. ValueTypeName: 'color'
  18799. // ValueBufferType is inherited
  18800. // DefaultInterpolation is inherited
  18801. // Note: Very basic implementation and nothing special yet.
  18802. // However, this is the place for color space parameterization.
  18803. } );
  18804. /**
  18805. *
  18806. * A timed sequence of keyframes for a specific property.
  18807. *
  18808. *
  18809. * @author Ben Houston / http://clara.io/
  18810. * @author David Sarno / http://lighthaus.us/
  18811. * @author tschw
  18812. */
  18813. function KeyframeTrack( name, times, values, interpolation ) {
  18814. KeyframeTrackConstructor.apply( this, arguments );
  18815. }
  18816. KeyframeTrack.prototype = KeyframeTrackPrototype;
  18817. KeyframeTrackPrototype.constructor = KeyframeTrack;
  18818. // Static methods:
  18819. Object.assign( KeyframeTrack, {
  18820. // Serialization (in static context, because of constructor invocation
  18821. // and automatic invocation of .toJSON):
  18822. parse: function( json ) {
  18823. if( json.type === undefined ) {
  18824. throw new Error( "track type undefined, can not parse" );
  18825. }
  18826. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  18827. if ( json.times === undefined ) {
  18828. var times = [], values = [];
  18829. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  18830. json.times = times;
  18831. json.values = values;
  18832. }
  18833. // derived classes can define a static parse method
  18834. if ( trackType.parse !== undefined ) {
  18835. return trackType.parse( json );
  18836. } else {
  18837. // by default, we asssume a constructor compatible with the base
  18838. return new trackType(
  18839. json.name, json.times, json.values, json.interpolation );
  18840. }
  18841. },
  18842. toJSON: function( track ) {
  18843. var trackType = track.constructor;
  18844. var json;
  18845. // derived classes can define a static toJSON method
  18846. if ( trackType.toJSON !== undefined ) {
  18847. json = trackType.toJSON( track );
  18848. } else {
  18849. // by default, we assume the data can be serialized as-is
  18850. json = {
  18851. 'name': track.name,
  18852. 'times': AnimationUtils.convertArray( track.times, Array ),
  18853. 'values': AnimationUtils.convertArray( track.values, Array )
  18854. };
  18855. var interpolation = track.getInterpolation();
  18856. if ( interpolation !== track.DefaultInterpolation ) {
  18857. json.interpolation = interpolation;
  18858. }
  18859. }
  18860. json.type = track.ValueTypeName; // mandatory
  18861. return json;
  18862. },
  18863. _getTrackTypeForValueTypeName: function( typeName ) {
  18864. switch( typeName.toLowerCase() ) {
  18865. case "scalar":
  18866. case "double":
  18867. case "float":
  18868. case "number":
  18869. case "integer":
  18870. return NumberKeyframeTrack;
  18871. case "vector":
  18872. case "vector2":
  18873. case "vector3":
  18874. case "vector4":
  18875. return VectorKeyframeTrack;
  18876. case "color":
  18877. return ColorKeyframeTrack;
  18878. case "quaternion":
  18879. return QuaternionKeyframeTrack;
  18880. case "bool":
  18881. case "boolean":
  18882. return BooleanKeyframeTrack;
  18883. case "string":
  18884. return StringKeyframeTrack;
  18885. }
  18886. throw new Error( "Unsupported typeName: " + typeName );
  18887. }
  18888. } );
  18889. /**
  18890. *
  18891. * Reusable set of Tracks that represent an animation.
  18892. *
  18893. * @author Ben Houston / http://clara.io/
  18894. * @author David Sarno / http://lighthaus.us/
  18895. */
  18896. function AnimationClip( name, duration, tracks ) {
  18897. this.name = name;
  18898. this.tracks = tracks;
  18899. this.duration = ( duration !== undefined ) ? duration : -1;
  18900. this.uuid = _Math.generateUUID();
  18901. // this means it should figure out its duration by scanning the tracks
  18902. if ( this.duration < 0 ) {
  18903. this.resetDuration();
  18904. }
  18905. this.optimize();
  18906. }
  18907. AnimationClip.prototype = {
  18908. constructor: AnimationClip,
  18909. resetDuration: function() {
  18910. var tracks = this.tracks,
  18911. duration = 0;
  18912. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  18913. var track = this.tracks[ i ];
  18914. duration = Math.max(
  18915. duration, track.times[ track.times.length - 1 ] );
  18916. }
  18917. this.duration = duration;
  18918. },
  18919. trim: function() {
  18920. for ( var i = 0; i < this.tracks.length; i ++ ) {
  18921. this.tracks[ i ].trim( 0, this.duration );
  18922. }
  18923. return this;
  18924. },
  18925. optimize: function() {
  18926. for ( var i = 0; i < this.tracks.length; i ++ ) {
  18927. this.tracks[ i ].optimize();
  18928. }
  18929. return this;
  18930. }
  18931. };
  18932. // Static methods:
  18933. Object.assign( AnimationClip, {
  18934. parse: function( json ) {
  18935. var tracks = [],
  18936. jsonTracks = json.tracks,
  18937. frameTime = 1.0 / ( json.fps || 1.0 );
  18938. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  18939. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  18940. }
  18941. return new AnimationClip( json.name, json.duration, tracks );
  18942. },
  18943. toJSON: function( clip ) {
  18944. var tracks = [],
  18945. clipTracks = clip.tracks;
  18946. var json = {
  18947. 'name': clip.name,
  18948. 'duration': clip.duration,
  18949. 'tracks': tracks
  18950. };
  18951. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  18952. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  18953. }
  18954. return json;
  18955. },
  18956. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) {
  18957. var numMorphTargets = morphTargetSequence.length;
  18958. var tracks = [];
  18959. for ( var i = 0; i < numMorphTargets; i ++ ) {
  18960. var times = [];
  18961. var values = [];
  18962. times.push(
  18963. ( i + numMorphTargets - 1 ) % numMorphTargets,
  18964. i,
  18965. ( i + 1 ) % numMorphTargets );
  18966. values.push( 0, 1, 0 );
  18967. var order = AnimationUtils.getKeyframeOrder( times );
  18968. times = AnimationUtils.sortedArray( times, 1, order );
  18969. values = AnimationUtils.sortedArray( values, 1, order );
  18970. // if there is a key at the first frame, duplicate it as the
  18971. // last frame as well for perfect loop.
  18972. if ( ! noLoop && times[ 0 ] === 0 ) {
  18973. times.push( numMorphTargets );
  18974. values.push( values[ 0 ] );
  18975. }
  18976. tracks.push(
  18977. new NumberKeyframeTrack(
  18978. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  18979. times, values
  18980. ).scale( 1.0 / fps ) );
  18981. }
  18982. return new AnimationClip( name, -1, tracks );
  18983. },
  18984. findByName: function( objectOrClipArray, name ) {
  18985. var clipArray = objectOrClipArray;
  18986. if ( ! Array.isArray( objectOrClipArray ) ) {
  18987. var o = objectOrClipArray;
  18988. clipArray = o.geometry && o.geometry.animations || o.animations;
  18989. }
  18990. for ( var i = 0; i < clipArray.length; i ++ ) {
  18991. if ( clipArray[ i ].name === name ) {
  18992. return clipArray[ i ];
  18993. }
  18994. }
  18995. return null;
  18996. },
  18997. CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) {
  18998. var animationToMorphTargets = {};
  18999. // tested with https://regex101.com/ on trick sequences
  19000. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  19001. var pattern = /^([\w-]*?)([\d]+)$/;
  19002. // sort morph target names into animation groups based
  19003. // patterns like Walk_001, Walk_002, Run_001, Run_002
  19004. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  19005. var morphTarget = morphTargets[ i ];
  19006. var parts = morphTarget.name.match( pattern );
  19007. if ( parts && parts.length > 1 ) {
  19008. var name = parts[ 1 ];
  19009. var animationMorphTargets = animationToMorphTargets[ name ];
  19010. if ( ! animationMorphTargets ) {
  19011. animationToMorphTargets[ name ] = animationMorphTargets = [];
  19012. }
  19013. animationMorphTargets.push( morphTarget );
  19014. }
  19015. }
  19016. var clips = [];
  19017. for ( var name in animationToMorphTargets ) {
  19018. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  19019. }
  19020. return clips;
  19021. },
  19022. // parse the animation.hierarchy format
  19023. parseAnimation: function( animation, bones ) {
  19024. if ( ! animation ) {
  19025. console.error( " no animation in JSONLoader data" );
  19026. return null;
  19027. }
  19028. var addNonemptyTrack = function(
  19029. trackType, trackName, animationKeys, propertyName, destTracks ) {
  19030. // only return track if there are actually keys.
  19031. if ( animationKeys.length !== 0 ) {
  19032. var times = [];
  19033. var values = [];
  19034. AnimationUtils.flattenJSON(
  19035. animationKeys, times, values, propertyName );
  19036. // empty keys are filtered out, so check again
  19037. if ( times.length !== 0 ) {
  19038. destTracks.push( new trackType( trackName, times, values ) );
  19039. }
  19040. }
  19041. };
  19042. var tracks = [];
  19043. var clipName = animation.name || 'default';
  19044. // automatic length determination in AnimationClip.
  19045. var duration = animation.length || -1;
  19046. var fps = animation.fps || 30;
  19047. var hierarchyTracks = animation.hierarchy || [];
  19048. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  19049. var animationKeys = hierarchyTracks[ h ].keys;
  19050. // skip empty tracks
  19051. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  19052. // process morph targets in a way exactly compatible
  19053. // with AnimationHandler.init( animation )
  19054. if ( animationKeys[0].morphTargets ) {
  19055. // figure out all morph targets used in this track
  19056. var morphTargetNames = {};
  19057. for ( var k = 0; k < animationKeys.length; k ++ ) {
  19058. if ( animationKeys[k].morphTargets ) {
  19059. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  19060. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  19061. }
  19062. }
  19063. }
  19064. // create a track for each morph target with all zero
  19065. // morphTargetInfluences except for the keys in which
  19066. // the morphTarget is named.
  19067. for ( var morphTargetName in morphTargetNames ) {
  19068. var times = [];
  19069. var values = [];
  19070. for ( var m = 0;
  19071. m !== animationKeys[k].morphTargets.length; ++ m ) {
  19072. var animationKey = animationKeys[k];
  19073. times.push( animationKey.time );
  19074. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  19075. }
  19076. tracks.push( new NumberKeyframeTrack(
  19077. '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  19078. }
  19079. duration = morphTargetNames.length * ( fps || 1.0 );
  19080. } else {
  19081. // ...assume skeletal animation
  19082. var boneName = '.bones[' + bones[ h ].name + ']';
  19083. addNonemptyTrack(
  19084. VectorKeyframeTrack, boneName + '.position',
  19085. animationKeys, 'pos', tracks );
  19086. addNonemptyTrack(
  19087. QuaternionKeyframeTrack, boneName + '.quaternion',
  19088. animationKeys, 'rot', tracks );
  19089. addNonemptyTrack(
  19090. VectorKeyframeTrack, boneName + '.scale',
  19091. animationKeys, 'scl', tracks );
  19092. }
  19093. }
  19094. if ( tracks.length === 0 ) {
  19095. return null;
  19096. }
  19097. var clip = new AnimationClip( clipName, duration, tracks );
  19098. return clip;
  19099. }
  19100. } );
  19101. /**
  19102. * @author mrdoob / http://mrdoob.com/
  19103. */
  19104. function MaterialLoader( manager ) {
  19105. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19106. this.textures = {};
  19107. }
  19108. Object.assign( MaterialLoader.prototype, {
  19109. load: function ( url, onLoad, onProgress, onError ) {
  19110. var scope = this;
  19111. var loader = new FileLoader( scope.manager );
  19112. loader.load( url, function ( text ) {
  19113. onLoad( scope.parse( JSON.parse( text ) ) );
  19114. }, onProgress, onError );
  19115. },
  19116. setTextures: function ( value ) {
  19117. this.textures = value;
  19118. },
  19119. parse: function ( json ) {
  19120. var textures = this.textures;
  19121. function getTexture( name ) {
  19122. if ( textures[ name ] === undefined ) {
  19123. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  19124. }
  19125. return textures[ name ];
  19126. }
  19127. var material = new Materials[ json.type ]();
  19128. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  19129. if ( json.name !== undefined ) material.name = json.name;
  19130. if ( json.color !== undefined ) material.color.setHex( json.color );
  19131. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  19132. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  19133. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  19134. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  19135. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  19136. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  19137. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  19138. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  19139. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  19140. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  19141. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  19142. if ( json.fog !== undefined ) material.fog = json.fog;
  19143. if ( json.shading !== undefined ) material.shading = json.shading;
  19144. if ( json.blending !== undefined ) material.blending = json.blending;
  19145. if ( json.side !== undefined ) material.side = json.side;
  19146. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  19147. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  19148. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  19149. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  19150. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  19151. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  19152. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  19153. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  19154. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  19155. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  19156. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  19157. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  19158. // for PointsMaterial
  19159. if ( json.size !== undefined ) material.size = json.size;
  19160. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  19161. // maps
  19162. if ( json.map !== undefined ) material.map = getTexture( json.map );
  19163. if ( json.alphaMap !== undefined ) {
  19164. material.alphaMap = getTexture( json.alphaMap );
  19165. material.transparent = true;
  19166. }
  19167. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  19168. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  19169. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  19170. if ( json.normalScale !== undefined ) {
  19171. var normalScale = json.normalScale;
  19172. if ( Array.isArray( normalScale ) === false ) {
  19173. // Blender exporter used to export a scalar. See #7459
  19174. normalScale = [ normalScale, normalScale ];
  19175. }
  19176. material.normalScale = new Vector2().fromArray( normalScale );
  19177. }
  19178. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  19179. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  19180. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  19181. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  19182. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  19183. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  19184. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  19185. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  19186. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  19187. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  19188. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  19189. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  19190. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  19191. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  19192. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  19193. // MultiMaterial
  19194. if ( json.materials !== undefined ) {
  19195. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  19196. material.materials.push( this.parse( json.materials[ i ] ) );
  19197. }
  19198. }
  19199. return material;
  19200. }
  19201. } );
  19202. /**
  19203. * @author mrdoob / http://mrdoob.com/
  19204. */
  19205. function BufferGeometryLoader( manager ) {
  19206. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19207. }
  19208. Object.assign( BufferGeometryLoader.prototype, {
  19209. load: function ( url, onLoad, onProgress, onError ) {
  19210. var scope = this;
  19211. var loader = new FileLoader( scope.manager );
  19212. loader.load( url, function ( text ) {
  19213. onLoad( scope.parse( JSON.parse( text ) ) );
  19214. }, onProgress, onError );
  19215. },
  19216. parse: function ( json ) {
  19217. var geometry = new BufferGeometry();
  19218. var index = json.data.index;
  19219. var TYPED_ARRAYS = {
  19220. 'Int8Array': Int8Array,
  19221. 'Uint8Array': Uint8Array,
  19222. 'Uint8ClampedArray': Uint8ClampedArray,
  19223. 'Int16Array': Int16Array,
  19224. 'Uint16Array': Uint16Array,
  19225. 'Int32Array': Int32Array,
  19226. 'Uint32Array': Uint32Array,
  19227. 'Float32Array': Float32Array,
  19228. 'Float64Array': Float64Array
  19229. };
  19230. if ( index !== undefined ) {
  19231. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  19232. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  19233. }
  19234. var attributes = json.data.attributes;
  19235. for ( var key in attributes ) {
  19236. var attribute = attributes[ key ];
  19237. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  19238. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  19239. }
  19240. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  19241. if ( groups !== undefined ) {
  19242. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  19243. var group = groups[ i ];
  19244. geometry.addGroup( group.start, group.count, group.materialIndex );
  19245. }
  19246. }
  19247. var boundingSphere = json.data.boundingSphere;
  19248. if ( boundingSphere !== undefined ) {
  19249. var center = new Vector3();
  19250. if ( boundingSphere.center !== undefined ) {
  19251. center.fromArray( boundingSphere.center );
  19252. }
  19253. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  19254. }
  19255. return geometry;
  19256. }
  19257. } );
  19258. /**
  19259. * @author alteredq / http://alteredqualia.com/
  19260. */
  19261. function Loader() {
  19262. this.onLoadStart = function () {};
  19263. this.onLoadProgress = function () {};
  19264. this.onLoadComplete = function () {};
  19265. }
  19266. Loader.prototype = {
  19267. constructor: Loader,
  19268. crossOrigin: undefined,
  19269. extractUrlBase: function ( url ) {
  19270. var parts = url.split( '/' );
  19271. if ( parts.length === 1 ) return './';
  19272. parts.pop();
  19273. return parts.join( '/' ) + '/';
  19274. },
  19275. initMaterials: function ( materials, texturePath, crossOrigin ) {
  19276. var array = [];
  19277. for ( var i = 0; i < materials.length; ++ i ) {
  19278. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  19279. }
  19280. return array;
  19281. },
  19282. createMaterial: ( function () {
  19283. var color, textureLoader, materialLoader;
  19284. return function createMaterial( m, texturePath, crossOrigin ) {
  19285. if ( color === undefined ) color = new Color();
  19286. if ( textureLoader === undefined ) textureLoader = new TextureLoader();
  19287. if ( materialLoader === undefined ) materialLoader = new MaterialLoader();
  19288. // convert from old material format
  19289. var textures = {};
  19290. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  19291. var fullPath = texturePath + path;
  19292. var loader = Loader.Handlers.get( fullPath );
  19293. var texture;
  19294. if ( loader !== null ) {
  19295. texture = loader.load( fullPath );
  19296. } else {
  19297. textureLoader.setCrossOrigin( crossOrigin );
  19298. texture = textureLoader.load( fullPath );
  19299. }
  19300. if ( repeat !== undefined ) {
  19301. texture.repeat.fromArray( repeat );
  19302. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  19303. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  19304. }
  19305. if ( offset !== undefined ) {
  19306. texture.offset.fromArray( offset );
  19307. }
  19308. if ( wrap !== undefined ) {
  19309. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  19310. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  19311. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  19312. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  19313. }
  19314. if ( anisotropy !== undefined ) {
  19315. texture.anisotropy = anisotropy;
  19316. }
  19317. var uuid = _Math.generateUUID();
  19318. textures[ uuid ] = texture;
  19319. return uuid;
  19320. }
  19321. //
  19322. var json = {
  19323. uuid: _Math.generateUUID(),
  19324. type: 'MeshLambertMaterial'
  19325. };
  19326. for ( var name in m ) {
  19327. var value = m[ name ];
  19328. switch ( name ) {
  19329. case 'DbgColor':
  19330. case 'DbgIndex':
  19331. case 'opticalDensity':
  19332. case 'illumination':
  19333. break;
  19334. case 'DbgName':
  19335. json.name = value;
  19336. break;
  19337. case 'blending':
  19338. json.blending = BlendingMode[ value ];
  19339. break;
  19340. case 'colorAmbient':
  19341. case 'mapAmbient':
  19342. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  19343. break;
  19344. case 'colorDiffuse':
  19345. json.color = color.fromArray( value ).getHex();
  19346. break;
  19347. case 'colorSpecular':
  19348. json.specular = color.fromArray( value ).getHex();
  19349. break;
  19350. case 'colorEmissive':
  19351. json.emissive = color.fromArray( value ).getHex();
  19352. break;
  19353. case 'specularCoef':
  19354. json.shininess = value;
  19355. break;
  19356. case 'shading':
  19357. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  19358. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  19359. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  19360. break;
  19361. case 'mapDiffuse':
  19362. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  19363. break;
  19364. case 'mapDiffuseRepeat':
  19365. case 'mapDiffuseOffset':
  19366. case 'mapDiffuseWrap':
  19367. case 'mapDiffuseAnisotropy':
  19368. break;
  19369. case 'mapEmissive':
  19370. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  19371. break;
  19372. case 'mapEmissiveRepeat':
  19373. case 'mapEmissiveOffset':
  19374. case 'mapEmissiveWrap':
  19375. case 'mapEmissiveAnisotropy':
  19376. break;
  19377. case 'mapLight':
  19378. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  19379. break;
  19380. case 'mapLightRepeat':
  19381. case 'mapLightOffset':
  19382. case 'mapLightWrap':
  19383. case 'mapLightAnisotropy':
  19384. break;
  19385. case 'mapAO':
  19386. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  19387. break;
  19388. case 'mapAORepeat':
  19389. case 'mapAOOffset':
  19390. case 'mapAOWrap':
  19391. case 'mapAOAnisotropy':
  19392. break;
  19393. case 'mapBump':
  19394. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  19395. break;
  19396. case 'mapBumpScale':
  19397. json.bumpScale = value;
  19398. break;
  19399. case 'mapBumpRepeat':
  19400. case 'mapBumpOffset':
  19401. case 'mapBumpWrap':
  19402. case 'mapBumpAnisotropy':
  19403. break;
  19404. case 'mapNormal':
  19405. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  19406. break;
  19407. case 'mapNormalFactor':
  19408. json.normalScale = [ value, value ];
  19409. break;
  19410. case 'mapNormalRepeat':
  19411. case 'mapNormalOffset':
  19412. case 'mapNormalWrap':
  19413. case 'mapNormalAnisotropy':
  19414. break;
  19415. case 'mapSpecular':
  19416. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  19417. break;
  19418. case 'mapSpecularRepeat':
  19419. case 'mapSpecularOffset':
  19420. case 'mapSpecularWrap':
  19421. case 'mapSpecularAnisotropy':
  19422. break;
  19423. case 'mapMetalness':
  19424. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  19425. break;
  19426. case 'mapMetalnessRepeat':
  19427. case 'mapMetalnessOffset':
  19428. case 'mapMetalnessWrap':
  19429. case 'mapMetalnessAnisotropy':
  19430. break;
  19431. case 'mapRoughness':
  19432. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  19433. break;
  19434. case 'mapRoughnessRepeat':
  19435. case 'mapRoughnessOffset':
  19436. case 'mapRoughnessWrap':
  19437. case 'mapRoughnessAnisotropy':
  19438. break;
  19439. case 'mapAlpha':
  19440. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  19441. break;
  19442. case 'mapAlphaRepeat':
  19443. case 'mapAlphaOffset':
  19444. case 'mapAlphaWrap':
  19445. case 'mapAlphaAnisotropy':
  19446. break;
  19447. case 'flipSided':
  19448. json.side = BackSide;
  19449. break;
  19450. case 'doubleSided':
  19451. json.side = DoubleSide;
  19452. break;
  19453. case 'transparency':
  19454. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  19455. json.opacity = value;
  19456. break;
  19457. case 'depthTest':
  19458. case 'depthWrite':
  19459. case 'colorWrite':
  19460. case 'opacity':
  19461. case 'reflectivity':
  19462. case 'transparent':
  19463. case 'visible':
  19464. case 'wireframe':
  19465. json[ name ] = value;
  19466. break;
  19467. case 'vertexColors':
  19468. if ( value === true ) json.vertexColors = VertexColors;
  19469. if ( value === 'face' ) json.vertexColors = FaceColors;
  19470. break;
  19471. default:
  19472. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  19473. break;
  19474. }
  19475. }
  19476. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  19477. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  19478. if ( json.opacity < 1 ) json.transparent = true;
  19479. materialLoader.setTextures( textures );
  19480. return materialLoader.parse( json );
  19481. };
  19482. } )()
  19483. };
  19484. Loader.Handlers = {
  19485. handlers: [],
  19486. add: function ( regex, loader ) {
  19487. this.handlers.push( regex, loader );
  19488. },
  19489. get: function ( file ) {
  19490. var handlers = this.handlers;
  19491. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  19492. var regex = handlers[ i ];
  19493. var loader = handlers[ i + 1 ];
  19494. if ( regex.test( file ) ) {
  19495. return loader;
  19496. }
  19497. }
  19498. return null;
  19499. }
  19500. };
  19501. /**
  19502. * @author mrdoob / http://mrdoob.com/
  19503. * @author alteredq / http://alteredqualia.com/
  19504. */
  19505. function JSONLoader( manager ) {
  19506. if ( typeof manager === 'boolean' ) {
  19507. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  19508. manager = undefined;
  19509. }
  19510. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19511. this.withCredentials = false;
  19512. }
  19513. Object.assign( JSONLoader.prototype, {
  19514. load: function( url, onLoad, onProgress, onError ) {
  19515. var scope = this;
  19516. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  19517. var loader = new FileLoader( this.manager );
  19518. loader.setWithCredentials( this.withCredentials );
  19519. loader.load( url, function ( text ) {
  19520. var json = JSON.parse( text );
  19521. var metadata = json.metadata;
  19522. if ( metadata !== undefined ) {
  19523. var type = metadata.type;
  19524. if ( type !== undefined ) {
  19525. if ( type.toLowerCase() === 'object' ) {
  19526. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  19527. return;
  19528. }
  19529. if ( type.toLowerCase() === 'scene' ) {
  19530. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  19531. return;
  19532. }
  19533. }
  19534. }
  19535. var object = scope.parse( json, texturePath );
  19536. onLoad( object.geometry, object.materials );
  19537. }, onProgress, onError );
  19538. },
  19539. setTexturePath: function ( value ) {
  19540. this.texturePath = value;
  19541. },
  19542. parse: function ( json, texturePath ) {
  19543. var geometry = new Geometry(),
  19544. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  19545. parseModel( scale );
  19546. parseSkin();
  19547. parseMorphing( scale );
  19548. parseAnimations();
  19549. geometry.computeFaceNormals();
  19550. geometry.computeBoundingSphere();
  19551. function parseModel( scale ) {
  19552. function isBitSet( value, position ) {
  19553. return value & ( 1 << position );
  19554. }
  19555. var i, j, fi,
  19556. offset, zLength,
  19557. colorIndex, normalIndex, uvIndex, materialIndex,
  19558. type,
  19559. isQuad,
  19560. hasMaterial,
  19561. hasFaceVertexUv,
  19562. hasFaceNormal, hasFaceVertexNormal,
  19563. hasFaceColor, hasFaceVertexColor,
  19564. vertex, face, faceA, faceB, hex, normal,
  19565. uvLayer, uv, u, v,
  19566. faces = json.faces,
  19567. vertices = json.vertices,
  19568. normals = json.normals,
  19569. colors = json.colors,
  19570. nUvLayers = 0;
  19571. if ( json.uvs !== undefined ) {
  19572. // disregard empty arrays
  19573. for ( i = 0; i < json.uvs.length; i ++ ) {
  19574. if ( json.uvs[ i ].length ) nUvLayers ++;
  19575. }
  19576. for ( i = 0; i < nUvLayers; i ++ ) {
  19577. geometry.faceVertexUvs[ i ] = [];
  19578. }
  19579. }
  19580. offset = 0;
  19581. zLength = vertices.length;
  19582. while ( offset < zLength ) {
  19583. vertex = new Vector3();
  19584. vertex.x = vertices[ offset ++ ] * scale;
  19585. vertex.y = vertices[ offset ++ ] * scale;
  19586. vertex.z = vertices[ offset ++ ] * scale;
  19587. geometry.vertices.push( vertex );
  19588. }
  19589. offset = 0;
  19590. zLength = faces.length;
  19591. while ( offset < zLength ) {
  19592. type = faces[ offset ++ ];
  19593. isQuad = isBitSet( type, 0 );
  19594. hasMaterial = isBitSet( type, 1 );
  19595. hasFaceVertexUv = isBitSet( type, 3 );
  19596. hasFaceNormal = isBitSet( type, 4 );
  19597. hasFaceVertexNormal = isBitSet( type, 5 );
  19598. hasFaceColor = isBitSet( type, 6 );
  19599. hasFaceVertexColor = isBitSet( type, 7 );
  19600. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  19601. if ( isQuad ) {
  19602. faceA = new Face3();
  19603. faceA.a = faces[ offset ];
  19604. faceA.b = faces[ offset + 1 ];
  19605. faceA.c = faces[ offset + 3 ];
  19606. faceB = new Face3();
  19607. faceB.a = faces[ offset + 1 ];
  19608. faceB.b = faces[ offset + 2 ];
  19609. faceB.c = faces[ offset + 3 ];
  19610. offset += 4;
  19611. if ( hasMaterial ) {
  19612. materialIndex = faces[ offset ++ ];
  19613. faceA.materialIndex = materialIndex;
  19614. faceB.materialIndex = materialIndex;
  19615. }
  19616. // to get face <=> uv index correspondence
  19617. fi = geometry.faces.length;
  19618. if ( hasFaceVertexUv ) {
  19619. for ( i = 0; i < nUvLayers; i ++ ) {
  19620. uvLayer = json.uvs[ i ];
  19621. geometry.faceVertexUvs[ i ][ fi ] = [];
  19622. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  19623. for ( j = 0; j < 4; j ++ ) {
  19624. uvIndex = faces[ offset ++ ];
  19625. u = uvLayer[ uvIndex * 2 ];
  19626. v = uvLayer[ uvIndex * 2 + 1 ];
  19627. uv = new Vector2( u, v );
  19628. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  19629. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  19630. }
  19631. }
  19632. }
  19633. if ( hasFaceNormal ) {
  19634. normalIndex = faces[ offset ++ ] * 3;
  19635. faceA.normal.set(
  19636. normals[ normalIndex ++ ],
  19637. normals[ normalIndex ++ ],
  19638. normals[ normalIndex ]
  19639. );
  19640. faceB.normal.copy( faceA.normal );
  19641. }
  19642. if ( hasFaceVertexNormal ) {
  19643. for ( i = 0; i < 4; i ++ ) {
  19644. normalIndex = faces[ offset ++ ] * 3;
  19645. normal = new Vector3(
  19646. normals[ normalIndex ++ ],
  19647. normals[ normalIndex ++ ],
  19648. normals[ normalIndex ]
  19649. );
  19650. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  19651. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  19652. }
  19653. }
  19654. if ( hasFaceColor ) {
  19655. colorIndex = faces[ offset ++ ];
  19656. hex = colors[ colorIndex ];
  19657. faceA.color.setHex( hex );
  19658. faceB.color.setHex( hex );
  19659. }
  19660. if ( hasFaceVertexColor ) {
  19661. for ( i = 0; i < 4; i ++ ) {
  19662. colorIndex = faces[ offset ++ ];
  19663. hex = colors[ colorIndex ];
  19664. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  19665. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  19666. }
  19667. }
  19668. geometry.faces.push( faceA );
  19669. geometry.faces.push( faceB );
  19670. } else {
  19671. face = new Face3();
  19672. face.a = faces[ offset ++ ];
  19673. face.b = faces[ offset ++ ];
  19674. face.c = faces[ offset ++ ];
  19675. if ( hasMaterial ) {
  19676. materialIndex = faces[ offset ++ ];
  19677. face.materialIndex = materialIndex;
  19678. }
  19679. // to get face <=> uv index correspondence
  19680. fi = geometry.faces.length;
  19681. if ( hasFaceVertexUv ) {
  19682. for ( i = 0; i < nUvLayers; i ++ ) {
  19683. uvLayer = json.uvs[ i ];
  19684. geometry.faceVertexUvs[ i ][ fi ] = [];
  19685. for ( j = 0; j < 3; j ++ ) {
  19686. uvIndex = faces[ offset ++ ];
  19687. u = uvLayer[ uvIndex * 2 ];
  19688. v = uvLayer[ uvIndex * 2 + 1 ];
  19689. uv = new Vector2( u, v );
  19690. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  19691. }
  19692. }
  19693. }
  19694. if ( hasFaceNormal ) {
  19695. normalIndex = faces[ offset ++ ] * 3;
  19696. face.normal.set(
  19697. normals[ normalIndex ++ ],
  19698. normals[ normalIndex ++ ],
  19699. normals[ normalIndex ]
  19700. );
  19701. }
  19702. if ( hasFaceVertexNormal ) {
  19703. for ( i = 0; i < 3; i ++ ) {
  19704. normalIndex = faces[ offset ++ ] * 3;
  19705. normal = new Vector3(
  19706. normals[ normalIndex ++ ],
  19707. normals[ normalIndex ++ ],
  19708. normals[ normalIndex ]
  19709. );
  19710. face.vertexNormals.push( normal );
  19711. }
  19712. }
  19713. if ( hasFaceColor ) {
  19714. colorIndex = faces[ offset ++ ];
  19715. face.color.setHex( colors[ colorIndex ] );
  19716. }
  19717. if ( hasFaceVertexColor ) {
  19718. for ( i = 0; i < 3; i ++ ) {
  19719. colorIndex = faces[ offset ++ ];
  19720. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  19721. }
  19722. }
  19723. geometry.faces.push( face );
  19724. }
  19725. }
  19726. }
  19727. function parseSkin() {
  19728. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  19729. if ( json.skinWeights ) {
  19730. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  19731. var x = json.skinWeights[ i ];
  19732. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  19733. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  19734. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  19735. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  19736. }
  19737. }
  19738. if ( json.skinIndices ) {
  19739. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  19740. var a = json.skinIndices[ i ];
  19741. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  19742. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  19743. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  19744. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  19745. }
  19746. }
  19747. geometry.bones = json.bones;
  19748. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  19749. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  19750. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  19751. }
  19752. }
  19753. function parseMorphing( scale ) {
  19754. if ( json.morphTargets !== undefined ) {
  19755. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  19756. geometry.morphTargets[ i ] = {};
  19757. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  19758. geometry.morphTargets[ i ].vertices = [];
  19759. var dstVertices = geometry.morphTargets[ i ].vertices;
  19760. var srcVertices = json.morphTargets[ i ].vertices;
  19761. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  19762. var vertex = new Vector3();
  19763. vertex.x = srcVertices[ v ] * scale;
  19764. vertex.y = srcVertices[ v + 1 ] * scale;
  19765. vertex.z = srcVertices[ v + 2 ] * scale;
  19766. dstVertices.push( vertex );
  19767. }
  19768. }
  19769. }
  19770. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  19771. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  19772. var faces = geometry.faces;
  19773. var morphColors = json.morphColors[ 0 ].colors;
  19774. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19775. faces[ i ].color.fromArray( morphColors, i * 3 );
  19776. }
  19777. }
  19778. }
  19779. function parseAnimations() {
  19780. var outputAnimations = [];
  19781. // parse old style Bone/Hierarchy animations
  19782. var animations = [];
  19783. if ( json.animation !== undefined ) {
  19784. animations.push( json.animation );
  19785. }
  19786. if ( json.animations !== undefined ) {
  19787. if ( json.animations.length ) {
  19788. animations = animations.concat( json.animations );
  19789. } else {
  19790. animations.push( json.animations );
  19791. }
  19792. }
  19793. for ( var i = 0; i < animations.length; i ++ ) {
  19794. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  19795. if ( clip ) outputAnimations.push( clip );
  19796. }
  19797. // parse implicit morph animations
  19798. if ( geometry.morphTargets ) {
  19799. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  19800. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  19801. outputAnimations = outputAnimations.concat( morphAnimationClips );
  19802. }
  19803. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  19804. }
  19805. if ( json.materials === undefined || json.materials.length === 0 ) {
  19806. return { geometry: geometry };
  19807. } else {
  19808. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  19809. return { geometry: geometry, materials: materials };
  19810. }
  19811. }
  19812. } );
  19813. /**
  19814. * @author mrdoob / http://mrdoob.com/
  19815. */
  19816. function ObjectLoader( manager ) {
  19817. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19818. this.texturePath = '';
  19819. }
  19820. Object.assign( ObjectLoader.prototype, {
  19821. load: function ( url, onLoad, onProgress, onError ) {
  19822. if ( this.texturePath === '' ) {
  19823. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  19824. }
  19825. var scope = this;
  19826. var loader = new FileLoader( scope.manager );
  19827. loader.load( url, function ( text ) {
  19828. var json = null;
  19829. try {
  19830. json = JSON.parse( text );
  19831. } catch ( error ) {
  19832. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  19833. return;
  19834. }
  19835. var metadata = json.metadata;
  19836. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  19837. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  19838. return;
  19839. }
  19840. scope.parse( json, onLoad );
  19841. }, onProgress, onError );
  19842. },
  19843. setTexturePath: function ( value ) {
  19844. this.texturePath = value;
  19845. },
  19846. setCrossOrigin: function ( value ) {
  19847. this.crossOrigin = value;
  19848. },
  19849. parse: function ( json, onLoad ) {
  19850. var geometries = this.parseGeometries( json.geometries );
  19851. var images = this.parseImages( json.images, function () {
  19852. if ( onLoad !== undefined ) onLoad( object );
  19853. } );
  19854. var textures = this.parseTextures( json.textures, images );
  19855. var materials = this.parseMaterials( json.materials, textures );
  19856. var object = this.parseObject( json.object, geometries, materials );
  19857. if ( json.animations ) {
  19858. object.animations = this.parseAnimations( json.animations );
  19859. }
  19860. if ( json.images === undefined || json.images.length === 0 ) {
  19861. if ( onLoad !== undefined ) onLoad( object );
  19862. }
  19863. return object;
  19864. },
  19865. parseGeometries: function ( json ) {
  19866. var geometries = {};
  19867. if ( json !== undefined ) {
  19868. var geometryLoader = new JSONLoader();
  19869. var bufferGeometryLoader = new BufferGeometryLoader();
  19870. for ( var i = 0, l = json.length; i < l; i ++ ) {
  19871. var geometry;
  19872. var data = json[ i ];
  19873. switch ( data.type ) {
  19874. case 'PlaneGeometry':
  19875. case 'PlaneBufferGeometry':
  19876. geometry = new Geometries[ data.type ](
  19877. data.width,
  19878. data.height,
  19879. data.widthSegments,
  19880. data.heightSegments
  19881. );
  19882. break;
  19883. case 'BoxGeometry':
  19884. case 'BoxBufferGeometry':
  19885. case 'CubeGeometry': // backwards compatible
  19886. geometry = new Geometries[ data.type ](
  19887. data.width,
  19888. data.height,
  19889. data.depth,
  19890. data.widthSegments,
  19891. data.heightSegments,
  19892. data.depthSegments
  19893. );
  19894. break;
  19895. case 'CircleGeometry':
  19896. case 'CircleBufferGeometry':
  19897. geometry = new Geometries[ data.type ](
  19898. data.radius,
  19899. data.segments,
  19900. data.thetaStart,
  19901. data.thetaLength
  19902. );
  19903. break;
  19904. case 'CylinderGeometry':
  19905. case 'CylinderBufferGeometry':
  19906. geometry = new Geometries[ data.type ](
  19907. data.radiusTop,
  19908. data.radiusBottom,
  19909. data.height,
  19910. data.radialSegments,
  19911. data.heightSegments,
  19912. data.openEnded,
  19913. data.thetaStart,
  19914. data.thetaLength
  19915. );
  19916. break;
  19917. case 'ConeGeometry':
  19918. case 'ConeBufferGeometry':
  19919. geometry = new Geometries[ data.type ](
  19920. data.radius,
  19921. data.height,
  19922. data.radialSegments,
  19923. data.heightSegments,
  19924. data.openEnded,
  19925. data.thetaStart,
  19926. data.thetaLength
  19927. );
  19928. break;
  19929. case 'SphereGeometry':
  19930. case 'SphereBufferGeometry':
  19931. geometry = new Geometries[ data.type ](
  19932. data.radius,
  19933. data.widthSegments,
  19934. data.heightSegments,
  19935. data.phiStart,
  19936. data.phiLength,
  19937. data.thetaStart,
  19938. data.thetaLength
  19939. );
  19940. break;
  19941. case 'DodecahedronGeometry':
  19942. case 'IcosahedronGeometry':
  19943. case 'OctahedronGeometry':
  19944. case 'TetrahedronGeometry':
  19945. geometry = new Geometries[ data.type ](
  19946. data.radius,
  19947. data.detail
  19948. );
  19949. break;
  19950. case 'RingGeometry':
  19951. case 'RingBufferGeometry':
  19952. geometry = new Geometries[ data.type ](
  19953. data.innerRadius,
  19954. data.outerRadius,
  19955. data.thetaSegments,
  19956. data.phiSegments,
  19957. data.thetaStart,
  19958. data.thetaLength
  19959. );
  19960. break;
  19961. case 'TorusGeometry':
  19962. case 'TorusBufferGeometry':
  19963. geometry = new Geometries[ data.type ](
  19964. data.radius,
  19965. data.tube,
  19966. data.radialSegments,
  19967. data.tubularSegments,
  19968. data.arc
  19969. );
  19970. break;
  19971. case 'TorusKnotGeometry':
  19972. case 'TorusKnotBufferGeometry':
  19973. geometry = new Geometries[ data.type ](
  19974. data.radius,
  19975. data.tube,
  19976. data.tubularSegments,
  19977. data.radialSegments,
  19978. data.p,
  19979. data.q
  19980. );
  19981. break;
  19982. case 'LatheGeometry':
  19983. case 'LatheBufferGeometry':
  19984. geometry = new Geometries[ data.type ](
  19985. data.points,
  19986. data.segments,
  19987. data.phiStart,
  19988. data.phiLength
  19989. );
  19990. break;
  19991. case 'BufferGeometry':
  19992. geometry = bufferGeometryLoader.parse( data );
  19993. break;
  19994. case 'Geometry':
  19995. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  19996. break;
  19997. default:
  19998. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  19999. continue;
  20000. }
  20001. geometry.uuid = data.uuid;
  20002. if ( data.name !== undefined ) geometry.name = data.name;
  20003. geometries[ data.uuid ] = geometry;
  20004. }
  20005. }
  20006. return geometries;
  20007. },
  20008. parseMaterials: function ( json, textures ) {
  20009. var materials = {};
  20010. if ( json !== undefined ) {
  20011. var loader = new MaterialLoader();
  20012. loader.setTextures( textures );
  20013. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20014. var material = loader.parse( json[ i ] );
  20015. materials[ material.uuid ] = material;
  20016. }
  20017. }
  20018. return materials;
  20019. },
  20020. parseAnimations: function ( json ) {
  20021. var animations = [];
  20022. for ( var i = 0; i < json.length; i ++ ) {
  20023. var clip = AnimationClip.parse( json[ i ] );
  20024. animations.push( clip );
  20025. }
  20026. return animations;
  20027. },
  20028. parseImages: function ( json, onLoad ) {
  20029. var scope = this;
  20030. var images = {};
  20031. function loadImage( url ) {
  20032. scope.manager.itemStart( url );
  20033. return loader.load( url, function () {
  20034. scope.manager.itemEnd( url );
  20035. }, undefined, function () {
  20036. scope.manager.itemError( url );
  20037. } );
  20038. }
  20039. if ( json !== undefined && json.length > 0 ) {
  20040. var manager = new LoadingManager( onLoad );
  20041. var loader = new ImageLoader( manager );
  20042. loader.setCrossOrigin( this.crossOrigin );
  20043. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20044. var image = json[ i ];
  20045. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  20046. images[ image.uuid ] = loadImage( path );
  20047. }
  20048. }
  20049. return images;
  20050. },
  20051. parseTextures: function ( json, images ) {
  20052. function parseConstant( value, type ) {
  20053. if ( typeof( value ) === 'number' ) return value;
  20054. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  20055. return type[ value ];
  20056. }
  20057. var textures = {};
  20058. if ( json !== undefined ) {
  20059. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20060. var data = json[ i ];
  20061. if ( data.image === undefined ) {
  20062. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  20063. }
  20064. if ( images[ data.image ] === undefined ) {
  20065. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  20066. }
  20067. var texture = new Texture( images[ data.image ] );
  20068. texture.needsUpdate = true;
  20069. texture.uuid = data.uuid;
  20070. if ( data.name !== undefined ) texture.name = data.name;
  20071. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TextureMapping );
  20072. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  20073. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  20074. if ( data.wrap !== undefined ) {
  20075. texture.wrapS = parseConstant( data.wrap[ 0 ], TextureWrapping );
  20076. texture.wrapT = parseConstant( data.wrap[ 1 ], TextureWrapping );
  20077. }
  20078. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TextureFilter );
  20079. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TextureFilter );
  20080. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  20081. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  20082. textures[ data.uuid ] = texture;
  20083. }
  20084. }
  20085. return textures;
  20086. },
  20087. parseObject: function () {
  20088. var matrix = new Matrix4();
  20089. return function parseObject( data, geometries, materials ) {
  20090. var object;
  20091. function getGeometry( name ) {
  20092. if ( geometries[ name ] === undefined ) {
  20093. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  20094. }
  20095. return geometries[ name ];
  20096. }
  20097. function getMaterial( name ) {
  20098. if ( name === undefined ) return undefined;
  20099. if ( materials[ name ] === undefined ) {
  20100. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  20101. }
  20102. return materials[ name ];
  20103. }
  20104. switch ( data.type ) {
  20105. case 'Scene':
  20106. object = new Scene();
  20107. if ( data.background !== undefined ) {
  20108. if ( Number.isInteger( data.background ) ) {
  20109. object.background = new Color( data.background );
  20110. }
  20111. }
  20112. if ( data.fog !== undefined ) {
  20113. if ( data.fog.type === 'Fog' ) {
  20114. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  20115. } else if ( data.fog.type === 'FogExp2' ) {
  20116. object.fog = new FogExp2( data.fog.color, data.fog.density );
  20117. }
  20118. }
  20119. break;
  20120. case 'PerspectiveCamera':
  20121. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  20122. if ( data.focus !== undefined ) object.focus = data.focus;
  20123. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  20124. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  20125. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  20126. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  20127. break;
  20128. case 'OrthographicCamera':
  20129. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  20130. break;
  20131. case 'AmbientLight':
  20132. object = new AmbientLight( data.color, data.intensity );
  20133. break;
  20134. case 'DirectionalLight':
  20135. object = new DirectionalLight( data.color, data.intensity );
  20136. break;
  20137. case 'PointLight':
  20138. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  20139. break;
  20140. case 'SpotLight':
  20141. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  20142. break;
  20143. case 'HemisphereLight':
  20144. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  20145. break;
  20146. case 'Mesh':
  20147. var geometry = getGeometry( data.geometry );
  20148. var material = getMaterial( data.material );
  20149. if ( geometry.bones && geometry.bones.length > 0 ) {
  20150. object = new SkinnedMesh( geometry, material );
  20151. } else {
  20152. object = new Mesh( geometry, material );
  20153. }
  20154. break;
  20155. case 'LOD':
  20156. object = new LOD();
  20157. break;
  20158. case 'Line':
  20159. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  20160. break;
  20161. case 'LineSegments':
  20162. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  20163. break;
  20164. case 'PointCloud':
  20165. case 'Points':
  20166. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  20167. break;
  20168. case 'Sprite':
  20169. object = new Sprite( getMaterial( data.material ) );
  20170. break;
  20171. case 'Group':
  20172. object = new Group();
  20173. break;
  20174. default:
  20175. object = new Object3D();
  20176. }
  20177. object.uuid = data.uuid;
  20178. if ( data.name !== undefined ) object.name = data.name;
  20179. if ( data.matrix !== undefined ) {
  20180. matrix.fromArray( data.matrix );
  20181. matrix.decompose( object.position, object.quaternion, object.scale );
  20182. } else {
  20183. if ( data.position !== undefined ) object.position.fromArray( data.position );
  20184. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  20185. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  20186. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  20187. }
  20188. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  20189. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  20190. if ( data.shadow ) {
  20191. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  20192. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  20193. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  20194. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  20195. }
  20196. if ( data.visible !== undefined ) object.visible = data.visible;
  20197. if ( data.userData !== undefined ) object.userData = data.userData;
  20198. if ( data.children !== undefined ) {
  20199. for ( var child in data.children ) {
  20200. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  20201. }
  20202. }
  20203. if ( data.type === 'LOD' ) {
  20204. var levels = data.levels;
  20205. for ( var l = 0; l < levels.length; l ++ ) {
  20206. var level = levels[ l ];
  20207. var child = object.getObjectByProperty( 'uuid', level.object );
  20208. if ( child !== undefined ) {
  20209. object.addLevel( child, level.distance );
  20210. }
  20211. }
  20212. }
  20213. return object;
  20214. };
  20215. }()
  20216. } );
  20217. /**
  20218. * @author zz85 / http://www.lab4games.net/zz85/blog
  20219. * Extensible curve object
  20220. *
  20221. * Some common of Curve methods
  20222. * .getPoint(t), getTangent(t)
  20223. * .getPointAt(u), getTangentAt(u)
  20224. * .getPoints(), .getSpacedPoints()
  20225. * .getLength()
  20226. * .updateArcLengths()
  20227. *
  20228. * This following classes subclasses THREE.Curve:
  20229. *
  20230. * -- 2d classes --
  20231. * THREE.LineCurve
  20232. * THREE.QuadraticBezierCurve
  20233. * THREE.CubicBezierCurve
  20234. * THREE.SplineCurve
  20235. * THREE.ArcCurve
  20236. * THREE.EllipseCurve
  20237. *
  20238. * -- 3d classes --
  20239. * THREE.LineCurve3
  20240. * THREE.QuadraticBezierCurve3
  20241. * THREE.CubicBezierCurve3
  20242. * THREE.SplineCurve3
  20243. *
  20244. * A series of curves can be represented as a THREE.CurvePath
  20245. *
  20246. **/
  20247. /**************************************************************
  20248. * Abstract Curve base class
  20249. **************************************************************/
  20250. function Curve() {}
  20251. Curve.prototype = {
  20252. constructor: Curve,
  20253. // Virtual base class method to overwrite and implement in subclasses
  20254. // - t [0 .. 1]
  20255. getPoint: function ( t ) {
  20256. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  20257. return null;
  20258. },
  20259. // Get point at relative position in curve according to arc length
  20260. // - u [0 .. 1]
  20261. getPointAt: function ( u ) {
  20262. var t = this.getUtoTmapping( u );
  20263. return this.getPoint( t );
  20264. },
  20265. // Get sequence of points using getPoint( t )
  20266. getPoints: function ( divisions ) {
  20267. if ( ! divisions ) divisions = 5;
  20268. var points = [];
  20269. for ( var d = 0; d <= divisions; d ++ ) {
  20270. points.push( this.getPoint( d / divisions ) );
  20271. }
  20272. return points;
  20273. },
  20274. // Get sequence of points using getPointAt( u )
  20275. getSpacedPoints: function ( divisions ) {
  20276. if ( ! divisions ) divisions = 5;
  20277. var points = [];
  20278. for ( var d = 0; d <= divisions; d ++ ) {
  20279. points.push( this.getPointAt( d / divisions ) );
  20280. }
  20281. return points;
  20282. },
  20283. // Get total curve arc length
  20284. getLength: function () {
  20285. var lengths = this.getLengths();
  20286. return lengths[ lengths.length - 1 ];
  20287. },
  20288. // Get list of cumulative segment lengths
  20289. getLengths: function ( divisions ) {
  20290. if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  20291. if ( this.cacheArcLengths
  20292. && ( this.cacheArcLengths.length === divisions + 1 )
  20293. && ! this.needsUpdate ) {
  20294. //console.log( "cached", this.cacheArcLengths );
  20295. return this.cacheArcLengths;
  20296. }
  20297. this.needsUpdate = false;
  20298. var cache = [];
  20299. var current, last = this.getPoint( 0 );
  20300. var p, sum = 0;
  20301. cache.push( 0 );
  20302. for ( p = 1; p <= divisions; p ++ ) {
  20303. current = this.getPoint ( p / divisions );
  20304. sum += current.distanceTo( last );
  20305. cache.push( sum );
  20306. last = current;
  20307. }
  20308. this.cacheArcLengths = cache;
  20309. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  20310. },
  20311. updateArcLengths: function() {
  20312. this.needsUpdate = true;
  20313. this.getLengths();
  20314. },
  20315. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20316. getUtoTmapping: function ( u, distance ) {
  20317. var arcLengths = this.getLengths();
  20318. var i = 0, il = arcLengths.length;
  20319. var targetArcLength; // The targeted u distance value to get
  20320. if ( distance ) {
  20321. targetArcLength = distance;
  20322. } else {
  20323. targetArcLength = u * arcLengths[ il - 1 ];
  20324. }
  20325. //var time = Date.now();
  20326. // binary search for the index with largest value smaller than target u distance
  20327. var low = 0, high = il - 1, comparison;
  20328. while ( low <= high ) {
  20329. 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
  20330. comparison = arcLengths[ i ] - targetArcLength;
  20331. if ( comparison < 0 ) {
  20332. low = i + 1;
  20333. } else if ( comparison > 0 ) {
  20334. high = i - 1;
  20335. } else {
  20336. high = i;
  20337. break;
  20338. // DONE
  20339. }
  20340. }
  20341. i = high;
  20342. //console.log('b' , i, low, high, Date.now()- time);
  20343. if ( arcLengths[ i ] === targetArcLength ) {
  20344. var t = i / ( il - 1 );
  20345. return t;
  20346. }
  20347. // we could get finer grain at lengths, or use simple interpolation between two points
  20348. var lengthBefore = arcLengths[ i ];
  20349. var lengthAfter = arcLengths[ i + 1 ];
  20350. var segmentLength = lengthAfter - lengthBefore;
  20351. // determine where we are between the 'before' and 'after' points
  20352. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20353. // add that fractional amount to t
  20354. var t = ( i + segmentFraction ) / ( il - 1 );
  20355. return t;
  20356. },
  20357. // Returns a unit vector tangent at t
  20358. // In case any sub curve does not implement its tangent derivation,
  20359. // 2 points a small delta apart will be used to find its gradient
  20360. // which seems to give a reasonable approximation
  20361. getTangent: function( t ) {
  20362. var delta = 0.0001;
  20363. var t1 = t - delta;
  20364. var t2 = t + delta;
  20365. // Capping in case of danger
  20366. if ( t1 < 0 ) t1 = 0;
  20367. if ( t2 > 1 ) t2 = 1;
  20368. var pt1 = this.getPoint( t1 );
  20369. var pt2 = this.getPoint( t2 );
  20370. var vec = pt2.clone().sub( pt1 );
  20371. return vec.normalize();
  20372. },
  20373. getTangentAt: function ( u ) {
  20374. var t = this.getUtoTmapping( u );
  20375. return this.getTangent( t );
  20376. },
  20377. computeFrenetFrames: function ( segments, closed ) {
  20378. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20379. var normal = new Vector3();
  20380. var tangents = [];
  20381. var normals = [];
  20382. var binormals = [];
  20383. var vec = new Vector3();
  20384. var mat = new Matrix4();
  20385. var i, u, theta;
  20386. // compute the tangent vectors for each segment on the curve
  20387. for ( i = 0; i <= segments; i ++ ) {
  20388. u = i / segments;
  20389. tangents[ i ] = this.getTangentAt( u );
  20390. tangents[ i ].normalize();
  20391. }
  20392. // select an initial normal vector perpendicular to the first tangent vector,
  20393. // and in the direction of the minimum tangent xyz component
  20394. normals[ 0 ] = new Vector3();
  20395. binormals[ 0 ] = new Vector3();
  20396. var min = Number.MAX_VALUE;
  20397. var tx = Math.abs( tangents[ 0 ].x );
  20398. var ty = Math.abs( tangents[ 0 ].y );
  20399. var tz = Math.abs( tangents[ 0 ].z );
  20400. if ( tx <= min ) {
  20401. min = tx;
  20402. normal.set( 1, 0, 0 );
  20403. }
  20404. if ( ty <= min ) {
  20405. min = ty;
  20406. normal.set( 0, 1, 0 );
  20407. }
  20408. if ( tz <= min ) {
  20409. normal.set( 0, 0, 1 );
  20410. }
  20411. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20412. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20413. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20414. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  20415. for ( i = 1; i <= segments; i ++ ) {
  20416. normals[ i ] = normals[ i - 1 ].clone();
  20417. binormals[ i ] = binormals[ i - 1 ].clone();
  20418. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  20419. if ( vec.length() > Number.EPSILON ) {
  20420. vec.normalize();
  20421. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  20422. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20423. }
  20424. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20425. }
  20426. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20427. if ( closed === true ) {
  20428. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  20429. theta /= segments;
  20430. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  20431. theta = - theta;
  20432. }
  20433. for ( i = 1; i <= segments; i ++ ) {
  20434. // twist a little...
  20435. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20436. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20437. }
  20438. }
  20439. return {
  20440. tangents: tangents,
  20441. normals: normals,
  20442. binormals: binormals
  20443. };
  20444. }
  20445. };
  20446. // TODO: Transformation for Curves?
  20447. /**************************************************************
  20448. * 3D Curves
  20449. **************************************************************/
  20450. // A Factory method for creating new curve subclasses
  20451. Curve.create = function ( constructor, getPointFunc ) {
  20452. constructor.prototype = Object.create( Curve.prototype );
  20453. constructor.prototype.constructor = constructor;
  20454. constructor.prototype.getPoint = getPointFunc;
  20455. return constructor;
  20456. };
  20457. /**************************************************************
  20458. * Line
  20459. **************************************************************/
  20460. function LineCurve( v1, v2 ) {
  20461. this.v1 = v1;
  20462. this.v2 = v2;
  20463. }
  20464. LineCurve.prototype = Object.create( Curve.prototype );
  20465. LineCurve.prototype.constructor = LineCurve;
  20466. LineCurve.prototype.isLineCurve = true;
  20467. LineCurve.prototype.getPoint = function ( t ) {
  20468. if ( t === 1 ) {
  20469. return this.v2.clone();
  20470. }
  20471. var point = this.v2.clone().sub( this.v1 );
  20472. point.multiplyScalar( t ).add( this.v1 );
  20473. return point;
  20474. };
  20475. // Line curve is linear, so we can overwrite default getPointAt
  20476. LineCurve.prototype.getPointAt = function ( u ) {
  20477. return this.getPoint( u );
  20478. };
  20479. LineCurve.prototype.getTangent = function( t ) {
  20480. var tangent = this.v2.clone().sub( this.v1 );
  20481. return tangent.normalize();
  20482. };
  20483. /**
  20484. * @author zz85 / http://www.lab4games.net/zz85/blog
  20485. *
  20486. **/
  20487. /**************************************************************
  20488. * Curved Path - a curve path is simply a array of connected
  20489. * curves, but retains the api of a curve
  20490. **************************************************************/
  20491. function CurvePath() {
  20492. this.curves = [];
  20493. this.autoClose = false; // Automatically closes the path
  20494. }
  20495. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  20496. constructor: CurvePath,
  20497. add: function ( curve ) {
  20498. this.curves.push( curve );
  20499. },
  20500. closePath: function () {
  20501. // Add a line curve if start and end of lines are not connected
  20502. var startPoint = this.curves[ 0 ].getPoint( 0 );
  20503. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20504. if ( ! startPoint.equals( endPoint ) ) {
  20505. this.curves.push( new LineCurve( endPoint, startPoint ) );
  20506. }
  20507. },
  20508. // To get accurate point with reference to
  20509. // entire path distance at time t,
  20510. // following has to be done:
  20511. // 1. Length of each sub path have to be known
  20512. // 2. Locate and identify type of curve
  20513. // 3. Get t for the curve
  20514. // 4. Return curve.getPointAt(t')
  20515. getPoint: function ( t ) {
  20516. var d = t * this.getLength();
  20517. var curveLengths = this.getCurveLengths();
  20518. var i = 0;
  20519. // To think about boundaries points.
  20520. while ( i < curveLengths.length ) {
  20521. if ( curveLengths[ i ] >= d ) {
  20522. var diff = curveLengths[ i ] - d;
  20523. var curve = this.curves[ i ];
  20524. var segmentLength = curve.getLength();
  20525. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  20526. return curve.getPointAt( u );
  20527. }
  20528. i ++;
  20529. }
  20530. return null;
  20531. // loop where sum != 0, sum > d , sum+1 <d
  20532. },
  20533. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20534. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20535. // getPoint() depends on getLength
  20536. getLength: function () {
  20537. var lens = this.getCurveLengths();
  20538. return lens[ lens.length - 1 ];
  20539. },
  20540. // cacheLengths must be recalculated.
  20541. updateArcLengths: function () {
  20542. this.needsUpdate = true;
  20543. this.cacheLengths = null;
  20544. this.getLengths();
  20545. },
  20546. // Compute lengths and cache them
  20547. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20548. getCurveLengths: function () {
  20549. // We use cache values if curves and cache array are same length
  20550. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20551. return this.cacheLengths;
  20552. }
  20553. // Get length of sub-curve
  20554. // Push sums into cached array
  20555. var lengths = [], sums = 0;
  20556. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  20557. sums += this.curves[ i ].getLength();
  20558. lengths.push( sums );
  20559. }
  20560. this.cacheLengths = lengths;
  20561. return lengths;
  20562. },
  20563. getSpacedPoints: function ( divisions ) {
  20564. if ( ! divisions ) divisions = 40;
  20565. var points = [];
  20566. for ( var i = 0; i <= divisions; i ++ ) {
  20567. points.push( this.getPoint( i / divisions ) );
  20568. }
  20569. if ( this.autoClose ) {
  20570. points.push( points[ 0 ] );
  20571. }
  20572. return points;
  20573. },
  20574. getPoints: function ( divisions ) {
  20575. divisions = divisions || 12;
  20576. var points = [], last;
  20577. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  20578. var curve = curves[ i ];
  20579. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  20580. : (curve && curve.isLineCurve) ? 1
  20581. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  20582. : divisions;
  20583. var pts = curve.getPoints( resolution );
  20584. for ( var j = 0; j < pts.length; j++ ) {
  20585. var point = pts[ j ];
  20586. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  20587. points.push( point );
  20588. last = point;
  20589. }
  20590. }
  20591. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  20592. points.push( points[ 0 ] );
  20593. }
  20594. return points;
  20595. },
  20596. /**************************************************************
  20597. * Create Geometries Helpers
  20598. **************************************************************/
  20599. /// Generate geometry from path points (for Line or Points objects)
  20600. createPointsGeometry: function ( divisions ) {
  20601. var pts = this.getPoints( divisions );
  20602. return this.createGeometry( pts );
  20603. },
  20604. // Generate geometry from equidistant sampling along the path
  20605. createSpacedPointsGeometry: function ( divisions ) {
  20606. var pts = this.getSpacedPoints( divisions );
  20607. return this.createGeometry( pts );
  20608. },
  20609. createGeometry: function ( points ) {
  20610. var geometry = new Geometry();
  20611. for ( var i = 0, l = points.length; i < l; i ++ ) {
  20612. var point = points[ i ];
  20613. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  20614. }
  20615. return geometry;
  20616. }
  20617. } );
  20618. /**************************************************************
  20619. * Ellipse curve
  20620. **************************************************************/
  20621. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20622. this.aX = aX;
  20623. this.aY = aY;
  20624. this.xRadius = xRadius;
  20625. this.yRadius = yRadius;
  20626. this.aStartAngle = aStartAngle;
  20627. this.aEndAngle = aEndAngle;
  20628. this.aClockwise = aClockwise;
  20629. this.aRotation = aRotation || 0;
  20630. }
  20631. EllipseCurve.prototype = Object.create( Curve.prototype );
  20632. EllipseCurve.prototype.constructor = EllipseCurve;
  20633. EllipseCurve.prototype.isEllipseCurve = true;
  20634. EllipseCurve.prototype.getPoint = function( t ) {
  20635. var twoPi = Math.PI * 2;
  20636. var deltaAngle = this.aEndAngle - this.aStartAngle;
  20637. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  20638. // ensures that deltaAngle is 0 .. 2 PI
  20639. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  20640. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  20641. if ( deltaAngle < Number.EPSILON ) {
  20642. if ( samePoints ) {
  20643. deltaAngle = 0;
  20644. } else {
  20645. deltaAngle = twoPi;
  20646. }
  20647. }
  20648. if ( this.aClockwise === true && ! samePoints ) {
  20649. if ( deltaAngle === twoPi ) {
  20650. deltaAngle = - twoPi;
  20651. } else {
  20652. deltaAngle = deltaAngle - twoPi;
  20653. }
  20654. }
  20655. var angle = this.aStartAngle + t * deltaAngle;
  20656. var x = this.aX + this.xRadius * Math.cos( angle );
  20657. var y = this.aY + this.yRadius * Math.sin( angle );
  20658. if ( this.aRotation !== 0 ) {
  20659. var cos = Math.cos( this.aRotation );
  20660. var sin = Math.sin( this.aRotation );
  20661. var tx = x - this.aX;
  20662. var ty = y - this.aY;
  20663. // Rotate the point about the center of the ellipse.
  20664. x = tx * cos - ty * sin + this.aX;
  20665. y = tx * sin + ty * cos + this.aY;
  20666. }
  20667. return new Vector2( x, y );
  20668. };
  20669. /**
  20670. * @author zz85 / http://www.lab4games.net/zz85/blog
  20671. */
  20672. var CurveUtils = {
  20673. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  20674. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  20675. },
  20676. // Puay Bing, thanks for helping with this derivative!
  20677. tangentCubicBezier: function ( t, p0, p1, p2, p3 ) {
  20678. return - 3 * p0 * ( 1 - t ) * ( 1 - t ) +
  20679. 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) +
  20680. 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 +
  20681. 3 * t * t * p3;
  20682. },
  20683. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  20684. // To check if my formulas are correct
  20685. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  20686. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  20687. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  20688. var h11 = 3 * t * t - 2 * t; // t3 − t2
  20689. return h00 + h10 + h01 + h11;
  20690. },
  20691. // Catmull-Rom
  20692. interpolate: function( p0, p1, p2, p3, t ) {
  20693. var v0 = ( p2 - p0 ) * 0.5;
  20694. var v1 = ( p3 - p1 ) * 0.5;
  20695. var t2 = t * t;
  20696. var t3 = t * t2;
  20697. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20698. }
  20699. };
  20700. /**************************************************************
  20701. * Spline curve
  20702. **************************************************************/
  20703. function SplineCurve( points /* array of Vector2 */ ) {
  20704. this.points = ( points === undefined ) ? [] : points;
  20705. }
  20706. SplineCurve.prototype = Object.create( Curve.prototype );
  20707. SplineCurve.prototype.constructor = SplineCurve;
  20708. SplineCurve.prototype.isSplineCurve = true;
  20709. SplineCurve.prototype.getPoint = function ( t ) {
  20710. var points = this.points;
  20711. var point = ( points.length - 1 ) * t;
  20712. var intPoint = Math.floor( point );
  20713. var weight = point - intPoint;
  20714. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  20715. var point1 = points[ intPoint ];
  20716. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  20717. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  20718. var interpolate = CurveUtils.interpolate;
  20719. return new Vector2(
  20720. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  20721. interpolate( point0.y, point1.y, point2.y, point3.y, weight )
  20722. );
  20723. };
  20724. /**************************************************************
  20725. * Cubic Bezier curve
  20726. **************************************************************/
  20727. function CubicBezierCurve( v0, v1, v2, v3 ) {
  20728. this.v0 = v0;
  20729. this.v1 = v1;
  20730. this.v2 = v2;
  20731. this.v3 = v3;
  20732. }
  20733. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  20734. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  20735. CubicBezierCurve.prototype.getPoint = function ( t ) {
  20736. var b3 = ShapeUtils.b3;
  20737. return new Vector2(
  20738. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20739. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  20740. );
  20741. };
  20742. CubicBezierCurve.prototype.getTangent = function( t ) {
  20743. var tangentCubicBezier = CurveUtils.tangentCubicBezier;
  20744. return new Vector2(
  20745. tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20746. tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  20747. ).normalize();
  20748. };
  20749. /**************************************************************
  20750. * Quadratic Bezier curve
  20751. **************************************************************/
  20752. function QuadraticBezierCurve( v0, v1, v2 ) {
  20753. this.v0 = v0;
  20754. this.v1 = v1;
  20755. this.v2 = v2;
  20756. }
  20757. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  20758. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  20759. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  20760. var b2 = ShapeUtils.b2;
  20761. return new Vector2(
  20762. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  20763. b2( t, this.v0.y, this.v1.y, this.v2.y )
  20764. );
  20765. };
  20766. QuadraticBezierCurve.prototype.getTangent = function( t ) {
  20767. var tangentQuadraticBezier = CurveUtils.tangentQuadraticBezier;
  20768. return new Vector2(
  20769. tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ),
  20770. tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y )
  20771. ).normalize();
  20772. };
  20773. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  20774. fromPoints: function ( vectors ) {
  20775. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  20776. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  20777. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  20778. }
  20779. },
  20780. moveTo: function ( x, y ) {
  20781. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  20782. },
  20783. lineTo: function ( x, y ) {
  20784. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  20785. this.curves.push( curve );
  20786. this.currentPoint.set( x, y );
  20787. },
  20788. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  20789. var curve = new QuadraticBezierCurve(
  20790. this.currentPoint.clone(),
  20791. new Vector2( aCPx, aCPy ),
  20792. new Vector2( aX, aY )
  20793. );
  20794. this.curves.push( curve );
  20795. this.currentPoint.set( aX, aY );
  20796. },
  20797. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20798. var curve = new CubicBezierCurve(
  20799. this.currentPoint.clone(),
  20800. new Vector2( aCP1x, aCP1y ),
  20801. new Vector2( aCP2x, aCP2y ),
  20802. new Vector2( aX, aY )
  20803. );
  20804. this.curves.push( curve );
  20805. this.currentPoint.set( aX, aY );
  20806. },
  20807. splineThru: function ( pts /*Array of Vector*/ ) {
  20808. var npts = [ this.currentPoint.clone() ].concat( pts );
  20809. var curve = new SplineCurve( npts );
  20810. this.curves.push( curve );
  20811. this.currentPoint.copy( pts[ pts.length - 1 ] );
  20812. },
  20813. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20814. var x0 = this.currentPoint.x;
  20815. var y0 = this.currentPoint.y;
  20816. this.absarc( aX + x0, aY + y0, aRadius,
  20817. aStartAngle, aEndAngle, aClockwise );
  20818. },
  20819. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20820. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20821. },
  20822. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20823. var x0 = this.currentPoint.x;
  20824. var y0 = this.currentPoint.y;
  20825. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20826. },
  20827. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20828. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20829. if ( this.curves.length > 0 ) {
  20830. // if a previous curve is present, attempt to join
  20831. var firstPoint = curve.getPoint( 0 );
  20832. if ( ! firstPoint.equals( this.currentPoint ) ) {
  20833. this.lineTo( firstPoint.x, firstPoint.y );
  20834. }
  20835. }
  20836. this.curves.push( curve );
  20837. var lastPoint = curve.getPoint( 1 );
  20838. this.currentPoint.copy( lastPoint );
  20839. }
  20840. } );
  20841. /**
  20842. * @author zz85 / http://www.lab4games.net/zz85/blog
  20843. * Defines a 2d shape plane using paths.
  20844. **/
  20845. // STEP 1 Create a path.
  20846. // STEP 2 Turn path into shape.
  20847. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  20848. // STEP 3a - Extract points from each shape, turn to vertices
  20849. // STEP 3b - Triangulate each shape, add faces.
  20850. function Shape() {
  20851. Path.apply( this, arguments );
  20852. this.holes = [];
  20853. }
  20854. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  20855. constructor: Shape,
  20856. getPointsHoles: function ( divisions ) {
  20857. var holesPts = [];
  20858. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  20859. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20860. }
  20861. return holesPts;
  20862. },
  20863. // Get points of shape and holes (keypoints based on segments parameter)
  20864. extractAllPoints: function ( divisions ) {
  20865. return {
  20866. shape: this.getPoints( divisions ),
  20867. holes: this.getPointsHoles( divisions )
  20868. };
  20869. },
  20870. extractPoints: function ( divisions ) {
  20871. return this.extractAllPoints( divisions );
  20872. }
  20873. } );
  20874. /**
  20875. * @author zz85 / http://www.lab4games.net/zz85/blog
  20876. * Creates free form 2d path using series of points, lines or curves.
  20877. *
  20878. **/
  20879. function Path( points ) {
  20880. CurvePath.call( this );
  20881. this.currentPoint = new Vector2();
  20882. if ( points ) {
  20883. this.fromPoints( points );
  20884. }
  20885. }
  20886. Path.prototype = PathPrototype;
  20887. PathPrototype.constructor = Path;
  20888. // minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  20889. function ShapePath() {
  20890. this.subPaths = [];
  20891. this.currentPath = null;
  20892. }
  20893. ShapePath.prototype = {
  20894. moveTo: function ( x, y ) {
  20895. this.currentPath = new Path();
  20896. this.subPaths.push(this.currentPath);
  20897. this.currentPath.moveTo( x, y );
  20898. },
  20899. lineTo: function ( x, y ) {
  20900. this.currentPath.lineTo( x, y );
  20901. },
  20902. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  20903. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  20904. },
  20905. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20906. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  20907. },
  20908. splineThru: function ( pts ) {
  20909. this.currentPath.splineThru( pts );
  20910. },
  20911. toShapes: function ( isCCW, noHoles ) {
  20912. function toShapesNoHoles( inSubpaths ) {
  20913. var shapes = [];
  20914. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  20915. var tmpPath = inSubpaths[ i ];
  20916. var tmpShape = new Shape();
  20917. tmpShape.curves = tmpPath.curves;
  20918. shapes.push( tmpShape );
  20919. }
  20920. return shapes;
  20921. }
  20922. function isPointInsidePolygon( inPt, inPolygon ) {
  20923. var polyLen = inPolygon.length;
  20924. // inPt on polygon contour => immediate success or
  20925. // toggling of inside/outside at every single! intersection point of an edge
  20926. // with the horizontal line through inPt, left of inPt
  20927. // not counting lowerY endpoints of edges and whole edges on that line
  20928. var inside = false;
  20929. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  20930. var edgeLowPt = inPolygon[ p ];
  20931. var edgeHighPt = inPolygon[ q ];
  20932. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  20933. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  20934. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  20935. // not parallel
  20936. if ( edgeDy < 0 ) {
  20937. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  20938. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  20939. }
  20940. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  20941. if ( inPt.y === edgeLowPt.y ) {
  20942. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  20943. // continue; // no intersection or edgeLowPt => doesn't count !!!
  20944. } else {
  20945. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  20946. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  20947. if ( perpEdge < 0 ) continue;
  20948. inside = ! inside; // true intersection left of inPt
  20949. }
  20950. } else {
  20951. // parallel or collinear
  20952. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  20953. // edge lies on the same horizontal line as inPt
  20954. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  20955. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  20956. // continue;
  20957. }
  20958. }
  20959. return inside;
  20960. }
  20961. var isClockWise = ShapeUtils.isClockWise;
  20962. var subPaths = this.subPaths;
  20963. if ( subPaths.length === 0 ) return [];
  20964. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  20965. var solid, tmpPath, tmpShape, shapes = [];
  20966. if ( subPaths.length === 1 ) {
  20967. tmpPath = subPaths[ 0 ];
  20968. tmpShape = new Shape();
  20969. tmpShape.curves = tmpPath.curves;
  20970. shapes.push( tmpShape );
  20971. return shapes;
  20972. }
  20973. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  20974. holesFirst = isCCW ? ! holesFirst : holesFirst;
  20975. // console.log("Holes first", holesFirst);
  20976. var betterShapeHoles = [];
  20977. var newShapes = [];
  20978. var newShapeHoles = [];
  20979. var mainIdx = 0;
  20980. var tmpPoints;
  20981. newShapes[ mainIdx ] = undefined;
  20982. newShapeHoles[ mainIdx ] = [];
  20983. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  20984. tmpPath = subPaths[ i ];
  20985. tmpPoints = tmpPath.getPoints();
  20986. solid = isClockWise( tmpPoints );
  20987. solid = isCCW ? ! solid : solid;
  20988. if ( solid ) {
  20989. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  20990. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  20991. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  20992. if ( holesFirst ) mainIdx ++;
  20993. newShapeHoles[ mainIdx ] = [];
  20994. //console.log('cw', i);
  20995. } else {
  20996. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  20997. //console.log('ccw', i);
  20998. }
  20999. }
  21000. // only Holes? -> probably all Shapes with wrong orientation
  21001. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21002. if ( newShapes.length > 1 ) {
  21003. var ambiguous = false;
  21004. var toChange = [];
  21005. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21006. betterShapeHoles[ sIdx ] = [];
  21007. }
  21008. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21009. var sho = newShapeHoles[ sIdx ];
  21010. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21011. var ho = sho[ hIdx ];
  21012. var hole_unassigned = true;
  21013. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21014. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21015. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  21016. if ( hole_unassigned ) {
  21017. hole_unassigned = false;
  21018. betterShapeHoles[ s2Idx ].push( ho );
  21019. } else {
  21020. ambiguous = true;
  21021. }
  21022. }
  21023. }
  21024. if ( hole_unassigned ) {
  21025. betterShapeHoles[ sIdx ].push( ho );
  21026. }
  21027. }
  21028. }
  21029. // console.log("ambiguous: ", ambiguous);
  21030. if ( toChange.length > 0 ) {
  21031. // console.log("to change: ", toChange);
  21032. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  21033. }
  21034. }
  21035. var tmpHoles;
  21036. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  21037. tmpShape = newShapes[ i ].s;
  21038. shapes.push( tmpShape );
  21039. tmpHoles = newShapeHoles[ i ];
  21040. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21041. tmpShape.holes.push( tmpHoles[ j ].h );
  21042. }
  21043. }
  21044. //console.log("shape", shapes);
  21045. return shapes;
  21046. }
  21047. };
  21048. /**
  21049. * @author zz85 / http://www.lab4games.net/zz85/blog
  21050. * @author mrdoob / http://mrdoob.com/
  21051. */
  21052. function Font( data ) {
  21053. this.data = data;
  21054. }
  21055. Object.assign( Font.prototype, {
  21056. isFont: true,
  21057. generateShapes: function ( text, size, divisions ) {
  21058. function createPaths( text ) {
  21059. var chars = String( text ).split( '' );
  21060. var scale = size / data.resolution;
  21061. var offset = 0;
  21062. var paths = [];
  21063. for ( var i = 0; i < chars.length; i ++ ) {
  21064. var ret = createPath( chars[ i ], scale, offset );
  21065. offset += ret.offset;
  21066. paths.push( ret.path );
  21067. }
  21068. return paths;
  21069. }
  21070. function createPath( c, scale, offset ) {
  21071. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  21072. if ( ! glyph ) return;
  21073. var path = new ShapePath();
  21074. var pts = [], b2 = ShapeUtils.b2, b3 = ShapeUtils.b3;
  21075. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  21076. if ( glyph.o ) {
  21077. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  21078. for ( var i = 0, l = outline.length; i < l; ) {
  21079. var action = outline[ i ++ ];
  21080. switch ( action ) {
  21081. case 'm': // moveTo
  21082. x = outline[ i ++ ] * scale + offset;
  21083. y = outline[ i ++ ] * scale;
  21084. path.moveTo( x, y );
  21085. break;
  21086. case 'l': // lineTo
  21087. x = outline[ i ++ ] * scale + offset;
  21088. y = outline[ i ++ ] * scale;
  21089. path.lineTo( x, y );
  21090. break;
  21091. case 'q': // quadraticCurveTo
  21092. cpx = outline[ i ++ ] * scale + offset;
  21093. cpy = outline[ i ++ ] * scale;
  21094. cpx1 = outline[ i ++ ] * scale + offset;
  21095. cpy1 = outline[ i ++ ] * scale;
  21096. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  21097. laste = pts[ pts.length - 1 ];
  21098. if ( laste ) {
  21099. cpx0 = laste.x;
  21100. cpy0 = laste.y;
  21101. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21102. var t = i2 / divisions;
  21103. b2( t, cpx0, cpx1, cpx );
  21104. b2( t, cpy0, cpy1, cpy );
  21105. }
  21106. }
  21107. break;
  21108. case 'b': // bezierCurveTo
  21109. cpx = outline[ i ++ ] * scale + offset;
  21110. cpy = outline[ i ++ ] * scale;
  21111. cpx1 = outline[ i ++ ] * scale + offset;
  21112. cpy1 = outline[ i ++ ] * scale;
  21113. cpx2 = outline[ i ++ ] * scale + offset;
  21114. cpy2 = outline[ i ++ ] * scale;
  21115. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  21116. laste = pts[ pts.length - 1 ];
  21117. if ( laste ) {
  21118. cpx0 = laste.x;
  21119. cpy0 = laste.y;
  21120. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21121. var t = i2 / divisions;
  21122. b3( t, cpx0, cpx1, cpx2, cpx );
  21123. b3( t, cpy0, cpy1, cpy2, cpy );
  21124. }
  21125. }
  21126. break;
  21127. }
  21128. }
  21129. }
  21130. return { offset: glyph.ha * scale, path: path };
  21131. }
  21132. //
  21133. if ( size === undefined ) size = 100;
  21134. if ( divisions === undefined ) divisions = 4;
  21135. var data = this.data;
  21136. var paths = createPaths( text );
  21137. var shapes = [];
  21138. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  21139. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  21140. }
  21141. return shapes;
  21142. }
  21143. } );
  21144. /**
  21145. * @author mrdoob / http://mrdoob.com/
  21146. */
  21147. function FontLoader( manager ) {
  21148. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21149. }
  21150. Object.assign( FontLoader.prototype, {
  21151. load: function ( url, onLoad, onProgress, onError ) {
  21152. var scope = this;
  21153. var loader = new FileLoader( this.manager );
  21154. loader.load( url, function ( text ) {
  21155. var json;
  21156. try {
  21157. json = JSON.parse( text );
  21158. } catch ( e ) {
  21159. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  21160. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  21161. }
  21162. var font = scope.parse( json );
  21163. if ( onLoad ) onLoad( font );
  21164. }, onProgress, onError );
  21165. },
  21166. parse: function ( json ) {
  21167. return new Font( json );
  21168. }
  21169. } );
  21170. var context;
  21171. var AudioContext = {
  21172. getContext: function () {
  21173. if ( context === undefined ) {
  21174. context = new ( window.AudioContext || window.webkitAudioContext )();
  21175. }
  21176. return context;
  21177. },
  21178. setContext: function ( value ) {
  21179. context = value;
  21180. }
  21181. };
  21182. /**
  21183. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21184. */
  21185. function AudioLoader( manager ) {
  21186. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21187. }
  21188. Object.assign( AudioLoader.prototype, {
  21189. load: function ( url, onLoad, onProgress, onError ) {
  21190. var loader = new FileLoader( this.manager );
  21191. loader.setResponseType( 'arraybuffer' );
  21192. loader.load( url, function ( buffer ) {
  21193. var context = AudioContext.getContext();
  21194. context.decodeAudioData( buffer, function ( audioBuffer ) {
  21195. onLoad( audioBuffer );
  21196. } );
  21197. }, onProgress, onError );
  21198. }
  21199. } );
  21200. /**
  21201. * @author abelnation / http://github.com/abelnation
  21202. */
  21203. function RectAreaLight ( color, intensity, width, height ) {
  21204. Light.call( this, color, intensity );
  21205. this.type = 'RectAreaLight';
  21206. this.position.set( 0, 1, 0 );
  21207. this.updateMatrix();
  21208. this.width = ( width !== undefined ) ? width : 10;
  21209. this.height = ( height !== undefined ) ? height : 10;
  21210. // TODO (abelnation): distance/decay
  21211. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  21212. // TODO (abelnation): shadows
  21213. // this.shadow = new THREE.RectAreaLightShadow( new THREE.PerspectiveCamera( 90, 1, 0.5, 500 ) );
  21214. }
  21215. // TODO (abelnation): RectAreaLight update when light shape is changed
  21216. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  21217. constructor: RectAreaLight,
  21218. isRectAreaLight: true,
  21219. copy: function ( source ) {
  21220. Light.prototype.copy.call( this, source );
  21221. this.width = source.width;
  21222. this.height = source.height;
  21223. // this.shadow = source.shadow.clone();
  21224. return this;
  21225. }
  21226. } );
  21227. /**
  21228. * @author mrdoob / http://mrdoob.com/
  21229. */
  21230. function StereoCamera() {
  21231. this.type = 'StereoCamera';
  21232. this.aspect = 1;
  21233. this.eyeSep = 0.064;
  21234. this.cameraL = new PerspectiveCamera();
  21235. this.cameraL.layers.enable( 1 );
  21236. this.cameraL.matrixAutoUpdate = false;
  21237. this.cameraR = new PerspectiveCamera();
  21238. this.cameraR.layers.enable( 2 );
  21239. this.cameraR.matrixAutoUpdate = false;
  21240. }
  21241. Object.assign( StereoCamera.prototype, {
  21242. update: ( function () {
  21243. var instance, focus, fov, aspect, near, far, zoom;
  21244. var eyeRight = new Matrix4();
  21245. var eyeLeft = new Matrix4();
  21246. return function update( camera ) {
  21247. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  21248. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  21249. far !== camera.far || zoom !== camera.zoom;
  21250. if ( needsUpdate ) {
  21251. instance = this;
  21252. focus = camera.focus;
  21253. fov = camera.fov;
  21254. aspect = camera.aspect * this.aspect;
  21255. near = camera.near;
  21256. far = camera.far;
  21257. zoom = camera.zoom;
  21258. // Off-axis stereoscopic effect based on
  21259. // http://paulbourke.net/stereographics/stereorender/
  21260. var projectionMatrix = camera.projectionMatrix.clone();
  21261. var eyeSep = this.eyeSep / 2;
  21262. var eyeSepOnProjection = eyeSep * near / focus;
  21263. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  21264. var xmin, xmax;
  21265. // translate xOffset
  21266. eyeLeft.elements[ 12 ] = - eyeSep;
  21267. eyeRight.elements[ 12 ] = eyeSep;
  21268. // for left eye
  21269. xmin = - ymax * aspect + eyeSepOnProjection;
  21270. xmax = ymax * aspect + eyeSepOnProjection;
  21271. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21272. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21273. this.cameraL.projectionMatrix.copy( projectionMatrix );
  21274. // for right eye
  21275. xmin = - ymax * aspect - eyeSepOnProjection;
  21276. xmax = ymax * aspect - eyeSepOnProjection;
  21277. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21278. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21279. this.cameraR.projectionMatrix.copy( projectionMatrix );
  21280. }
  21281. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  21282. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  21283. };
  21284. } )()
  21285. } );
  21286. /**
  21287. * Camera for rendering cube maps
  21288. * - renders scene into axis-aligned cube
  21289. *
  21290. * @author alteredq / http://alteredqualia.com/
  21291. */
  21292. function CubeCamera( near, far, cubeResolution ) {
  21293. Object3D.call( this );
  21294. this.type = 'CubeCamera';
  21295. var fov = 90, aspect = 1;
  21296. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  21297. cameraPX.up.set( 0, - 1, 0 );
  21298. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  21299. this.add( cameraPX );
  21300. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  21301. cameraNX.up.set( 0, - 1, 0 );
  21302. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  21303. this.add( cameraNX );
  21304. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  21305. cameraPY.up.set( 0, 0, 1 );
  21306. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  21307. this.add( cameraPY );
  21308. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  21309. cameraNY.up.set( 0, 0, - 1 );
  21310. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  21311. this.add( cameraNY );
  21312. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  21313. cameraPZ.up.set( 0, - 1, 0 );
  21314. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  21315. this.add( cameraPZ );
  21316. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  21317. cameraNZ.up.set( 0, - 1, 0 );
  21318. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  21319. this.add( cameraNZ );
  21320. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  21321. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  21322. this.updateCubeMap = function ( renderer, scene ) {
  21323. if ( this.parent === null ) this.updateMatrixWorld();
  21324. var renderTarget = this.renderTarget;
  21325. var generateMipmaps = renderTarget.texture.generateMipmaps;
  21326. renderTarget.texture.generateMipmaps = false;
  21327. renderTarget.activeCubeFace = 0;
  21328. renderer.render( scene, cameraPX, renderTarget );
  21329. renderTarget.activeCubeFace = 1;
  21330. renderer.render( scene, cameraNX, renderTarget );
  21331. renderTarget.activeCubeFace = 2;
  21332. renderer.render( scene, cameraPY, renderTarget );
  21333. renderTarget.activeCubeFace = 3;
  21334. renderer.render( scene, cameraNY, renderTarget );
  21335. renderTarget.activeCubeFace = 4;
  21336. renderer.render( scene, cameraPZ, renderTarget );
  21337. renderTarget.texture.generateMipmaps = generateMipmaps;
  21338. renderTarget.activeCubeFace = 5;
  21339. renderer.render( scene, cameraNZ, renderTarget );
  21340. renderer.setRenderTarget( null );
  21341. };
  21342. }
  21343. CubeCamera.prototype = Object.create( Object3D.prototype );
  21344. CubeCamera.prototype.constructor = CubeCamera;
  21345. /**
  21346. * @author mrdoob / http://mrdoob.com/
  21347. */
  21348. function AudioListener() {
  21349. Object3D.call( this );
  21350. this.type = 'AudioListener';
  21351. this.context = AudioContext.getContext();
  21352. this.gain = this.context.createGain();
  21353. this.gain.connect( this.context.destination );
  21354. this.filter = null;
  21355. }
  21356. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21357. constructor: AudioListener,
  21358. getInput: function () {
  21359. return this.gain;
  21360. },
  21361. removeFilter: function ( ) {
  21362. if ( this.filter !== null ) {
  21363. this.gain.disconnect( this.filter );
  21364. this.filter.disconnect( this.context.destination );
  21365. this.gain.connect( this.context.destination );
  21366. this.filter = null;
  21367. }
  21368. },
  21369. getFilter: function () {
  21370. return this.filter;
  21371. },
  21372. setFilter: function ( value ) {
  21373. if ( this.filter !== null ) {
  21374. this.gain.disconnect( this.filter );
  21375. this.filter.disconnect( this.context.destination );
  21376. } else {
  21377. this.gain.disconnect( this.context.destination );
  21378. }
  21379. this.filter = value;
  21380. this.gain.connect( this.filter );
  21381. this.filter.connect( this.context.destination );
  21382. },
  21383. getMasterVolume: function () {
  21384. return this.gain.gain.value;
  21385. },
  21386. setMasterVolume: function ( value ) {
  21387. this.gain.gain.value = value;
  21388. },
  21389. updateMatrixWorld: ( function () {
  21390. var position = new Vector3();
  21391. var quaternion = new Quaternion();
  21392. var scale = new Vector3();
  21393. var orientation = new Vector3();
  21394. return function updateMatrixWorld( force ) {
  21395. Object3D.prototype.updateMatrixWorld.call( this, force );
  21396. var listener = this.context.listener;
  21397. var up = this.up;
  21398. this.matrixWorld.decompose( position, quaternion, scale );
  21399. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  21400. if ( listener.positionX ) {
  21401. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  21402. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  21403. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  21404. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  21405. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  21406. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  21407. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  21408. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  21409. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  21410. } else {
  21411. listener.setPosition( position.x, position.y, position.z );
  21412. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  21413. }
  21414. };
  21415. } )()
  21416. } );
  21417. /**
  21418. * @author mrdoob / http://mrdoob.com/
  21419. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21420. */
  21421. function Audio( listener ) {
  21422. Object3D.call( this );
  21423. this.type = 'Audio';
  21424. this.context = listener.context;
  21425. this.gain = this.context.createGain();
  21426. this.gain.connect( listener.getInput() );
  21427. this.autoplay = false;
  21428. this.buffer = null;
  21429. this.loop = false;
  21430. this.startTime = 0;
  21431. this.playbackRate = 1;
  21432. this.isPlaying = false;
  21433. this.hasPlaybackControl = true;
  21434. this.sourceType = 'empty';
  21435. this.filters = [];
  21436. }
  21437. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21438. constructor: Audio,
  21439. getOutput: function () {
  21440. return this.gain;
  21441. },
  21442. setNodeSource: function ( audioNode ) {
  21443. this.hasPlaybackControl = false;
  21444. this.sourceType = 'audioNode';
  21445. this.source = audioNode;
  21446. this.connect();
  21447. return this;
  21448. },
  21449. setBuffer: function ( audioBuffer ) {
  21450. this.buffer = audioBuffer;
  21451. this.sourceType = 'buffer';
  21452. if ( this.autoplay ) this.play();
  21453. return this;
  21454. },
  21455. play: function () {
  21456. if ( this.isPlaying === true ) {
  21457. console.warn( 'THREE.Audio: Audio is already playing.' );
  21458. return;
  21459. }
  21460. if ( this.hasPlaybackControl === false ) {
  21461. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21462. return;
  21463. }
  21464. var source = this.context.createBufferSource();
  21465. source.buffer = this.buffer;
  21466. source.loop = this.loop;
  21467. source.onended = this.onEnded.bind( this );
  21468. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  21469. source.start( 0, this.startTime );
  21470. this.isPlaying = true;
  21471. this.source = source;
  21472. return this.connect();
  21473. },
  21474. pause: function () {
  21475. if ( this.hasPlaybackControl === false ) {
  21476. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21477. return;
  21478. }
  21479. this.source.stop();
  21480. this.startTime = this.context.currentTime;
  21481. this.isPlaying = false;
  21482. return this;
  21483. },
  21484. stop: function () {
  21485. if ( this.hasPlaybackControl === false ) {
  21486. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21487. return;
  21488. }
  21489. this.source.stop();
  21490. this.startTime = 0;
  21491. this.isPlaying = false;
  21492. return this;
  21493. },
  21494. connect: function () {
  21495. if ( this.filters.length > 0 ) {
  21496. this.source.connect( this.filters[ 0 ] );
  21497. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21498. this.filters[ i - 1 ].connect( this.filters[ i ] );
  21499. }
  21500. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  21501. } else {
  21502. this.source.connect( this.getOutput() );
  21503. }
  21504. return this;
  21505. },
  21506. disconnect: function () {
  21507. if ( this.filters.length > 0 ) {
  21508. this.source.disconnect( this.filters[ 0 ] );
  21509. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21510. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  21511. }
  21512. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  21513. } else {
  21514. this.source.disconnect( this.getOutput() );
  21515. }
  21516. return this;
  21517. },
  21518. getFilters: function () {
  21519. return this.filters;
  21520. },
  21521. setFilters: function ( value ) {
  21522. if ( ! value ) value = [];
  21523. if ( this.isPlaying === true ) {
  21524. this.disconnect();
  21525. this.filters = value;
  21526. this.connect();
  21527. } else {
  21528. this.filters = value;
  21529. }
  21530. return this;
  21531. },
  21532. getFilter: function () {
  21533. return this.getFilters()[ 0 ];
  21534. },
  21535. setFilter: function ( filter ) {
  21536. return this.setFilters( filter ? [ filter ] : [] );
  21537. },
  21538. setPlaybackRate: function ( value ) {
  21539. if ( this.hasPlaybackControl === false ) {
  21540. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21541. return;
  21542. }
  21543. this.playbackRate = value;
  21544. if ( this.isPlaying === true ) {
  21545. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  21546. }
  21547. return this;
  21548. },
  21549. getPlaybackRate: function () {
  21550. return this.playbackRate;
  21551. },
  21552. onEnded: function () {
  21553. this.isPlaying = false;
  21554. },
  21555. getLoop: function () {
  21556. if ( this.hasPlaybackControl === false ) {
  21557. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21558. return false;
  21559. }
  21560. return this.loop;
  21561. },
  21562. setLoop: function ( value ) {
  21563. if ( this.hasPlaybackControl === false ) {
  21564. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21565. return;
  21566. }
  21567. this.loop = value;
  21568. if ( this.isPlaying === true ) {
  21569. this.source.loop = this.loop;
  21570. }
  21571. return this;
  21572. },
  21573. getVolume: function () {
  21574. return this.gain.gain.value;
  21575. },
  21576. setVolume: function ( value ) {
  21577. this.gain.gain.value = value;
  21578. return this;
  21579. }
  21580. } );
  21581. /**
  21582. * @author mrdoob / http://mrdoob.com/
  21583. */
  21584. function PositionalAudio( listener ) {
  21585. Audio.call( this, listener );
  21586. this.panner = this.context.createPanner();
  21587. this.panner.connect( this.gain );
  21588. }
  21589. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  21590. constructor: PositionalAudio,
  21591. getOutput: function () {
  21592. return this.panner;
  21593. },
  21594. getRefDistance: function () {
  21595. return this.panner.refDistance;
  21596. },
  21597. setRefDistance: function ( value ) {
  21598. this.panner.refDistance = value;
  21599. },
  21600. getRolloffFactor: function () {
  21601. return this.panner.rolloffFactor;
  21602. },
  21603. setRolloffFactor: function ( value ) {
  21604. this.panner.rolloffFactor = value;
  21605. },
  21606. getDistanceModel: function () {
  21607. return this.panner.distanceModel;
  21608. },
  21609. setDistanceModel: function ( value ) {
  21610. this.panner.distanceModel = value;
  21611. },
  21612. getMaxDistance: function () {
  21613. return this.panner.maxDistance;
  21614. },
  21615. setMaxDistance: function ( value ) {
  21616. this.panner.maxDistance = value;
  21617. },
  21618. updateMatrixWorld: ( function () {
  21619. var position = new Vector3();
  21620. return function updateMatrixWorld( force ) {
  21621. Object3D.prototype.updateMatrixWorld.call( this, force );
  21622. position.setFromMatrixPosition( this.matrixWorld );
  21623. this.panner.setPosition( position.x, position.y, position.z );
  21624. };
  21625. } )()
  21626. } );
  21627. /**
  21628. * @author mrdoob / http://mrdoob.com/
  21629. */
  21630. function AudioAnalyser( audio, fftSize ) {
  21631. this.analyser = audio.context.createAnalyser();
  21632. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  21633. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  21634. audio.getOutput().connect( this.analyser );
  21635. }
  21636. Object.assign( AudioAnalyser.prototype, {
  21637. getFrequencyData: function () {
  21638. this.analyser.getByteFrequencyData( this.data );
  21639. return this.data;
  21640. },
  21641. getAverageFrequency: function () {
  21642. var value = 0, data = this.getFrequencyData();
  21643. for ( var i = 0; i < data.length; i ++ ) {
  21644. value += data[ i ];
  21645. }
  21646. return value / data.length;
  21647. }
  21648. } );
  21649. /**
  21650. *
  21651. * Buffered scene graph property that allows weighted accumulation.
  21652. *
  21653. *
  21654. * @author Ben Houston / http://clara.io/
  21655. * @author David Sarno / http://lighthaus.us/
  21656. * @author tschw
  21657. */
  21658. function PropertyMixer( binding, typeName, valueSize ) {
  21659. this.binding = binding;
  21660. this.valueSize = valueSize;
  21661. var bufferType = Float64Array,
  21662. mixFunction;
  21663. switch ( typeName ) {
  21664. case 'quaternion': mixFunction = this._slerp; break;
  21665. case 'string':
  21666. case 'bool':
  21667. bufferType = Array, mixFunction = this._select; break;
  21668. default: mixFunction = this._lerp;
  21669. }
  21670. this.buffer = new bufferType( valueSize * 4 );
  21671. // layout: [ incoming | accu0 | accu1 | orig ]
  21672. //
  21673. // interpolators can use .buffer as their .result
  21674. // the data then goes to 'incoming'
  21675. //
  21676. // 'accu0' and 'accu1' are used frame-interleaved for
  21677. // the cumulative result and are compared to detect
  21678. // changes
  21679. //
  21680. // 'orig' stores the original state of the property
  21681. this._mixBufferRegion = mixFunction;
  21682. this.cumulativeWeight = 0;
  21683. this.useCount = 0;
  21684. this.referenceCount = 0;
  21685. }
  21686. PropertyMixer.prototype = {
  21687. constructor: PropertyMixer,
  21688. // accumulate data in the 'incoming' region into 'accu<i>'
  21689. accumulate: function( accuIndex, weight ) {
  21690. // note: happily accumulating nothing when weight = 0, the caller knows
  21691. // the weight and shouldn't have made the call in the first place
  21692. var buffer = this.buffer,
  21693. stride = this.valueSize,
  21694. offset = accuIndex * stride + stride,
  21695. currentWeight = this.cumulativeWeight;
  21696. if ( currentWeight === 0 ) {
  21697. // accuN := incoming * weight
  21698. for ( var i = 0; i !== stride; ++ i ) {
  21699. buffer[ offset + i ] = buffer[ i ];
  21700. }
  21701. currentWeight = weight;
  21702. } else {
  21703. // accuN := accuN + incoming * weight
  21704. currentWeight += weight;
  21705. var mix = weight / currentWeight;
  21706. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  21707. }
  21708. this.cumulativeWeight = currentWeight;
  21709. },
  21710. // apply the state of 'accu<i>' to the binding when accus differ
  21711. apply: function( accuIndex ) {
  21712. var stride = this.valueSize,
  21713. buffer = this.buffer,
  21714. offset = accuIndex * stride + stride,
  21715. weight = this.cumulativeWeight,
  21716. binding = this.binding;
  21717. this.cumulativeWeight = 0;
  21718. if ( weight < 1 ) {
  21719. // accuN := accuN + original * ( 1 - cumulativeWeight )
  21720. var originalValueOffset = stride * 3;
  21721. this._mixBufferRegion(
  21722. buffer, offset, originalValueOffset, 1 - weight, stride );
  21723. }
  21724. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  21725. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  21726. // value has changed -> update scene graph
  21727. binding.setValue( buffer, offset );
  21728. break;
  21729. }
  21730. }
  21731. },
  21732. // remember the state of the bound property and copy it to both accus
  21733. saveOriginalState: function() {
  21734. var binding = this.binding;
  21735. var buffer = this.buffer,
  21736. stride = this.valueSize,
  21737. originalValueOffset = stride * 3;
  21738. binding.getValue( buffer, originalValueOffset );
  21739. // accu[0..1] := orig -- initially detect changes against the original
  21740. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  21741. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  21742. }
  21743. this.cumulativeWeight = 0;
  21744. },
  21745. // apply the state previously taken via 'saveOriginalState' to the binding
  21746. restoreOriginalState: function() {
  21747. var originalValueOffset = this.valueSize * 3;
  21748. this.binding.setValue( this.buffer, originalValueOffset );
  21749. },
  21750. // mix functions
  21751. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  21752. if ( t >= 0.5 ) {
  21753. for ( var i = 0; i !== stride; ++ i ) {
  21754. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  21755. }
  21756. }
  21757. },
  21758. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  21759. Quaternion.slerpFlat( buffer, dstOffset,
  21760. buffer, dstOffset, buffer, srcOffset, t );
  21761. },
  21762. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  21763. var s = 1 - t;
  21764. for ( var i = 0; i !== stride; ++ i ) {
  21765. var j = dstOffset + i;
  21766. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  21767. }
  21768. }
  21769. };
  21770. /**
  21771. *
  21772. * A reference to a real property in the scene graph.
  21773. *
  21774. *
  21775. * @author Ben Houston / http://clara.io/
  21776. * @author David Sarno / http://lighthaus.us/
  21777. * @author tschw
  21778. */
  21779. function PropertyBinding( rootNode, path, parsedPath ) {
  21780. this.path = path;
  21781. this.parsedPath = parsedPath ||
  21782. PropertyBinding.parseTrackName( path );
  21783. this.node = PropertyBinding.findNode(
  21784. rootNode, this.parsedPath.nodeName ) || rootNode;
  21785. this.rootNode = rootNode;
  21786. }
  21787. PropertyBinding.prototype = {
  21788. constructor: PropertyBinding,
  21789. getValue: function getValue_unbound( targetArray, offset ) {
  21790. this.bind();
  21791. this.getValue( targetArray, offset );
  21792. // Note: This class uses a State pattern on a per-method basis:
  21793. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  21794. // prototype version of these methods with one that represents
  21795. // the bound state. When the property is not found, the methods
  21796. // become no-ops.
  21797. },
  21798. setValue: function getValue_unbound( sourceArray, offset ) {
  21799. this.bind();
  21800. this.setValue( sourceArray, offset );
  21801. },
  21802. // create getter / setter pair for a property in the scene graph
  21803. bind: function() {
  21804. var targetObject = this.node,
  21805. parsedPath = this.parsedPath,
  21806. objectName = parsedPath.objectName,
  21807. propertyName = parsedPath.propertyName,
  21808. propertyIndex = parsedPath.propertyIndex;
  21809. if ( ! targetObject ) {
  21810. targetObject = PropertyBinding.findNode(
  21811. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  21812. this.node = targetObject;
  21813. }
  21814. // set fail state so we can just 'return' on error
  21815. this.getValue = this._getValue_unavailable;
  21816. this.setValue = this._setValue_unavailable;
  21817. // ensure there is a value node
  21818. if ( ! targetObject ) {
  21819. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  21820. return;
  21821. }
  21822. if ( objectName ) {
  21823. var objectIndex = parsedPath.objectIndex;
  21824. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  21825. switch ( objectName ) {
  21826. case 'materials':
  21827. if ( ! targetObject.material ) {
  21828. console.error( ' can not bind to material as node does not have a material', this );
  21829. return;
  21830. }
  21831. if ( ! targetObject.material.materials ) {
  21832. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  21833. return;
  21834. }
  21835. targetObject = targetObject.material.materials;
  21836. break;
  21837. case 'bones':
  21838. if ( ! targetObject.skeleton ) {
  21839. console.error( ' can not bind to bones as node does not have a skeleton', this );
  21840. return;
  21841. }
  21842. // potential future optimization: skip this if propertyIndex is already an integer
  21843. // and convert the integer string to a true integer.
  21844. targetObject = targetObject.skeleton.bones;
  21845. // support resolving morphTarget names into indices.
  21846. for ( var i = 0; i < targetObject.length; i ++ ) {
  21847. if ( targetObject[ i ].name === objectIndex ) {
  21848. objectIndex = i;
  21849. break;
  21850. }
  21851. }
  21852. break;
  21853. default:
  21854. if ( targetObject[ objectName ] === undefined ) {
  21855. console.error( ' can not bind to objectName of node, undefined', this );
  21856. return;
  21857. }
  21858. targetObject = targetObject[ objectName ];
  21859. }
  21860. if ( objectIndex !== undefined ) {
  21861. if ( targetObject[ objectIndex ] === undefined ) {
  21862. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  21863. return;
  21864. }
  21865. targetObject = targetObject[ objectIndex ];
  21866. }
  21867. }
  21868. // resolve property
  21869. var nodeProperty = targetObject[ propertyName ];
  21870. if ( nodeProperty === undefined ) {
  21871. var nodeName = parsedPath.nodeName;
  21872. console.error( " trying to update property for track: " + nodeName +
  21873. '.' + propertyName + " but it wasn't found.", targetObject );
  21874. return;
  21875. }
  21876. // determine versioning scheme
  21877. var versioning = this.Versioning.None;
  21878. if ( targetObject.needsUpdate !== undefined ) { // material
  21879. versioning = this.Versioning.NeedsUpdate;
  21880. this.targetObject = targetObject;
  21881. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  21882. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  21883. this.targetObject = targetObject;
  21884. }
  21885. // determine how the property gets bound
  21886. var bindingType = this.BindingType.Direct;
  21887. if ( propertyIndex !== undefined ) {
  21888. // access a sub element of the property array (only primitives are supported right now)
  21889. if ( propertyName === "morphTargetInfluences" ) {
  21890. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  21891. // support resolving morphTarget names into indices.
  21892. if ( ! targetObject.geometry ) {
  21893. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  21894. return;
  21895. }
  21896. if ( ! targetObject.geometry.morphTargets ) {
  21897. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  21898. return;
  21899. }
  21900. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  21901. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  21902. propertyIndex = i;
  21903. break;
  21904. }
  21905. }
  21906. }
  21907. bindingType = this.BindingType.ArrayElement;
  21908. this.resolvedProperty = nodeProperty;
  21909. this.propertyIndex = propertyIndex;
  21910. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  21911. // must use copy for Object3D.Euler/Quaternion
  21912. bindingType = this.BindingType.HasFromToArray;
  21913. this.resolvedProperty = nodeProperty;
  21914. } else if ( nodeProperty.length !== undefined ) {
  21915. bindingType = this.BindingType.EntireArray;
  21916. this.resolvedProperty = nodeProperty;
  21917. } else {
  21918. this.propertyName = propertyName;
  21919. }
  21920. // select getter / setter
  21921. this.getValue = this.GetterByBindingType[ bindingType ];
  21922. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  21923. },
  21924. unbind: function() {
  21925. this.node = null;
  21926. // back to the prototype version of getValue / setValue
  21927. // note: avoiding to mutate the shape of 'this' via 'delete'
  21928. this.getValue = this._getValue_unbound;
  21929. this.setValue = this._setValue_unbound;
  21930. }
  21931. };
  21932. Object.assign( PropertyBinding.prototype, { // prototype, continued
  21933. // these are used to "bind" a nonexistent property
  21934. _getValue_unavailable: function() {},
  21935. _setValue_unavailable: function() {},
  21936. // initial state of these methods that calls 'bind'
  21937. _getValue_unbound: PropertyBinding.prototype.getValue,
  21938. _setValue_unbound: PropertyBinding.prototype.setValue,
  21939. BindingType: {
  21940. Direct: 0,
  21941. EntireArray: 1,
  21942. ArrayElement: 2,
  21943. HasFromToArray: 3
  21944. },
  21945. Versioning: {
  21946. None: 0,
  21947. NeedsUpdate: 1,
  21948. MatrixWorldNeedsUpdate: 2
  21949. },
  21950. GetterByBindingType: [
  21951. function getValue_direct( buffer, offset ) {
  21952. buffer[ offset ] = this.node[ this.propertyName ];
  21953. },
  21954. function getValue_array( buffer, offset ) {
  21955. var source = this.resolvedProperty;
  21956. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  21957. buffer[ offset ++ ] = source[ i ];
  21958. }
  21959. },
  21960. function getValue_arrayElement( buffer, offset ) {
  21961. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  21962. },
  21963. function getValue_toArray( buffer, offset ) {
  21964. this.resolvedProperty.toArray( buffer, offset );
  21965. }
  21966. ],
  21967. SetterByBindingTypeAndVersioning: [
  21968. [
  21969. // Direct
  21970. function setValue_direct( buffer, offset ) {
  21971. this.node[ this.propertyName ] = buffer[ offset ];
  21972. },
  21973. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  21974. this.node[ this.propertyName ] = buffer[ offset ];
  21975. this.targetObject.needsUpdate = true;
  21976. },
  21977. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  21978. this.node[ this.propertyName ] = buffer[ offset ];
  21979. this.targetObject.matrixWorldNeedsUpdate = true;
  21980. }
  21981. ], [
  21982. // EntireArray
  21983. function setValue_array( buffer, offset ) {
  21984. var dest = this.resolvedProperty;
  21985. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  21986. dest[ i ] = buffer[ offset ++ ];
  21987. }
  21988. },
  21989. function setValue_array_setNeedsUpdate( buffer, offset ) {
  21990. var dest = this.resolvedProperty;
  21991. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  21992. dest[ i ] = buffer[ offset ++ ];
  21993. }
  21994. this.targetObject.needsUpdate = true;
  21995. },
  21996. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  21997. var dest = this.resolvedProperty;
  21998. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  21999. dest[ i ] = buffer[ offset ++ ];
  22000. }
  22001. this.targetObject.matrixWorldNeedsUpdate = true;
  22002. }
  22003. ], [
  22004. // ArrayElement
  22005. function setValue_arrayElement( buffer, offset ) {
  22006. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22007. },
  22008. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  22009. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22010. this.targetObject.needsUpdate = true;
  22011. },
  22012. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22013. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22014. this.targetObject.matrixWorldNeedsUpdate = true;
  22015. }
  22016. ], [
  22017. // HasToFromArray
  22018. function setValue_fromArray( buffer, offset ) {
  22019. this.resolvedProperty.fromArray( buffer, offset );
  22020. },
  22021. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  22022. this.resolvedProperty.fromArray( buffer, offset );
  22023. this.targetObject.needsUpdate = true;
  22024. },
  22025. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22026. this.resolvedProperty.fromArray( buffer, offset );
  22027. this.targetObject.matrixWorldNeedsUpdate = true;
  22028. }
  22029. ]
  22030. ]
  22031. } );
  22032. PropertyBinding.Composite =
  22033. function( targetGroup, path, optionalParsedPath ) {
  22034. var parsedPath = optionalParsedPath ||
  22035. PropertyBinding.parseTrackName( path );
  22036. this._targetGroup = targetGroup;
  22037. this._bindings = targetGroup.subscribe_( path, parsedPath );
  22038. };
  22039. PropertyBinding.Composite.prototype = {
  22040. constructor: PropertyBinding.Composite,
  22041. getValue: function( array, offset ) {
  22042. this.bind(); // bind all binding
  22043. var firstValidIndex = this._targetGroup.nCachedObjects_,
  22044. binding = this._bindings[ firstValidIndex ];
  22045. // and only call .getValue on the first
  22046. if ( binding !== undefined ) binding.getValue( array, offset );
  22047. },
  22048. setValue: function( array, offset ) {
  22049. var bindings = this._bindings;
  22050. for ( var i = this._targetGroup.nCachedObjects_,
  22051. n = bindings.length; i !== n; ++ i ) {
  22052. bindings[ i ].setValue( array, offset );
  22053. }
  22054. },
  22055. bind: function() {
  22056. var bindings = this._bindings;
  22057. for ( var i = this._targetGroup.nCachedObjects_,
  22058. n = bindings.length; i !== n; ++ i ) {
  22059. bindings[ i ].bind();
  22060. }
  22061. },
  22062. unbind: function() {
  22063. var bindings = this._bindings;
  22064. for ( var i = this._targetGroup.nCachedObjects_,
  22065. n = bindings.length; i !== n; ++ i ) {
  22066. bindings[ i ].unbind();
  22067. }
  22068. }
  22069. };
  22070. PropertyBinding.create = function( root, path, parsedPath ) {
  22071. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  22072. return new PropertyBinding( root, path, parsedPath );
  22073. } else {
  22074. return new PropertyBinding.Composite( root, path, parsedPath );
  22075. }
  22076. };
  22077. PropertyBinding.parseTrackName = function( trackName ) {
  22078. // matches strings in the form of:
  22079. // nodeName.property
  22080. // nodeName.property[accessor]
  22081. // nodeName.material.property[accessor]
  22082. // uuid.property[accessor]
  22083. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  22084. // parentName/nodeName.property
  22085. // parentName/parentName/nodeName.property[index]
  22086. // .bone[Armature.DEF_cog].position
  22087. // scene:helium_balloon_model:helium_balloon_model.position
  22088. // created and tested via https://regex101.com/#javascript
  22089. var re = /^((?:\w+[\/:])*)(\w+)?(?:\.(\w+)(?:\[(.+)\])?)?\.(\w+)(?:\[(.+)\])?$/;
  22090. var matches = re.exec( trackName );
  22091. if ( ! matches ) {
  22092. throw new Error( "cannot parse trackName at all: " + trackName );
  22093. }
  22094. var results = {
  22095. // directoryName: matches[ 1 ], // (tschw) currently unused
  22096. nodeName: matches[ 2 ], // allowed to be null, specified root node.
  22097. objectName: matches[ 3 ],
  22098. objectIndex: matches[ 4 ],
  22099. propertyName: matches[ 5 ],
  22100. propertyIndex: matches[ 6 ] // allowed to be null, specifies that the whole property is set.
  22101. };
  22102. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  22103. throw new Error( "can not parse propertyName from trackName: " + trackName );
  22104. }
  22105. return results;
  22106. };
  22107. PropertyBinding.findNode = function( root, nodeName ) {
  22108. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  22109. return root;
  22110. }
  22111. // search into skeleton bones.
  22112. if ( root.skeleton ) {
  22113. var searchSkeleton = function( skeleton ) {
  22114. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  22115. var bone = skeleton.bones[ i ];
  22116. if ( bone.name === nodeName ) {
  22117. return bone;
  22118. }
  22119. }
  22120. return null;
  22121. };
  22122. var bone = searchSkeleton( root.skeleton );
  22123. if ( bone ) {
  22124. return bone;
  22125. }
  22126. }
  22127. // search into node subtree.
  22128. if ( root.children ) {
  22129. var searchNodeSubtree = function( children ) {
  22130. for( var i = 0; i < children.length; i ++ ) {
  22131. var childNode = children[ i ];
  22132. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  22133. return childNode;
  22134. }
  22135. var result = searchNodeSubtree( childNode.children );
  22136. if ( result ) return result;
  22137. }
  22138. return null;
  22139. };
  22140. var subTreeNode = searchNodeSubtree( root.children );
  22141. if ( subTreeNode ) {
  22142. return subTreeNode;
  22143. }
  22144. }
  22145. return null;
  22146. };
  22147. /**
  22148. *
  22149. * A group of objects that receives a shared animation state.
  22150. *
  22151. * Usage:
  22152. *
  22153. * - Add objects you would otherwise pass as 'root' to the
  22154. * constructor or the .clipAction method of AnimationMixer.
  22155. *
  22156. * - Instead pass this object as 'root'.
  22157. *
  22158. * - You can also add and remove objects later when the mixer
  22159. * is running.
  22160. *
  22161. * Note:
  22162. *
  22163. * Objects of this class appear as one object to the mixer,
  22164. * so cache control of the individual objects must be done
  22165. * on the group.
  22166. *
  22167. * Limitation:
  22168. *
  22169. * - The animated properties must be compatible among the
  22170. * all objects in the group.
  22171. *
  22172. * - A single property can either be controlled through a
  22173. * target group or directly, but not both.
  22174. *
  22175. * @author tschw
  22176. */
  22177. function AnimationObjectGroup( var_args ) {
  22178. this.uuid = _Math.generateUUID();
  22179. // cached objects followed by the active ones
  22180. this._objects = Array.prototype.slice.call( arguments );
  22181. this.nCachedObjects_ = 0; // threshold
  22182. // note: read by PropertyBinding.Composite
  22183. var indices = {};
  22184. this._indicesByUUID = indices; // for bookkeeping
  22185. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22186. indices[ arguments[ i ].uuid ] = i;
  22187. }
  22188. this._paths = []; // inside: string
  22189. this._parsedPaths = []; // inside: { we don't care, here }
  22190. this._bindings = []; // inside: Array< PropertyBinding >
  22191. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  22192. var scope = this;
  22193. this.stats = {
  22194. objects: {
  22195. get total() { return scope._objects.length; },
  22196. get inUse() { return this.total - scope.nCachedObjects_; }
  22197. },
  22198. get bindingsPerObject() { return scope._bindings.length; }
  22199. };
  22200. }
  22201. AnimationObjectGroup.prototype = {
  22202. constructor: AnimationObjectGroup,
  22203. isAnimationObjectGroup: true,
  22204. add: function( var_args ) {
  22205. var objects = this._objects,
  22206. nObjects = objects.length,
  22207. nCachedObjects = this.nCachedObjects_,
  22208. indicesByUUID = this._indicesByUUID,
  22209. paths = this._paths,
  22210. parsedPaths = this._parsedPaths,
  22211. bindings = this._bindings,
  22212. nBindings = bindings.length;
  22213. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22214. var object = arguments[ i ],
  22215. uuid = object.uuid,
  22216. index = indicesByUUID[ uuid ];
  22217. if ( index === undefined ) {
  22218. // unknown object -> add it to the ACTIVE region
  22219. index = nObjects ++;
  22220. indicesByUUID[ uuid ] = index;
  22221. objects.push( object );
  22222. // accounting is done, now do the same for all bindings
  22223. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22224. bindings[ j ].push(
  22225. new PropertyBinding(
  22226. object, paths[ j ], parsedPaths[ j ] ) );
  22227. }
  22228. } else if ( index < nCachedObjects ) {
  22229. var knownObject = objects[ index ];
  22230. // move existing object to the ACTIVE region
  22231. var firstActiveIndex = -- nCachedObjects,
  22232. lastCachedObject = objects[ firstActiveIndex ];
  22233. indicesByUUID[ lastCachedObject.uuid ] = index;
  22234. objects[ index ] = lastCachedObject;
  22235. indicesByUUID[ uuid ] = firstActiveIndex;
  22236. objects[ firstActiveIndex ] = object;
  22237. // accounting is done, now do the same for all bindings
  22238. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22239. var bindingsForPath = bindings[ j ],
  22240. lastCached = bindingsForPath[ firstActiveIndex ],
  22241. binding = bindingsForPath[ index ];
  22242. bindingsForPath[ index ] = lastCached;
  22243. if ( binding === undefined ) {
  22244. // since we do not bother to create new bindings
  22245. // for objects that are cached, the binding may
  22246. // or may not exist
  22247. binding = new PropertyBinding(
  22248. object, paths[ j ], parsedPaths[ j ] );
  22249. }
  22250. bindingsForPath[ firstActiveIndex ] = binding;
  22251. }
  22252. } else if ( objects[ index ] !== knownObject) {
  22253. console.error( "Different objects with the same UUID " +
  22254. "detected. Clean the caches or recreate your " +
  22255. "infrastructure when reloading scenes..." );
  22256. } // else the object is already where we want it to be
  22257. } // for arguments
  22258. this.nCachedObjects_ = nCachedObjects;
  22259. },
  22260. remove: function( var_args ) {
  22261. var objects = this._objects,
  22262. nCachedObjects = this.nCachedObjects_,
  22263. indicesByUUID = this._indicesByUUID,
  22264. bindings = this._bindings,
  22265. nBindings = bindings.length;
  22266. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22267. var object = arguments[ i ],
  22268. uuid = object.uuid,
  22269. index = indicesByUUID[ uuid ];
  22270. if ( index !== undefined && index >= nCachedObjects ) {
  22271. // move existing object into the CACHED region
  22272. var lastCachedIndex = nCachedObjects ++,
  22273. firstActiveObject = objects[ lastCachedIndex ];
  22274. indicesByUUID[ firstActiveObject.uuid ] = index;
  22275. objects[ index ] = firstActiveObject;
  22276. indicesByUUID[ uuid ] = lastCachedIndex;
  22277. objects[ lastCachedIndex ] = object;
  22278. // accounting is done, now do the same for all bindings
  22279. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22280. var bindingsForPath = bindings[ j ],
  22281. firstActive = bindingsForPath[ lastCachedIndex ],
  22282. binding = bindingsForPath[ index ];
  22283. bindingsForPath[ index ] = firstActive;
  22284. bindingsForPath[ lastCachedIndex ] = binding;
  22285. }
  22286. }
  22287. } // for arguments
  22288. this.nCachedObjects_ = nCachedObjects;
  22289. },
  22290. // remove & forget
  22291. uncache: function( var_args ) {
  22292. var objects = this._objects,
  22293. nObjects = objects.length,
  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 ) {
  22303. delete indicesByUUID[ uuid ];
  22304. if ( index < nCachedObjects ) {
  22305. // object is cached, shrink the CACHED region
  22306. var firstActiveIndex = -- nCachedObjects,
  22307. lastCachedObject = objects[ firstActiveIndex ],
  22308. lastIndex = -- nObjects,
  22309. lastObject = objects[ lastIndex ];
  22310. // last cached object takes this object's place
  22311. indicesByUUID[ lastCachedObject.uuid ] = index;
  22312. objects[ index ] = lastCachedObject;
  22313. // last object goes to the activated slot and pop
  22314. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  22315. objects[ firstActiveIndex ] = lastObject;
  22316. objects.pop();
  22317. // accounting is done, now do the same for all bindings
  22318. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22319. var bindingsForPath = bindings[ j ],
  22320. lastCached = bindingsForPath[ firstActiveIndex ],
  22321. last = bindingsForPath[ lastIndex ];
  22322. bindingsForPath[ index ] = lastCached;
  22323. bindingsForPath[ firstActiveIndex ] = last;
  22324. bindingsForPath.pop();
  22325. }
  22326. } else {
  22327. // object is active, just swap with the last and pop
  22328. var lastIndex = -- nObjects,
  22329. lastObject = objects[ lastIndex ];
  22330. indicesByUUID[ lastObject.uuid ] = index;
  22331. objects[ index ] = lastObject;
  22332. objects.pop();
  22333. // accounting is done, now do the same for all bindings
  22334. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22335. var bindingsForPath = bindings[ j ];
  22336. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  22337. bindingsForPath.pop();
  22338. }
  22339. } // cached or active
  22340. } // if object is known
  22341. } // for arguments
  22342. this.nCachedObjects_ = nCachedObjects;
  22343. },
  22344. // Internal interface used by befriended PropertyBinding.Composite:
  22345. subscribe_: function( path, parsedPath ) {
  22346. // returns an array of bindings for the given path that is changed
  22347. // according to the contained objects in the group
  22348. var indicesByPath = this._bindingsIndicesByPath,
  22349. index = indicesByPath[ path ],
  22350. bindings = this._bindings;
  22351. if ( index !== undefined ) return bindings[ index ];
  22352. var paths = this._paths,
  22353. parsedPaths = this._parsedPaths,
  22354. objects = this._objects,
  22355. nObjects = objects.length,
  22356. nCachedObjects = this.nCachedObjects_,
  22357. bindingsForPath = new Array( nObjects );
  22358. index = bindings.length;
  22359. indicesByPath[ path ] = index;
  22360. paths.push( path );
  22361. parsedPaths.push( parsedPath );
  22362. bindings.push( bindingsForPath );
  22363. for ( var i = nCachedObjects,
  22364. n = objects.length; i !== n; ++ i ) {
  22365. var object = objects[ i ];
  22366. bindingsForPath[ i ] =
  22367. new PropertyBinding( object, path, parsedPath );
  22368. }
  22369. return bindingsForPath;
  22370. },
  22371. unsubscribe_: function( path ) {
  22372. // tells the group to forget about a property path and no longer
  22373. // update the array previously obtained with 'subscribe_'
  22374. var indicesByPath = this._bindingsIndicesByPath,
  22375. index = indicesByPath[ path ];
  22376. if ( index !== undefined ) {
  22377. var paths = this._paths,
  22378. parsedPaths = this._parsedPaths,
  22379. bindings = this._bindings,
  22380. lastBindingsIndex = bindings.length - 1,
  22381. lastBindings = bindings[ lastBindingsIndex ],
  22382. lastBindingsPath = path[ lastBindingsIndex ];
  22383. indicesByPath[ lastBindingsPath ] = index;
  22384. bindings[ index ] = lastBindings;
  22385. bindings.pop();
  22386. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  22387. parsedPaths.pop();
  22388. paths[ index ] = paths[ lastBindingsIndex ];
  22389. paths.pop();
  22390. }
  22391. }
  22392. };
  22393. /**
  22394. *
  22395. * Action provided by AnimationMixer for scheduling clip playback on specific
  22396. * objects.
  22397. *
  22398. * @author Ben Houston / http://clara.io/
  22399. * @author David Sarno / http://lighthaus.us/
  22400. * @author tschw
  22401. *
  22402. */
  22403. function AnimationAction( mixer, clip, localRoot ) {
  22404. this._mixer = mixer;
  22405. this._clip = clip;
  22406. this._localRoot = localRoot || null;
  22407. var tracks = clip.tracks,
  22408. nTracks = tracks.length,
  22409. interpolants = new Array( nTracks );
  22410. var interpolantSettings = {
  22411. endingStart: ZeroCurvatureEnding,
  22412. endingEnd: ZeroCurvatureEnding
  22413. };
  22414. for ( var i = 0; i !== nTracks; ++ i ) {
  22415. var interpolant = tracks[ i ].createInterpolant( null );
  22416. interpolants[ i ] = interpolant;
  22417. interpolant.settings = interpolantSettings;
  22418. }
  22419. this._interpolantSettings = interpolantSettings;
  22420. this._interpolants = interpolants; // bound by the mixer
  22421. // inside: PropertyMixer (managed by the mixer)
  22422. this._propertyBindings = new Array( nTracks );
  22423. this._cacheIndex = null; // for the memory manager
  22424. this._byClipCacheIndex = null; // for the memory manager
  22425. this._timeScaleInterpolant = null;
  22426. this._weightInterpolant = null;
  22427. this.loop = LoopRepeat;
  22428. this._loopCount = -1;
  22429. // global mixer time when the action is to be started
  22430. // it's set back to 'null' upon start of the action
  22431. this._startTime = null;
  22432. // scaled local time of the action
  22433. // gets clamped or wrapped to 0..clip.duration according to loop
  22434. this.time = 0;
  22435. this.timeScale = 1;
  22436. this._effectiveTimeScale = 1;
  22437. this.weight = 1;
  22438. this._effectiveWeight = 1;
  22439. this.repetitions = Infinity; // no. of repetitions when looping
  22440. this.paused = false; // false -> zero effective time scale
  22441. this.enabled = true; // true -> zero effective weight
  22442. this.clampWhenFinished = false; // keep feeding the last frame?
  22443. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  22444. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  22445. }
  22446. AnimationAction.prototype = {
  22447. constructor: AnimationAction,
  22448. // State & Scheduling
  22449. play: function() {
  22450. this._mixer._activateAction( this );
  22451. return this;
  22452. },
  22453. stop: function() {
  22454. this._mixer._deactivateAction( this );
  22455. return this.reset();
  22456. },
  22457. reset: function() {
  22458. this.paused = false;
  22459. this.enabled = true;
  22460. this.time = 0; // restart clip
  22461. this._loopCount = -1; // forget previous loops
  22462. this._startTime = null; // forget scheduling
  22463. return this.stopFading().stopWarping();
  22464. },
  22465. isRunning: function() {
  22466. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  22467. this._startTime === null && this._mixer._isActiveAction( this );
  22468. },
  22469. // return true when play has been called
  22470. isScheduled: function() {
  22471. return this._mixer._isActiveAction( this );
  22472. },
  22473. startAt: function( time ) {
  22474. this._startTime = time;
  22475. return this;
  22476. },
  22477. setLoop: function( mode, repetitions ) {
  22478. this.loop = mode;
  22479. this.repetitions = repetitions;
  22480. return this;
  22481. },
  22482. // Weight
  22483. // set the weight stopping any scheduled fading
  22484. // although .enabled = false yields an effective weight of zero, this
  22485. // method does *not* change .enabled, because it would be confusing
  22486. setEffectiveWeight: function( weight ) {
  22487. this.weight = weight;
  22488. // note: same logic as when updated at runtime
  22489. this._effectiveWeight = this.enabled ? weight : 0;
  22490. return this.stopFading();
  22491. },
  22492. // return the weight considering fading and .enabled
  22493. getEffectiveWeight: function() {
  22494. return this._effectiveWeight;
  22495. },
  22496. fadeIn: function( duration ) {
  22497. return this._scheduleFading( duration, 0, 1 );
  22498. },
  22499. fadeOut: function( duration ) {
  22500. return this._scheduleFading( duration, 1, 0 );
  22501. },
  22502. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  22503. fadeOutAction.fadeOut( duration );
  22504. this.fadeIn( duration );
  22505. if( warp ) {
  22506. var fadeInDuration = this._clip.duration,
  22507. fadeOutDuration = fadeOutAction._clip.duration,
  22508. startEndRatio = fadeOutDuration / fadeInDuration,
  22509. endStartRatio = fadeInDuration / fadeOutDuration;
  22510. fadeOutAction.warp( 1.0, startEndRatio, duration );
  22511. this.warp( endStartRatio, 1.0, duration );
  22512. }
  22513. return this;
  22514. },
  22515. crossFadeTo: function( fadeInAction, duration, warp ) {
  22516. return fadeInAction.crossFadeFrom( this, duration, warp );
  22517. },
  22518. stopFading: function() {
  22519. var weightInterpolant = this._weightInterpolant;
  22520. if ( weightInterpolant !== null ) {
  22521. this._weightInterpolant = null;
  22522. this._mixer._takeBackControlInterpolant( weightInterpolant );
  22523. }
  22524. return this;
  22525. },
  22526. // Time Scale Control
  22527. // set the weight stopping any scheduled warping
  22528. // although .paused = true yields an effective time scale of zero, this
  22529. // method does *not* change .paused, because it would be confusing
  22530. setEffectiveTimeScale: function( timeScale ) {
  22531. this.timeScale = timeScale;
  22532. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  22533. return this.stopWarping();
  22534. },
  22535. // return the time scale considering warping and .paused
  22536. getEffectiveTimeScale: function() {
  22537. return this._effectiveTimeScale;
  22538. },
  22539. setDuration: function( duration ) {
  22540. this.timeScale = this._clip.duration / duration;
  22541. return this.stopWarping();
  22542. },
  22543. syncWith: function( action ) {
  22544. this.time = action.time;
  22545. this.timeScale = action.timeScale;
  22546. return this.stopWarping();
  22547. },
  22548. halt: function( duration ) {
  22549. return this.warp( this._effectiveTimeScale, 0, duration );
  22550. },
  22551. warp: function( startTimeScale, endTimeScale, duration ) {
  22552. var mixer = this._mixer, now = mixer.time,
  22553. interpolant = this._timeScaleInterpolant,
  22554. timeScale = this.timeScale;
  22555. if ( interpolant === null ) {
  22556. interpolant = mixer._lendControlInterpolant(),
  22557. this._timeScaleInterpolant = interpolant;
  22558. }
  22559. var times = interpolant.parameterPositions,
  22560. values = interpolant.sampleValues;
  22561. times[ 0 ] = now;
  22562. times[ 1 ] = now + duration;
  22563. values[ 0 ] = startTimeScale / timeScale;
  22564. values[ 1 ] = endTimeScale / timeScale;
  22565. return this;
  22566. },
  22567. stopWarping: function() {
  22568. var timeScaleInterpolant = this._timeScaleInterpolant;
  22569. if ( timeScaleInterpolant !== null ) {
  22570. this._timeScaleInterpolant = null;
  22571. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  22572. }
  22573. return this;
  22574. },
  22575. // Object Accessors
  22576. getMixer: function() {
  22577. return this._mixer;
  22578. },
  22579. getClip: function() {
  22580. return this._clip;
  22581. },
  22582. getRoot: function() {
  22583. return this._localRoot || this._mixer._root;
  22584. },
  22585. // Interna
  22586. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  22587. // called by the mixer
  22588. var startTime = this._startTime;
  22589. if ( startTime !== null ) {
  22590. // check for scheduled start of action
  22591. var timeRunning = ( time - startTime ) * timeDirection;
  22592. if ( timeRunning < 0 || timeDirection === 0 ) {
  22593. return; // yet to come / don't decide when delta = 0
  22594. }
  22595. // start
  22596. this._startTime = null; // unschedule
  22597. deltaTime = timeDirection * timeRunning;
  22598. }
  22599. // apply time scale and advance time
  22600. deltaTime *= this._updateTimeScale( time );
  22601. var clipTime = this._updateTime( deltaTime );
  22602. // note: _updateTime may disable the action resulting in
  22603. // an effective weight of 0
  22604. var weight = this._updateWeight( time );
  22605. if ( weight > 0 ) {
  22606. var interpolants = this._interpolants;
  22607. var propertyMixers = this._propertyBindings;
  22608. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  22609. interpolants[ j ].evaluate( clipTime );
  22610. propertyMixers[ j ].accumulate( accuIndex, weight );
  22611. }
  22612. }
  22613. },
  22614. _updateWeight: function( time ) {
  22615. var weight = 0;
  22616. if ( this.enabled ) {
  22617. weight = this.weight;
  22618. var interpolant = this._weightInterpolant;
  22619. if ( interpolant !== null ) {
  22620. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  22621. weight *= interpolantValue;
  22622. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22623. this.stopFading();
  22624. if ( interpolantValue === 0 ) {
  22625. // faded out, disable
  22626. this.enabled = false;
  22627. }
  22628. }
  22629. }
  22630. }
  22631. this._effectiveWeight = weight;
  22632. return weight;
  22633. },
  22634. _updateTimeScale: function( time ) {
  22635. var timeScale = 0;
  22636. if ( ! this.paused ) {
  22637. timeScale = this.timeScale;
  22638. var interpolant = this._timeScaleInterpolant;
  22639. if ( interpolant !== null ) {
  22640. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  22641. timeScale *= interpolantValue;
  22642. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22643. this.stopWarping();
  22644. if ( timeScale === 0 ) {
  22645. // motion has halted, pause
  22646. this.paused = true;
  22647. } else {
  22648. // warp done - apply final time scale
  22649. this.timeScale = timeScale;
  22650. }
  22651. }
  22652. }
  22653. }
  22654. this._effectiveTimeScale = timeScale;
  22655. return timeScale;
  22656. },
  22657. _updateTime: function( deltaTime ) {
  22658. var time = this.time + deltaTime;
  22659. if ( deltaTime === 0 ) return time;
  22660. var duration = this._clip.duration,
  22661. loop = this.loop,
  22662. loopCount = this._loopCount;
  22663. if ( loop === LoopOnce ) {
  22664. if ( loopCount === -1 ) {
  22665. // just started
  22666. this.loopCount = 0;
  22667. this._setEndings( true, true, false );
  22668. }
  22669. handle_stop: {
  22670. if ( time >= duration ) {
  22671. time = duration;
  22672. } else if ( time < 0 ) {
  22673. time = 0;
  22674. } else break handle_stop;
  22675. if ( this.clampWhenFinished ) this.paused = true;
  22676. else this.enabled = false;
  22677. this._mixer.dispatchEvent( {
  22678. type: 'finished', action: this,
  22679. direction: deltaTime < 0 ? -1 : 1
  22680. } );
  22681. }
  22682. } else { // repetitive Repeat or PingPong
  22683. var pingPong = ( loop === LoopPingPong );
  22684. if ( loopCount === -1 ) {
  22685. // just started
  22686. if ( deltaTime >= 0 ) {
  22687. loopCount = 0;
  22688. this._setEndings(
  22689. true, this.repetitions === 0, pingPong );
  22690. } else {
  22691. // when looping in reverse direction, the initial
  22692. // transition through zero counts as a repetition,
  22693. // so leave loopCount at -1
  22694. this._setEndings(
  22695. this.repetitions === 0, true, pingPong );
  22696. }
  22697. }
  22698. if ( time >= duration || time < 0 ) {
  22699. // wrap around
  22700. var loopDelta = Math.floor( time / duration ); // signed
  22701. time -= duration * loopDelta;
  22702. loopCount += Math.abs( loopDelta );
  22703. var pending = this.repetitions - loopCount;
  22704. if ( pending < 0 ) {
  22705. // have to stop (switch state, clamp time, fire event)
  22706. if ( this.clampWhenFinished ) this.paused = true;
  22707. else this.enabled = false;
  22708. time = deltaTime > 0 ? duration : 0;
  22709. this._mixer.dispatchEvent( {
  22710. type: 'finished', action: this,
  22711. direction: deltaTime > 0 ? 1 : -1
  22712. } );
  22713. } else {
  22714. // keep running
  22715. if ( pending === 0 ) {
  22716. // entering the last round
  22717. var atStart = deltaTime < 0;
  22718. this._setEndings( atStart, ! atStart, pingPong );
  22719. } else {
  22720. this._setEndings( false, false, pingPong );
  22721. }
  22722. this._loopCount = loopCount;
  22723. this._mixer.dispatchEvent( {
  22724. type: 'loop', action: this, loopDelta: loopDelta
  22725. } );
  22726. }
  22727. }
  22728. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  22729. // invert time for the "pong round"
  22730. this.time = time;
  22731. return duration - time;
  22732. }
  22733. }
  22734. this.time = time;
  22735. return time;
  22736. },
  22737. _setEndings: function( atStart, atEnd, pingPong ) {
  22738. var settings = this._interpolantSettings;
  22739. if ( pingPong ) {
  22740. settings.endingStart = ZeroSlopeEnding;
  22741. settings.endingEnd = ZeroSlopeEnding;
  22742. } else {
  22743. // assuming for LoopOnce atStart == atEnd == true
  22744. if ( atStart ) {
  22745. settings.endingStart = this.zeroSlopeAtStart ?
  22746. ZeroSlopeEnding : ZeroCurvatureEnding;
  22747. } else {
  22748. settings.endingStart = WrapAroundEnding;
  22749. }
  22750. if ( atEnd ) {
  22751. settings.endingEnd = this.zeroSlopeAtEnd ?
  22752. ZeroSlopeEnding : ZeroCurvatureEnding;
  22753. } else {
  22754. settings.endingEnd = WrapAroundEnding;
  22755. }
  22756. }
  22757. },
  22758. _scheduleFading: function( duration, weightNow, weightThen ) {
  22759. var mixer = this._mixer, now = mixer.time,
  22760. interpolant = this._weightInterpolant;
  22761. if ( interpolant === null ) {
  22762. interpolant = mixer._lendControlInterpolant(),
  22763. this._weightInterpolant = interpolant;
  22764. }
  22765. var times = interpolant.parameterPositions,
  22766. values = interpolant.sampleValues;
  22767. times[ 0 ] = now; values[ 0 ] = weightNow;
  22768. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  22769. return this;
  22770. }
  22771. };
  22772. /**
  22773. *
  22774. * Player for AnimationClips.
  22775. *
  22776. *
  22777. * @author Ben Houston / http://clara.io/
  22778. * @author David Sarno / http://lighthaus.us/
  22779. * @author tschw
  22780. */
  22781. function AnimationMixer( root ) {
  22782. this._root = root;
  22783. this._initMemoryManager();
  22784. this._accuIndex = 0;
  22785. this.time = 0;
  22786. this.timeScale = 1.0;
  22787. }
  22788. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, {
  22789. // return an action for a clip optionally using a custom root target
  22790. // object (this method allocates a lot of dynamic memory in case a
  22791. // previously unknown clip/root combination is specified)
  22792. clipAction: function( clip, optionalRoot ) {
  22793. var root = optionalRoot || this._root,
  22794. rootUuid = root.uuid,
  22795. clipObject = typeof clip === 'string' ?
  22796. AnimationClip.findByName( root, clip ) : clip,
  22797. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  22798. actionsForClip = this._actionsByClip[ clipUuid ],
  22799. prototypeAction = null;
  22800. if ( actionsForClip !== undefined ) {
  22801. var existingAction =
  22802. actionsForClip.actionByRoot[ rootUuid ];
  22803. if ( existingAction !== undefined ) {
  22804. return existingAction;
  22805. }
  22806. // we know the clip, so we don't have to parse all
  22807. // the bindings again but can just copy
  22808. prototypeAction = actionsForClip.knownActions[ 0 ];
  22809. // also, take the clip from the prototype action
  22810. if ( clipObject === null )
  22811. clipObject = prototypeAction._clip;
  22812. }
  22813. // clip must be known when specified via string
  22814. if ( clipObject === null ) return null;
  22815. // allocate all resources required to run it
  22816. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  22817. this._bindAction( newAction, prototypeAction );
  22818. // and make the action known to the memory manager
  22819. this._addInactiveAction( newAction, clipUuid, rootUuid );
  22820. return newAction;
  22821. },
  22822. // get an existing action
  22823. existingAction: function( clip, optionalRoot ) {
  22824. var root = optionalRoot || this._root,
  22825. rootUuid = root.uuid,
  22826. clipObject = typeof clip === 'string' ?
  22827. AnimationClip.findByName( root, clip ) : clip,
  22828. clipUuid = clipObject ? clipObject.uuid : clip,
  22829. actionsForClip = this._actionsByClip[ clipUuid ];
  22830. if ( actionsForClip !== undefined ) {
  22831. return actionsForClip.actionByRoot[ rootUuid ] || null;
  22832. }
  22833. return null;
  22834. },
  22835. // deactivates all previously scheduled actions
  22836. stopAllAction: function() {
  22837. var actions = this._actions,
  22838. nActions = this._nActiveActions,
  22839. bindings = this._bindings,
  22840. nBindings = this._nActiveBindings;
  22841. this._nActiveActions = 0;
  22842. this._nActiveBindings = 0;
  22843. for ( var i = 0; i !== nActions; ++ i ) {
  22844. actions[ i ].reset();
  22845. }
  22846. for ( var i = 0; i !== nBindings; ++ i ) {
  22847. bindings[ i ].useCount = 0;
  22848. }
  22849. return this;
  22850. },
  22851. // advance the time and update apply the animation
  22852. update: function( deltaTime ) {
  22853. deltaTime *= this.timeScale;
  22854. var actions = this._actions,
  22855. nActions = this._nActiveActions,
  22856. time = this.time += deltaTime,
  22857. timeDirection = Math.sign( deltaTime ),
  22858. accuIndex = this._accuIndex ^= 1;
  22859. // run active actions
  22860. for ( var i = 0; i !== nActions; ++ i ) {
  22861. var action = actions[ i ];
  22862. if ( action.enabled ) {
  22863. action._update( time, deltaTime, timeDirection, accuIndex );
  22864. }
  22865. }
  22866. // update scene graph
  22867. var bindings = this._bindings,
  22868. nBindings = this._nActiveBindings;
  22869. for ( var i = 0; i !== nBindings; ++ i ) {
  22870. bindings[ i ].apply( accuIndex );
  22871. }
  22872. return this;
  22873. },
  22874. // return this mixer's root target object
  22875. getRoot: function() {
  22876. return this._root;
  22877. },
  22878. // free all resources specific to a particular clip
  22879. uncacheClip: function( clip ) {
  22880. var actions = this._actions,
  22881. clipUuid = clip.uuid,
  22882. actionsByClip = this._actionsByClip,
  22883. actionsForClip = actionsByClip[ clipUuid ];
  22884. if ( actionsForClip !== undefined ) {
  22885. // note: just calling _removeInactiveAction would mess up the
  22886. // iteration state and also require updating the state we can
  22887. // just throw away
  22888. var actionsToRemove = actionsForClip.knownActions;
  22889. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  22890. var action = actionsToRemove[ i ];
  22891. this._deactivateAction( action );
  22892. var cacheIndex = action._cacheIndex,
  22893. lastInactiveAction = actions[ actions.length - 1 ];
  22894. action._cacheIndex = null;
  22895. action._byClipCacheIndex = null;
  22896. lastInactiveAction._cacheIndex = cacheIndex;
  22897. actions[ cacheIndex ] = lastInactiveAction;
  22898. actions.pop();
  22899. this._removeInactiveBindingsForAction( action );
  22900. }
  22901. delete actionsByClip[ clipUuid ];
  22902. }
  22903. },
  22904. // free all resources specific to a particular root target object
  22905. uncacheRoot: function( root ) {
  22906. var rootUuid = root.uuid,
  22907. actionsByClip = this._actionsByClip;
  22908. for ( var clipUuid in actionsByClip ) {
  22909. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  22910. action = actionByRoot[ rootUuid ];
  22911. if ( action !== undefined ) {
  22912. this._deactivateAction( action );
  22913. this._removeInactiveAction( action );
  22914. }
  22915. }
  22916. var bindingsByRoot = this._bindingsByRootAndName,
  22917. bindingByName = bindingsByRoot[ rootUuid ];
  22918. if ( bindingByName !== undefined ) {
  22919. for ( var trackName in bindingByName ) {
  22920. var binding = bindingByName[ trackName ];
  22921. binding.restoreOriginalState();
  22922. this._removeInactiveBinding( binding );
  22923. }
  22924. }
  22925. },
  22926. // remove a targeted clip from the cache
  22927. uncacheAction: function( clip, optionalRoot ) {
  22928. var action = this.existingAction( clip, optionalRoot );
  22929. if ( action !== null ) {
  22930. this._deactivateAction( action );
  22931. this._removeInactiveAction( action );
  22932. }
  22933. }
  22934. } );
  22935. // Implementation details:
  22936. Object.assign( AnimationMixer.prototype, {
  22937. _bindAction: function( action, prototypeAction ) {
  22938. var root = action._localRoot || this._root,
  22939. tracks = action._clip.tracks,
  22940. nTracks = tracks.length,
  22941. bindings = action._propertyBindings,
  22942. interpolants = action._interpolants,
  22943. rootUuid = root.uuid,
  22944. bindingsByRoot = this._bindingsByRootAndName,
  22945. bindingsByName = bindingsByRoot[ rootUuid ];
  22946. if ( bindingsByName === undefined ) {
  22947. bindingsByName = {};
  22948. bindingsByRoot[ rootUuid ] = bindingsByName;
  22949. }
  22950. for ( var i = 0; i !== nTracks; ++ i ) {
  22951. var track = tracks[ i ],
  22952. trackName = track.name,
  22953. binding = bindingsByName[ trackName ];
  22954. if ( binding !== undefined ) {
  22955. bindings[ i ] = binding;
  22956. } else {
  22957. binding = bindings[ i ];
  22958. if ( binding !== undefined ) {
  22959. // existing binding, make sure the cache knows
  22960. if ( binding._cacheIndex === null ) {
  22961. ++ binding.referenceCount;
  22962. this._addInactiveBinding( binding, rootUuid, trackName );
  22963. }
  22964. continue;
  22965. }
  22966. var path = prototypeAction && prototypeAction.
  22967. _propertyBindings[ i ].binding.parsedPath;
  22968. binding = new PropertyMixer(
  22969. PropertyBinding.create( root, trackName, path ),
  22970. track.ValueTypeName, track.getValueSize() );
  22971. ++ binding.referenceCount;
  22972. this._addInactiveBinding( binding, rootUuid, trackName );
  22973. bindings[ i ] = binding;
  22974. }
  22975. interpolants[ i ].resultBuffer = binding.buffer;
  22976. }
  22977. },
  22978. _activateAction: function( action ) {
  22979. if ( ! this._isActiveAction( action ) ) {
  22980. if ( action._cacheIndex === null ) {
  22981. // this action has been forgotten by the cache, but the user
  22982. // appears to be still using it -> rebind
  22983. var rootUuid = ( action._localRoot || this._root ).uuid,
  22984. clipUuid = action._clip.uuid,
  22985. actionsForClip = this._actionsByClip[ clipUuid ];
  22986. this._bindAction( action,
  22987. actionsForClip && actionsForClip.knownActions[ 0 ] );
  22988. this._addInactiveAction( action, clipUuid, rootUuid );
  22989. }
  22990. var bindings = action._propertyBindings;
  22991. // increment reference counts / sort out state
  22992. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  22993. var binding = bindings[ i ];
  22994. if ( binding.useCount ++ === 0 ) {
  22995. this._lendBinding( binding );
  22996. binding.saveOriginalState();
  22997. }
  22998. }
  22999. this._lendAction( action );
  23000. }
  23001. },
  23002. _deactivateAction: function( action ) {
  23003. if ( this._isActiveAction( action ) ) {
  23004. var bindings = action._propertyBindings;
  23005. // decrement reference counts / sort out state
  23006. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23007. var binding = bindings[ i ];
  23008. if ( -- binding.useCount === 0 ) {
  23009. binding.restoreOriginalState();
  23010. this._takeBackBinding( binding );
  23011. }
  23012. }
  23013. this._takeBackAction( action );
  23014. }
  23015. },
  23016. // Memory manager
  23017. _initMemoryManager: function() {
  23018. this._actions = []; // 'nActiveActions' followed by inactive ones
  23019. this._nActiveActions = 0;
  23020. this._actionsByClip = {};
  23021. // inside:
  23022. // {
  23023. // knownActions: Array< AnimationAction > - used as prototypes
  23024. // actionByRoot: AnimationAction - lookup
  23025. // }
  23026. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  23027. this._nActiveBindings = 0;
  23028. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  23029. this._controlInterpolants = []; // same game as above
  23030. this._nActiveControlInterpolants = 0;
  23031. var scope = this;
  23032. this.stats = {
  23033. actions: {
  23034. get total() { return scope._actions.length; },
  23035. get inUse() { return scope._nActiveActions; }
  23036. },
  23037. bindings: {
  23038. get total() { return scope._bindings.length; },
  23039. get inUse() { return scope._nActiveBindings; }
  23040. },
  23041. controlInterpolants: {
  23042. get total() { return scope._controlInterpolants.length; },
  23043. get inUse() { return scope._nActiveControlInterpolants; }
  23044. }
  23045. };
  23046. },
  23047. // Memory management for AnimationAction objects
  23048. _isActiveAction: function( action ) {
  23049. var index = action._cacheIndex;
  23050. return index !== null && index < this._nActiveActions;
  23051. },
  23052. _addInactiveAction: function( action, clipUuid, rootUuid ) {
  23053. var actions = this._actions,
  23054. actionsByClip = this._actionsByClip,
  23055. actionsForClip = actionsByClip[ clipUuid ];
  23056. if ( actionsForClip === undefined ) {
  23057. actionsForClip = {
  23058. knownActions: [ action ],
  23059. actionByRoot: {}
  23060. };
  23061. action._byClipCacheIndex = 0;
  23062. actionsByClip[ clipUuid ] = actionsForClip;
  23063. } else {
  23064. var knownActions = actionsForClip.knownActions;
  23065. action._byClipCacheIndex = knownActions.length;
  23066. knownActions.push( action );
  23067. }
  23068. action._cacheIndex = actions.length;
  23069. actions.push( action );
  23070. actionsForClip.actionByRoot[ rootUuid ] = action;
  23071. },
  23072. _removeInactiveAction: function( action ) {
  23073. var actions = this._actions,
  23074. lastInactiveAction = actions[ actions.length - 1 ],
  23075. cacheIndex = action._cacheIndex;
  23076. lastInactiveAction._cacheIndex = cacheIndex;
  23077. actions[ cacheIndex ] = lastInactiveAction;
  23078. actions.pop();
  23079. action._cacheIndex = null;
  23080. var clipUuid = action._clip.uuid,
  23081. actionsByClip = this._actionsByClip,
  23082. actionsForClip = actionsByClip[ clipUuid ],
  23083. knownActionsForClip = actionsForClip.knownActions,
  23084. lastKnownAction =
  23085. knownActionsForClip[ knownActionsForClip.length - 1 ],
  23086. byClipCacheIndex = action._byClipCacheIndex;
  23087. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  23088. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  23089. knownActionsForClip.pop();
  23090. action._byClipCacheIndex = null;
  23091. var actionByRoot = actionsForClip.actionByRoot,
  23092. rootUuid = ( actions._localRoot || this._root ).uuid;
  23093. delete actionByRoot[ rootUuid ];
  23094. if ( knownActionsForClip.length === 0 ) {
  23095. delete actionsByClip[ clipUuid ];
  23096. }
  23097. this._removeInactiveBindingsForAction( action );
  23098. },
  23099. _removeInactiveBindingsForAction: function( action ) {
  23100. var bindings = action._propertyBindings;
  23101. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23102. var binding = bindings[ i ];
  23103. if ( -- binding.referenceCount === 0 ) {
  23104. this._removeInactiveBinding( binding );
  23105. }
  23106. }
  23107. },
  23108. _lendAction: function( action ) {
  23109. // [ active actions | inactive actions ]
  23110. // [ active actions >| inactive actions ]
  23111. // s a
  23112. // <-swap->
  23113. // a s
  23114. var actions = this._actions,
  23115. prevIndex = action._cacheIndex,
  23116. lastActiveIndex = this._nActiveActions ++,
  23117. firstInactiveAction = actions[ lastActiveIndex ];
  23118. action._cacheIndex = lastActiveIndex;
  23119. actions[ lastActiveIndex ] = action;
  23120. firstInactiveAction._cacheIndex = prevIndex;
  23121. actions[ prevIndex ] = firstInactiveAction;
  23122. },
  23123. _takeBackAction: function( action ) {
  23124. // [ active actions | inactive actions ]
  23125. // [ active actions |< inactive actions ]
  23126. // a s
  23127. // <-swap->
  23128. // s a
  23129. var actions = this._actions,
  23130. prevIndex = action._cacheIndex,
  23131. firstInactiveIndex = -- this._nActiveActions,
  23132. lastActiveAction = actions[ firstInactiveIndex ];
  23133. action._cacheIndex = firstInactiveIndex;
  23134. actions[ firstInactiveIndex ] = action;
  23135. lastActiveAction._cacheIndex = prevIndex;
  23136. actions[ prevIndex ] = lastActiveAction;
  23137. },
  23138. // Memory management for PropertyMixer objects
  23139. _addInactiveBinding: function( binding, rootUuid, trackName ) {
  23140. var bindingsByRoot = this._bindingsByRootAndName,
  23141. bindingByName = bindingsByRoot[ rootUuid ],
  23142. bindings = this._bindings;
  23143. if ( bindingByName === undefined ) {
  23144. bindingByName = {};
  23145. bindingsByRoot[ rootUuid ] = bindingByName;
  23146. }
  23147. bindingByName[ trackName ] = binding;
  23148. binding._cacheIndex = bindings.length;
  23149. bindings.push( binding );
  23150. },
  23151. _removeInactiveBinding: function( binding ) {
  23152. var bindings = this._bindings,
  23153. propBinding = binding.binding,
  23154. rootUuid = propBinding.rootNode.uuid,
  23155. trackName = propBinding.path,
  23156. bindingsByRoot = this._bindingsByRootAndName,
  23157. bindingByName = bindingsByRoot[ rootUuid ],
  23158. lastInactiveBinding = bindings[ bindings.length - 1 ],
  23159. cacheIndex = binding._cacheIndex;
  23160. lastInactiveBinding._cacheIndex = cacheIndex;
  23161. bindings[ cacheIndex ] = lastInactiveBinding;
  23162. bindings.pop();
  23163. delete bindingByName[ trackName ];
  23164. remove_empty_map: {
  23165. for ( var _ in bindingByName ) break remove_empty_map;
  23166. delete bindingsByRoot[ rootUuid ];
  23167. }
  23168. },
  23169. _lendBinding: function( binding ) {
  23170. var bindings = this._bindings,
  23171. prevIndex = binding._cacheIndex,
  23172. lastActiveIndex = this._nActiveBindings ++,
  23173. firstInactiveBinding = bindings[ lastActiveIndex ];
  23174. binding._cacheIndex = lastActiveIndex;
  23175. bindings[ lastActiveIndex ] = binding;
  23176. firstInactiveBinding._cacheIndex = prevIndex;
  23177. bindings[ prevIndex ] = firstInactiveBinding;
  23178. },
  23179. _takeBackBinding: function( binding ) {
  23180. var bindings = this._bindings,
  23181. prevIndex = binding._cacheIndex,
  23182. firstInactiveIndex = -- this._nActiveBindings,
  23183. lastActiveBinding = bindings[ firstInactiveIndex ];
  23184. binding._cacheIndex = firstInactiveIndex;
  23185. bindings[ firstInactiveIndex ] = binding;
  23186. lastActiveBinding._cacheIndex = prevIndex;
  23187. bindings[ prevIndex ] = lastActiveBinding;
  23188. },
  23189. // Memory management of Interpolants for weight and time scale
  23190. _lendControlInterpolant: function() {
  23191. var interpolants = this._controlInterpolants,
  23192. lastActiveIndex = this._nActiveControlInterpolants ++,
  23193. interpolant = interpolants[ lastActiveIndex ];
  23194. if ( interpolant === undefined ) {
  23195. interpolant = new LinearInterpolant(
  23196. new Float32Array( 2 ), new Float32Array( 2 ),
  23197. 1, this._controlInterpolantsResultBuffer );
  23198. interpolant.__cacheIndex = lastActiveIndex;
  23199. interpolants[ lastActiveIndex ] = interpolant;
  23200. }
  23201. return interpolant;
  23202. },
  23203. _takeBackControlInterpolant: function( interpolant ) {
  23204. var interpolants = this._controlInterpolants,
  23205. prevIndex = interpolant.__cacheIndex,
  23206. firstInactiveIndex = -- this._nActiveControlInterpolants,
  23207. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  23208. interpolant.__cacheIndex = firstInactiveIndex;
  23209. interpolants[ firstInactiveIndex ] = interpolant;
  23210. lastActiveInterpolant.__cacheIndex = prevIndex;
  23211. interpolants[ prevIndex ] = lastActiveInterpolant;
  23212. },
  23213. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  23214. } );
  23215. /**
  23216. * @author mrdoob / http://mrdoob.com/
  23217. */
  23218. function Uniform( value ) {
  23219. if ( typeof value === 'string' ) {
  23220. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  23221. value = arguments[ 1 ];
  23222. }
  23223. this.value = value;
  23224. }
  23225. Uniform.prototype.clone = function () {
  23226. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  23227. };
  23228. /**
  23229. * @author benaadams / https://twitter.com/ben_a_adams
  23230. */
  23231. function InstancedBufferGeometry() {
  23232. BufferGeometry.call( this );
  23233. this.type = 'InstancedBufferGeometry';
  23234. this.maxInstancedCount = undefined;
  23235. }
  23236. InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23237. InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry;
  23238. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  23239. InstancedBufferGeometry.prototype.addGroup = function ( start, count, materialIndex ) {
  23240. this.groups.push( {
  23241. start: start,
  23242. count: count,
  23243. materialIndex: materialIndex
  23244. } );
  23245. };
  23246. InstancedBufferGeometry.prototype.copy = function ( source ) {
  23247. var index = source.index;
  23248. if ( index !== null ) {
  23249. this.setIndex( index.clone() );
  23250. }
  23251. var attributes = source.attributes;
  23252. for ( var name in attributes ) {
  23253. var attribute = attributes[ name ];
  23254. this.addAttribute( name, attribute.clone() );
  23255. }
  23256. var groups = source.groups;
  23257. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  23258. var group = groups[ i ];
  23259. this.addGroup( group.start, group.count, group.materialIndex );
  23260. }
  23261. return this;
  23262. };
  23263. /**
  23264. * @author benaadams / https://twitter.com/ben_a_adams
  23265. */
  23266. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  23267. this.uuid = _Math.generateUUID();
  23268. this.data = interleavedBuffer;
  23269. this.itemSize = itemSize;
  23270. this.offset = offset;
  23271. this.normalized = normalized === true;
  23272. }
  23273. InterleavedBufferAttribute.prototype = {
  23274. constructor: InterleavedBufferAttribute,
  23275. isInterleavedBufferAttribute: true,
  23276. get count() {
  23277. return this.data.count;
  23278. },
  23279. get array() {
  23280. return this.data.array;
  23281. },
  23282. setX: function ( index, x ) {
  23283. this.data.array[ index * this.data.stride + this.offset ] = x;
  23284. return this;
  23285. },
  23286. setY: function ( index, y ) {
  23287. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  23288. return this;
  23289. },
  23290. setZ: function ( index, z ) {
  23291. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  23292. return this;
  23293. },
  23294. setW: function ( index, w ) {
  23295. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  23296. return this;
  23297. },
  23298. getX: function ( index ) {
  23299. return this.data.array[ index * this.data.stride + this.offset ];
  23300. },
  23301. getY: function ( index ) {
  23302. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  23303. },
  23304. getZ: function ( index ) {
  23305. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  23306. },
  23307. getW: function ( index ) {
  23308. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  23309. },
  23310. setXY: function ( index, x, y ) {
  23311. index = index * this.data.stride + this.offset;
  23312. this.data.array[ index + 0 ] = x;
  23313. this.data.array[ index + 1 ] = y;
  23314. return this;
  23315. },
  23316. setXYZ: function ( index, x, y, z ) {
  23317. index = index * this.data.stride + this.offset;
  23318. this.data.array[ index + 0 ] = x;
  23319. this.data.array[ index + 1 ] = y;
  23320. this.data.array[ index + 2 ] = z;
  23321. return this;
  23322. },
  23323. setXYZW: function ( index, x, y, z, w ) {
  23324. index = index * this.data.stride + this.offset;
  23325. this.data.array[ index + 0 ] = x;
  23326. this.data.array[ index + 1 ] = y;
  23327. this.data.array[ index + 2 ] = z;
  23328. this.data.array[ index + 3 ] = w;
  23329. return this;
  23330. }
  23331. };
  23332. /**
  23333. * @author benaadams / https://twitter.com/ben_a_adams
  23334. */
  23335. function InterleavedBuffer( array, stride ) {
  23336. this.uuid = _Math.generateUUID();
  23337. this.array = array;
  23338. this.stride = stride;
  23339. this.count = array !== undefined ? array.length / stride : 0;
  23340. this.dynamic = false;
  23341. this.updateRange = { offset: 0, count: - 1 };
  23342. this.onUploadCallback = function () {};
  23343. this.version = 0;
  23344. }
  23345. InterleavedBuffer.prototype = {
  23346. constructor: InterleavedBuffer,
  23347. isInterleavedBuffer: true,
  23348. set needsUpdate( value ) {
  23349. if ( value === true ) this.version ++;
  23350. },
  23351. setArray: function ( array ) {
  23352. if ( Array.isArray( array ) ) {
  23353. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  23354. }
  23355. this.count = array !== undefined ? array.length / this.stride : 0;
  23356. this.array = array;
  23357. },
  23358. setDynamic: function ( value ) {
  23359. this.dynamic = value;
  23360. return this;
  23361. },
  23362. copy: function ( source ) {
  23363. this.array = new source.array.constructor( source.array );
  23364. this.count = source.count;
  23365. this.stride = source.stride;
  23366. this.dynamic = source.dynamic;
  23367. return this;
  23368. },
  23369. copyAt: function ( index1, attribute, index2 ) {
  23370. index1 *= this.stride;
  23371. index2 *= attribute.stride;
  23372. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  23373. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  23374. }
  23375. return this;
  23376. },
  23377. set: function ( value, offset ) {
  23378. if ( offset === undefined ) offset = 0;
  23379. this.array.set( value, offset );
  23380. return this;
  23381. },
  23382. clone: function () {
  23383. return new this.constructor().copy( this );
  23384. },
  23385. onUpload: function ( callback ) {
  23386. this.onUploadCallback = callback;
  23387. return this;
  23388. }
  23389. };
  23390. /**
  23391. * @author benaadams / https://twitter.com/ben_a_adams
  23392. */
  23393. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  23394. InterleavedBuffer.call( this, array, stride );
  23395. this.meshPerAttribute = meshPerAttribute || 1;
  23396. }
  23397. InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype );
  23398. InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer;
  23399. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  23400. InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  23401. InterleavedBuffer.prototype.copy.call( this, source );
  23402. this.meshPerAttribute = source.meshPerAttribute;
  23403. return this;
  23404. };
  23405. /**
  23406. * @author benaadams / https://twitter.com/ben_a_adams
  23407. */
  23408. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  23409. BufferAttribute.call( this, array, itemSize );
  23410. this.meshPerAttribute = meshPerAttribute || 1;
  23411. }
  23412. InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  23413. InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute;
  23414. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  23415. InstancedBufferAttribute.prototype.copy = function ( source ) {
  23416. BufferAttribute.prototype.copy.call( this, source );
  23417. this.meshPerAttribute = source.meshPerAttribute;
  23418. return this;
  23419. };
  23420. /**
  23421. * @author mrdoob / http://mrdoob.com/
  23422. * @author bhouston / http://clara.io/
  23423. * @author stephomi / http://stephaneginier.com/
  23424. */
  23425. function Raycaster( origin, direction, near, far ) {
  23426. this.ray = new Ray( origin, direction );
  23427. // direction is assumed to be normalized (for accurate distance calculations)
  23428. this.near = near || 0;
  23429. this.far = far || Infinity;
  23430. this.params = {
  23431. Mesh: {},
  23432. Line: {},
  23433. LOD: {},
  23434. Points: { threshold: 1 },
  23435. Sprite: {}
  23436. };
  23437. Object.defineProperties( this.params, {
  23438. PointCloud: {
  23439. get: function () {
  23440. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  23441. return this.Points;
  23442. }
  23443. }
  23444. } );
  23445. }
  23446. function ascSort( a, b ) {
  23447. return a.distance - b.distance;
  23448. }
  23449. function intersectObject( object, raycaster, intersects, recursive ) {
  23450. if ( object.visible === false ) return;
  23451. object.raycast( raycaster, intersects );
  23452. if ( recursive === true ) {
  23453. var children = object.children;
  23454. for ( var i = 0, l = children.length; i < l; i ++ ) {
  23455. intersectObject( children[ i ], raycaster, intersects, true );
  23456. }
  23457. }
  23458. }
  23459. //
  23460. Raycaster.prototype = {
  23461. constructor: Raycaster,
  23462. linePrecision: 1,
  23463. set: function ( origin, direction ) {
  23464. // direction is assumed to be normalized (for accurate distance calculations)
  23465. this.ray.set( origin, direction );
  23466. },
  23467. setFromCamera: function ( coords, camera ) {
  23468. if ( (camera && camera.isPerspectiveCamera) ) {
  23469. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  23470. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  23471. } else if ( (camera && camera.isOrthographicCamera) ) {
  23472. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  23473. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  23474. } else {
  23475. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  23476. }
  23477. },
  23478. intersectObject: function ( object, recursive ) {
  23479. var intersects = [];
  23480. intersectObject( object, this, intersects, recursive );
  23481. intersects.sort( ascSort );
  23482. return intersects;
  23483. },
  23484. intersectObjects: function ( objects, recursive ) {
  23485. var intersects = [];
  23486. if ( Array.isArray( objects ) === false ) {
  23487. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  23488. return intersects;
  23489. }
  23490. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  23491. intersectObject( objects[ i ], this, intersects, recursive );
  23492. }
  23493. intersects.sort( ascSort );
  23494. return intersects;
  23495. }
  23496. };
  23497. /**
  23498. * @author alteredq / http://alteredqualia.com/
  23499. */
  23500. function Clock( autoStart ) {
  23501. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  23502. this.startTime = 0;
  23503. this.oldTime = 0;
  23504. this.elapsedTime = 0;
  23505. this.running = false;
  23506. }
  23507. Clock.prototype = {
  23508. constructor: Clock,
  23509. start: function () {
  23510. this.startTime = ( performance || Date ).now();
  23511. this.oldTime = this.startTime;
  23512. this.elapsedTime = 0;
  23513. this.running = true;
  23514. },
  23515. stop: function () {
  23516. this.getElapsedTime();
  23517. this.running = false;
  23518. },
  23519. getElapsedTime: function () {
  23520. this.getDelta();
  23521. return this.elapsedTime;
  23522. },
  23523. getDelta: function () {
  23524. var diff = 0;
  23525. if ( this.autoStart && ! this.running ) {
  23526. this.start();
  23527. }
  23528. if ( this.running ) {
  23529. var newTime = ( performance || Date ).now();
  23530. diff = ( newTime - this.oldTime ) / 1000;
  23531. this.oldTime = newTime;
  23532. this.elapsedTime += diff;
  23533. }
  23534. return diff;
  23535. }
  23536. };
  23537. /**
  23538. * Spline from Tween.js, slightly optimized (and trashed)
  23539. * http://sole.github.com/tween.js/examples/05_spline.html
  23540. *
  23541. * @author mrdoob / http://mrdoob.com/
  23542. * @author alteredq / http://alteredqualia.com/
  23543. */
  23544. function Spline( points ) {
  23545. this.points = points;
  23546. var c = [], v3 = { x: 0, y: 0, z: 0 },
  23547. point, intPoint, weight, w2, w3,
  23548. pa, pb, pc, pd;
  23549. this.initFromArray = function ( a ) {
  23550. this.points = [];
  23551. for ( var i = 0; i < a.length; i ++ ) {
  23552. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  23553. }
  23554. };
  23555. this.getPoint = function ( k ) {
  23556. point = ( this.points.length - 1 ) * k;
  23557. intPoint = Math.floor( point );
  23558. weight = point - intPoint;
  23559. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  23560. c[ 1 ] = intPoint;
  23561. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  23562. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  23563. pa = this.points[ c[ 0 ] ];
  23564. pb = this.points[ c[ 1 ] ];
  23565. pc = this.points[ c[ 2 ] ];
  23566. pd = this.points[ c[ 3 ] ];
  23567. w2 = weight * weight;
  23568. w3 = weight * w2;
  23569. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  23570. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  23571. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  23572. return v3;
  23573. };
  23574. this.getControlPointsArray = function () {
  23575. var i, p, l = this.points.length,
  23576. coords = [];
  23577. for ( i = 0; i < l; i ++ ) {
  23578. p = this.points[ i ];
  23579. coords[ i ] = [ p.x, p.y, p.z ];
  23580. }
  23581. return coords;
  23582. };
  23583. // approximate length by summing linear segments
  23584. this.getLength = function ( nSubDivisions ) {
  23585. var i, index, nSamples, position,
  23586. point = 0, intPoint = 0, oldIntPoint = 0,
  23587. oldPosition = new Vector3(),
  23588. tmpVec = new Vector3(),
  23589. chunkLengths = [],
  23590. totalLength = 0;
  23591. // first point has 0 length
  23592. chunkLengths[ 0 ] = 0;
  23593. if ( ! nSubDivisions ) nSubDivisions = 100;
  23594. nSamples = this.points.length * nSubDivisions;
  23595. oldPosition.copy( this.points[ 0 ] );
  23596. for ( i = 1; i < nSamples; i ++ ) {
  23597. index = i / nSamples;
  23598. position = this.getPoint( index );
  23599. tmpVec.copy( position );
  23600. totalLength += tmpVec.distanceTo( oldPosition );
  23601. oldPosition.copy( position );
  23602. point = ( this.points.length - 1 ) * index;
  23603. intPoint = Math.floor( point );
  23604. if ( intPoint !== oldIntPoint ) {
  23605. chunkLengths[ intPoint ] = totalLength;
  23606. oldIntPoint = intPoint;
  23607. }
  23608. }
  23609. // last point ends with total length
  23610. chunkLengths[ chunkLengths.length ] = totalLength;
  23611. return { chunks: chunkLengths, total: totalLength };
  23612. };
  23613. this.reparametrizeByArcLength = function ( samplingCoef ) {
  23614. var i, j,
  23615. index, indexCurrent, indexNext,
  23616. realDistance,
  23617. sampling, position,
  23618. newpoints = [],
  23619. tmpVec = new Vector3(),
  23620. sl = this.getLength();
  23621. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  23622. for ( i = 1; i < this.points.length; i ++ ) {
  23623. //tmpVec.copy( this.points[ i - 1 ] );
  23624. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  23625. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  23626. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  23627. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  23628. indexNext = i / ( this.points.length - 1 );
  23629. for ( j = 1; j < sampling - 1; j ++ ) {
  23630. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  23631. position = this.getPoint( index );
  23632. newpoints.push( tmpVec.copy( position ).clone() );
  23633. }
  23634. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  23635. }
  23636. this.points = newpoints;
  23637. };
  23638. // Catmull-Rom
  23639. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  23640. var v0 = ( p2 - p0 ) * 0.5,
  23641. v1 = ( p3 - p1 ) * 0.5;
  23642. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23643. }
  23644. }
  23645. /**
  23646. * @author bhouston / http://clara.io
  23647. * @author WestLangley / http://github.com/WestLangley
  23648. *
  23649. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  23650. *
  23651. * The poles (phi) are at the positive and negative y axis.
  23652. * The equator starts at positive z.
  23653. */
  23654. function Spherical( radius, phi, theta ) {
  23655. this.radius = ( radius !== undefined ) ? radius : 1.0;
  23656. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  23657. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  23658. return this;
  23659. }
  23660. Spherical.prototype = {
  23661. constructor: Spherical,
  23662. set: function ( radius, phi, theta ) {
  23663. this.radius = radius;
  23664. this.phi = phi;
  23665. this.theta = theta;
  23666. return this;
  23667. },
  23668. clone: function () {
  23669. return new this.constructor().copy( this );
  23670. },
  23671. copy: function ( other ) {
  23672. this.radius = other.radius;
  23673. this.phi = other.phi;
  23674. this.theta = other.theta;
  23675. return this;
  23676. },
  23677. // restrict phi to be betwee EPS and PI-EPS
  23678. makeSafe: function() {
  23679. var EPS = 0.000001;
  23680. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  23681. return this;
  23682. },
  23683. setFromVector3: function( vec3 ) {
  23684. this.radius = vec3.length();
  23685. if ( this.radius === 0 ) {
  23686. this.theta = 0;
  23687. this.phi = 0;
  23688. } else {
  23689. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  23690. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  23691. }
  23692. return this;
  23693. }
  23694. };
  23695. /**
  23696. * @author alteredq / http://alteredqualia.com/
  23697. */
  23698. function MorphBlendMesh( geometry, material ) {
  23699. Mesh.call( this, geometry, material );
  23700. this.animationsMap = {};
  23701. this.animationsList = [];
  23702. // prepare default animation
  23703. // (all frames played together in 1 second)
  23704. var numFrames = this.geometry.morphTargets.length;
  23705. var name = "__default";
  23706. var startFrame = 0;
  23707. var endFrame = numFrames - 1;
  23708. var fps = numFrames / 1;
  23709. this.createAnimation( name, startFrame, endFrame, fps );
  23710. this.setAnimationWeight( name, 1 );
  23711. }
  23712. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  23713. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  23714. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  23715. var animation = {
  23716. start: start,
  23717. end: end,
  23718. length: end - start + 1,
  23719. fps: fps,
  23720. duration: ( end - start ) / fps,
  23721. lastFrame: 0,
  23722. currentFrame: 0,
  23723. active: false,
  23724. time: 0,
  23725. direction: 1,
  23726. weight: 1,
  23727. directionBackwards: false,
  23728. mirroredLoop: false
  23729. };
  23730. this.animationsMap[ name ] = animation;
  23731. this.animationsList.push( animation );
  23732. };
  23733. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  23734. var pattern = /([a-z]+)_?(\d+)/i;
  23735. var firstAnimation, frameRanges = {};
  23736. var geometry = this.geometry;
  23737. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  23738. var morph = geometry.morphTargets[ i ];
  23739. var chunks = morph.name.match( pattern );
  23740. if ( chunks && chunks.length > 1 ) {
  23741. var name = chunks[ 1 ];
  23742. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  23743. var range = frameRanges[ name ];
  23744. if ( i < range.start ) range.start = i;
  23745. if ( i > range.end ) range.end = i;
  23746. if ( ! firstAnimation ) firstAnimation = name;
  23747. }
  23748. }
  23749. for ( var name in frameRanges ) {
  23750. var range = frameRanges[ name ];
  23751. this.createAnimation( name, range.start, range.end, fps );
  23752. }
  23753. this.firstAnimation = firstAnimation;
  23754. };
  23755. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  23756. var animation = this.animationsMap[ name ];
  23757. if ( animation ) {
  23758. animation.direction = 1;
  23759. animation.directionBackwards = false;
  23760. }
  23761. };
  23762. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  23763. var animation = this.animationsMap[ name ];
  23764. if ( animation ) {
  23765. animation.direction = - 1;
  23766. animation.directionBackwards = true;
  23767. }
  23768. };
  23769. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  23770. var animation = this.animationsMap[ name ];
  23771. if ( animation ) {
  23772. animation.fps = fps;
  23773. animation.duration = ( animation.end - animation.start ) / animation.fps;
  23774. }
  23775. };
  23776. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  23777. var animation = this.animationsMap[ name ];
  23778. if ( animation ) {
  23779. animation.duration = duration;
  23780. animation.fps = ( animation.end - animation.start ) / animation.duration;
  23781. }
  23782. };
  23783. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  23784. var animation = this.animationsMap[ name ];
  23785. if ( animation ) {
  23786. animation.weight = weight;
  23787. }
  23788. };
  23789. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  23790. var animation = this.animationsMap[ name ];
  23791. if ( animation ) {
  23792. animation.time = time;
  23793. }
  23794. };
  23795. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  23796. var time = 0;
  23797. var animation = this.animationsMap[ name ];
  23798. if ( animation ) {
  23799. time = animation.time;
  23800. }
  23801. return time;
  23802. };
  23803. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  23804. var duration = - 1;
  23805. var animation = this.animationsMap[ name ];
  23806. if ( animation ) {
  23807. duration = animation.duration;
  23808. }
  23809. return duration;
  23810. };
  23811. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  23812. var animation = this.animationsMap[ name ];
  23813. if ( animation ) {
  23814. animation.time = 0;
  23815. animation.active = true;
  23816. } else {
  23817. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  23818. }
  23819. };
  23820. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  23821. var animation = this.animationsMap[ name ];
  23822. if ( animation ) {
  23823. animation.active = false;
  23824. }
  23825. };
  23826. MorphBlendMesh.prototype.update = function ( delta ) {
  23827. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  23828. var animation = this.animationsList[ i ];
  23829. if ( ! animation.active ) continue;
  23830. var frameTime = animation.duration / animation.length;
  23831. animation.time += animation.direction * delta;
  23832. if ( animation.mirroredLoop ) {
  23833. if ( animation.time > animation.duration || animation.time < 0 ) {
  23834. animation.direction *= - 1;
  23835. if ( animation.time > animation.duration ) {
  23836. animation.time = animation.duration;
  23837. animation.directionBackwards = true;
  23838. }
  23839. if ( animation.time < 0 ) {
  23840. animation.time = 0;
  23841. animation.directionBackwards = false;
  23842. }
  23843. }
  23844. } else {
  23845. animation.time = animation.time % animation.duration;
  23846. if ( animation.time < 0 ) animation.time += animation.duration;
  23847. }
  23848. var keyframe = animation.start + _Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  23849. var weight = animation.weight;
  23850. if ( keyframe !== animation.currentFrame ) {
  23851. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  23852. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  23853. this.morphTargetInfluences[ keyframe ] = 0;
  23854. animation.lastFrame = animation.currentFrame;
  23855. animation.currentFrame = keyframe;
  23856. }
  23857. var mix = ( animation.time % frameTime ) / frameTime;
  23858. if ( animation.directionBackwards ) mix = 1 - mix;
  23859. if ( animation.currentFrame !== animation.lastFrame ) {
  23860. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  23861. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  23862. } else {
  23863. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  23864. }
  23865. }
  23866. };
  23867. /**
  23868. * @author alteredq / http://alteredqualia.com/
  23869. */
  23870. function ImmediateRenderObject( material ) {
  23871. Object3D.call( this );
  23872. this.material = material;
  23873. this.render = function ( renderCallback ) {};
  23874. }
  23875. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  23876. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  23877. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  23878. /**
  23879. * @author mrdoob / http://mrdoob.com/
  23880. * @author WestLangley / http://github.com/WestLangley
  23881. */
  23882. function VertexNormalsHelper( object, size, hex, linewidth ) {
  23883. this.object = object;
  23884. this.size = ( size !== undefined ) ? size : 1;
  23885. var color = ( hex !== undefined ) ? hex : 0xff0000;
  23886. var width = ( linewidth !== undefined ) ? linewidth : 1;
  23887. //
  23888. var nNormals = 0;
  23889. var objGeometry = this.object.geometry;
  23890. if ( objGeometry && objGeometry.isGeometry ) {
  23891. nNormals = objGeometry.faces.length * 3;
  23892. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  23893. nNormals = objGeometry.attributes.normal.count;
  23894. }
  23895. //
  23896. var geometry = new BufferGeometry();
  23897. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  23898. geometry.addAttribute( 'position', positions );
  23899. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  23900. //
  23901. this.matrixAutoUpdate = false;
  23902. this.update();
  23903. }
  23904. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  23905. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  23906. VertexNormalsHelper.prototype.update = ( function () {
  23907. var v1 = new Vector3();
  23908. var v2 = new Vector3();
  23909. var normalMatrix = new Matrix3();
  23910. return function update() {
  23911. var keys = [ 'a', 'b', 'c' ];
  23912. this.object.updateMatrixWorld( true );
  23913. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  23914. var matrixWorld = this.object.matrixWorld;
  23915. var position = this.geometry.attributes.position;
  23916. //
  23917. var objGeometry = this.object.geometry;
  23918. if ( objGeometry && objGeometry.isGeometry ) {
  23919. var vertices = objGeometry.vertices;
  23920. var faces = objGeometry.faces;
  23921. var idx = 0;
  23922. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23923. var face = faces[ i ];
  23924. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  23925. var vertex = vertices[ face[ keys[ j ] ] ];
  23926. var normal = face.vertexNormals[ j ];
  23927. v1.copy( vertex ).applyMatrix4( matrixWorld );
  23928. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23929. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23930. idx = idx + 1;
  23931. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23932. idx = idx + 1;
  23933. }
  23934. }
  23935. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  23936. var objPos = objGeometry.attributes.position;
  23937. var objNorm = objGeometry.attributes.normal;
  23938. var idx = 0;
  23939. // for simplicity, ignore index and drawcalls, and render every normal
  23940. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  23941. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  23942. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  23943. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23944. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23945. idx = idx + 1;
  23946. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23947. idx = idx + 1;
  23948. }
  23949. }
  23950. position.needsUpdate = true;
  23951. return this;
  23952. };
  23953. }() );
  23954. /**
  23955. * @author alteredq / http://alteredqualia.com/
  23956. * @author mrdoob / http://mrdoob.com/
  23957. * @author WestLangley / http://github.com/WestLangley
  23958. */
  23959. function SpotLightHelper( light ) {
  23960. Object3D.call( this );
  23961. this.light = light;
  23962. this.light.updateMatrixWorld();
  23963. this.matrix = light.matrixWorld;
  23964. this.matrixAutoUpdate = false;
  23965. var geometry = new BufferGeometry();
  23966. var positions = [
  23967. 0, 0, 0, 0, 0, 1,
  23968. 0, 0, 0, 1, 0, 1,
  23969. 0, 0, 0, - 1, 0, 1,
  23970. 0, 0, 0, 0, 1, 1,
  23971. 0, 0, 0, 0, - 1, 1
  23972. ];
  23973. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  23974. var p1 = ( i / l ) * Math.PI * 2;
  23975. var p2 = ( j / l ) * Math.PI * 2;
  23976. positions.push(
  23977. Math.cos( p1 ), Math.sin( p1 ), 1,
  23978. Math.cos( p2 ), Math.sin( p2 ), 1
  23979. );
  23980. }
  23981. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  23982. var material = new LineBasicMaterial( { fog: false } );
  23983. this.cone = new LineSegments( geometry, material );
  23984. this.add( this.cone );
  23985. this.update();
  23986. }
  23987. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  23988. SpotLightHelper.prototype.constructor = SpotLightHelper;
  23989. SpotLightHelper.prototype.dispose = function () {
  23990. this.cone.geometry.dispose();
  23991. this.cone.material.dispose();
  23992. };
  23993. SpotLightHelper.prototype.update = function () {
  23994. var vector = new Vector3();
  23995. var vector2 = new Vector3();
  23996. return function update() {
  23997. var coneLength = this.light.distance ? this.light.distance : 1000;
  23998. var coneWidth = coneLength * Math.tan( this.light.angle );
  23999. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  24000. vector.setFromMatrixPosition( this.light.matrixWorld );
  24001. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24002. this.cone.lookAt( vector2.sub( vector ) );
  24003. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24004. };
  24005. }();
  24006. /**
  24007. * @author Sean Griffin / http://twitter.com/sgrif
  24008. * @author Michael Guerrero / http://realitymeltdown.com
  24009. * @author mrdoob / http://mrdoob.com/
  24010. * @author ikerr / http://verold.com
  24011. * @author Mugen87 / https://github.com/Mugen87
  24012. */
  24013. function SkeletonHelper( object ) {
  24014. this.bones = this.getBoneList( object );
  24015. var geometry = new BufferGeometry();
  24016. var vertices = [];
  24017. var colors = [];
  24018. var color1 = new Color( 0, 0, 1 );
  24019. var color2 = new Color( 0, 1, 0 );
  24020. for ( var i = 0; i < this.bones.length; i ++ ) {
  24021. var bone = this.bones[ i ];
  24022. if ( bone.parent && bone.parent.isBone ) {
  24023. vertices.push( 0, 0, 0 );
  24024. vertices.push( 0, 0, 0 );
  24025. colors.push( color1.r, color1.g, color1.b );
  24026. colors.push( color2.r, color2.g, color2.b );
  24027. }
  24028. }
  24029. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24030. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24031. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  24032. LineSegments.call( this, geometry, material );
  24033. this.root = object;
  24034. this.matrix = object.matrixWorld;
  24035. this.matrixAutoUpdate = false;
  24036. this.update();
  24037. }
  24038. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  24039. SkeletonHelper.prototype.constructor = SkeletonHelper;
  24040. SkeletonHelper.prototype.getBoneList = function( object ) {
  24041. var boneList = [];
  24042. if ( object && object.isBone ) {
  24043. boneList.push( object );
  24044. }
  24045. for ( var i = 0; i < object.children.length; i ++ ) {
  24046. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  24047. }
  24048. return boneList;
  24049. };
  24050. SkeletonHelper.prototype.update = function () {
  24051. var vector = new Vector3();
  24052. var boneMatrix = new Matrix4();
  24053. var matrixWorldInv = new Matrix4();
  24054. return function update() {
  24055. var geometry = this.geometry;
  24056. var position = geometry.getAttribute( 'position' );
  24057. matrixWorldInv.getInverse( this.root.matrixWorld );
  24058. for ( var i = 0, j = 0; i < this.bones.length; i ++, j += 2 ) {
  24059. var bone = this.bones[ i ];
  24060. if ( bone.parent && bone.parent.isBone ) {
  24061. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  24062. vector.setFromMatrixPosition( boneMatrix );
  24063. position.setXYZ( j, vector.x, vector.y, vector.z );
  24064. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  24065. vector.setFromMatrixPosition( boneMatrix );
  24066. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  24067. }
  24068. }
  24069. geometry.getAttribute( 'position' ).needsUpdate = true;
  24070. };
  24071. }();
  24072. /**
  24073. * @author alteredq / http://alteredqualia.com/
  24074. * @author mrdoob / http://mrdoob.com/
  24075. */
  24076. function PointLightHelper( light, sphereSize ) {
  24077. this.light = light;
  24078. this.light.updateMatrixWorld();
  24079. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  24080. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  24081. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24082. Mesh.call( this, geometry, material );
  24083. this.matrix = this.light.matrixWorld;
  24084. this.matrixAutoUpdate = false;
  24085. /*
  24086. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  24087. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  24088. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  24089. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  24090. var d = light.distance;
  24091. if ( d === 0.0 ) {
  24092. this.lightDistance.visible = false;
  24093. } else {
  24094. this.lightDistance.scale.set( d, d, d );
  24095. }
  24096. this.add( this.lightDistance );
  24097. */
  24098. }
  24099. PointLightHelper.prototype = Object.create( Mesh.prototype );
  24100. PointLightHelper.prototype.constructor = PointLightHelper;
  24101. PointLightHelper.prototype.dispose = function () {
  24102. this.geometry.dispose();
  24103. this.material.dispose();
  24104. };
  24105. PointLightHelper.prototype.update = function () {
  24106. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24107. /*
  24108. var d = this.light.distance;
  24109. if ( d === 0.0 ) {
  24110. this.lightDistance.visible = false;
  24111. } else {
  24112. this.lightDistance.visible = true;
  24113. this.lightDistance.scale.set( d, d, d );
  24114. }
  24115. */
  24116. };
  24117. /**
  24118. * @author abelnation / http://github.com/abelnation
  24119. */
  24120. function RectAreaLightHelper( light ) {
  24121. Object3D.call( this );
  24122. this.light = light;
  24123. this.light.updateMatrixWorld();
  24124. this.lightMat = new MeshBasicMaterial( {
  24125. color: light.color,
  24126. fog: false
  24127. } );
  24128. this.lightWireMat = new MeshBasicMaterial( {
  24129. color: light.color,
  24130. fog: false,
  24131. wireframe: true
  24132. } );
  24133. var hx = this.light.width / 2.0;
  24134. var hy = this.light.height / 2.0;
  24135. this.lightShape = new ShapeBufferGeometry( new Shape( [
  24136. new Vector3( - hx, hy, 0 ),
  24137. new Vector3( hx, hy, 0 ),
  24138. new Vector3( hx, - hy, 0 ),
  24139. new Vector3( - hx, - hy, 0 )
  24140. ] ) );
  24141. // shows the "front" of the light, e.g. where light comes from
  24142. this.lightMesh = new Mesh( this.lightShape, this.lightMat );
  24143. // shows the "back" of the light, which does not emit light
  24144. this.lightWireMesh = new Mesh( this.lightShape, this.lightWireMat );
  24145. this.add( this.lightMesh );
  24146. this.add( this.lightWireMesh );
  24147. this.update();
  24148. }
  24149. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  24150. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  24151. RectAreaLightHelper.prototype.dispose = function () {
  24152. this.lightMesh.geometry.dispose();
  24153. this.lightMesh.material.dispose();
  24154. this.lightWireMesh.geometry.dispose();
  24155. this.lightWireMesh.material.dispose();
  24156. };
  24157. RectAreaLightHelper.prototype.update = function () {
  24158. var vector = new Vector3();
  24159. var vector2 = new Vector3();
  24160. // TODO (abelnation) why not just make light helpers a child of the light object?
  24161. if ( this.light.target ) {
  24162. vector.setFromMatrixPosition( this.light.matrixWorld );
  24163. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24164. var lookVec = vector2.clone().sub( vector );
  24165. this.lightMesh.lookAt( lookVec );
  24166. this.lightWireMesh.lookAt( lookVec );
  24167. }
  24168. this.lightMesh.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24169. this.lightWireMesh.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24170. var oldShape = this.lightShape;
  24171. var hx = this.light.width / 2.0;
  24172. var hy = this.light.height / 2.0;
  24173. this.lightShape = new ShapeBufferGeometry( new Shape( [
  24174. new Vector3( - hx, hy, 0 ),
  24175. new Vector3( hx, hy, 0 ),
  24176. new Vector3( hx, - hy, 0 ),
  24177. new Vector3( - hx, - hy, 0 )
  24178. ] ) );
  24179. this.lightMesh.geometry = this.lightShape;
  24180. this.lightWireMesh.geometry = this.lightShape;
  24181. oldShape.dispose();
  24182. };
  24183. /**
  24184. * @author alteredq / http://alteredqualia.com/
  24185. * @author mrdoob / http://mrdoob.com/
  24186. */
  24187. function HemisphereLightHelper( light, sphereSize ) {
  24188. Object3D.call( this );
  24189. this.light = light;
  24190. this.light.updateMatrixWorld();
  24191. this.matrix = light.matrixWorld;
  24192. this.matrixAutoUpdate = false;
  24193. this.colors = [ new Color(), new Color() ];
  24194. var geometry = new SphereGeometry( sphereSize, 4, 2 );
  24195. geometry.rotateX( - Math.PI / 2 );
  24196. for ( var i = 0, il = 8; i < il; i ++ ) {
  24197. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  24198. }
  24199. var material = new MeshBasicMaterial( { vertexColors: FaceColors, wireframe: true } );
  24200. this.lightSphere = new Mesh( geometry, material );
  24201. this.add( this.lightSphere );
  24202. this.update();
  24203. }
  24204. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  24205. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  24206. HemisphereLightHelper.prototype.dispose = function () {
  24207. this.lightSphere.geometry.dispose();
  24208. this.lightSphere.material.dispose();
  24209. };
  24210. HemisphereLightHelper.prototype.update = function () {
  24211. var vector = new Vector3();
  24212. return function update() {
  24213. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  24214. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  24215. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  24216. this.lightSphere.geometry.colorsNeedUpdate = true;
  24217. };
  24218. }();
  24219. /**
  24220. * @author mrdoob / http://mrdoob.com/
  24221. */
  24222. function GridHelper( size, divisions, color1, color2 ) {
  24223. size = size || 10;
  24224. divisions = divisions || 10;
  24225. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24226. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24227. var center = divisions / 2;
  24228. var step = ( size * 2 ) / divisions;
  24229. var vertices = [], colors = [];
  24230. for ( var i = 0, j = 0, k = - size; i <= divisions; i ++, k += step ) {
  24231. vertices.push( - size, 0, k, size, 0, k );
  24232. vertices.push( k, 0, - size, k, 0, size );
  24233. var color = i === center ? color1 : color2;
  24234. color.toArray( colors, j ); j += 3;
  24235. color.toArray( colors, j ); j += 3;
  24236. color.toArray( colors, j ); j += 3;
  24237. color.toArray( colors, j ); j += 3;
  24238. }
  24239. var geometry = new BufferGeometry();
  24240. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24241. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24242. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24243. LineSegments.call( this, geometry, material );
  24244. }
  24245. GridHelper.prototype = Object.create( LineSegments.prototype );
  24246. GridHelper.prototype.constructor = GridHelper;
  24247. /**
  24248. * @author mrdoob / http://mrdoob.com/
  24249. * @author Mugen87 / http://github.com/Mugen87
  24250. * @author Hectate / http://www.github.com/Hectate
  24251. */
  24252. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  24253. radius = radius || 10;
  24254. radials = radials || 16;
  24255. circles = circles || 8;
  24256. divisions = divisions || 64;
  24257. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24258. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24259. var vertices = [];
  24260. var colors = [];
  24261. var x, z;
  24262. var v, i, j, r, color;
  24263. // create the radials
  24264. for ( i = 0; i <= radials; i ++ ) {
  24265. v = ( i / radials ) * ( Math.PI * 2 );
  24266. x = Math.sin( v ) * radius;
  24267. z = Math.cos( v ) * radius;
  24268. vertices.push( 0, 0, 0 );
  24269. vertices.push( x, 0, z );
  24270. color = ( i & 1 ) ? color1 : color2;
  24271. colors.push( color.r, color.g, color.b );
  24272. colors.push( color.r, color.g, color.b );
  24273. }
  24274. // create the circles
  24275. for ( i = 0; i <= circles; i ++ ) {
  24276. color = ( i & 1 ) ? color1 : color2;
  24277. r = radius - ( radius / circles * i );
  24278. for ( j = 0; j < divisions; j ++ ) {
  24279. // first vertex
  24280. v = ( j / divisions ) * ( Math.PI * 2 );
  24281. x = Math.sin( v ) * r;
  24282. z = Math.cos( v ) * r;
  24283. vertices.push( x, 0, z );
  24284. colors.push( color.r, color.g, color.b );
  24285. // second vertex
  24286. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  24287. x = Math.sin( v ) * r;
  24288. z = Math.cos( v ) * r;
  24289. vertices.push( x, 0, z );
  24290. colors.push( color.r, color.g, color.b );
  24291. }
  24292. }
  24293. var geometry = new BufferGeometry();
  24294. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24295. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24296. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24297. LineSegments.call( this, geometry, material );
  24298. }
  24299. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  24300. PolarGridHelper.prototype.constructor = PolarGridHelper;
  24301. /**
  24302. * @author mrdoob / http://mrdoob.com/
  24303. * @author WestLangley / http://github.com/WestLangley
  24304. */
  24305. function FaceNormalsHelper( object, size, hex, linewidth ) {
  24306. // FaceNormalsHelper only supports THREE.Geometry
  24307. this.object = object;
  24308. this.size = ( size !== undefined ) ? size : 1;
  24309. var color = ( hex !== undefined ) ? hex : 0xffff00;
  24310. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24311. //
  24312. var nNormals = 0;
  24313. var objGeometry = this.object.geometry;
  24314. if ( objGeometry && objGeometry.isGeometry ) {
  24315. nNormals = objGeometry.faces.length;
  24316. } else {
  24317. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  24318. }
  24319. //
  24320. var geometry = new BufferGeometry();
  24321. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24322. geometry.addAttribute( 'position', positions );
  24323. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24324. //
  24325. this.matrixAutoUpdate = false;
  24326. this.update();
  24327. }
  24328. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24329. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  24330. FaceNormalsHelper.prototype.update = ( function () {
  24331. var v1 = new Vector3();
  24332. var v2 = new Vector3();
  24333. var normalMatrix = new Matrix3();
  24334. return function update() {
  24335. this.object.updateMatrixWorld( true );
  24336. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24337. var matrixWorld = this.object.matrixWorld;
  24338. var position = this.geometry.attributes.position;
  24339. //
  24340. var objGeometry = this.object.geometry;
  24341. var vertices = objGeometry.vertices;
  24342. var faces = objGeometry.faces;
  24343. var idx = 0;
  24344. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24345. var face = faces[ i ];
  24346. var normal = face.normal;
  24347. v1.copy( vertices[ face.a ] )
  24348. .add( vertices[ face.b ] )
  24349. .add( vertices[ face.c ] )
  24350. .divideScalar( 3 )
  24351. .applyMatrix4( matrixWorld );
  24352. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24353. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24354. idx = idx + 1;
  24355. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24356. idx = idx + 1;
  24357. }
  24358. position.needsUpdate = true;
  24359. return this;
  24360. };
  24361. }() );
  24362. /**
  24363. * @author alteredq / http://alteredqualia.com/
  24364. * @author mrdoob / http://mrdoob.com/
  24365. * @author WestLangley / http://github.com/WestLangley
  24366. */
  24367. function DirectionalLightHelper( light, size ) {
  24368. Object3D.call( this );
  24369. this.light = light;
  24370. this.light.updateMatrixWorld();
  24371. this.matrix = light.matrixWorld;
  24372. this.matrixAutoUpdate = false;
  24373. if ( size === undefined ) size = 1;
  24374. var geometry = new BufferGeometry();
  24375. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  24376. - size, size, 0,
  24377. size, size, 0,
  24378. size, - size, 0,
  24379. - size, - size, 0,
  24380. - size, size, 0
  24381. ], 3 ) );
  24382. var material = new LineBasicMaterial( { fog: false } );
  24383. this.add( new Line( geometry, material ) );
  24384. geometry = new BufferGeometry();
  24385. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  24386. this.add( new Line( geometry, material ));
  24387. this.update();
  24388. }
  24389. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  24390. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  24391. DirectionalLightHelper.prototype.dispose = function () {
  24392. var lightPlane = this.children[ 0 ];
  24393. var targetLine = this.children[ 1 ];
  24394. lightPlane.geometry.dispose();
  24395. lightPlane.material.dispose();
  24396. targetLine.geometry.dispose();
  24397. targetLine.material.dispose();
  24398. };
  24399. DirectionalLightHelper.prototype.update = function () {
  24400. var v1 = new Vector3();
  24401. var v2 = new Vector3();
  24402. var v3 = new Vector3();
  24403. return function update() {
  24404. v1.setFromMatrixPosition( this.light.matrixWorld );
  24405. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  24406. v3.subVectors( v2, v1 );
  24407. var lightPlane = this.children[ 0 ];
  24408. var targetLine = this.children[ 1 ];
  24409. lightPlane.lookAt( v3 );
  24410. lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24411. targetLine.lookAt( v3 );
  24412. targetLine.scale.z = v3.length();
  24413. };
  24414. }();
  24415. /**
  24416. * @author alteredq / http://alteredqualia.com/
  24417. * @author Mugen87 / https://github.com/Mugen87
  24418. *
  24419. * - shows frustum, line of sight and up of the camera
  24420. * - suitable for fast updates
  24421. * - based on frustum visualization in lightgl.js shadowmap example
  24422. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  24423. */
  24424. function CameraHelper( camera ) {
  24425. var geometry = new BufferGeometry();
  24426. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  24427. var vertices = [];
  24428. var colors = [];
  24429. var pointMap = {};
  24430. // colors
  24431. var colorFrustum = new Color( 0xffaa00 );
  24432. var colorCone = new Color( 0xff0000 );
  24433. var colorUp = new Color( 0x00aaff );
  24434. var colorTarget = new Color( 0xffffff );
  24435. var colorCross = new Color( 0x333333 );
  24436. // near
  24437. addLine( "n1", "n2", colorFrustum );
  24438. addLine( "n2", "n4", colorFrustum );
  24439. addLine( "n4", "n3", colorFrustum );
  24440. addLine( "n3", "n1", colorFrustum );
  24441. // far
  24442. addLine( "f1", "f2", colorFrustum );
  24443. addLine( "f2", "f4", colorFrustum );
  24444. addLine( "f4", "f3", colorFrustum );
  24445. addLine( "f3", "f1", colorFrustum );
  24446. // sides
  24447. addLine( "n1", "f1", colorFrustum );
  24448. addLine( "n2", "f2", colorFrustum );
  24449. addLine( "n3", "f3", colorFrustum );
  24450. addLine( "n4", "f4", colorFrustum );
  24451. // cone
  24452. addLine( "p", "n1", colorCone );
  24453. addLine( "p", "n2", colorCone );
  24454. addLine( "p", "n3", colorCone );
  24455. addLine( "p", "n4", colorCone );
  24456. // up
  24457. addLine( "u1", "u2", colorUp );
  24458. addLine( "u2", "u3", colorUp );
  24459. addLine( "u3", "u1", colorUp );
  24460. // target
  24461. addLine( "c", "t", colorTarget );
  24462. addLine( "p", "c", colorCross );
  24463. // cross
  24464. addLine( "cn1", "cn2", colorCross );
  24465. addLine( "cn3", "cn4", colorCross );
  24466. addLine( "cf1", "cf2", colorCross );
  24467. addLine( "cf3", "cf4", colorCross );
  24468. function addLine( a, b, color ) {
  24469. addPoint( a, color );
  24470. addPoint( b, color );
  24471. }
  24472. function addPoint( id, color ) {
  24473. vertices.push( 0, 0, 0 );
  24474. colors.push( color.r, color.g, color.b );
  24475. if ( pointMap[ id ] === undefined ) {
  24476. pointMap[ id ] = [];
  24477. }
  24478. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  24479. }
  24480. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24481. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24482. LineSegments.call( this, geometry, material );
  24483. this.camera = camera;
  24484. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  24485. this.matrix = camera.matrixWorld;
  24486. this.matrixAutoUpdate = false;
  24487. this.pointMap = pointMap;
  24488. this.update();
  24489. }
  24490. CameraHelper.prototype = Object.create( LineSegments.prototype );
  24491. CameraHelper.prototype.constructor = CameraHelper;
  24492. CameraHelper.prototype.update = function () {
  24493. var geometry, pointMap;
  24494. var vector = new Vector3();
  24495. var camera = new Camera();
  24496. function setPoint( point, x, y, z ) {
  24497. vector.set( x, y, z ).unproject( camera );
  24498. var points = pointMap[ point ];
  24499. if ( points !== undefined ) {
  24500. var position = geometry.getAttribute( 'position' );
  24501. for ( var i = 0, l = points.length; i < l; i ++ ) {
  24502. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  24503. }
  24504. }
  24505. }
  24506. return function update() {
  24507. geometry = this.geometry;
  24508. pointMap = this.pointMap;
  24509. var w = 1, h = 1;
  24510. // we need just camera projection matrix
  24511. // world matrix must be identity
  24512. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  24513. // center / target
  24514. setPoint( "c", 0, 0, - 1 );
  24515. setPoint( "t", 0, 0, 1 );
  24516. // near
  24517. setPoint( "n1", - w, - h, - 1 );
  24518. setPoint( "n2", w, - h, - 1 );
  24519. setPoint( "n3", - w, h, - 1 );
  24520. setPoint( "n4", w, h, - 1 );
  24521. // far
  24522. setPoint( "f1", - w, - h, 1 );
  24523. setPoint( "f2", w, - h, 1 );
  24524. setPoint( "f3", - w, h, 1 );
  24525. setPoint( "f4", w, h, 1 );
  24526. // up
  24527. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  24528. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  24529. setPoint( "u3", 0, h * 2, - 1 );
  24530. // cross
  24531. setPoint( "cf1", - w, 0, 1 );
  24532. setPoint( "cf2", w, 0, 1 );
  24533. setPoint( "cf3", 0, - h, 1 );
  24534. setPoint( "cf4", 0, h, 1 );
  24535. setPoint( "cn1", - w, 0, - 1 );
  24536. setPoint( "cn2", w, 0, - 1 );
  24537. setPoint( "cn3", 0, - h, - 1 );
  24538. setPoint( "cn4", 0, h, - 1 );
  24539. geometry.getAttribute( 'position' ).needsUpdate = true;
  24540. };
  24541. }();
  24542. /**
  24543. * @author mrdoob / http://mrdoob.com/
  24544. */
  24545. function BoxHelper( object, color ) {
  24546. if ( color === undefined ) color = 0xffff00;
  24547. 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 ] );
  24548. var positions = new Float32Array( 8 * 3 );
  24549. var geometry = new BufferGeometry();
  24550. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  24551. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  24552. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  24553. if ( object !== undefined ) {
  24554. this.update( object );
  24555. }
  24556. }
  24557. BoxHelper.prototype = Object.create( LineSegments.prototype );
  24558. BoxHelper.prototype.constructor = BoxHelper;
  24559. BoxHelper.prototype.update = ( function () {
  24560. var box = new Box3();
  24561. return function update( object ) {
  24562. if ( object && object.isBox3 ) {
  24563. box.copy( object );
  24564. } else {
  24565. box.setFromObject( object );
  24566. }
  24567. if ( box.isEmpty() ) return;
  24568. var min = box.min;
  24569. var max = box.max;
  24570. /*
  24571. 5____4
  24572. 1/___0/|
  24573. | 6__|_7
  24574. 2/___3/
  24575. 0: max.x, max.y, max.z
  24576. 1: min.x, max.y, max.z
  24577. 2: min.x, min.y, max.z
  24578. 3: max.x, min.y, max.z
  24579. 4: max.x, max.y, min.z
  24580. 5: min.x, max.y, min.z
  24581. 6: min.x, min.y, min.z
  24582. 7: max.x, min.y, min.z
  24583. */
  24584. var position = this.geometry.attributes.position;
  24585. var array = position.array;
  24586. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  24587. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  24588. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  24589. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  24590. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  24591. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  24592. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  24593. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  24594. position.needsUpdate = true;
  24595. this.geometry.computeBoundingSphere();
  24596. };
  24597. } )();
  24598. /**
  24599. * @author WestLangley / http://github.com/WestLangley
  24600. * @author zz85 / http://github.com/zz85
  24601. * @author bhouston / http://clara.io
  24602. *
  24603. * Creates an arrow for visualizing directions
  24604. *
  24605. * Parameters:
  24606. * dir - Vector3
  24607. * origin - Vector3
  24608. * length - Number
  24609. * color - color in hex value
  24610. * headLength - Number
  24611. * headWidth - Number
  24612. */
  24613. var lineGeometry = new BufferGeometry();
  24614. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  24615. var coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  24616. coneGeometry.translate( 0, - 0.5, 0 );
  24617. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  24618. // dir is assumed to be normalized
  24619. Object3D.call( this );
  24620. if ( color === undefined ) color = 0xffff00;
  24621. if ( length === undefined ) length = 1;
  24622. if ( headLength === undefined ) headLength = 0.2 * length;
  24623. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24624. this.position.copy( origin );
  24625. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  24626. this.line.matrixAutoUpdate = false;
  24627. this.add( this.line );
  24628. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  24629. this.cone.matrixAutoUpdate = false;
  24630. this.add( this.cone );
  24631. this.setDirection( dir );
  24632. this.setLength( length, headLength, headWidth );
  24633. }
  24634. ArrowHelper.prototype = Object.create( Object3D.prototype );
  24635. ArrowHelper.prototype.constructor = ArrowHelper;
  24636. ArrowHelper.prototype.setDirection = ( function () {
  24637. var axis = new Vector3();
  24638. var radians;
  24639. return function setDirection( dir ) {
  24640. // dir is assumed to be normalized
  24641. if ( dir.y > 0.99999 ) {
  24642. this.quaternion.set( 0, 0, 0, 1 );
  24643. } else if ( dir.y < - 0.99999 ) {
  24644. this.quaternion.set( 1, 0, 0, 0 );
  24645. } else {
  24646. axis.set( dir.z, 0, - dir.x ).normalize();
  24647. radians = Math.acos( dir.y );
  24648. this.quaternion.setFromAxisAngle( axis, radians );
  24649. }
  24650. };
  24651. }() );
  24652. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  24653. if ( headLength === undefined ) headLength = 0.2 * length;
  24654. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24655. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  24656. this.line.updateMatrix();
  24657. this.cone.scale.set( headWidth, headLength, headWidth );
  24658. this.cone.position.y = length;
  24659. this.cone.updateMatrix();
  24660. };
  24661. ArrowHelper.prototype.setColor = function ( color ) {
  24662. this.line.material.color.copy( color );
  24663. this.cone.material.color.copy( color );
  24664. };
  24665. /**
  24666. * @author sroucheray / http://sroucheray.org/
  24667. * @author mrdoob / http://mrdoob.com/
  24668. */
  24669. function AxisHelper( size ) {
  24670. size = size || 1;
  24671. var vertices = [
  24672. 0, 0, 0, size, 0, 0,
  24673. 0, 0, 0, 0, size, 0,
  24674. 0, 0, 0, 0, 0, size
  24675. ];
  24676. var colors = [
  24677. 1, 0, 0, 1, 0.6, 0,
  24678. 0, 1, 0, 0.6, 1, 0,
  24679. 0, 0, 1, 0, 0.6, 1
  24680. ];
  24681. var geometry = new BufferGeometry();
  24682. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24683. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24684. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24685. LineSegments.call( this, geometry, material );
  24686. }
  24687. AxisHelper.prototype = Object.create( LineSegments.prototype );
  24688. AxisHelper.prototype.constructor = AxisHelper;
  24689. /**
  24690. * @author zz85 https://github.com/zz85
  24691. *
  24692. * Centripetal CatmullRom Curve - which is useful for avoiding
  24693. * cusps and self-intersections in non-uniform catmull rom curves.
  24694. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  24695. *
  24696. * curve.type accepts centripetal(default), chordal and catmullrom
  24697. * curve.tension is used for catmullrom which defaults to 0.5
  24698. */
  24699. var CatmullRomCurve3 = ( function() {
  24700. var
  24701. tmp = new Vector3(),
  24702. px = new CubicPoly(),
  24703. py = new CubicPoly(),
  24704. pz = new CubicPoly();
  24705. /*
  24706. Based on an optimized c++ solution in
  24707. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  24708. - http://ideone.com/NoEbVM
  24709. This CubicPoly class could be used for reusing some variables and calculations,
  24710. but for three.js curve use, it could be possible inlined and flatten into a single function call
  24711. which can be placed in CurveUtils.
  24712. */
  24713. function CubicPoly() {}
  24714. /*
  24715. * Compute coefficients for a cubic polynomial
  24716. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  24717. * such that
  24718. * p(0) = x0, p(1) = x1
  24719. * and
  24720. * p'(0) = t0, p'(1) = t1.
  24721. */
  24722. CubicPoly.prototype.init = function( x0, x1, t0, t1 ) {
  24723. this.c0 = x0;
  24724. this.c1 = t0;
  24725. this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  24726. this.c3 = 2 * x0 - 2 * x1 + t0 + t1;
  24727. };
  24728. CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  24729. // compute tangents when parameterized in [t1,t2]
  24730. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  24731. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  24732. // rescale tangents for parametrization in [0,1]
  24733. t1 *= dt1;
  24734. t2 *= dt1;
  24735. // initCubicPoly
  24736. this.init( x1, x2, t1, t2 );
  24737. };
  24738. // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4
  24739. CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) {
  24740. this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  24741. };
  24742. CubicPoly.prototype.calc = function( t ) {
  24743. var t2 = t * t;
  24744. var t3 = t2 * t;
  24745. return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3;
  24746. };
  24747. // Subclass Three.js curve
  24748. return Curve.create(
  24749. function ( p /* array of Vector3 */ ) {
  24750. this.points = p || [];
  24751. this.closed = false;
  24752. },
  24753. function ( t ) {
  24754. var points = this.points,
  24755. point, intPoint, weight, l;
  24756. l = points.length;
  24757. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  24758. point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  24759. intPoint = Math.floor( point );
  24760. weight = point - intPoint;
  24761. if ( this.closed ) {
  24762. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  24763. } else if ( weight === 0 && intPoint === l - 1 ) {
  24764. intPoint = l - 2;
  24765. weight = 1;
  24766. }
  24767. var p0, p1, p2, p3; // 4 points
  24768. if ( this.closed || intPoint > 0 ) {
  24769. p0 = points[ ( intPoint - 1 ) % l ];
  24770. } else {
  24771. // extrapolate first point
  24772. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  24773. p0 = tmp;
  24774. }
  24775. p1 = points[ intPoint % l ];
  24776. p2 = points[ ( intPoint + 1 ) % l ];
  24777. if ( this.closed || intPoint + 2 < l ) {
  24778. p3 = points[ ( intPoint + 2 ) % l ];
  24779. } else {
  24780. // extrapolate last point
  24781. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24782. p3 = tmp;
  24783. }
  24784. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  24785. // init Centripetal / Chordal Catmull-Rom
  24786. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  24787. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24788. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24789. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24790. // safety check for repeated points
  24791. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24792. if ( dt0 < 1e-4 ) dt0 = dt1;
  24793. if ( dt2 < 1e-4 ) dt2 = dt1;
  24794. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24795. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24796. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24797. } else if ( this.type === 'catmullrom' ) {
  24798. var tension = this.tension !== undefined ? this.tension : 0.5;
  24799. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  24800. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  24801. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  24802. }
  24803. var v = new Vector3(
  24804. px.calc( weight ),
  24805. py.calc( weight ),
  24806. pz.calc( weight )
  24807. );
  24808. return v;
  24809. }
  24810. );
  24811. } )();
  24812. /**************************************************************
  24813. * Spline 3D curve
  24814. **************************************************************/
  24815. var SplineCurve3 = Curve.create(
  24816. function ( points /* array of Vector3 */ ) {
  24817. console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' );
  24818. this.points = ( points === undefined ) ? [] : points;
  24819. },
  24820. function ( t ) {
  24821. var points = this.points;
  24822. var point = ( points.length - 1 ) * t;
  24823. var intPoint = Math.floor( point );
  24824. var weight = point - intPoint;
  24825. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  24826. var point1 = points[ intPoint ];
  24827. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24828. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24829. var interpolate = CurveUtils.interpolate;
  24830. return new Vector3(
  24831. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  24832. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  24833. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  24834. );
  24835. }
  24836. );
  24837. /**************************************************************
  24838. * Cubic Bezier 3D curve
  24839. **************************************************************/
  24840. var CubicBezierCurve3 = Curve.create(
  24841. function ( v0, v1, v2, v3 ) {
  24842. this.v0 = v0;
  24843. this.v1 = v1;
  24844. this.v2 = v2;
  24845. this.v3 = v3;
  24846. },
  24847. function ( t ) {
  24848. var b3 = ShapeUtils.b3;
  24849. return new Vector3(
  24850. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  24851. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ),
  24852. b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z )
  24853. );
  24854. }
  24855. );
  24856. /**************************************************************
  24857. * Quadratic Bezier 3D curve
  24858. **************************************************************/
  24859. var QuadraticBezierCurve3 = Curve.create(
  24860. function ( v0, v1, v2 ) {
  24861. this.v0 = v0;
  24862. this.v1 = v1;
  24863. this.v2 = v2;
  24864. },
  24865. function ( t ) {
  24866. var b2 = ShapeUtils.b2;
  24867. return new Vector3(
  24868. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  24869. b2( t, this.v0.y, this.v1.y, this.v2.y ),
  24870. b2( t, this.v0.z, this.v1.z, this.v2.z )
  24871. );
  24872. }
  24873. );
  24874. /**************************************************************
  24875. * Line3D
  24876. **************************************************************/
  24877. var LineCurve3 = Curve.create(
  24878. function ( v1, v2 ) {
  24879. this.v1 = v1;
  24880. this.v2 = v2;
  24881. },
  24882. function ( t ) {
  24883. if ( t === 1 ) {
  24884. return this.v2.clone();
  24885. }
  24886. var vector = new Vector3();
  24887. vector.subVectors( this.v2, this.v1 ); // diff
  24888. vector.multiplyScalar( t );
  24889. vector.add( this.v1 );
  24890. return vector;
  24891. }
  24892. );
  24893. /**************************************************************
  24894. * Arc curve
  24895. **************************************************************/
  24896. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24897. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24898. }
  24899. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  24900. ArcCurve.prototype.constructor = ArcCurve;
  24901. /**
  24902. * @author alteredq / http://alteredqualia.com/
  24903. */
  24904. var SceneUtils = {
  24905. createMultiMaterialObject: function ( geometry, materials ) {
  24906. var group = new Group();
  24907. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  24908. group.add( new Mesh( geometry, materials[ i ] ) );
  24909. }
  24910. return group;
  24911. },
  24912. detach: function ( child, parent, scene ) {
  24913. child.applyMatrix( parent.matrixWorld );
  24914. parent.remove( child );
  24915. scene.add( child );
  24916. },
  24917. attach: function ( child, scene, parent ) {
  24918. var matrixWorldInverse = new Matrix4();
  24919. matrixWorldInverse.getInverse( parent.matrixWorld );
  24920. child.applyMatrix( matrixWorldInverse );
  24921. scene.remove( child );
  24922. parent.add( child );
  24923. }
  24924. };
  24925. /**
  24926. * @author mrdoob / http://mrdoob.com/
  24927. */
  24928. function Face4( a, b, c, d, normal, color, materialIndex ) {
  24929. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  24930. return new Face3( a, b, c, normal, color, materialIndex );
  24931. }
  24932. var LineStrip = 0;
  24933. var LinePieces = 1;
  24934. function MeshFaceMaterial( materials ) {
  24935. console.warn( 'THREE.MeshFaceMaterial has been renamed to THREE.MultiMaterial.' );
  24936. return new MultiMaterial( materials );
  24937. }
  24938. function PointCloud( geometry, material ) {
  24939. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  24940. return new Points( geometry, material );
  24941. }
  24942. function Particle( material ) {
  24943. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  24944. return new Sprite( material );
  24945. }
  24946. function ParticleSystem( geometry, material ) {
  24947. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  24948. return new Points( geometry, material );
  24949. }
  24950. function PointCloudMaterial( parameters ) {
  24951. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  24952. return new PointsMaterial( parameters );
  24953. }
  24954. function ParticleBasicMaterial( parameters ) {
  24955. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  24956. return new PointsMaterial( parameters );
  24957. }
  24958. function ParticleSystemMaterial( parameters ) {
  24959. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  24960. return new PointsMaterial( parameters );
  24961. }
  24962. function Vertex( x, y, z ) {
  24963. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  24964. return new Vector3( x, y, z );
  24965. }
  24966. //
  24967. function DynamicBufferAttribute( array, itemSize ) {
  24968. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  24969. return new BufferAttribute( array, itemSize ).setDynamic( true );
  24970. }
  24971. function Int8Attribute( array, itemSize ) {
  24972. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  24973. return new Int8BufferAttribute( array, itemSize );
  24974. }
  24975. function Uint8Attribute( array, itemSize ) {
  24976. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  24977. return new Uint8BufferAttribute( array, itemSize );
  24978. }
  24979. function Uint8ClampedAttribute( array, itemSize ) {
  24980. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  24981. return new Uint8ClampedBufferAttribute( array, itemSize );
  24982. }
  24983. function Int16Attribute( array, itemSize ) {
  24984. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  24985. return new Int16BufferAttribute( array, itemSize );
  24986. }
  24987. function Uint16Attribute( array, itemSize ) {
  24988. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  24989. return new Uint16BufferAttribute( array, itemSize );
  24990. }
  24991. function Int32Attribute( array, itemSize ) {
  24992. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  24993. return new Int32BufferAttribute( array, itemSize );
  24994. }
  24995. function Uint32Attribute( array, itemSize ) {
  24996. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  24997. return new Uint32BufferAttribute( array, itemSize );
  24998. }
  24999. function Float32Attribute( array, itemSize ) {
  25000. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  25001. return new Float32BufferAttribute( array, itemSize );
  25002. }
  25003. function Float64Attribute( array, itemSize ) {
  25004. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  25005. return new Float64BufferAttribute( array, itemSize );
  25006. }
  25007. //
  25008. function ClosedSplineCurve3( points ) {
  25009. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25010. CatmullRomCurve3.call( this, points );
  25011. this.type = 'catmullrom';
  25012. this.closed = true;
  25013. }
  25014. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25015. //
  25016. function BoundingBoxHelper( object, color ) {
  25017. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  25018. return new BoxHelper( object, color );
  25019. }
  25020. function EdgesHelper( object, hex ) {
  25021. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  25022. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25023. }
  25024. GridHelper.prototype.setColors = function () {
  25025. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  25026. };
  25027. function WireframeHelper( object, hex ) {
  25028. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  25029. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25030. }
  25031. //
  25032. function XHRLoader( manager ) {
  25033. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  25034. return new FileLoader( manager );
  25035. }
  25036. //
  25037. Object.assign( Box2.prototype, {
  25038. center: function ( optionalTarget ) {
  25039. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  25040. return this.getCenter( optionalTarget );
  25041. },
  25042. empty: function () {
  25043. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  25044. return this.isEmpty();
  25045. },
  25046. isIntersectionBox: function ( box ) {
  25047. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25048. return this.intersectsBox( box );
  25049. },
  25050. size: function ( optionalTarget ) {
  25051. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  25052. return this.getSize( optionalTarget );
  25053. }
  25054. } );
  25055. Object.assign( Box3.prototype, {
  25056. center: function ( optionalTarget ) {
  25057. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  25058. return this.getCenter( optionalTarget );
  25059. },
  25060. empty: function () {
  25061. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  25062. return this.isEmpty();
  25063. },
  25064. isIntersectionBox: function ( box ) {
  25065. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25066. return this.intersectsBox( box );
  25067. },
  25068. isIntersectionSphere: function ( sphere ) {
  25069. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25070. return this.intersectsSphere( sphere );
  25071. },
  25072. size: function ( optionalTarget ) {
  25073. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  25074. return this.getSize( optionalTarget );
  25075. }
  25076. } );
  25077. Line3.prototype.center = function ( optionalTarget ) {
  25078. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  25079. return this.getCenter( optionalTarget );
  25080. };
  25081. _Math.random16 = function () {
  25082. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  25083. return Math.random();
  25084. };
  25085. Object.assign( Matrix3.prototype, {
  25086. flattenToArrayOffset: function ( array, offset ) {
  25087. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25088. return this.toArray( array, offset );
  25089. },
  25090. multiplyVector3: function ( vector ) {
  25091. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  25092. return vector.applyMatrix3( this );
  25093. },
  25094. multiplyVector3Array: function ( a ) {
  25095. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  25096. return this.applyToVector3Array( a );
  25097. }
  25098. } );
  25099. Object.assign( Matrix4.prototype, {
  25100. extractPosition: function ( m ) {
  25101. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  25102. return this.copyPosition( m );
  25103. },
  25104. flattenToArrayOffset: function ( array, offset ) {
  25105. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25106. return this.toArray( array, offset );
  25107. },
  25108. getPosition: function () {
  25109. var v1;
  25110. return function getPosition() {
  25111. if ( v1 === undefined ) v1 = new Vector3();
  25112. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  25113. return v1.setFromMatrixColumn( this, 3 );
  25114. };
  25115. }(),
  25116. setRotationFromQuaternion: function ( q ) {
  25117. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  25118. return this.makeRotationFromQuaternion( q );
  25119. },
  25120. multiplyVector3: function ( vector ) {
  25121. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  25122. return vector.applyProjection( this );
  25123. },
  25124. multiplyVector4: function ( vector ) {
  25125. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25126. return vector.applyMatrix4( this );
  25127. },
  25128. multiplyVector3Array: function ( a ) {
  25129. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  25130. return this.applyToVector3Array( a );
  25131. },
  25132. rotateAxis: function ( v ) {
  25133. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  25134. v.transformDirection( this );
  25135. },
  25136. crossVector: function ( vector ) {
  25137. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25138. return vector.applyMatrix4( this );
  25139. },
  25140. translate: function () {
  25141. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  25142. },
  25143. rotateX: function () {
  25144. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  25145. },
  25146. rotateY: function () {
  25147. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  25148. },
  25149. rotateZ: function () {
  25150. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  25151. },
  25152. rotateByAxis: function () {
  25153. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  25154. }
  25155. } );
  25156. Plane.prototype.isIntersectionLine = function ( line ) {
  25157. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  25158. return this.intersectsLine( line );
  25159. };
  25160. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  25161. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  25162. return vector.applyQuaternion( this );
  25163. };
  25164. Object.assign( Ray.prototype, {
  25165. isIntersectionBox: function ( box ) {
  25166. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25167. return this.intersectsBox( box );
  25168. },
  25169. isIntersectionPlane: function ( plane ) {
  25170. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  25171. return this.intersectsPlane( plane );
  25172. },
  25173. isIntersectionSphere: function ( sphere ) {
  25174. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25175. return this.intersectsSphere( sphere );
  25176. }
  25177. } );
  25178. Object.assign( Shape.prototype, {
  25179. extrude: function ( options ) {
  25180. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  25181. return new ExtrudeGeometry( this, options );
  25182. },
  25183. makeGeometry: function ( options ) {
  25184. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  25185. return new ShapeGeometry( this, options );
  25186. }
  25187. } );
  25188. Object.assign( Vector3.prototype, {
  25189. setEulerFromRotationMatrix: function () {
  25190. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  25191. },
  25192. setEulerFromQuaternion: function () {
  25193. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  25194. },
  25195. getPositionFromMatrix: function ( m ) {
  25196. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  25197. return this.setFromMatrixPosition( m );
  25198. },
  25199. getScaleFromMatrix: function ( m ) {
  25200. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  25201. return this.setFromMatrixScale( m );
  25202. },
  25203. getColumnFromMatrix: function ( index, matrix ) {
  25204. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  25205. return this.setFromMatrixColumn( matrix, index );
  25206. }
  25207. } );
  25208. //
  25209. Geometry.prototype.computeTangents = function () {
  25210. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  25211. };
  25212. Object.assign( Object3D.prototype, {
  25213. getChildByName: function ( name ) {
  25214. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  25215. return this.getObjectByName( name );
  25216. },
  25217. renderDepth: function () {
  25218. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  25219. },
  25220. translate: function ( distance, axis ) {
  25221. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  25222. return this.translateOnAxis( axis, distance );
  25223. }
  25224. } );
  25225. Object.defineProperties( Object3D.prototype, {
  25226. eulerOrder: {
  25227. get: function () {
  25228. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25229. return this.rotation.order;
  25230. },
  25231. set: function ( value ) {
  25232. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25233. this.rotation.order = value;
  25234. }
  25235. },
  25236. useQuaternion: {
  25237. get: function () {
  25238. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25239. },
  25240. set: function () {
  25241. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25242. }
  25243. }
  25244. } );
  25245. Object.defineProperties( LOD.prototype, {
  25246. objects: {
  25247. get: function () {
  25248. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  25249. return this.levels;
  25250. }
  25251. }
  25252. } );
  25253. //
  25254. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  25255. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  25256. "Use .setFocalLength and .filmGauge for a photographic setup." );
  25257. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  25258. this.setFocalLength( focalLength );
  25259. };
  25260. //
  25261. Object.defineProperties( Light.prototype, {
  25262. onlyShadow: {
  25263. set: function () {
  25264. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  25265. }
  25266. },
  25267. shadowCameraFov: {
  25268. set: function ( value ) {
  25269. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  25270. this.shadow.camera.fov = value;
  25271. }
  25272. },
  25273. shadowCameraLeft: {
  25274. set: function ( value ) {
  25275. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  25276. this.shadow.camera.left = value;
  25277. }
  25278. },
  25279. shadowCameraRight: {
  25280. set: function ( value ) {
  25281. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  25282. this.shadow.camera.right = value;
  25283. }
  25284. },
  25285. shadowCameraTop: {
  25286. set: function ( value ) {
  25287. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  25288. this.shadow.camera.top = value;
  25289. }
  25290. },
  25291. shadowCameraBottom: {
  25292. set: function ( value ) {
  25293. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  25294. this.shadow.camera.bottom = value;
  25295. }
  25296. },
  25297. shadowCameraNear: {
  25298. set: function ( value ) {
  25299. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  25300. this.shadow.camera.near = value;
  25301. }
  25302. },
  25303. shadowCameraFar: {
  25304. set: function ( value ) {
  25305. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  25306. this.shadow.camera.far = value;
  25307. }
  25308. },
  25309. shadowCameraVisible: {
  25310. set: function () {
  25311. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  25312. }
  25313. },
  25314. shadowBias: {
  25315. set: function ( value ) {
  25316. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  25317. this.shadow.bias = value;
  25318. }
  25319. },
  25320. shadowDarkness: {
  25321. set: function () {
  25322. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  25323. }
  25324. },
  25325. shadowMapWidth: {
  25326. set: function ( value ) {
  25327. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  25328. this.shadow.mapSize.width = value;
  25329. }
  25330. },
  25331. shadowMapHeight: {
  25332. set: function ( value ) {
  25333. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  25334. this.shadow.mapSize.height = value;
  25335. }
  25336. }
  25337. } );
  25338. //
  25339. Object.defineProperties( BufferAttribute.prototype, {
  25340. length: {
  25341. get: function () {
  25342. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  25343. return this.array.length;
  25344. }
  25345. }
  25346. } );
  25347. Object.assign( BufferGeometry.prototype, {
  25348. addIndex: function ( index ) {
  25349. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  25350. this.setIndex( index );
  25351. },
  25352. addDrawCall: function ( start, count, indexOffset ) {
  25353. if ( indexOffset !== undefined ) {
  25354. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  25355. }
  25356. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  25357. this.addGroup( start, count );
  25358. },
  25359. clearDrawCalls: function () {
  25360. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  25361. this.clearGroups();
  25362. },
  25363. computeTangents: function () {
  25364. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  25365. },
  25366. computeOffsets: function () {
  25367. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  25368. }
  25369. } );
  25370. Object.defineProperties( BufferGeometry.prototype, {
  25371. drawcalls: {
  25372. get: function () {
  25373. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  25374. return this.groups;
  25375. }
  25376. },
  25377. offsets: {
  25378. get: function () {
  25379. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  25380. return this.groups;
  25381. }
  25382. }
  25383. } );
  25384. //
  25385. Object.defineProperties( Uniform.prototype, {
  25386. dynamic: {
  25387. set: function () {
  25388. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  25389. }
  25390. },
  25391. onUpdate: {
  25392. value: function () {
  25393. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  25394. return this;
  25395. }
  25396. }
  25397. } );
  25398. //
  25399. Object.defineProperties( Material.prototype, {
  25400. wrapAround: {
  25401. get: function () {
  25402. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  25403. },
  25404. set: function () {
  25405. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  25406. }
  25407. },
  25408. wrapRGB: {
  25409. get: function () {
  25410. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  25411. return new Color();
  25412. }
  25413. }
  25414. } );
  25415. Object.defineProperties( MeshPhongMaterial.prototype, {
  25416. metal: {
  25417. get: function () {
  25418. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  25419. return false;
  25420. },
  25421. set: function () {
  25422. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  25423. }
  25424. }
  25425. } );
  25426. Object.defineProperties( ShaderMaterial.prototype, {
  25427. derivatives: {
  25428. get: function () {
  25429. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25430. return this.extensions.derivatives;
  25431. },
  25432. set: function ( value ) {
  25433. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25434. this.extensions.derivatives = value;
  25435. }
  25436. }
  25437. } );
  25438. //
  25439. EventDispatcher.prototype = Object.assign( Object.create( {
  25440. // Note: Extra base ensures these properties are not 'assign'ed.
  25441. constructor: EventDispatcher,
  25442. apply: function ( target ) {
  25443. console.warn( "THREE.EventDispatcher: .apply is deprecated, " +
  25444. "just inherit or Object.assign the prototype to mix-in." );
  25445. Object.assign( target, this );
  25446. }
  25447. } ), EventDispatcher.prototype );
  25448. //
  25449. Object.assign( WebGLRenderer.prototype, {
  25450. supportsFloatTextures: function () {
  25451. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  25452. return this.extensions.get( 'OES_texture_float' );
  25453. },
  25454. supportsHalfFloatTextures: function () {
  25455. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  25456. return this.extensions.get( 'OES_texture_half_float' );
  25457. },
  25458. supportsStandardDerivatives: function () {
  25459. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  25460. return this.extensions.get( 'OES_standard_derivatives' );
  25461. },
  25462. supportsCompressedTextureS3TC: function () {
  25463. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  25464. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  25465. },
  25466. supportsCompressedTexturePVRTC: function () {
  25467. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  25468. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  25469. },
  25470. supportsBlendMinMax: function () {
  25471. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  25472. return this.extensions.get( 'EXT_blend_minmax' );
  25473. },
  25474. supportsVertexTextures: function () {
  25475. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  25476. return this.capabilities.vertexTextures;
  25477. },
  25478. supportsInstancedArrays: function () {
  25479. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  25480. return this.extensions.get( 'ANGLE_instanced_arrays' );
  25481. },
  25482. enableScissorTest: function ( boolean ) {
  25483. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  25484. this.setScissorTest( boolean );
  25485. },
  25486. initMaterial: function () {
  25487. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  25488. },
  25489. addPrePlugin: function () {
  25490. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  25491. },
  25492. addPostPlugin: function () {
  25493. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  25494. },
  25495. updateShadowMap: function () {
  25496. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  25497. }
  25498. } );
  25499. Object.defineProperties( WebGLRenderer.prototype, {
  25500. shadowMapEnabled: {
  25501. get: function () {
  25502. return this.shadowMap.enabled;
  25503. },
  25504. set: function ( value ) {
  25505. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  25506. this.shadowMap.enabled = value;
  25507. }
  25508. },
  25509. shadowMapType: {
  25510. get: function () {
  25511. return this.shadowMap.type;
  25512. },
  25513. set: function ( value ) {
  25514. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  25515. this.shadowMap.type = value;
  25516. }
  25517. },
  25518. shadowMapCullFace: {
  25519. get: function () {
  25520. return this.shadowMap.cullFace;
  25521. },
  25522. set: function ( value ) {
  25523. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  25524. this.shadowMap.cullFace = value;
  25525. }
  25526. }
  25527. } );
  25528. Object.defineProperties( WebGLShadowMap.prototype, {
  25529. cullFace: {
  25530. get: function () {
  25531. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  25532. },
  25533. set: function ( cullFace ) {
  25534. var value = ( cullFace !== CullFaceBack );
  25535. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  25536. this.renderReverseSided = value;
  25537. }
  25538. }
  25539. } );
  25540. //
  25541. Object.defineProperties( WebGLRenderTarget.prototype, {
  25542. wrapS: {
  25543. get: function () {
  25544. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25545. return this.texture.wrapS;
  25546. },
  25547. set: function ( value ) {
  25548. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25549. this.texture.wrapS = value;
  25550. }
  25551. },
  25552. wrapT: {
  25553. get: function () {
  25554. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25555. return this.texture.wrapT;
  25556. },
  25557. set: function ( value ) {
  25558. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25559. this.texture.wrapT = value;
  25560. }
  25561. },
  25562. magFilter: {
  25563. get: function () {
  25564. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25565. return this.texture.magFilter;
  25566. },
  25567. set: function ( value ) {
  25568. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25569. this.texture.magFilter = value;
  25570. }
  25571. },
  25572. minFilter: {
  25573. get: function () {
  25574. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25575. return this.texture.minFilter;
  25576. },
  25577. set: function ( value ) {
  25578. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25579. this.texture.minFilter = value;
  25580. }
  25581. },
  25582. anisotropy: {
  25583. get: function () {
  25584. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25585. return this.texture.anisotropy;
  25586. },
  25587. set: function ( value ) {
  25588. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25589. this.texture.anisotropy = value;
  25590. }
  25591. },
  25592. offset: {
  25593. get: function () {
  25594. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25595. return this.texture.offset;
  25596. },
  25597. set: function ( value ) {
  25598. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25599. this.texture.offset = value;
  25600. }
  25601. },
  25602. repeat: {
  25603. get: function () {
  25604. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25605. return this.texture.repeat;
  25606. },
  25607. set: function ( value ) {
  25608. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25609. this.texture.repeat = value;
  25610. }
  25611. },
  25612. format: {
  25613. get: function () {
  25614. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25615. return this.texture.format;
  25616. },
  25617. set: function ( value ) {
  25618. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25619. this.texture.format = value;
  25620. }
  25621. },
  25622. type: {
  25623. get: function () {
  25624. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25625. return this.texture.type;
  25626. },
  25627. set: function ( value ) {
  25628. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25629. this.texture.type = value;
  25630. }
  25631. },
  25632. generateMipmaps: {
  25633. get: function () {
  25634. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25635. return this.texture.generateMipmaps;
  25636. },
  25637. set: function ( value ) {
  25638. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25639. this.texture.generateMipmaps = value;
  25640. }
  25641. }
  25642. } );
  25643. //
  25644. Audio.prototype.load = function ( file ) {
  25645. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  25646. var scope = this;
  25647. var audioLoader = new AudioLoader();
  25648. audioLoader.load( file, function ( buffer ) {
  25649. scope.setBuffer( buffer );
  25650. } );
  25651. return this;
  25652. };
  25653. AudioAnalyser.prototype.getData = function () {
  25654. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  25655. return this.getFrequencyData();
  25656. };
  25657. //
  25658. var GeometryUtils = {
  25659. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  25660. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  25661. var matrix;
  25662. if ( geometry2.isMesh ) {
  25663. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  25664. matrix = geometry2.matrix;
  25665. geometry2 = geometry2.geometry;
  25666. }
  25667. geometry1.merge( geometry2, matrix, materialIndexOffset );
  25668. },
  25669. center: function ( geometry ) {
  25670. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  25671. return geometry.center();
  25672. }
  25673. };
  25674. var ImageUtils = {
  25675. crossOrigin: undefined,
  25676. loadTexture: function ( url, mapping, onLoad, onError ) {
  25677. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  25678. var loader = new TextureLoader();
  25679. loader.setCrossOrigin( this.crossOrigin );
  25680. var texture = loader.load( url, onLoad, undefined, onError );
  25681. if ( mapping ) texture.mapping = mapping;
  25682. return texture;
  25683. },
  25684. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  25685. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  25686. var loader = new CubeTextureLoader();
  25687. loader.setCrossOrigin( this.crossOrigin );
  25688. var texture = loader.load( urls, onLoad, undefined, onError );
  25689. if ( mapping ) texture.mapping = mapping;
  25690. return texture;
  25691. },
  25692. loadCompressedTexture: function () {
  25693. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  25694. },
  25695. loadCompressedTextureCube: function () {
  25696. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  25697. }
  25698. };
  25699. var UniformsUtils = {
  25700. merge: function ( uniforms ) {
  25701. console.warn( 'THREE.UniformsUtils.merge() has been deprecated. Use Object.assign() instead.' );
  25702. var merged = {};
  25703. for ( var u = 0; u < uniforms.length; u ++ ) {
  25704. var tmp = this.clone( uniforms[ u ] );
  25705. for ( var p in tmp ) {
  25706. merged[ p ] = tmp[ p ];
  25707. }
  25708. }
  25709. return merged;
  25710. },
  25711. clone: function ( uniforms_src ) {
  25712. console.warn( 'THREE.UniformsUtils.clone() has been deprecated.' );
  25713. var uniforms_dst = {};
  25714. for ( var u in uniforms_src ) {
  25715. uniforms_dst[ u ] = {};
  25716. for ( var p in uniforms_src[ u ] ) {
  25717. var parameter_src = uniforms_src[ u ][ p ];
  25718. if ( parameter_src && ( parameter_src.isColor ||
  25719. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  25720. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  25721. parameter_src.isTexture ) ) {
  25722. uniforms_dst[ u ][ p ] = parameter_src.clone();
  25723. } else if ( Array.isArray( parameter_src ) ) {
  25724. uniforms_dst[ u ][ p ] = parameter_src.slice();
  25725. } else {
  25726. uniforms_dst[ u ][ p ] = parameter_src;
  25727. }
  25728. }
  25729. }
  25730. return uniforms_dst;
  25731. }
  25732. };
  25733. //
  25734. function Projector() {
  25735. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  25736. this.projectVector = function ( vector, camera ) {
  25737. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  25738. vector.project( camera );
  25739. };
  25740. this.unprojectVector = function ( vector, camera ) {
  25741. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  25742. vector.unproject( camera );
  25743. };
  25744. this.pickingRay = function () {
  25745. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  25746. };
  25747. }
  25748. //
  25749. function CanvasRenderer() {
  25750. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  25751. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  25752. this.clear = function () {};
  25753. this.render = function () {};
  25754. this.setClearColor = function () {};
  25755. this.setSize = function () {};
  25756. }
  25757. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  25758. exports.WebGLRenderTarget = WebGLRenderTarget;
  25759. exports.WebGLRenderer = WebGLRenderer;
  25760. exports.ShaderLib = ShaderLib;
  25761. exports.UniformsLib = UniformsLib;
  25762. exports.ShaderChunk = ShaderChunk;
  25763. exports.FogExp2 = FogExp2;
  25764. exports.Fog = Fog;
  25765. exports.Scene = Scene;
  25766. exports.LensFlare = LensFlare;
  25767. exports.Sprite = Sprite;
  25768. exports.LOD = LOD;
  25769. exports.SkinnedMesh = SkinnedMesh;
  25770. exports.Skeleton = Skeleton;
  25771. exports.Bone = Bone;
  25772. exports.Mesh = Mesh;
  25773. exports.LineSegments = LineSegments;
  25774. exports.Line = Line;
  25775. exports.Points = Points;
  25776. exports.Group = Group;
  25777. exports.VideoTexture = VideoTexture;
  25778. exports.DataTexture = DataTexture;
  25779. exports.CompressedTexture = CompressedTexture;
  25780. exports.CubeTexture = CubeTexture;
  25781. exports.CanvasTexture = CanvasTexture;
  25782. exports.DepthTexture = DepthTexture;
  25783. exports.Texture = Texture;
  25784. exports.CompressedTextureLoader = CompressedTextureLoader;
  25785. exports.BinaryTextureLoader = BinaryTextureLoader;
  25786. exports.DataTextureLoader = DataTextureLoader;
  25787. exports.CubeTextureLoader = CubeTextureLoader;
  25788. exports.TextureLoader = TextureLoader;
  25789. exports.ObjectLoader = ObjectLoader;
  25790. exports.MaterialLoader = MaterialLoader;
  25791. exports.BufferGeometryLoader = BufferGeometryLoader;
  25792. exports.DefaultLoadingManager = DefaultLoadingManager;
  25793. exports.LoadingManager = LoadingManager;
  25794. exports.JSONLoader = JSONLoader;
  25795. exports.ImageLoader = ImageLoader;
  25796. exports.FontLoader = FontLoader;
  25797. exports.FileLoader = FileLoader;
  25798. exports.Loader = Loader;
  25799. exports.Cache = Cache;
  25800. exports.AudioLoader = AudioLoader;
  25801. exports.SpotLightShadow = SpotLightShadow;
  25802. exports.SpotLight = SpotLight;
  25803. exports.PointLight = PointLight;
  25804. exports.RectAreaLight = RectAreaLight;
  25805. exports.HemisphereLight = HemisphereLight;
  25806. exports.DirectionalLightShadow = DirectionalLightShadow;
  25807. exports.DirectionalLight = DirectionalLight;
  25808. exports.AmbientLight = AmbientLight;
  25809. exports.LightShadow = LightShadow;
  25810. exports.Light = Light;
  25811. exports.StereoCamera = StereoCamera;
  25812. exports.PerspectiveCamera = PerspectiveCamera;
  25813. exports.OrthographicCamera = OrthographicCamera;
  25814. exports.CubeCamera = CubeCamera;
  25815. exports.Camera = Camera;
  25816. exports.AudioListener = AudioListener;
  25817. exports.PositionalAudio = PositionalAudio;
  25818. exports.AudioContext = AudioContext;
  25819. exports.AudioAnalyser = AudioAnalyser;
  25820. exports.Audio = Audio;
  25821. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  25822. exports.StringKeyframeTrack = StringKeyframeTrack;
  25823. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  25824. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  25825. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  25826. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  25827. exports.PropertyMixer = PropertyMixer;
  25828. exports.PropertyBinding = PropertyBinding;
  25829. exports.KeyframeTrack = KeyframeTrack;
  25830. exports.AnimationUtils = AnimationUtils;
  25831. exports.AnimationObjectGroup = AnimationObjectGroup;
  25832. exports.AnimationMixer = AnimationMixer;
  25833. exports.AnimationClip = AnimationClip;
  25834. exports.Uniform = Uniform;
  25835. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  25836. exports.BufferGeometry = BufferGeometry;
  25837. exports.GeometryIdCount = GeometryIdCount;
  25838. exports.Geometry = Geometry;
  25839. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  25840. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  25841. exports.InterleavedBuffer = InterleavedBuffer;
  25842. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  25843. exports.Face3 = Face3;
  25844. exports.Object3D = Object3D;
  25845. exports.Raycaster = Raycaster;
  25846. exports.Layers = Layers;
  25847. exports.EventDispatcher = EventDispatcher;
  25848. exports.Clock = Clock;
  25849. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  25850. exports.LinearInterpolant = LinearInterpolant;
  25851. exports.DiscreteInterpolant = DiscreteInterpolant;
  25852. exports.CubicInterpolant = CubicInterpolant;
  25853. exports.Interpolant = Interpolant;
  25854. exports.Triangle = Triangle;
  25855. exports.Spline = Spline;
  25856. exports.Math = _Math;
  25857. exports.Spherical = Spherical;
  25858. exports.Plane = Plane;
  25859. exports.Frustum = Frustum;
  25860. exports.Sphere = Sphere;
  25861. exports.Ray = Ray;
  25862. exports.Matrix4 = Matrix4;
  25863. exports.Matrix3 = Matrix3;
  25864. exports.Box3 = Box3;
  25865. exports.Box2 = Box2;
  25866. exports.Line3 = Line3;
  25867. exports.Euler = Euler;
  25868. exports.Vector4 = Vector4;
  25869. exports.Vector3 = Vector3;
  25870. exports.Vector2 = Vector2;
  25871. exports.Quaternion = Quaternion;
  25872. exports.Color = Color;
  25873. exports.MorphBlendMesh = MorphBlendMesh;
  25874. exports.ImmediateRenderObject = ImmediateRenderObject;
  25875. exports.VertexNormalsHelper = VertexNormalsHelper;
  25876. exports.SpotLightHelper = SpotLightHelper;
  25877. exports.SkeletonHelper = SkeletonHelper;
  25878. exports.PointLightHelper = PointLightHelper;
  25879. exports.RectAreaLightHelper = RectAreaLightHelper;
  25880. exports.HemisphereLightHelper = HemisphereLightHelper;
  25881. exports.GridHelper = GridHelper;
  25882. exports.PolarGridHelper = PolarGridHelper;
  25883. exports.FaceNormalsHelper = FaceNormalsHelper;
  25884. exports.DirectionalLightHelper = DirectionalLightHelper;
  25885. exports.CameraHelper = CameraHelper;
  25886. exports.BoxHelper = BoxHelper;
  25887. exports.ArrowHelper = ArrowHelper;
  25888. exports.AxisHelper = AxisHelper;
  25889. exports.CatmullRomCurve3 = CatmullRomCurve3;
  25890. exports.SplineCurve3 = SplineCurve3;
  25891. exports.CubicBezierCurve3 = CubicBezierCurve3;
  25892. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  25893. exports.LineCurve3 = LineCurve3;
  25894. exports.ArcCurve = ArcCurve;
  25895. exports.EllipseCurve = EllipseCurve;
  25896. exports.SplineCurve = SplineCurve;
  25897. exports.CubicBezierCurve = CubicBezierCurve;
  25898. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  25899. exports.LineCurve = LineCurve;
  25900. exports.Shape = Shape;
  25901. exports.ShapePath = ShapePath;
  25902. exports.Path = Path;
  25903. exports.Font = Font;
  25904. exports.CurvePath = CurvePath;
  25905. exports.Curve = Curve;
  25906. exports.ShapeUtils = ShapeUtils;
  25907. exports.SceneUtils = SceneUtils;
  25908. exports.CurveUtils = CurveUtils;
  25909. exports.WireframeGeometry = WireframeGeometry;
  25910. exports.ParametricGeometry = ParametricGeometry;
  25911. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  25912. exports.TetrahedronGeometry = TetrahedronGeometry;
  25913. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  25914. exports.OctahedronGeometry = OctahedronGeometry;
  25915. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  25916. exports.IcosahedronGeometry = IcosahedronGeometry;
  25917. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  25918. exports.DodecahedronGeometry = DodecahedronGeometry;
  25919. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  25920. exports.PolyhedronGeometry = PolyhedronGeometry;
  25921. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  25922. exports.TubeGeometry = TubeGeometry;
  25923. exports.TubeBufferGeometry = TubeBufferGeometry;
  25924. exports.TorusKnotGeometry = TorusKnotGeometry;
  25925. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  25926. exports.TorusGeometry = TorusGeometry;
  25927. exports.TorusBufferGeometry = TorusBufferGeometry;
  25928. exports.TextGeometry = TextGeometry;
  25929. exports.SphereBufferGeometry = SphereBufferGeometry;
  25930. exports.SphereGeometry = SphereGeometry;
  25931. exports.RingGeometry = RingGeometry;
  25932. exports.RingBufferGeometry = RingBufferGeometry;
  25933. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  25934. exports.PlaneGeometry = PlaneGeometry;
  25935. exports.LatheGeometry = LatheGeometry;
  25936. exports.LatheBufferGeometry = LatheBufferGeometry;
  25937. exports.ShapeGeometry = ShapeGeometry;
  25938. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  25939. exports.ExtrudeGeometry = ExtrudeGeometry;
  25940. exports.EdgesGeometry = EdgesGeometry;
  25941. exports.ConeGeometry = ConeGeometry;
  25942. exports.ConeBufferGeometry = ConeBufferGeometry;
  25943. exports.CylinderGeometry = CylinderGeometry;
  25944. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  25945. exports.CircleBufferGeometry = CircleBufferGeometry;
  25946. exports.CircleGeometry = CircleGeometry;
  25947. exports.BoxBufferGeometry = BoxBufferGeometry;
  25948. exports.BoxGeometry = BoxGeometry;
  25949. exports.ShadowMaterial = ShadowMaterial;
  25950. exports.SpriteMaterial = SpriteMaterial;
  25951. exports.RawShaderMaterial = RawShaderMaterial;
  25952. exports.ShaderMaterial = ShaderMaterial;
  25953. exports.PointsMaterial = PointsMaterial;
  25954. exports.MultiMaterial = MultiMaterial;
  25955. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  25956. exports.MeshStandardMaterial = MeshStandardMaterial;
  25957. exports.MeshPhongMaterial = MeshPhongMaterial;
  25958. exports.MeshToonMaterial = MeshToonMaterial;
  25959. exports.MeshNormalMaterial = MeshNormalMaterial;
  25960. exports.MeshLambertMaterial = MeshLambertMaterial;
  25961. exports.MeshDepthMaterial = MeshDepthMaterial;
  25962. exports.MeshBasicMaterial = MeshBasicMaterial;
  25963. exports.LineDashedMaterial = LineDashedMaterial;
  25964. exports.LineBasicMaterial = LineBasicMaterial;
  25965. exports.Material = Material;
  25966. exports.Float64BufferAttribute = Float64BufferAttribute;
  25967. exports.Float32BufferAttribute = Float32BufferAttribute;
  25968. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  25969. exports.Int32BufferAttribute = Int32BufferAttribute;
  25970. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  25971. exports.Int16BufferAttribute = Int16BufferAttribute;
  25972. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  25973. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  25974. exports.Int8BufferAttribute = Int8BufferAttribute;
  25975. exports.BufferAttribute = BufferAttribute;
  25976. exports.REVISION = REVISION;
  25977. exports.MOUSE = MOUSE;
  25978. exports.CullFaceNone = CullFaceNone;
  25979. exports.CullFaceBack = CullFaceBack;
  25980. exports.CullFaceFront = CullFaceFront;
  25981. exports.CullFaceFrontBack = CullFaceFrontBack;
  25982. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  25983. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  25984. exports.BasicShadowMap = BasicShadowMap;
  25985. exports.PCFShadowMap = PCFShadowMap;
  25986. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  25987. exports.FrontSide = FrontSide;
  25988. exports.BackSide = BackSide;
  25989. exports.DoubleSide = DoubleSide;
  25990. exports.FlatShading = FlatShading;
  25991. exports.SmoothShading = SmoothShading;
  25992. exports.NoColors = NoColors;
  25993. exports.FaceColors = FaceColors;
  25994. exports.VertexColors = VertexColors;
  25995. exports.NoBlending = NoBlending;
  25996. exports.NormalBlending = NormalBlending;
  25997. exports.AdditiveBlending = AdditiveBlending;
  25998. exports.SubtractiveBlending = SubtractiveBlending;
  25999. exports.MultiplyBlending = MultiplyBlending;
  26000. exports.CustomBlending = CustomBlending;
  26001. exports.BlendingMode = BlendingMode;
  26002. exports.AddEquation = AddEquation;
  26003. exports.SubtractEquation = SubtractEquation;
  26004. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  26005. exports.MinEquation = MinEquation;
  26006. exports.MaxEquation = MaxEquation;
  26007. exports.ZeroFactor = ZeroFactor;
  26008. exports.OneFactor = OneFactor;
  26009. exports.SrcColorFactor = SrcColorFactor;
  26010. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  26011. exports.SrcAlphaFactor = SrcAlphaFactor;
  26012. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  26013. exports.DstAlphaFactor = DstAlphaFactor;
  26014. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  26015. exports.DstColorFactor = DstColorFactor;
  26016. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  26017. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  26018. exports.NeverDepth = NeverDepth;
  26019. exports.AlwaysDepth = AlwaysDepth;
  26020. exports.LessDepth = LessDepth;
  26021. exports.LessEqualDepth = LessEqualDepth;
  26022. exports.EqualDepth = EqualDepth;
  26023. exports.GreaterEqualDepth = GreaterEqualDepth;
  26024. exports.GreaterDepth = GreaterDepth;
  26025. exports.NotEqualDepth = NotEqualDepth;
  26026. exports.MultiplyOperation = MultiplyOperation;
  26027. exports.MixOperation = MixOperation;
  26028. exports.AddOperation = AddOperation;
  26029. exports.NoToneMapping = NoToneMapping;
  26030. exports.LinearToneMapping = LinearToneMapping;
  26031. exports.ReinhardToneMapping = ReinhardToneMapping;
  26032. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  26033. exports.CineonToneMapping = CineonToneMapping;
  26034. exports.UVMapping = UVMapping;
  26035. exports.CubeReflectionMapping = CubeReflectionMapping;
  26036. exports.CubeRefractionMapping = CubeRefractionMapping;
  26037. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  26038. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  26039. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  26040. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  26041. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  26042. exports.TextureMapping = TextureMapping;
  26043. exports.RepeatWrapping = RepeatWrapping;
  26044. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  26045. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  26046. exports.TextureWrapping = TextureWrapping;
  26047. exports.NearestFilter = NearestFilter;
  26048. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  26049. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  26050. exports.LinearFilter = LinearFilter;
  26051. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  26052. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  26053. exports.TextureFilter = TextureFilter;
  26054. exports.UnsignedByteType = UnsignedByteType;
  26055. exports.ByteType = ByteType;
  26056. exports.ShortType = ShortType;
  26057. exports.UnsignedShortType = UnsignedShortType;
  26058. exports.IntType = IntType;
  26059. exports.UnsignedIntType = UnsignedIntType;
  26060. exports.FloatType = FloatType;
  26061. exports.HalfFloatType = HalfFloatType;
  26062. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  26063. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  26064. exports.UnsignedShort565Type = UnsignedShort565Type;
  26065. exports.UnsignedInt248Type = UnsignedInt248Type;
  26066. exports.AlphaFormat = AlphaFormat;
  26067. exports.RGBFormat = RGBFormat;
  26068. exports.RGBAFormat = RGBAFormat;
  26069. exports.LuminanceFormat = LuminanceFormat;
  26070. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  26071. exports.RGBEFormat = RGBEFormat;
  26072. exports.DepthFormat = DepthFormat;
  26073. exports.DepthStencilFormat = DepthStencilFormat;
  26074. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  26075. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  26076. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  26077. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  26078. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  26079. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  26080. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  26081. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  26082. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  26083. exports.LoopOnce = LoopOnce;
  26084. exports.LoopRepeat = LoopRepeat;
  26085. exports.LoopPingPong = LoopPingPong;
  26086. exports.InterpolateDiscrete = InterpolateDiscrete;
  26087. exports.InterpolateLinear = InterpolateLinear;
  26088. exports.InterpolateSmooth = InterpolateSmooth;
  26089. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  26090. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  26091. exports.WrapAroundEnding = WrapAroundEnding;
  26092. exports.TrianglesDrawMode = TrianglesDrawMode;
  26093. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  26094. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  26095. exports.LinearEncoding = LinearEncoding;
  26096. exports.sRGBEncoding = sRGBEncoding;
  26097. exports.GammaEncoding = GammaEncoding;
  26098. exports.RGBEEncoding = RGBEEncoding;
  26099. exports.LogLuvEncoding = LogLuvEncoding;
  26100. exports.RGBM7Encoding = RGBM7Encoding;
  26101. exports.RGBM16Encoding = RGBM16Encoding;
  26102. exports.RGBDEncoding = RGBDEncoding;
  26103. exports.BasicDepthPacking = BasicDepthPacking;
  26104. exports.RGBADepthPacking = RGBADepthPacking;
  26105. exports.CubeGeometry = BoxGeometry;
  26106. exports.Face4 = Face4;
  26107. exports.LineStrip = LineStrip;
  26108. exports.LinePieces = LinePieces;
  26109. exports.MeshFaceMaterial = MeshFaceMaterial;
  26110. exports.PointCloud = PointCloud;
  26111. exports.Particle = Particle;
  26112. exports.ParticleSystem = ParticleSystem;
  26113. exports.PointCloudMaterial = PointCloudMaterial;
  26114. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  26115. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  26116. exports.Vertex = Vertex;
  26117. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  26118. exports.Int8Attribute = Int8Attribute;
  26119. exports.Uint8Attribute = Uint8Attribute;
  26120. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  26121. exports.Int16Attribute = Int16Attribute;
  26122. exports.Uint16Attribute = Uint16Attribute;
  26123. exports.Int32Attribute = Int32Attribute;
  26124. exports.Uint32Attribute = Uint32Attribute;
  26125. exports.Float32Attribute = Float32Attribute;
  26126. exports.Float64Attribute = Float64Attribute;
  26127. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  26128. exports.BoundingBoxHelper = BoundingBoxHelper;
  26129. exports.EdgesHelper = EdgesHelper;
  26130. exports.WireframeHelper = WireframeHelper;
  26131. exports.XHRLoader = XHRLoader;
  26132. exports.GeometryUtils = GeometryUtils;
  26133. exports.ImageUtils = ImageUtils;
  26134. exports.UniformsUtils = UniformsUtils;
  26135. exports.Projector = Projector;
  26136. exports.CanvasRenderer = CanvasRenderer;
  26137. Object.defineProperty(exports, '__esModule', { value: true });
  26138. })));