WebGLRenderer.js 149 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433
  1. /**
  2. * @author supereggbert / http://www.paulbrunt.co.uk/
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author alteredq / http://alteredqualia.com/
  5. * @author szimek / https://github.com/szimek/
  6. */
  7. THREE.WebGLRenderer = function ( parameters ) {
  8. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  9. parameters = parameters || {};
  10. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11. _context = parameters.context !== undefined ? parameters.context : null,
  12. pixelRatio = 1,
  13. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  14. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15. _depth = parameters.depth !== undefined ? parameters.depth : true,
  16. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  17. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  18. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  19. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  20. _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false,
  21. _clearColor = new THREE.Color( 0x000000 ),
  22. _clearAlpha = 0;
  23. var lights = [];
  24. var _webglObjects = {};
  25. var _webglObjectsImmediate = [];
  26. var opaqueObjects = [];
  27. var transparentObjects = [];
  28. var sprites = [];
  29. var lensFlares = [];
  30. // public properties
  31. this.domElement = _canvas;
  32. this.context = null;
  33. // clearing
  34. this.autoClear = true;
  35. this.autoClearColor = true;
  36. this.autoClearDepth = true;
  37. this.autoClearStencil = true;
  38. // scene graph
  39. this.sortObjects = true;
  40. // physically based shading
  41. this.gammaFactor = 2.0; // for backwards compatibility
  42. this.gammaInput = false;
  43. this.gammaOutput = false;
  44. // shadow map
  45. this.shadowMapEnabled = false;
  46. this.shadowMapType = THREE.PCFShadowMap;
  47. this.shadowMapCullFace = THREE.CullFaceFront;
  48. this.shadowMapDebug = false;
  49. this.shadowMapCascade = false;
  50. // morphs
  51. this.maxMorphTargets = 8;
  52. this.maxMorphNormals = 4;
  53. // flags
  54. this.autoScaleCubemaps = true;
  55. // info
  56. this.info = {
  57. memory: {
  58. programs: 0,
  59. geometries: 0,
  60. textures: 0
  61. },
  62. render: {
  63. calls: 0,
  64. vertices: 0,
  65. faces: 0,
  66. points: 0
  67. }
  68. };
  69. // internal properties
  70. var _this = this,
  71. _programs = [],
  72. // internal state cache
  73. _currentProgram = null,
  74. _currentFramebuffer = null,
  75. _currentMaterialId = - 1,
  76. _currentGeometryProgram = '',
  77. _currentCamera = null,
  78. _usedTextureUnits = 0,
  79. // GL state cache
  80. _oldDoubleSided = - 1,
  81. _oldFlipSided = - 1,
  82. _oldBlending = - 1,
  83. _oldBlendEquation = - 1,
  84. _oldBlendSrc = - 1,
  85. _oldBlendDst = - 1,
  86. _oldBlendEquationAlpha = - 1,
  87. _oldBlendSrcAlpha = - 1,
  88. _oldBlendDstAlpha = - 1,
  89. _oldDepthTest = - 1,
  90. _oldDepthWrite = - 1,
  91. _oldPolygonOffset = null,
  92. _oldPolygonOffsetFactor = null,
  93. _oldPolygonOffsetUnits = null,
  94. _oldLineWidth = null,
  95. _viewportX = 0,
  96. _viewportY = 0,
  97. _viewportWidth = _canvas.width,
  98. _viewportHeight = _canvas.height,
  99. _currentWidth = 0,
  100. _currentHeight = 0,
  101. _newAttributes = new Uint8Array( 16 ),
  102. _enabledAttributes = new Uint8Array( 16 ),
  103. // frustum
  104. _frustum = new THREE.Frustum(),
  105. // camera matrices cache
  106. _projScreenMatrix = new THREE.Matrix4(),
  107. _projScreenMatrixPS = new THREE.Matrix4(),
  108. _vector3 = new THREE.Vector3(),
  109. // light arrays cache
  110. _direction = new THREE.Vector3(),
  111. _lightsNeedUpdate = true,
  112. _lights = {
  113. ambient: [ 0, 0, 0 ],
  114. directional: { length: 0, colors:[], positions: [] },
  115. point: { length: 0, colors: [], positions: [], distances: [], decays: [] },
  116. spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [], decays: [] },
  117. hemi: { length: 0, skyColors: [], groundColors: [], positions: [] }
  118. };
  119. // initialize
  120. var _gl;
  121. try {
  122. var attributes = {
  123. alpha: _alpha,
  124. depth: _depth,
  125. stencil: _stencil,
  126. antialias: _antialias,
  127. premultipliedAlpha: _premultipliedAlpha,
  128. preserveDrawingBuffer: _preserveDrawingBuffer
  129. };
  130. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  131. if ( _gl === null ) {
  132. if ( _canvas.getContext( 'webgl') !== null ) {
  133. throw 'Error creating WebGL context with your selected attributes.';
  134. } else {
  135. throw 'Error creating WebGL context.';
  136. }
  137. }
  138. _canvas.addEventListener( 'webglcontextlost', function ( event ) {
  139. event.preventDefault();
  140. resetGLState();
  141. setDefaultGLState();
  142. _webglObjects = {};
  143. }, false);
  144. } catch ( error ) {
  145. THREE.error( 'THREE.WebGLRenderer: ' + error );
  146. }
  147. if ( _gl.getShaderPrecisionFormat === undefined ) {
  148. _gl.getShaderPrecisionFormat = function () {
  149. return {
  150. 'rangeMin': 1,
  151. 'rangeMax': 1,
  152. 'precision': 1
  153. };
  154. }
  155. }
  156. var extensions = new THREE.WebGLExtensions( _gl );
  157. extensions.get( 'OES_texture_float' );
  158. extensions.get( 'OES_texture_float_linear' );
  159. extensions.get( 'OES_texture_half_float' );
  160. extensions.get( 'OES_texture_half_float_linear' );
  161. extensions.get( 'OES_standard_derivatives' );
  162. if ( _logarithmicDepthBuffer ) {
  163. extensions.get( 'EXT_frag_depth' );
  164. }
  165. //
  166. var glClearColor = function ( r, g, b, a ) {
  167. if ( _premultipliedAlpha === true ) {
  168. r *= a; g *= a; b *= a;
  169. }
  170. _gl.clearColor( r, g, b, a );
  171. };
  172. var setDefaultGLState = function () {
  173. _gl.clearColor( 0, 0, 0, 1 );
  174. _gl.clearDepth( 1 );
  175. _gl.clearStencil( 0 );
  176. _gl.enable( _gl.DEPTH_TEST );
  177. _gl.depthFunc( _gl.LEQUAL );
  178. _gl.frontFace( _gl.CCW );
  179. _gl.cullFace( _gl.BACK );
  180. _gl.enable( _gl.CULL_FACE );
  181. _gl.enable( _gl.BLEND );
  182. _gl.blendEquation( _gl.FUNC_ADD );
  183. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  184. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  185. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  186. };
  187. var resetGLState = function () {
  188. _currentProgram = null;
  189. _currentCamera = null;
  190. _oldBlending = - 1;
  191. _oldDepthTest = - 1;
  192. _oldDepthWrite = - 1;
  193. _oldDoubleSided = - 1;
  194. _oldFlipSided = - 1;
  195. _currentGeometryProgram = '';
  196. _currentMaterialId = - 1;
  197. _lightsNeedUpdate = true;
  198. for ( var i = 0; i < _enabledAttributes.length; i ++ ) {
  199. _enabledAttributes[ i ] = 0;
  200. }
  201. };
  202. setDefaultGLState();
  203. this.context = _gl;
  204. // GPU capabilities
  205. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  206. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  207. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  208. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  209. var _supportsVertexTextures = _maxVertexTextures > 0;
  210. var _supportsBoneTextures = _supportsVertexTextures && extensions.get( 'OES_texture_float' );
  211. //
  212. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  213. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  214. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  215. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  216. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  217. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  218. var getCompressedTextureFormats = ( function () {
  219. var array;
  220. return function () {
  221. if ( array !== undefined ) {
  222. return array;
  223. }
  224. array = [];
  225. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || extensions.get( 'WEBGL_compressed_texture_s3tc' ) ) {
  226. var formats = _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS );
  227. for ( var i = 0; i < formats.length; i ++ ){
  228. array.push( formats[ i ] );
  229. }
  230. }
  231. return array;
  232. };
  233. } )();
  234. // clamp precision to maximum available
  235. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  236. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  237. if ( _precision === 'highp' && ! highpAvailable ) {
  238. if ( mediumpAvailable ) {
  239. _precision = 'mediump';
  240. THREE.warn( 'THREE.WebGLRenderer: highp not supported, using mediump.' );
  241. } else {
  242. _precision = 'lowp';
  243. THREE.warn( 'THREE.WebGLRenderer: highp and mediump not supported, using lowp.' );
  244. }
  245. }
  246. if ( _precision === 'mediump' && ! mediumpAvailable ) {
  247. _precision = 'lowp';
  248. THREE.warn( 'THREE.WebGLRenderer: mediump not supported, using lowp.' );
  249. }
  250. // Plugins
  251. var shadowMapPlugin = new THREE.ShadowMapPlugin( this, lights, _webglObjects, _webglObjectsImmediate );
  252. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  253. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  254. // API
  255. this.getContext = function () {
  256. return _gl;
  257. };
  258. this.forceContextLoss = function () {
  259. extensions.get( 'WEBGL_lose_context' ).loseContext();
  260. };
  261. this.supportsVertexTextures = function () {
  262. return _supportsVertexTextures;
  263. };
  264. this.supportsFloatTextures = function () {
  265. return extensions.get( 'OES_texture_float' );
  266. };
  267. this.supportsHalfFloatTextures = function () {
  268. return extensions.get( 'OES_texture_half_float' );
  269. };
  270. this.supportsStandardDerivatives = function () {
  271. return extensions.get( 'OES_standard_derivatives' );
  272. };
  273. this.supportsCompressedTextureS3TC = function () {
  274. return extensions.get( 'WEBGL_compressed_texture_s3tc' );
  275. };
  276. this.supportsCompressedTexturePVRTC = function () {
  277. return extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  278. };
  279. this.supportsBlendMinMax = function () {
  280. return extensions.get( 'EXT_blend_minmax' );
  281. };
  282. this.getMaxAnisotropy = ( function () {
  283. var value;
  284. return function () {
  285. if ( value !== undefined ) {
  286. return value;
  287. }
  288. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  289. value = extension !== null ? _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  290. return value;
  291. }
  292. } )();
  293. this.getPrecision = function () {
  294. return _precision;
  295. };
  296. this.getPixelRatio = function () {
  297. return pixelRatio;
  298. };
  299. this.setPixelRatio = function ( value ) {
  300. pixelRatio = value;
  301. };
  302. this.setSize = function ( width, height, updateStyle ) {
  303. _canvas.width = width * pixelRatio;
  304. _canvas.height = height * pixelRatio;
  305. if ( updateStyle !== false ) {
  306. _canvas.style.width = width + 'px';
  307. _canvas.style.height = height + 'px';
  308. }
  309. this.setViewport( 0, 0, width, height );
  310. };
  311. this.setViewport = function ( x, y, width, height ) {
  312. _viewportX = x * pixelRatio;
  313. _viewportY = y * pixelRatio;
  314. _viewportWidth = width * pixelRatio;
  315. _viewportHeight = height * pixelRatio;
  316. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  317. };
  318. this.setScissor = function ( x, y, width, height ) {
  319. _gl.scissor(
  320. x * pixelRatio,
  321. y * pixelRatio,
  322. width * pixelRatio,
  323. height * pixelRatio
  324. );
  325. };
  326. this.enableScissorTest = function ( enable ) {
  327. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  328. };
  329. // Clearing
  330. this.getClearColor = function () {
  331. return _clearColor;
  332. };
  333. this.setClearColor = function ( color, alpha ) {
  334. _clearColor.set( color );
  335. _clearAlpha = alpha !== undefined ? alpha : 1;
  336. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  337. };
  338. this.getClearAlpha = function () {
  339. return _clearAlpha;
  340. };
  341. this.setClearAlpha = function ( alpha ) {
  342. _clearAlpha = alpha;
  343. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  344. };
  345. this.clear = function ( color, depth, stencil ) {
  346. var bits = 0;
  347. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  348. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  349. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  350. _gl.clear( bits );
  351. };
  352. this.clearColor = function () {
  353. _gl.clear( _gl.COLOR_BUFFER_BIT );
  354. };
  355. this.clearDepth = function () {
  356. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  357. };
  358. this.clearStencil = function () {
  359. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  360. };
  361. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  362. this.setRenderTarget( renderTarget );
  363. this.clear( color, depth, stencil );
  364. };
  365. // Reset
  366. this.resetGLState = resetGLState;
  367. // Buffer allocation
  368. function createParticleBuffers ( geometry ) {
  369. geometry.__webglVertexBuffer = _gl.createBuffer();
  370. geometry.__webglColorBuffer = _gl.createBuffer();
  371. _this.info.memory.geometries ++;
  372. };
  373. function createLineBuffers ( geometry ) {
  374. geometry.__webglVertexBuffer = _gl.createBuffer();
  375. geometry.__webglColorBuffer = _gl.createBuffer();
  376. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  377. _this.info.memory.geometries ++;
  378. };
  379. function createMeshBuffers ( geometryGroup ) {
  380. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  381. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  382. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  383. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  384. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  385. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  386. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  387. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  388. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  389. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  390. var numMorphTargets = geometryGroup.numMorphTargets;
  391. if ( numMorphTargets ) {
  392. geometryGroup.__webglMorphTargetsBuffers = [];
  393. for ( var m = 0, ml = numMorphTargets; m < ml; m ++ ) {
  394. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  395. }
  396. }
  397. var numMorphNormals = geometryGroup.numMorphNormals;
  398. if ( numMorphNormals ) {
  399. geometryGroup.__webglMorphNormalsBuffers = [];
  400. for ( var m = 0, ml = numMorphNormals; m < ml; m ++ ) {
  401. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  402. }
  403. }
  404. _this.info.memory.geometries ++;
  405. };
  406. // Events
  407. var onObjectRemoved = function ( event ) {
  408. var object = event.target;
  409. object.traverse( function ( child ) {
  410. child.removeEventListener( 'remove', onObjectRemoved );
  411. removeObject( child );
  412. } );
  413. };
  414. var onGeometryDispose = function ( event ) {
  415. var geometry = event.target;
  416. geometry.removeEventListener( 'dispose', onGeometryDispose );
  417. deallocateGeometry( geometry );
  418. };
  419. var onTextureDispose = function ( event ) {
  420. var texture = event.target;
  421. texture.removeEventListener( 'dispose', onTextureDispose );
  422. deallocateTexture( texture );
  423. _this.info.memory.textures --;
  424. };
  425. var onRenderTargetDispose = function ( event ) {
  426. var renderTarget = event.target;
  427. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  428. deallocateRenderTarget( renderTarget );
  429. _this.info.memory.textures --;
  430. };
  431. var onMaterialDispose = function ( event ) {
  432. var material = event.target;
  433. material.removeEventListener( 'dispose', onMaterialDispose );
  434. deallocateMaterial( material );
  435. };
  436. // Buffer deallocation
  437. var deleteBuffers = function ( geometry ) {
  438. var buffers = [
  439. '__webglVertexBuffer',
  440. '__webglNormalBuffer',
  441. '__webglTangentBuffer',
  442. '__webglColorBuffer',
  443. '__webglUVBuffer',
  444. '__webglUV2Buffer',
  445. '__webglSkinIndicesBuffer',
  446. '__webglSkinWeightsBuffer',
  447. '__webglFaceBuffer',
  448. '__webglLineBuffer',
  449. '__webglLineDistanceBuffer'
  450. ];
  451. for ( var i = 0, l = buffers.length; i < l; i ++ ) {
  452. var name = buffers[ i ];
  453. if ( geometry[ name ] !== undefined ) {
  454. _gl.deleteBuffer( geometry[ name ] );
  455. delete geometry[ name ];
  456. }
  457. }
  458. // custom attributes
  459. if ( geometry.__webglCustomAttributesList !== undefined ) {
  460. for ( var name in geometry.__webglCustomAttributesList ) {
  461. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ name ].buffer );
  462. }
  463. delete geometry.__webglCustomAttributesList;
  464. }
  465. _this.info.memory.geometries --;
  466. };
  467. var deallocateGeometry = function ( geometry ) {
  468. delete geometry.__webglInit;
  469. if ( geometry instanceof THREE.BufferGeometry ) {
  470. for ( var name in geometry.attributes ) {
  471. var attribute = geometry.attributes[ name ];
  472. if ( attribute.buffer !== undefined ) {
  473. _gl.deleteBuffer( attribute.buffer );
  474. delete attribute.buffer;
  475. }
  476. }
  477. _this.info.memory.geometries --;
  478. } else {
  479. var geometryGroupsList = geometryGroups[ geometry.id ];
  480. if ( geometryGroupsList !== undefined ) {
  481. for ( var i = 0, l = geometryGroupsList.length; i < l; i ++ ) {
  482. var geometryGroup = geometryGroupsList[ i ];
  483. if ( geometryGroup.numMorphTargets !== undefined ) {
  484. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  485. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  486. }
  487. delete geometryGroup.__webglMorphTargetsBuffers;
  488. }
  489. if ( geometryGroup.numMorphNormals !== undefined ) {
  490. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  491. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  492. }
  493. delete geometryGroup.__webglMorphNormalsBuffers;
  494. }
  495. deleteBuffers( geometryGroup );
  496. }
  497. delete geometryGroups[ geometry.id ];
  498. } else {
  499. deleteBuffers( geometry );
  500. }
  501. }
  502. // TOFIX: Workaround for deleted geometry being currently bound
  503. _currentGeometryProgram = '';
  504. };
  505. var deallocateTexture = function ( texture ) {
  506. if ( texture.image && texture.image.__webglTextureCube ) {
  507. // cube texture
  508. _gl.deleteTexture( texture.image.__webglTextureCube );
  509. delete texture.image.__webglTextureCube;
  510. } else {
  511. // 2D texture
  512. if ( texture.__webglInit === undefined ) return;
  513. _gl.deleteTexture( texture.__webglTexture );
  514. delete texture.__webglTexture;
  515. delete texture.__webglInit;
  516. }
  517. };
  518. var deallocateRenderTarget = function ( renderTarget ) {
  519. if ( ! renderTarget || renderTarget.__webglTexture === undefined ) return;
  520. _gl.deleteTexture( renderTarget.__webglTexture );
  521. delete renderTarget.__webglTexture;
  522. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  523. for ( var i = 0; i < 6; i ++ ) {
  524. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  525. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  526. }
  527. } else {
  528. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  529. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  530. }
  531. delete renderTarget.__webglFramebuffer;
  532. delete renderTarget.__webglRenderbuffer;
  533. };
  534. var deallocateMaterial = function ( material ) {
  535. var program = material.program.program;
  536. if ( program === undefined ) return;
  537. material.program = undefined;
  538. // only deallocate GL program if this was the last use of shared program
  539. // assumed there is only single copy of any program in the _programs list
  540. // (that's how it's constructed)
  541. var i, il, programInfo;
  542. var deleteProgram = false;
  543. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  544. programInfo = _programs[ i ];
  545. if ( programInfo.program === program ) {
  546. programInfo.usedTimes --;
  547. if ( programInfo.usedTimes === 0 ) {
  548. deleteProgram = true;
  549. }
  550. break;
  551. }
  552. }
  553. if ( deleteProgram === true ) {
  554. // avoid using array.splice, this is costlier than creating new array from scratch
  555. var newPrograms = [];
  556. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  557. programInfo = _programs[ i ];
  558. if ( programInfo.program !== program ) {
  559. newPrograms.push( programInfo );
  560. }
  561. }
  562. _programs = newPrograms;
  563. _gl.deleteProgram( program );
  564. _this.info.memory.programs --;
  565. }
  566. };
  567. // Buffer initialization
  568. function initCustomAttributes ( object ) {
  569. var geometry = object.geometry;
  570. var material = object.material;
  571. var nvertices = geometry.vertices.length;
  572. if ( material.attributes ) {
  573. if ( geometry.__webglCustomAttributesList === undefined ) {
  574. geometry.__webglCustomAttributesList = [];
  575. }
  576. for ( var name in material.attributes ) {
  577. var attribute = material.attributes[ name ];
  578. if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  579. attribute.__webglInitialized = true;
  580. var size = 1; // "f" and "i"
  581. if ( attribute.type === 'v2' ) size = 2;
  582. else if ( attribute.type === 'v3' ) size = 3;
  583. else if ( attribute.type === 'v4' ) size = 4;
  584. else if ( attribute.type === 'c' ) size = 3;
  585. attribute.size = size;
  586. attribute.array = new Float32Array( nvertices * size );
  587. attribute.buffer = _gl.createBuffer();
  588. attribute.buffer.belongsToAttribute = name;
  589. attribute.needsUpdate = true;
  590. }
  591. geometry.__webglCustomAttributesList.push( attribute );
  592. }
  593. }
  594. };
  595. function initParticleBuffers ( geometry, object ) {
  596. var nvertices = geometry.vertices.length;
  597. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  598. geometry.__colorArray = new Float32Array( nvertices * 3 );
  599. geometry.__sortArray = [];
  600. geometry.__webglParticleCount = nvertices;
  601. initCustomAttributes( object );
  602. };
  603. function initLineBuffers ( geometry, object ) {
  604. var nvertices = geometry.vertices.length;
  605. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  606. geometry.__colorArray = new Float32Array( nvertices * 3 );
  607. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  608. geometry.__webglLineCount = nvertices;
  609. initCustomAttributes( object );
  610. };
  611. function initMeshBuffers ( geometryGroup, object ) {
  612. var geometry = object.geometry,
  613. faces3 = geometryGroup.faces3,
  614. nvertices = faces3.length * 3,
  615. ntris = faces3.length * 1,
  616. nlines = faces3.length * 3,
  617. material = getBufferMaterial( object, geometryGroup );
  618. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  619. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  620. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  621. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  622. if ( geometry.faceVertexUvs.length > 1 ) {
  623. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  624. }
  625. if ( geometry.hasTangents ) {
  626. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  627. }
  628. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  629. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  630. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  631. }
  632. var UintArray = extensions.get( 'OES_element_index_uint' ) !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3
  633. geometryGroup.__typeArray = UintArray;
  634. geometryGroup.__faceArray = new UintArray( ntris * 3 );
  635. geometryGroup.__lineArray = new UintArray( nlines * 2 );
  636. var numMorphTargets = geometryGroup.numMorphTargets;
  637. if ( numMorphTargets ) {
  638. geometryGroup.__morphTargetsArrays = [];
  639. for ( var m = 0, ml = numMorphTargets; m < ml; m ++ ) {
  640. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  641. }
  642. }
  643. var numMorphNormals = geometryGroup.numMorphNormals;
  644. if ( numMorphNormals ) {
  645. geometryGroup.__morphNormalsArrays = [];
  646. for ( var m = 0, ml = numMorphNormals; m < ml; m ++ ) {
  647. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  648. }
  649. }
  650. geometryGroup.__webglFaceCount = ntris * 3;
  651. geometryGroup.__webglLineCount = nlines * 2;
  652. // custom attributes
  653. if ( material.attributes ) {
  654. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  655. geometryGroup.__webglCustomAttributesList = [];
  656. }
  657. for ( var name in material.attributes ) {
  658. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  659. // attribute buffers which are correctly indexed in the setMeshBuffers function
  660. var originalAttribute = material.attributes[ name ];
  661. var attribute = {};
  662. for ( var property in originalAttribute ) {
  663. attribute[ property ] = originalAttribute[ property ];
  664. }
  665. if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  666. attribute.__webglInitialized = true;
  667. var size = 1; // "f" and "i"
  668. if ( attribute.type === 'v2' ) size = 2;
  669. else if ( attribute.type === 'v3' ) size = 3;
  670. else if ( attribute.type === 'v4' ) size = 4;
  671. else if ( attribute.type === 'c' ) size = 3;
  672. attribute.size = size;
  673. attribute.array = new Float32Array( nvertices * size );
  674. attribute.buffer = _gl.createBuffer();
  675. attribute.buffer.belongsToAttribute = name;
  676. originalAttribute.needsUpdate = true;
  677. attribute.__original = originalAttribute;
  678. }
  679. geometryGroup.__webglCustomAttributesList.push( attribute );
  680. }
  681. }
  682. geometryGroup.__inittedArrays = true;
  683. };
  684. function getBufferMaterial( object, geometryGroup ) {
  685. return object.material instanceof THREE.MeshFaceMaterial
  686. ? object.material.materials[ geometryGroup.materialIndex ]
  687. : object.material;
  688. };
  689. function materialNeedsSmoothNormals ( material ) {
  690. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  691. };
  692. // Buffer setting
  693. function setParticleBuffers ( geometry, hint, object ) {
  694. var v, c, vertex, offset, index, color,
  695. vertices = geometry.vertices,
  696. vl = vertices.length,
  697. colors = geometry.colors,
  698. cl = colors.length,
  699. vertexArray = geometry.__vertexArray,
  700. colorArray = geometry.__colorArray,
  701. sortArray = geometry.__sortArray,
  702. dirtyVertices = geometry.verticesNeedUpdate,
  703. dirtyElements = geometry.elementsNeedUpdate,
  704. dirtyColors = geometry.colorsNeedUpdate,
  705. customAttributes = geometry.__webglCustomAttributesList,
  706. i, il,
  707. a, ca, cal, value,
  708. customAttribute;
  709. if ( dirtyVertices ) {
  710. for ( v = 0; v < vl; v ++ ) {
  711. vertex = vertices[ v ];
  712. offset = v * 3;
  713. vertexArray[ offset ] = vertex.x;
  714. vertexArray[ offset + 1 ] = vertex.y;
  715. vertexArray[ offset + 2 ] = vertex.z;
  716. }
  717. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  718. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  719. }
  720. if ( dirtyColors ) {
  721. for ( c = 0; c < cl; c ++ ) {
  722. color = colors[ c ];
  723. offset = c * 3;
  724. colorArray[ offset ] = color.r;
  725. colorArray[ offset + 1 ] = color.g;
  726. colorArray[ offset + 2 ] = color.b;
  727. }
  728. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  729. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  730. }
  731. if ( customAttributes ) {
  732. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  733. customAttribute = customAttributes[ i ];
  734. if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) {
  735. cal = customAttribute.value.length;
  736. offset = 0;
  737. if ( customAttribute.size === 1 ) {
  738. for ( ca = 0; ca < cal; ca ++ ) {
  739. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  740. }
  741. } else if ( customAttribute.size === 2 ) {
  742. for ( ca = 0; ca < cal; ca ++ ) {
  743. value = customAttribute.value[ ca ];
  744. customAttribute.array[ offset ] = value.x;
  745. customAttribute.array[ offset + 1 ] = value.y;
  746. offset += 2;
  747. }
  748. } else if ( customAttribute.size === 3 ) {
  749. if ( customAttribute.type === 'c' ) {
  750. for ( ca = 0; ca < cal; ca ++ ) {
  751. value = customAttribute.value[ ca ];
  752. customAttribute.array[ offset ] = value.r;
  753. customAttribute.array[ offset + 1 ] = value.g;
  754. customAttribute.array[ offset + 2 ] = value.b;
  755. offset += 3;
  756. }
  757. } else {
  758. for ( ca = 0; ca < cal; ca ++ ) {
  759. value = customAttribute.value[ ca ];
  760. customAttribute.array[ offset ] = value.x;
  761. customAttribute.array[ offset + 1 ] = value.y;
  762. customAttribute.array[ offset + 2 ] = value.z;
  763. offset += 3;
  764. }
  765. }
  766. } else if ( customAttribute.size === 4 ) {
  767. for ( ca = 0; ca < cal; ca ++ ) {
  768. value = customAttribute.value[ ca ];
  769. customAttribute.array[ offset ] = value.x;
  770. customAttribute.array[ offset + 1 ] = value.y;
  771. customAttribute.array[ offset + 2 ] = value.z;
  772. customAttribute.array[ offset + 3 ] = value.w;
  773. offset += 4;
  774. }
  775. }
  776. }
  777. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  778. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  779. customAttribute.needsUpdate = false;
  780. }
  781. }
  782. }
  783. function setLineBuffers ( geometry, hint ) {
  784. var v, c, d, vertex, offset, color,
  785. vertices = geometry.vertices,
  786. colors = geometry.colors,
  787. lineDistances = geometry.lineDistances,
  788. vl = vertices.length,
  789. cl = colors.length,
  790. dl = lineDistances.length,
  791. vertexArray = geometry.__vertexArray,
  792. colorArray = geometry.__colorArray,
  793. lineDistanceArray = geometry.__lineDistanceArray,
  794. dirtyVertices = geometry.verticesNeedUpdate,
  795. dirtyColors = geometry.colorsNeedUpdate,
  796. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  797. customAttributes = geometry.__webglCustomAttributesList,
  798. i, il,
  799. a, ca, cal, value,
  800. customAttribute;
  801. if ( dirtyVertices ) {
  802. for ( v = 0; v < vl; v ++ ) {
  803. vertex = vertices[ v ];
  804. offset = v * 3;
  805. vertexArray[ offset ] = vertex.x;
  806. vertexArray[ offset + 1 ] = vertex.y;
  807. vertexArray[ offset + 2 ] = vertex.z;
  808. }
  809. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  810. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  811. }
  812. if ( dirtyColors ) {
  813. for ( c = 0; c < cl; c ++ ) {
  814. color = colors[ c ];
  815. offset = c * 3;
  816. colorArray[ offset ] = color.r;
  817. colorArray[ offset + 1 ] = color.g;
  818. colorArray[ offset + 2 ] = color.b;
  819. }
  820. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  821. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  822. }
  823. if ( dirtyLineDistances ) {
  824. for ( d = 0; d < dl; d ++ ) {
  825. lineDistanceArray[ d ] = lineDistances[ d ];
  826. }
  827. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  828. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  829. }
  830. if ( customAttributes ) {
  831. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  832. customAttribute = customAttributes[ i ];
  833. if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) {
  834. offset = 0;
  835. cal = customAttribute.value.length;
  836. if ( customAttribute.size === 1 ) {
  837. for ( ca = 0; ca < cal; ca ++ ) {
  838. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  839. }
  840. } else if ( customAttribute.size === 2 ) {
  841. for ( ca = 0; ca < cal; ca ++ ) {
  842. value = customAttribute.value[ ca ];
  843. customAttribute.array[ offset ] = value.x;
  844. customAttribute.array[ offset + 1 ] = value.y;
  845. offset += 2;
  846. }
  847. } else if ( customAttribute.size === 3 ) {
  848. if ( customAttribute.type === 'c' ) {
  849. for ( ca = 0; ca < cal; ca ++ ) {
  850. value = customAttribute.value[ ca ];
  851. customAttribute.array[ offset ] = value.r;
  852. customAttribute.array[ offset + 1 ] = value.g;
  853. customAttribute.array[ offset + 2 ] = value.b;
  854. offset += 3;
  855. }
  856. } else {
  857. for ( ca = 0; ca < cal; ca ++ ) {
  858. value = customAttribute.value[ ca ];
  859. customAttribute.array[ offset ] = value.x;
  860. customAttribute.array[ offset + 1 ] = value.y;
  861. customAttribute.array[ offset + 2 ] = value.z;
  862. offset += 3;
  863. }
  864. }
  865. } else if ( customAttribute.size === 4 ) {
  866. for ( ca = 0; ca < cal; ca ++ ) {
  867. value = customAttribute.value[ ca ];
  868. customAttribute.array[ offset ] = value.x;
  869. customAttribute.array[ offset + 1 ] = value.y;
  870. customAttribute.array[ offset + 2 ] = value.z;
  871. customAttribute.array[ offset + 3 ] = value.w;
  872. offset += 4;
  873. }
  874. }
  875. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  876. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  877. customAttribute.needsUpdate = false;
  878. }
  879. }
  880. }
  881. }
  882. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  883. if ( ! geometryGroup.__inittedArrays ) {
  884. return;
  885. }
  886. var needsSmoothNormals = materialNeedsSmoothNormals( material );
  887. var f, fl, fi, face,
  888. vertexNormals, faceNormal, normal,
  889. vertexColors, faceColor,
  890. vertexTangents,
  891. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  892. c1, c2, c3,
  893. sw1, sw2, sw3, sw4,
  894. si1, si2, si3, si4,
  895. sa1, sa2, sa3, sa4,
  896. sb1, sb2, sb3, sb4,
  897. m, ml, i, il,
  898. vn, uvi, uv2i,
  899. vk, vkl, vka,
  900. nka, chf, faceVertexNormals,
  901. a,
  902. vertexIndex = 0,
  903. offset = 0,
  904. offset_uv = 0,
  905. offset_uv2 = 0,
  906. offset_face = 0,
  907. offset_normal = 0,
  908. offset_tangent = 0,
  909. offset_line = 0,
  910. offset_color = 0,
  911. offset_skin = 0,
  912. offset_morphTarget = 0,
  913. offset_custom = 0,
  914. offset_customSrc = 0,
  915. value,
  916. vertexArray = geometryGroup.__vertexArray,
  917. uvArray = geometryGroup.__uvArray,
  918. uv2Array = geometryGroup.__uv2Array,
  919. normalArray = geometryGroup.__normalArray,
  920. tangentArray = geometryGroup.__tangentArray,
  921. colorArray = geometryGroup.__colorArray,
  922. skinIndexArray = geometryGroup.__skinIndexArray,
  923. skinWeightArray = geometryGroup.__skinWeightArray,
  924. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  925. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  926. customAttributes = geometryGroup.__webglCustomAttributesList,
  927. customAttribute,
  928. faceArray = geometryGroup.__faceArray,
  929. lineArray = geometryGroup.__lineArray,
  930. geometry = object.geometry, // this is shared for all chunks
  931. dirtyVertices = geometry.verticesNeedUpdate,
  932. dirtyElements = geometry.elementsNeedUpdate,
  933. dirtyUvs = geometry.uvsNeedUpdate,
  934. dirtyNormals = geometry.normalsNeedUpdate,
  935. dirtyTangents = geometry.tangentsNeedUpdate,
  936. dirtyColors = geometry.colorsNeedUpdate,
  937. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  938. vertices = geometry.vertices,
  939. chunk_faces3 = geometryGroup.faces3,
  940. obj_faces = geometry.faces,
  941. obj_uvs = geometry.faceVertexUvs[ 0 ],
  942. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  943. obj_colors = geometry.colors,
  944. obj_skinIndices = geometry.skinIndices,
  945. obj_skinWeights = geometry.skinWeights,
  946. morphTargets = geometry.morphTargets,
  947. morphNormals = geometry.morphNormals;
  948. if ( dirtyVertices ) {
  949. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  950. face = obj_faces[ chunk_faces3[ f ] ];
  951. v1 = vertices[ face.a ];
  952. v2 = vertices[ face.b ];
  953. v3 = vertices[ face.c ];
  954. vertexArray[ offset ] = v1.x;
  955. vertexArray[ offset + 1 ] = v1.y;
  956. vertexArray[ offset + 2 ] = v1.z;
  957. vertexArray[ offset + 3 ] = v2.x;
  958. vertexArray[ offset + 4 ] = v2.y;
  959. vertexArray[ offset + 5 ] = v2.z;
  960. vertexArray[ offset + 6 ] = v3.x;
  961. vertexArray[ offset + 7 ] = v3.y;
  962. vertexArray[ offset + 8 ] = v3.z;
  963. offset += 9;
  964. }
  965. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  966. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  967. }
  968. if ( dirtyMorphTargets ) {
  969. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  970. offset_morphTarget = 0;
  971. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  972. chf = chunk_faces3[ f ];
  973. face = obj_faces[ chf ];
  974. // morph positions
  975. v1 = morphTargets[ vk ].vertices[ face.a ];
  976. v2 = morphTargets[ vk ].vertices[ face.b ];
  977. v3 = morphTargets[ vk ].vertices[ face.c ];
  978. vka = morphTargetsArrays[ vk ];
  979. vka[ offset_morphTarget ] = v1.x;
  980. vka[ offset_morphTarget + 1 ] = v1.y;
  981. vka[ offset_morphTarget + 2 ] = v1.z;
  982. vka[ offset_morphTarget + 3 ] = v2.x;
  983. vka[ offset_morphTarget + 4 ] = v2.y;
  984. vka[ offset_morphTarget + 5 ] = v2.z;
  985. vka[ offset_morphTarget + 6 ] = v3.x;
  986. vka[ offset_morphTarget + 7 ] = v3.y;
  987. vka[ offset_morphTarget + 8 ] = v3.z;
  988. // morph normals
  989. if ( material.morphNormals ) {
  990. if ( needsSmoothNormals ) {
  991. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  992. n1 = faceVertexNormals.a;
  993. n2 = faceVertexNormals.b;
  994. n3 = faceVertexNormals.c;
  995. } else {
  996. n1 = morphNormals[ vk ].faceNormals[ chf ];
  997. n2 = n1;
  998. n3 = n1;
  999. }
  1000. nka = morphNormalsArrays[ vk ];
  1001. nka[ offset_morphTarget ] = n1.x;
  1002. nka[ offset_morphTarget + 1 ] = n1.y;
  1003. nka[ offset_morphTarget + 2 ] = n1.z;
  1004. nka[ offset_morphTarget + 3 ] = n2.x;
  1005. nka[ offset_morphTarget + 4 ] = n2.y;
  1006. nka[ offset_morphTarget + 5 ] = n2.z;
  1007. nka[ offset_morphTarget + 6 ] = n3.x;
  1008. nka[ offset_morphTarget + 7 ] = n3.y;
  1009. nka[ offset_morphTarget + 8 ] = n3.z;
  1010. }
  1011. //
  1012. offset_morphTarget += 9;
  1013. }
  1014. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  1015. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  1016. if ( material.morphNormals ) {
  1017. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  1018. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  1019. }
  1020. }
  1021. }
  1022. if ( obj_skinWeights.length ) {
  1023. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1024. face = obj_faces[ chunk_faces3[ f ] ];
  1025. // weights
  1026. sw1 = obj_skinWeights[ face.a ];
  1027. sw2 = obj_skinWeights[ face.b ];
  1028. sw3 = obj_skinWeights[ face.c ];
  1029. skinWeightArray[ offset_skin ] = sw1.x;
  1030. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  1031. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  1032. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  1033. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  1034. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  1035. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  1036. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  1037. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  1038. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  1039. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  1040. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  1041. // indices
  1042. si1 = obj_skinIndices[ face.a ];
  1043. si2 = obj_skinIndices[ face.b ];
  1044. si3 = obj_skinIndices[ face.c ];
  1045. skinIndexArray[ offset_skin ] = si1.x;
  1046. skinIndexArray[ offset_skin + 1 ] = si1.y;
  1047. skinIndexArray[ offset_skin + 2 ] = si1.z;
  1048. skinIndexArray[ offset_skin + 3 ] = si1.w;
  1049. skinIndexArray[ offset_skin + 4 ] = si2.x;
  1050. skinIndexArray[ offset_skin + 5 ] = si2.y;
  1051. skinIndexArray[ offset_skin + 6 ] = si2.z;
  1052. skinIndexArray[ offset_skin + 7 ] = si2.w;
  1053. skinIndexArray[ offset_skin + 8 ] = si3.x;
  1054. skinIndexArray[ offset_skin + 9 ] = si3.y;
  1055. skinIndexArray[ offset_skin + 10 ] = si3.z;
  1056. skinIndexArray[ offset_skin + 11 ] = si3.w;
  1057. offset_skin += 12;
  1058. }
  1059. if ( offset_skin > 0 ) {
  1060. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  1061. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  1062. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  1063. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  1064. }
  1065. }
  1066. if ( dirtyColors ) {
  1067. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1068. face = obj_faces[ chunk_faces3[ f ] ];
  1069. vertexColors = face.vertexColors;
  1070. faceColor = face.color;
  1071. if ( vertexColors.length === 3 && material.vertexColors === THREE.VertexColors ) {
  1072. c1 = vertexColors[ 0 ];
  1073. c2 = vertexColors[ 1 ];
  1074. c3 = vertexColors[ 2 ];
  1075. } else {
  1076. c1 = faceColor;
  1077. c2 = faceColor;
  1078. c3 = faceColor;
  1079. }
  1080. colorArray[ offset_color ] = c1.r;
  1081. colorArray[ offset_color + 1 ] = c1.g;
  1082. colorArray[ offset_color + 2 ] = c1.b;
  1083. colorArray[ offset_color + 3 ] = c2.r;
  1084. colorArray[ offset_color + 4 ] = c2.g;
  1085. colorArray[ offset_color + 5 ] = c2.b;
  1086. colorArray[ offset_color + 6 ] = c3.r;
  1087. colorArray[ offset_color + 7 ] = c3.g;
  1088. colorArray[ offset_color + 8 ] = c3.b;
  1089. offset_color += 9;
  1090. }
  1091. if ( offset_color > 0 ) {
  1092. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  1093. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  1094. }
  1095. }
  1096. if ( dirtyTangents && geometry.hasTangents ) {
  1097. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1098. face = obj_faces[ chunk_faces3[ f ] ];
  1099. vertexTangents = face.vertexTangents;
  1100. t1 = vertexTangents[ 0 ];
  1101. t2 = vertexTangents[ 1 ];
  1102. t3 = vertexTangents[ 2 ];
  1103. tangentArray[ offset_tangent ] = t1.x;
  1104. tangentArray[ offset_tangent + 1 ] = t1.y;
  1105. tangentArray[ offset_tangent + 2 ] = t1.z;
  1106. tangentArray[ offset_tangent + 3 ] = t1.w;
  1107. tangentArray[ offset_tangent + 4 ] = t2.x;
  1108. tangentArray[ offset_tangent + 5 ] = t2.y;
  1109. tangentArray[ offset_tangent + 6 ] = t2.z;
  1110. tangentArray[ offset_tangent + 7 ] = t2.w;
  1111. tangentArray[ offset_tangent + 8 ] = t3.x;
  1112. tangentArray[ offset_tangent + 9 ] = t3.y;
  1113. tangentArray[ offset_tangent + 10 ] = t3.z;
  1114. tangentArray[ offset_tangent + 11 ] = t3.w;
  1115. offset_tangent += 12;
  1116. }
  1117. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  1118. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  1119. }
  1120. if ( dirtyNormals ) {
  1121. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1122. face = obj_faces[ chunk_faces3[ f ] ];
  1123. vertexNormals = face.vertexNormals;
  1124. faceNormal = face.normal;
  1125. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  1126. for ( i = 0; i < 3; i ++ ) {
  1127. vn = vertexNormals[ i ];
  1128. normalArray[ offset_normal ] = vn.x;
  1129. normalArray[ offset_normal + 1 ] = vn.y;
  1130. normalArray[ offset_normal + 2 ] = vn.z;
  1131. offset_normal += 3;
  1132. }
  1133. } else {
  1134. for ( i = 0; i < 3; i ++ ) {
  1135. normalArray[ offset_normal ] = faceNormal.x;
  1136. normalArray[ offset_normal + 1 ] = faceNormal.y;
  1137. normalArray[ offset_normal + 2 ] = faceNormal.z;
  1138. offset_normal += 3;
  1139. }
  1140. }
  1141. }
  1142. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  1143. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  1144. }
  1145. if ( dirtyUvs && obj_uvs ) {
  1146. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1147. fi = chunk_faces3[ f ];
  1148. uv = obj_uvs[ fi ];
  1149. if ( uv === undefined ) continue;
  1150. for ( i = 0; i < 3; i ++ ) {
  1151. uvi = uv[ i ];
  1152. uvArray[ offset_uv ] = uvi.x;
  1153. uvArray[ offset_uv + 1 ] = uvi.y;
  1154. offset_uv += 2;
  1155. }
  1156. }
  1157. if ( offset_uv > 0 ) {
  1158. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  1159. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  1160. }
  1161. }
  1162. if ( dirtyUvs && obj_uvs2 ) {
  1163. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1164. fi = chunk_faces3[ f ];
  1165. uv2 = obj_uvs2[ fi ];
  1166. if ( uv2 === undefined ) continue;
  1167. for ( i = 0; i < 3; i ++ ) {
  1168. uv2i = uv2[ i ];
  1169. uv2Array[ offset_uv2 ] = uv2i.x;
  1170. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  1171. offset_uv2 += 2;
  1172. }
  1173. }
  1174. if ( offset_uv2 > 0 ) {
  1175. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  1176. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  1177. }
  1178. }
  1179. if ( dirtyElements ) {
  1180. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1181. faceArray[ offset_face ] = vertexIndex;
  1182. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  1183. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  1184. offset_face += 3;
  1185. lineArray[ offset_line ] = vertexIndex;
  1186. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  1187. lineArray[ offset_line + 2 ] = vertexIndex;
  1188. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  1189. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  1190. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  1191. offset_line += 6;
  1192. vertexIndex += 3;
  1193. }
  1194. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  1195. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  1196. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  1197. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  1198. }
  1199. if ( customAttributes ) {
  1200. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  1201. customAttribute = customAttributes[ i ];
  1202. if ( ! customAttribute.__original.needsUpdate ) continue;
  1203. offset_custom = 0;
  1204. offset_customSrc = 0;
  1205. if ( customAttribute.size === 1 ) {
  1206. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  1207. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1208. face = obj_faces[ chunk_faces3[ f ] ];
  1209. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  1210. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  1211. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  1212. offset_custom += 3;
  1213. }
  1214. } else if ( customAttribute.boundTo === 'faces' ) {
  1215. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1216. value = customAttribute.value[ chunk_faces3[ f ] ];
  1217. customAttribute.array[ offset_custom ] = value;
  1218. customAttribute.array[ offset_custom + 1 ] = value;
  1219. customAttribute.array[ offset_custom + 2 ] = value;
  1220. offset_custom += 3;
  1221. }
  1222. }
  1223. } else if ( customAttribute.size === 2 ) {
  1224. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  1225. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1226. face = obj_faces[ chunk_faces3[ f ] ];
  1227. v1 = customAttribute.value[ face.a ];
  1228. v2 = customAttribute.value[ face.b ];
  1229. v3 = customAttribute.value[ face.c ];
  1230. customAttribute.array[ offset_custom ] = v1.x;
  1231. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1232. customAttribute.array[ offset_custom + 2 ] = v2.x;
  1233. customAttribute.array[ offset_custom + 3 ] = v2.y;
  1234. customAttribute.array[ offset_custom + 4 ] = v3.x;
  1235. customAttribute.array[ offset_custom + 5 ] = v3.y;
  1236. offset_custom += 6;
  1237. }
  1238. } else if ( customAttribute.boundTo === 'faces' ) {
  1239. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1240. value = customAttribute.value[ chunk_faces3[ f ] ];
  1241. v1 = value;
  1242. v2 = value;
  1243. v3 = value;
  1244. customAttribute.array[ offset_custom ] = v1.x;
  1245. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1246. customAttribute.array[ offset_custom + 2 ] = v2.x;
  1247. customAttribute.array[ offset_custom + 3 ] = v2.y;
  1248. customAttribute.array[ offset_custom + 4 ] = v3.x;
  1249. customAttribute.array[ offset_custom + 5 ] = v3.y;
  1250. offset_custom += 6;
  1251. }
  1252. }
  1253. } else if ( customAttribute.size === 3 ) {
  1254. var pp;
  1255. if ( customAttribute.type === 'c' ) {
  1256. pp = [ 'r', 'g', 'b' ];
  1257. } else {
  1258. pp = [ 'x', 'y', 'z' ];
  1259. }
  1260. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  1261. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1262. face = obj_faces[ chunk_faces3[ f ] ];
  1263. v1 = customAttribute.value[ face.a ];
  1264. v2 = customAttribute.value[ face.b ];
  1265. v3 = customAttribute.value[ face.c ];
  1266. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  1267. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  1268. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  1269. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  1270. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  1271. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  1272. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  1273. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  1274. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  1275. offset_custom += 9;
  1276. }
  1277. } else if ( customAttribute.boundTo === 'faces' ) {
  1278. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1279. value = customAttribute.value[ chunk_faces3[ f ] ];
  1280. v1 = value;
  1281. v2 = value;
  1282. v3 = value;
  1283. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  1284. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  1285. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  1286. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  1287. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  1288. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  1289. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  1290. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  1291. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  1292. offset_custom += 9;
  1293. }
  1294. } else if ( customAttribute.boundTo === 'faceVertices' ) {
  1295. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1296. value = customAttribute.value[ chunk_faces3[ f ] ];
  1297. v1 = value[ 0 ];
  1298. v2 = value[ 1 ];
  1299. v3 = value[ 2 ];
  1300. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  1301. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  1302. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  1303. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  1304. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  1305. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  1306. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  1307. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  1308. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  1309. offset_custom += 9;
  1310. }
  1311. }
  1312. } else if ( customAttribute.size === 4 ) {
  1313. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  1314. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1315. face = obj_faces[ chunk_faces3[ f ] ];
  1316. v1 = customAttribute.value[ face.a ];
  1317. v2 = customAttribute.value[ face.b ];
  1318. v3 = customAttribute.value[ face.c ];
  1319. customAttribute.array[ offset_custom ] = v1.x;
  1320. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1321. customAttribute.array[ offset_custom + 2 ] = v1.z;
  1322. customAttribute.array[ offset_custom + 3 ] = v1.w;
  1323. customAttribute.array[ offset_custom + 4 ] = v2.x;
  1324. customAttribute.array[ offset_custom + 5 ] = v2.y;
  1325. customAttribute.array[ offset_custom + 6 ] = v2.z;
  1326. customAttribute.array[ offset_custom + 7 ] = v2.w;
  1327. customAttribute.array[ offset_custom + 8 ] = v3.x;
  1328. customAttribute.array[ offset_custom + 9 ] = v3.y;
  1329. customAttribute.array[ offset_custom + 10 ] = v3.z;
  1330. customAttribute.array[ offset_custom + 11 ] = v3.w;
  1331. offset_custom += 12;
  1332. }
  1333. } else if ( customAttribute.boundTo === 'faces' ) {
  1334. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1335. value = customAttribute.value[ chunk_faces3[ f ] ];
  1336. v1 = value;
  1337. v2 = value;
  1338. v3 = value;
  1339. customAttribute.array[ offset_custom ] = v1.x;
  1340. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1341. customAttribute.array[ offset_custom + 2 ] = v1.z;
  1342. customAttribute.array[ offset_custom + 3 ] = v1.w;
  1343. customAttribute.array[ offset_custom + 4 ] = v2.x;
  1344. customAttribute.array[ offset_custom + 5 ] = v2.y;
  1345. customAttribute.array[ offset_custom + 6 ] = v2.z;
  1346. customAttribute.array[ offset_custom + 7 ] = v2.w;
  1347. customAttribute.array[ offset_custom + 8 ] = v3.x;
  1348. customAttribute.array[ offset_custom + 9 ] = v3.y;
  1349. customAttribute.array[ offset_custom + 10 ] = v3.z;
  1350. customAttribute.array[ offset_custom + 11 ] = v3.w;
  1351. offset_custom += 12;
  1352. }
  1353. } else if ( customAttribute.boundTo === 'faceVertices' ) {
  1354. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1355. value = customAttribute.value[ chunk_faces3[ f ] ];
  1356. v1 = value[ 0 ];
  1357. v2 = value[ 1 ];
  1358. v3 = value[ 2 ];
  1359. customAttribute.array[ offset_custom ] = v1.x;
  1360. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1361. customAttribute.array[ offset_custom + 2 ] = v1.z;
  1362. customAttribute.array[ offset_custom + 3 ] = v1.w;
  1363. customAttribute.array[ offset_custom + 4 ] = v2.x;
  1364. customAttribute.array[ offset_custom + 5 ] = v2.y;
  1365. customAttribute.array[ offset_custom + 6 ] = v2.z;
  1366. customAttribute.array[ offset_custom + 7 ] = v2.w;
  1367. customAttribute.array[ offset_custom + 8 ] = v3.x;
  1368. customAttribute.array[ offset_custom + 9 ] = v3.y;
  1369. customAttribute.array[ offset_custom + 10 ] = v3.z;
  1370. customAttribute.array[ offset_custom + 11 ] = v3.w;
  1371. offset_custom += 12;
  1372. }
  1373. }
  1374. }
  1375. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  1376. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  1377. }
  1378. }
  1379. if ( dispose ) {
  1380. delete geometryGroup.__inittedArrays;
  1381. delete geometryGroup.__colorArray;
  1382. delete geometryGroup.__normalArray;
  1383. delete geometryGroup.__tangentArray;
  1384. delete geometryGroup.__uvArray;
  1385. delete geometryGroup.__uv2Array;
  1386. delete geometryGroup.__faceArray;
  1387. delete geometryGroup.__vertexArray;
  1388. delete geometryGroup.__lineArray;
  1389. delete geometryGroup.__skinIndexArray;
  1390. delete geometryGroup.__skinWeightArray;
  1391. }
  1392. };
  1393. // Buffer rendering
  1394. this.renderBufferImmediate = function ( object, program, material ) {
  1395. initAttributes();
  1396. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  1397. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  1398. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  1399. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  1400. if ( object.hasPositions ) {
  1401. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  1402. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  1403. enableAttribute( program.attributes.position );
  1404. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  1405. }
  1406. if ( object.hasNormals ) {
  1407. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  1408. if ( material.shading === THREE.FlatShading ) {
  1409. var nx, ny, nz,
  1410. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  1411. normalArray,
  1412. i, il = object.count * 3;
  1413. for ( i = 0; i < il; i += 9 ) {
  1414. normalArray = object.normalArray;
  1415. nax = normalArray[ i ];
  1416. nay = normalArray[ i + 1 ];
  1417. naz = normalArray[ i + 2 ];
  1418. nbx = normalArray[ i + 3 ];
  1419. nby = normalArray[ i + 4 ];
  1420. nbz = normalArray[ i + 5 ];
  1421. ncx = normalArray[ i + 6 ];
  1422. ncy = normalArray[ i + 7 ];
  1423. ncz = normalArray[ i + 8 ];
  1424. nx = ( nax + nbx + ncx ) / 3;
  1425. ny = ( nay + nby + ncy ) / 3;
  1426. nz = ( naz + nbz + ncz ) / 3;
  1427. normalArray[ i ] = nx;
  1428. normalArray[ i + 1 ] = ny;
  1429. normalArray[ i + 2 ] = nz;
  1430. normalArray[ i + 3 ] = nx;
  1431. normalArray[ i + 4 ] = ny;
  1432. normalArray[ i + 5 ] = nz;
  1433. normalArray[ i + 6 ] = nx;
  1434. normalArray[ i + 7 ] = ny;
  1435. normalArray[ i + 8 ] = nz;
  1436. }
  1437. }
  1438. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  1439. enableAttribute( program.attributes.normal );
  1440. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  1441. }
  1442. if ( object.hasUvs && material.map ) {
  1443. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  1444. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  1445. enableAttribute( program.attributes.uv );
  1446. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  1447. }
  1448. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  1449. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  1450. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  1451. enableAttribute( program.attributes.color );
  1452. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  1453. }
  1454. disableUnusedAttributes();
  1455. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  1456. object.count = 0;
  1457. };
  1458. function setupVertexAttributes( material, program, geometry, startIndex ) {
  1459. var geometryAttributes = geometry.attributes;
  1460. var programAttributes = program.attributes;
  1461. var programAttributesKeys = program.attributesKeys;
  1462. for ( var i = 0, l = programAttributesKeys.length; i < l; i ++ ) {
  1463. var key = programAttributesKeys[ i ];
  1464. var programAttribute = programAttributes[ key ];
  1465. if ( programAttribute >= 0 ) {
  1466. var geometryAttribute = geometryAttributes[ key ];
  1467. if ( geometryAttribute !== undefined ) {
  1468. var size = geometryAttribute.itemSize;
  1469. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryAttribute.buffer );
  1470. enableAttribute( programAttribute );
  1471. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32
  1472. } else if ( material.defaultAttributeValues !== undefined ) {
  1473. if ( material.defaultAttributeValues[ key ].length === 2 ) {
  1474. _gl.vertexAttrib2fv( programAttribute, material.defaultAttributeValues[ key ] );
  1475. } else if ( material.defaultAttributeValues[ key ].length === 3 ) {
  1476. _gl.vertexAttrib3fv( programAttribute, material.defaultAttributeValues[ key ] );
  1477. }
  1478. }
  1479. }
  1480. }
  1481. disableUnusedAttributes();
  1482. }
  1483. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  1484. if ( material.visible === false ) return;
  1485. updateObject( object );
  1486. var program = setProgram( camera, lights, fog, material, object );
  1487. var updateBuffers = false,
  1488. wireframeBit = material.wireframe ? 1 : 0,
  1489. geometryProgram = 'direct_' + geometry.id + '_' + program.id + '_' + wireframeBit;
  1490. if ( geometryProgram !== _currentGeometryProgram ) {
  1491. _currentGeometryProgram = geometryProgram;
  1492. updateBuffers = true;
  1493. }
  1494. if ( updateBuffers ) {
  1495. initAttributes();
  1496. }
  1497. // render mesh
  1498. if ( object instanceof THREE.Mesh ) {
  1499. var mode = material.wireframe === true ? _gl.LINES : _gl.TRIANGLES;
  1500. var index = geometry.attributes.index;
  1501. if ( index ) {
  1502. // indexed triangles
  1503. var type, size;
  1504. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  1505. type = _gl.UNSIGNED_INT;
  1506. size = 4;
  1507. } else {
  1508. type = _gl.UNSIGNED_SHORT;
  1509. size = 2;
  1510. }
  1511. var offsets = geometry.offsets;
  1512. if ( offsets.length === 0 ) {
  1513. if ( updateBuffers ) {
  1514. setupVertexAttributes( material, program, geometry, 0 );
  1515. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  1516. }
  1517. _gl.drawElements( mode, index.array.length, type, 0 );
  1518. _this.info.render.calls ++;
  1519. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  1520. _this.info.render.faces += index.array.length / 3;
  1521. } else {
  1522. // if there is more than 1 chunk
  1523. // must set attribute pointers to use new offsets for each chunk
  1524. // even if geometry and materials didn't change
  1525. updateBuffers = true;
  1526. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  1527. var startIndex = offsets[ i ].index;
  1528. if ( updateBuffers ) {
  1529. setupVertexAttributes( material, program, geometry, startIndex );
  1530. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  1531. }
  1532. // render indexed triangles
  1533. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size );
  1534. _this.info.render.calls ++;
  1535. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  1536. _this.info.render.faces += offsets[ i ].count / 3;
  1537. }
  1538. }
  1539. } else {
  1540. // non-indexed triangles
  1541. if ( updateBuffers ) {
  1542. setupVertexAttributes( material, program, geometry, 0 );
  1543. }
  1544. var position = geometry.attributes[ 'position' ];
  1545. // render non-indexed triangles
  1546. _gl.drawArrays( mode, 0, position.array.length / position.itemSize );
  1547. _this.info.render.calls ++;
  1548. _this.info.render.vertices += position.array.length / position.itemSize;
  1549. _this.info.render.faces += position.array.length / ( 3 * position.itemsize );
  1550. }
  1551. } else if ( object instanceof THREE.PointCloud ) {
  1552. // render particles
  1553. var mode = _gl.POINTS;
  1554. var index = geometry.attributes.index;
  1555. if ( index ) {
  1556. // indexed points
  1557. var type, size;
  1558. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  1559. type = _gl.UNSIGNED_INT;
  1560. size = 4;
  1561. } else {
  1562. type = _gl.UNSIGNED_SHORT;
  1563. size = 2;
  1564. }
  1565. var offsets = geometry.offsets;
  1566. if ( offsets.length === 0 ) {
  1567. if ( updateBuffers ) {
  1568. setupVertexAttributes( material, program, geometry, 0 );
  1569. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  1570. }
  1571. _gl.drawElements( mode, index.array.length, type, 0);
  1572. _this.info.render.calls ++;
  1573. _this.info.render.points += index.array.length;
  1574. } else {
  1575. // if there is more than 1 chunk
  1576. // must set attribute pointers to use new offsets for each chunk
  1577. // even if geometry and materials didn't change
  1578. if ( offsets.length > 1 ) updateBuffers = true;
  1579. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  1580. var startIndex = offsets[ i ].index;
  1581. if ( updateBuffers ) {
  1582. setupVertexAttributes( material, program, geometry, startIndex );
  1583. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  1584. }
  1585. // render indexed points
  1586. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size );
  1587. _this.info.render.calls ++;
  1588. _this.info.render.points += offsets[ i ].count;
  1589. }
  1590. }
  1591. } else {
  1592. // non-indexed points
  1593. if ( updateBuffers ) {
  1594. setupVertexAttributes( material, program, geometry, 0 );
  1595. }
  1596. var position = geometry.attributes.position;
  1597. var offsets = geometry.offsets;
  1598. if ( offsets.length === 0 ) {
  1599. _gl.drawArrays( mode, 0, position.array.length / 3 );
  1600. _this.info.render.calls ++;
  1601. _this.info.render.points += position.array.length / 3;
  1602. } else {
  1603. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  1604. _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count );
  1605. _this.info.render.calls ++;
  1606. _this.info.render.points += offsets[ i ].count;
  1607. }
  1608. }
  1609. }
  1610. } else if ( object instanceof THREE.Line ) {
  1611. var mode = ( object.mode === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  1612. setLineWidth( material.linewidth );
  1613. var index = geometry.attributes.index;
  1614. if ( index ) {
  1615. // indexed lines
  1616. var type, size;
  1617. if ( index.array instanceof Uint32Array ) {
  1618. type = _gl.UNSIGNED_INT;
  1619. size = 4;
  1620. } else {
  1621. type = _gl.UNSIGNED_SHORT;
  1622. size = 2;
  1623. }
  1624. var offsets = geometry.offsets;
  1625. if ( offsets.length === 0 ) {
  1626. if ( updateBuffers ) {
  1627. setupVertexAttributes( material, program, geometry, 0 );
  1628. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  1629. }
  1630. _gl.drawElements( mode, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  1631. _this.info.render.calls ++;
  1632. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  1633. } else {
  1634. // if there is more than 1 chunk
  1635. // must set attribute pointers to use new offsets for each chunk
  1636. // even if geometry and materials didn't change
  1637. if ( offsets.length > 1 ) updateBuffers = true;
  1638. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  1639. var startIndex = offsets[ i ].index;
  1640. if ( updateBuffers ) {
  1641. setupVertexAttributes( material, program, geometry, startIndex );
  1642. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  1643. }
  1644. // render indexed lines
  1645. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  1646. _this.info.render.calls ++;
  1647. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  1648. }
  1649. }
  1650. } else {
  1651. // non-indexed lines
  1652. if ( updateBuffers ) {
  1653. setupVertexAttributes( material, program, geometry, 0 );
  1654. }
  1655. var position = geometry.attributes.position;
  1656. var offsets = geometry.offsets;
  1657. if ( offsets.length === 0 ) {
  1658. _gl.drawArrays( mode, 0, position.array.length / 3 );
  1659. _this.info.render.calls ++;
  1660. _this.info.render.vertices += position.array.length / 3;
  1661. } else {
  1662. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  1663. _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count );
  1664. _this.info.render.calls ++;
  1665. _this.info.render.vertices += offsets[ i ].count;
  1666. }
  1667. }
  1668. }
  1669. }
  1670. };
  1671. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  1672. if ( material.visible === false ) return;
  1673. updateObject( object );
  1674. var program = setProgram( camera, lights, fog, material, object );
  1675. var attributes = program.attributes;
  1676. var updateBuffers = false,
  1677. wireframeBit = material.wireframe ? 1 : 0,
  1678. geometryProgram = geometryGroup.id + '_' + program.id + '_' + wireframeBit;
  1679. if ( geometryProgram !== _currentGeometryProgram ) {
  1680. _currentGeometryProgram = geometryProgram;
  1681. updateBuffers = true;
  1682. }
  1683. if ( updateBuffers ) {
  1684. initAttributes();
  1685. }
  1686. // vertices
  1687. if ( ! material.morphTargets && attributes.position >= 0 ) {
  1688. if ( updateBuffers ) {
  1689. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  1690. enableAttribute( attributes.position );
  1691. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  1692. }
  1693. } else {
  1694. if ( object.morphTargetBase ) {
  1695. setupMorphTargets( material, geometryGroup, object );
  1696. }
  1697. }
  1698. if ( updateBuffers ) {
  1699. // custom attributes
  1700. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  1701. if ( geometryGroup.__webglCustomAttributesList ) {
  1702. for ( var i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  1703. var attribute = geometryGroup.__webglCustomAttributesList[ i ];
  1704. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  1705. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  1706. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  1707. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  1708. }
  1709. }
  1710. }
  1711. // colors
  1712. if ( attributes.color >= 0 ) {
  1713. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  1714. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  1715. enableAttribute( attributes.color );
  1716. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  1717. } else if ( material.defaultAttributeValues !== undefined ) {
  1718. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  1719. }
  1720. }
  1721. // normals
  1722. if ( attributes.normal >= 0 ) {
  1723. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  1724. enableAttribute( attributes.normal );
  1725. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  1726. }
  1727. // tangents
  1728. if ( attributes.tangent >= 0 ) {
  1729. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  1730. enableAttribute( attributes.tangent );
  1731. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  1732. }
  1733. // uvs
  1734. if ( attributes.uv >= 0 ) {
  1735. if ( object.geometry.faceVertexUvs[ 0 ] ) {
  1736. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  1737. enableAttribute( attributes.uv );
  1738. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  1739. } else if ( material.defaultAttributeValues !== undefined ) {
  1740. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  1741. }
  1742. }
  1743. if ( attributes.uv2 >= 0 ) {
  1744. if ( object.geometry.faceVertexUvs[ 1 ] ) {
  1745. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  1746. enableAttribute( attributes.uv2 );
  1747. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  1748. } else if ( material.defaultAttributeValues !== undefined ) {
  1749. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  1750. }
  1751. }
  1752. if ( material.skinning &&
  1753. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  1754. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  1755. enableAttribute( attributes.skinIndex );
  1756. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  1757. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  1758. enableAttribute( attributes.skinWeight );
  1759. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  1760. }
  1761. // line distances
  1762. if ( attributes.lineDistance >= 0 ) {
  1763. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  1764. enableAttribute( attributes.lineDistance );
  1765. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  1766. }
  1767. }
  1768. disableUnusedAttributes();
  1769. // render mesh
  1770. if ( object instanceof THREE.Mesh ) {
  1771. var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT;
  1772. // wireframe
  1773. if ( material.wireframe ) {
  1774. setLineWidth( material.wireframeLinewidth );
  1775. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  1776. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 );
  1777. // triangles
  1778. } else {
  1779. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  1780. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 );
  1781. }
  1782. _this.info.render.calls ++;
  1783. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  1784. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  1785. // render lines
  1786. } else if ( object instanceof THREE.Line ) {
  1787. var mode = ( object.mode === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  1788. setLineWidth( material.linewidth );
  1789. _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount );
  1790. _this.info.render.calls ++;
  1791. // render particles
  1792. } else if ( object instanceof THREE.PointCloud ) {
  1793. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  1794. _this.info.render.calls ++;
  1795. _this.info.render.points += geometryGroup.__webglParticleCount;
  1796. }
  1797. };
  1798. function initAttributes() {
  1799. for ( var i = 0, l = _newAttributes.length; i < l; i ++ ) {
  1800. _newAttributes[ i ] = 0;
  1801. }
  1802. }
  1803. function enableAttribute( attribute ) {
  1804. _newAttributes[ attribute ] = 1;
  1805. if ( _enabledAttributes[ attribute ] === 0 ) {
  1806. _gl.enableVertexAttribArray( attribute );
  1807. _enabledAttributes[ attribute ] = 1;
  1808. }
  1809. }
  1810. function disableUnusedAttributes() {
  1811. for ( var i = 0, l = _enabledAttributes.length; i < l; i ++ ) {
  1812. if ( _enabledAttributes[ i ] !== _newAttributes[ i ] ) {
  1813. _gl.disableVertexAttribArray( i );
  1814. _enabledAttributes[ i ] = 0;
  1815. }
  1816. }
  1817. }
  1818. function setupMorphTargets ( material, geometryGroup, object ) {
  1819. // set base
  1820. var attributes = material.program.attributes;
  1821. if ( object.morphTargetBase !== - 1 && attributes.position >= 0 ) {
  1822. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  1823. enableAttribute( attributes.position );
  1824. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  1825. } else if ( attributes.position >= 0 ) {
  1826. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  1827. enableAttribute( attributes.position );
  1828. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  1829. }
  1830. if ( object.morphTargetForcedOrder.length ) {
  1831. // set forced order
  1832. var m = 0;
  1833. var order = object.morphTargetForcedOrder;
  1834. var influences = object.morphTargetInfluences;
  1835. var attribute;
  1836. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  1837. attribute = attributes[ 'morphTarget' + m ];
  1838. if ( attribute >= 0 ) {
  1839. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  1840. enableAttribute( attribute );
  1841. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  1842. }
  1843. attribute = attributes[ 'morphNormal' + m ];
  1844. if ( attribute >= 0 && material.morphNormals ) {
  1845. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  1846. enableAttribute( attribute );
  1847. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  1848. }
  1849. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  1850. m ++;
  1851. }
  1852. } else {
  1853. // find the most influencing
  1854. var activeInfluenceIndices = [];
  1855. var influences = object.morphTargetInfluences;
  1856. var morphTargets = object.geometry.morphTargets;
  1857. if ( influences.length > morphTargets.length ) {
  1858. console.warn( 'THREE.WebGLRenderer: Influences array is bigger than morphTargets array.' );
  1859. influences.length = morphTargets.length;
  1860. }
  1861. for ( var i = 0, il = influences.length; i < il; i ++ ) {
  1862. var influence = influences[ i ];
  1863. activeInfluenceIndices.push( [ influence, i ] );
  1864. }
  1865. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  1866. activeInfluenceIndices.sort( numericalSort );
  1867. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  1868. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  1869. activeInfluenceIndices.sort( numericalSort );
  1870. } else if ( activeInfluenceIndices.length === 0 ) {
  1871. activeInfluenceIndices.push( [ 0, 0 ] );
  1872. }
  1873. var attribute;
  1874. for ( var m = 0, ml = material.numSupportedMorphTargets; m < ml; m ++ ) {
  1875. if ( activeInfluenceIndices[ m ] ) {
  1876. var influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  1877. attribute = attributes[ 'morphTarget' + m ];
  1878. if ( attribute >= 0 ) {
  1879. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  1880. enableAttribute( attribute );
  1881. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  1882. }
  1883. attribute = attributes[ 'morphNormal' + m ];
  1884. if ( attribute >= 0 && material.morphNormals ) {
  1885. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  1886. enableAttribute( attribute );
  1887. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  1888. }
  1889. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  1890. } else {
  1891. /*
  1892. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  1893. if ( material.morphNormals ) {
  1894. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  1895. }
  1896. */
  1897. object.__webglMorphTargetInfluences[ m ] = 0;
  1898. }
  1899. }
  1900. }
  1901. // load updated influences uniform
  1902. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  1903. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  1904. }
  1905. }
  1906. // Sorting
  1907. function painterSortStable ( a, b ) {
  1908. if ( a.material.id !== b.material.id ) {
  1909. return a.material.id - b.material.id;
  1910. } else if ( a.z !== b.z ) {
  1911. return a.z - b.z;
  1912. } else {
  1913. return a.id - b.id;
  1914. }
  1915. }
  1916. function reversePainterSortStable ( a, b ) {
  1917. if ( a.z !== b.z ) {
  1918. return b.z - a.z;
  1919. } else {
  1920. return a.id - b.id;
  1921. }
  1922. }
  1923. function numericalSort ( a, b ) {
  1924. return b[ 0 ] - a[ 0 ];
  1925. }
  1926. // Rendering
  1927. this.render = function ( scene, camera, renderTarget, forceClear ) {
  1928. if ( camera instanceof THREE.Camera === false ) {
  1929. THREE.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  1930. return;
  1931. }
  1932. var fog = scene.fog;
  1933. // reset caching for this frame
  1934. _currentGeometryProgram = '';
  1935. _currentMaterialId = - 1;
  1936. _currentCamera = null;
  1937. _lightsNeedUpdate = true;
  1938. // update scene graph
  1939. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  1940. // update camera matrices and frustum
  1941. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  1942. // update Skeleton objects
  1943. scene.traverse( function ( object ) {
  1944. if ( object instanceof THREE.SkinnedMesh ) {
  1945. object.skeleton.update();
  1946. }
  1947. } );
  1948. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  1949. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  1950. _frustum.setFromMatrix( _projScreenMatrix );
  1951. lights.length = 0;
  1952. opaqueObjects.length = 0;
  1953. transparentObjects.length = 0;
  1954. sprites.length = 0;
  1955. lensFlares.length = 0;
  1956. projectObject( scene );
  1957. if ( _this.sortObjects === true ) {
  1958. opaqueObjects.sort( painterSortStable );
  1959. transparentObjects.sort( reversePainterSortStable );
  1960. }
  1961. // custom render plugins (pre pass)
  1962. shadowMapPlugin.render( scene, camera );
  1963. //
  1964. _this.info.render.calls = 0;
  1965. _this.info.render.vertices = 0;
  1966. _this.info.render.faces = 0;
  1967. _this.info.render.points = 0;
  1968. this.setRenderTarget( renderTarget );
  1969. if ( this.autoClear || forceClear ) {
  1970. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  1971. }
  1972. // set matrices for immediate objects
  1973. for ( var i = 0, il = _webglObjectsImmediate.length; i < il; i ++ ) {
  1974. var webglObject = _webglObjectsImmediate[ i ];
  1975. var object = webglObject.object;
  1976. if ( object.visible ) {
  1977. setupMatrices( object, camera );
  1978. unrollImmediateBufferMaterial( webglObject );
  1979. }
  1980. }
  1981. if ( scene.overrideMaterial ) {
  1982. var material = scene.overrideMaterial;
  1983. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  1984. this.setDepthTest( material.depthTest );
  1985. this.setDepthWrite( material.depthWrite );
  1986. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  1987. renderObjects( opaqueObjects, camera, lights, fog, true, material );
  1988. renderObjects( transparentObjects, camera, lights, fog, true, material );
  1989. renderObjectsImmediate( _webglObjectsImmediate, '', camera, lights, fog, false, material );
  1990. } else {
  1991. var material = null;
  1992. // opaque pass (front-to-back order)
  1993. this.setBlending( THREE.NoBlending );
  1994. renderObjects( opaqueObjects, camera, lights, fog, false, material );
  1995. renderObjectsImmediate( _webglObjectsImmediate, 'opaque', camera, lights, fog, false, material );
  1996. // transparent pass (back-to-front order)
  1997. renderObjects( transparentObjects, camera, lights, fog, true, material );
  1998. renderObjectsImmediate( _webglObjectsImmediate, 'transparent', camera, lights, fog, true, material );
  1999. }
  2000. // custom render plugins (post pass)
  2001. spritePlugin.render( scene, camera );
  2002. lensFlarePlugin.render( scene, camera, _currentWidth, _currentHeight );
  2003. // Generate mipmap if we're using any kind of mipmap filtering
  2004. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  2005. updateRenderTargetMipmap( renderTarget );
  2006. }
  2007. // Ensure depth buffer writing is enabled so it can be cleared on next render
  2008. this.setDepthTest( true );
  2009. this.setDepthWrite( true );
  2010. // _gl.finish();
  2011. };
  2012. function projectObject( object ) {
  2013. if ( object.visible === false ) return;
  2014. if ( object instanceof THREE.Scene || object instanceof THREE.Group ) {
  2015. // skip
  2016. } else {
  2017. initObject( object );
  2018. if ( object instanceof THREE.Light ) {
  2019. lights.push( object );
  2020. } else if ( object instanceof THREE.Sprite ) {
  2021. sprites.push( object );
  2022. } else if ( object instanceof THREE.LensFlare ) {
  2023. lensFlares.push( object );
  2024. } else {
  2025. var webglObjects = _webglObjects[ object.id ];
  2026. if ( webglObjects && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  2027. for ( var i = 0, l = webglObjects.length; i < l; i ++ ) {
  2028. var webglObject = webglObjects[ i ];
  2029. unrollBufferMaterial( webglObject );
  2030. webglObject.render = true;
  2031. if ( _this.sortObjects === true ) {
  2032. _vector3.setFromMatrixPosition( object.matrixWorld );
  2033. _vector3.applyProjection( _projScreenMatrix );
  2034. webglObject.z = _vector3.z;
  2035. }
  2036. }
  2037. }
  2038. }
  2039. }
  2040. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  2041. projectObject( object.children[ i ] );
  2042. }
  2043. }
  2044. function renderObjects( renderList, camera, lights, fog, useBlending, overrideMaterial ) {
  2045. var material;
  2046. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  2047. var webglObject = renderList[ i ];
  2048. var object = webglObject.object;
  2049. var buffer = webglObject.buffer;
  2050. setupMatrices( object, camera );
  2051. if ( overrideMaterial ) {
  2052. material = overrideMaterial;
  2053. } else {
  2054. material = webglObject.material;
  2055. if ( ! material ) continue;
  2056. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  2057. _this.setDepthTest( material.depthTest );
  2058. _this.setDepthWrite( material.depthWrite );
  2059. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  2060. }
  2061. _this.setMaterialFaces( material );
  2062. if ( buffer instanceof THREE.BufferGeometry ) {
  2063. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  2064. } else {
  2065. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  2066. }
  2067. }
  2068. }
  2069. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  2070. var material;
  2071. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  2072. var webglObject = renderList[ i ];
  2073. var object = webglObject.object;
  2074. if ( object.visible ) {
  2075. if ( overrideMaterial ) {
  2076. material = overrideMaterial;
  2077. } else {
  2078. material = webglObject[ materialType ];
  2079. if ( ! material ) continue;
  2080. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  2081. _this.setDepthTest( material.depthTest );
  2082. _this.setDepthWrite( material.depthWrite );
  2083. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  2084. }
  2085. _this.renderImmediateObject( camera, lights, fog, material, object );
  2086. }
  2087. }
  2088. }
  2089. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  2090. var program = setProgram( camera, lights, fog, material, object );
  2091. _currentGeometryProgram = '';
  2092. _this.setMaterialFaces( material );
  2093. if ( object.immediateRenderCallback ) {
  2094. object.immediateRenderCallback( program, _gl, _frustum );
  2095. } else {
  2096. object.render( function ( object ) { _this.renderBufferImmediate( object, program, material ); } );
  2097. }
  2098. };
  2099. function unrollImmediateBufferMaterial ( globject ) {
  2100. var object = globject.object,
  2101. material = object.material;
  2102. if ( material.transparent ) {
  2103. globject.transparent = material;
  2104. globject.opaque = null;
  2105. } else {
  2106. globject.opaque = material;
  2107. globject.transparent = null;
  2108. }
  2109. }
  2110. function unrollBufferMaterial ( globject ) {
  2111. var object = globject.object;
  2112. var buffer = globject.buffer;
  2113. var geometry = object.geometry;
  2114. var material = object.material;
  2115. if ( material instanceof THREE.MeshFaceMaterial ) {
  2116. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  2117. material = material.materials[ materialIndex ];
  2118. globject.material = material;
  2119. if ( material.transparent ) {
  2120. transparentObjects.push( globject );
  2121. } else {
  2122. opaqueObjects.push( globject );
  2123. }
  2124. } else if ( material ) {
  2125. globject.material = material;
  2126. if ( material.transparent ) {
  2127. transparentObjects.push( globject );
  2128. } else {
  2129. opaqueObjects.push( globject );
  2130. }
  2131. }
  2132. }
  2133. function initObject( object ) {
  2134. if ( object.__webglInit === undefined ) {
  2135. object.__webglInit = true;
  2136. object._modelViewMatrix = new THREE.Matrix4();
  2137. object._normalMatrix = new THREE.Matrix3();
  2138. object.addEventListener( 'removed', onObjectRemoved );
  2139. }
  2140. var geometry = object.geometry;
  2141. if ( geometry === undefined ) {
  2142. // ImmediateRenderObject
  2143. } else if ( geometry.__webglInit === undefined ) {
  2144. geometry.__webglInit = true;
  2145. geometry.addEventListener( 'dispose', onGeometryDispose );
  2146. if ( geometry instanceof THREE.BufferGeometry ) {
  2147. _this.info.memory.geometries ++;
  2148. } else if ( object instanceof THREE.Mesh ) {
  2149. initGeometryGroups( object, geometry );
  2150. } else if ( object instanceof THREE.Line ) {
  2151. if ( geometry.__webglVertexBuffer === undefined ) {
  2152. createLineBuffers( geometry );
  2153. initLineBuffers( geometry, object );
  2154. geometry.verticesNeedUpdate = true;
  2155. geometry.colorsNeedUpdate = true;
  2156. geometry.lineDistancesNeedUpdate = true;
  2157. }
  2158. } else if ( object instanceof THREE.PointCloud ) {
  2159. if ( geometry.__webglVertexBuffer === undefined ) {
  2160. createParticleBuffers( geometry );
  2161. initParticleBuffers( geometry, object );
  2162. geometry.verticesNeedUpdate = true;
  2163. geometry.colorsNeedUpdate = true;
  2164. }
  2165. }
  2166. }
  2167. if ( object.__webglActive === undefined) {
  2168. object.__webglActive = true;
  2169. if ( object instanceof THREE.Mesh ) {
  2170. if ( geometry instanceof THREE.BufferGeometry ) {
  2171. addBuffer( _webglObjects, geometry, object );
  2172. } else if ( geometry instanceof THREE.Geometry ) {
  2173. var geometryGroupsList = geometryGroups[ geometry.id ];
  2174. for ( var i = 0,l = geometryGroupsList.length; i < l; i ++ ) {
  2175. addBuffer( _webglObjects, geometryGroupsList[ i ], object );
  2176. }
  2177. }
  2178. } else if ( object instanceof THREE.Line || object instanceof THREE.PointCloud ) {
  2179. addBuffer( _webglObjects, geometry, object );
  2180. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  2181. addBufferImmediate( _webglObjectsImmediate, object );
  2182. }
  2183. }
  2184. }
  2185. // Geometry splitting
  2186. var geometryGroups = {};
  2187. var geometryGroupCounter = 0;
  2188. function makeGroups( geometry, usesFaceMaterial ) {
  2189. var maxVerticesInGroup = extensions.get( 'OES_element_index_uint' ) ? 4294967296 : 65535;
  2190. var groupHash, hash_map = {};
  2191. var numMorphTargets = geometry.morphTargets.length;
  2192. var numMorphNormals = geometry.morphNormals.length;
  2193. var group;
  2194. var groups = {};
  2195. var groupsList = [];
  2196. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  2197. var face = geometry.faces[ f ];
  2198. var materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  2199. if ( ! ( materialIndex in hash_map ) ) {
  2200. hash_map[ materialIndex ] = { hash: materialIndex, counter: 0 };
  2201. }
  2202. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  2203. if ( ! ( groupHash in groups ) ) {
  2204. group = {
  2205. id: geometryGroupCounter ++,
  2206. faces3: [],
  2207. materialIndex: materialIndex,
  2208. vertices: 0,
  2209. numMorphTargets: numMorphTargets,
  2210. numMorphNormals: numMorphNormals
  2211. };
  2212. groups[ groupHash ] = group;
  2213. groupsList.push( group );
  2214. }
  2215. if ( groups[ groupHash ].vertices + 3 > maxVerticesInGroup ) {
  2216. hash_map[ materialIndex ].counter += 1;
  2217. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  2218. if ( ! ( groupHash in groups ) ) {
  2219. group = {
  2220. id: geometryGroupCounter ++,
  2221. faces3: [],
  2222. materialIndex: materialIndex,
  2223. vertices: 0,
  2224. numMorphTargets: numMorphTargets,
  2225. numMorphNormals: numMorphNormals
  2226. };
  2227. groups[ groupHash ] = group;
  2228. groupsList.push( group );
  2229. }
  2230. }
  2231. groups[ groupHash ].faces3.push( f );
  2232. groups[ groupHash ].vertices += 3;
  2233. }
  2234. return groupsList;
  2235. }
  2236. function initGeometryGroups( object, geometry ) {
  2237. var material = object.material, addBuffers = false;
  2238. if ( geometryGroups[ geometry.id ] === undefined || geometry.groupsNeedUpdate === true ) {
  2239. delete _webglObjects[ object.id ];
  2240. geometryGroups[ geometry.id ] = makeGroups( geometry, material instanceof THREE.MeshFaceMaterial );
  2241. geometry.groupsNeedUpdate = false;
  2242. }
  2243. var geometryGroupsList = geometryGroups[ geometry.id ];
  2244. // create separate VBOs per geometry chunk
  2245. for ( var i = 0, il = geometryGroupsList.length; i < il; i ++ ) {
  2246. var geometryGroup = geometryGroupsList[ i ];
  2247. // initialise VBO on the first access
  2248. if ( geometryGroup.__webglVertexBuffer === undefined ) {
  2249. createMeshBuffers( geometryGroup );
  2250. initMeshBuffers( geometryGroup, object );
  2251. geometry.verticesNeedUpdate = true;
  2252. geometry.morphTargetsNeedUpdate = true;
  2253. geometry.elementsNeedUpdate = true;
  2254. geometry.uvsNeedUpdate = true;
  2255. geometry.normalsNeedUpdate = true;
  2256. geometry.tangentsNeedUpdate = true;
  2257. geometry.colorsNeedUpdate = true;
  2258. addBuffers = true;
  2259. } else {
  2260. addBuffers = false;
  2261. }
  2262. if ( addBuffers || object.__webglActive === undefined ) {
  2263. addBuffer( _webglObjects, geometryGroup, object );
  2264. }
  2265. }
  2266. object.__webglActive = true;
  2267. }
  2268. function addBuffer( objlist, buffer, object ) {
  2269. var id = object.id;
  2270. objlist[id] = objlist[id] || [];
  2271. objlist[id].push(
  2272. {
  2273. id: id,
  2274. buffer: buffer,
  2275. object: object,
  2276. material: null,
  2277. z: 0
  2278. }
  2279. );
  2280. };
  2281. function addBufferImmediate( objlist, object ) {
  2282. objlist.push(
  2283. {
  2284. id: null,
  2285. object: object,
  2286. opaque: null,
  2287. transparent: null,
  2288. z: 0
  2289. }
  2290. );
  2291. };
  2292. // Objects updates
  2293. function updateObject( object ) {
  2294. var geometry = object.geometry;
  2295. if ( geometry instanceof THREE.BufferGeometry ) {
  2296. var attributes = geometry.attributes;
  2297. var attributesKeys = geometry.attributesKeys;
  2298. for ( var i = 0, l = attributesKeys.length; i < l; i ++ ) {
  2299. var key = attributesKeys[ i ];
  2300. var attribute = attributes[ key ];
  2301. var bufferType = ( key === 'index' ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER;
  2302. if ( attribute.buffer === undefined ) {
  2303. attribute.buffer = _gl.createBuffer();
  2304. _gl.bindBuffer( bufferType, attribute.buffer );
  2305. _gl.bufferData( bufferType, attribute.array, ( attribute instanceof THREE.DynamicBufferAttribute ) ? _gl.DYNAMIC_DRAW : _gl.STATIC_DRAW );
  2306. attribute.needsUpdate = false;
  2307. } else if ( attribute.needsUpdate === true ) {
  2308. _gl.bindBuffer( bufferType, attribute.buffer );
  2309. if ( attribute.updateRange === undefined || attribute.updateRange.count === -1 ) { // Not using update ranges
  2310. _gl.bufferSubData( bufferType, 0, attribute.array );
  2311. } else if ( attribute.updateRange.count === 0 ) {
  2312. console.error( 'THREE.WebGLRenderer.updateObject: using updateRange for THREE.DynamicBufferAttribute and marked as needsUpdate but count is 0, ensure you are using set methods or updating manually.' );
  2313. } else {
  2314. _gl.bufferSubData( bufferType, attribute.updateRange.offset * attribute.array.BYTES_PER_ELEMENT,
  2315. attribute.array.subarray( attribute.updateRange.offset, attribute.updateRange.offset + attribute.updateRange.count ) );
  2316. attribute.updateRange.count = 0; // reset range
  2317. }
  2318. attribute.needsUpdate = false;
  2319. }
  2320. }
  2321. } else if ( object instanceof THREE.Mesh ) {
  2322. // check all geometry groups
  2323. if ( geometry.groupsNeedUpdate === true ) {
  2324. initGeometryGroups( object, geometry );
  2325. }
  2326. var geometryGroupsList = geometryGroups[ geometry.id ];
  2327. for ( var i = 0, il = geometryGroupsList.length; i < il; i ++ ) {
  2328. var geometryGroup = geometryGroupsList[ i ];
  2329. var material = getBufferMaterial( object, geometryGroup );
  2330. var customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  2331. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  2332. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  2333. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  2334. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, ! geometry.dynamic, material );
  2335. }
  2336. }
  2337. geometry.verticesNeedUpdate = false;
  2338. geometry.morphTargetsNeedUpdate = false;
  2339. geometry.elementsNeedUpdate = false;
  2340. geometry.uvsNeedUpdate = false;
  2341. geometry.normalsNeedUpdate = false;
  2342. geometry.colorsNeedUpdate = false;
  2343. geometry.tangentsNeedUpdate = false;
  2344. material.attributes && clearCustomAttributes( material );
  2345. } else if ( object instanceof THREE.Line ) {
  2346. var material = getBufferMaterial( object, geometry );
  2347. var customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  2348. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  2349. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  2350. }
  2351. geometry.verticesNeedUpdate = false;
  2352. geometry.colorsNeedUpdate = false;
  2353. geometry.lineDistancesNeedUpdate = false;
  2354. material.attributes && clearCustomAttributes( material );
  2355. } else if ( object instanceof THREE.PointCloud ) {
  2356. var material = getBufferMaterial( object, geometry );
  2357. var customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  2358. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || customAttributesDirty ) {
  2359. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  2360. }
  2361. geometry.verticesNeedUpdate = false;
  2362. geometry.colorsNeedUpdate = false;
  2363. material.attributes && clearCustomAttributes( material );
  2364. }
  2365. }
  2366. // Objects updates - custom attributes check
  2367. function areCustomAttributesDirty( material ) {
  2368. for ( var name in material.attributes ) {
  2369. if ( material.attributes[ name ].needsUpdate ) return true;
  2370. }
  2371. return false;
  2372. }
  2373. function clearCustomAttributes( material ) {
  2374. for ( var name in material.attributes ) {
  2375. material.attributes[ name ].needsUpdate = false;
  2376. }
  2377. }
  2378. // Objects removal
  2379. function removeObject( object ) {
  2380. if ( object instanceof THREE.Mesh ||
  2381. object instanceof THREE.PointCloud ||
  2382. object instanceof THREE.Line ) {
  2383. delete _webglObjects[ object.id ];
  2384. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  2385. removeInstances( _webglObjectsImmediate, object );
  2386. }
  2387. delete object.__webglInit;
  2388. delete object._modelViewMatrix;
  2389. delete object._normalMatrix;
  2390. delete object.__webglActive;
  2391. }
  2392. function removeInstances( objlist, object ) {
  2393. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  2394. if ( objlist[ o ].object === object ) {
  2395. objlist.splice( o, 1 );
  2396. }
  2397. }
  2398. }
  2399. // Materials
  2400. var shaderIDs = {
  2401. MeshDepthMaterial: 'depth',
  2402. MeshNormalMaterial: 'normal',
  2403. MeshBasicMaterial: 'basic',
  2404. MeshLambertMaterial: 'lambert',
  2405. MeshPhongMaterial: 'phong',
  2406. LineBasicMaterial: 'basic',
  2407. LineDashedMaterial: 'dashed',
  2408. PointCloudMaterial: 'particle_basic'
  2409. };
  2410. function initMaterial( material, lights, fog, object ) {
  2411. material.addEventListener( 'dispose', onMaterialDispose );
  2412. var shaderID = shaderIDs[ material.type ];
  2413. if ( shaderID ) {
  2414. var shader = THREE.ShaderLib[ shaderID ];
  2415. material.__webglShader = {
  2416. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  2417. vertexShader: shader.vertexShader,
  2418. fragmentShader: shader.fragmentShader
  2419. }
  2420. } else {
  2421. material.__webglShader = {
  2422. uniforms: material.uniforms,
  2423. vertexShader: material.vertexShader,
  2424. fragmentShader: material.fragmentShader
  2425. }
  2426. }
  2427. // heuristics to create shader parameters according to lights in the scene
  2428. // (not to blow over maxLights budget)
  2429. var maxLightCount = allocateLights( lights );
  2430. var maxShadows = allocateShadows( lights );
  2431. var maxBones = allocateBones( object );
  2432. var parameters = {
  2433. precision: _precision,
  2434. supportsVertexTextures: _supportsVertexTextures,
  2435. map: !! material.map,
  2436. envMap: !! material.envMap,
  2437. envMapMode: material.envMap && material.envMap.mapping,
  2438. lightMap: !! material.lightMap,
  2439. bumpMap: !! material.bumpMap,
  2440. normalMap: !! material.normalMap,
  2441. specularMap: !! material.specularMap,
  2442. alphaMap: !! material.alphaMap,
  2443. combine: material.combine,
  2444. vertexColors: material.vertexColors,
  2445. fog: fog,
  2446. useFog: material.fog,
  2447. fogExp: fog instanceof THREE.FogExp2,
  2448. sizeAttenuation: material.sizeAttenuation,
  2449. logarithmicDepthBuffer: _logarithmicDepthBuffer,
  2450. skinning: material.skinning,
  2451. maxBones: maxBones,
  2452. useVertexTexture: _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  2453. morphTargets: material.morphTargets,
  2454. morphNormals: material.morphNormals,
  2455. maxMorphTargets: _this.maxMorphTargets,
  2456. maxMorphNormals: _this.maxMorphNormals,
  2457. maxDirLights: maxLightCount.directional,
  2458. maxPointLights: maxLightCount.point,
  2459. maxSpotLights: maxLightCount.spot,
  2460. maxHemiLights: maxLightCount.hemi,
  2461. maxShadows: maxShadows,
  2462. shadowMapEnabled: _this.shadowMapEnabled && object.receiveShadow && maxShadows > 0,
  2463. shadowMapType: _this.shadowMapType,
  2464. shadowMapDebug: _this.shadowMapDebug,
  2465. shadowMapCascade: _this.shadowMapCascade,
  2466. alphaTest: material.alphaTest,
  2467. metal: material.metal,
  2468. wrapAround: material.wrapAround,
  2469. doubleSided: material.side === THREE.DoubleSide,
  2470. flipSided: material.side === THREE.BackSide
  2471. };
  2472. // Generate code
  2473. var chunks = [];
  2474. if ( shaderID ) {
  2475. chunks.push( shaderID );
  2476. } else {
  2477. chunks.push( material.fragmentShader );
  2478. chunks.push( material.vertexShader );
  2479. }
  2480. if ( material.defines !== undefined ) {
  2481. for ( var name in material.defines ) {
  2482. chunks.push( name );
  2483. chunks.push( material.defines[ name ] );
  2484. }
  2485. }
  2486. for ( var name in parameters ) {
  2487. chunks.push( name );
  2488. chunks.push( parameters[ name ] );
  2489. }
  2490. var code = chunks.join();
  2491. var program;
  2492. // Check if code has been already compiled
  2493. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  2494. var programInfo = _programs[ p ];
  2495. if ( programInfo.code === code ) {
  2496. program = programInfo;
  2497. program.usedTimes ++;
  2498. break;
  2499. }
  2500. }
  2501. if ( program === undefined ) {
  2502. program = new THREE.WebGLProgram( _this, code, material, parameters );
  2503. _programs.push( program );
  2504. _this.info.memory.programs = _programs.length;
  2505. }
  2506. material.program = program;
  2507. var attributes = program.attributes;
  2508. if ( material.morphTargets ) {
  2509. material.numSupportedMorphTargets = 0;
  2510. var id, base = 'morphTarget';
  2511. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  2512. id = base + i;
  2513. if ( attributes[ id ] >= 0 ) {
  2514. material.numSupportedMorphTargets ++;
  2515. }
  2516. }
  2517. }
  2518. if ( material.morphNormals ) {
  2519. material.numSupportedMorphNormals = 0;
  2520. var id, base = 'morphNormal';
  2521. for ( i = 0; i < _this.maxMorphNormals; i ++ ) {
  2522. id = base + i;
  2523. if ( attributes[ id ] >= 0 ) {
  2524. material.numSupportedMorphNormals ++;
  2525. }
  2526. }
  2527. }
  2528. material.uniformsList = [];
  2529. for ( var u in material.__webglShader.uniforms ) {
  2530. var location = material.program.uniforms[ u ];
  2531. if ( location ) {
  2532. material.uniformsList.push( [ material.__webglShader.uniforms[ u ], location ] );
  2533. }
  2534. }
  2535. }
  2536. function setProgram( camera, lights, fog, material, object ) {
  2537. _usedTextureUnits = 0;
  2538. if ( material.needsUpdate ) {
  2539. if ( material.program ) deallocateMaterial( material );
  2540. initMaterial( material, lights, fog, object );
  2541. material.needsUpdate = false;
  2542. }
  2543. if ( material.morphTargets ) {
  2544. if ( ! object.__webglMorphTargetInfluences ) {
  2545. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  2546. }
  2547. }
  2548. var refreshProgram = false;
  2549. var refreshMaterial = false;
  2550. var refreshLights = false;
  2551. var program = material.program,
  2552. p_uniforms = program.uniforms,
  2553. m_uniforms = material.__webglShader.uniforms;
  2554. if ( program.id !== _currentProgram ) {
  2555. _gl.useProgram( program.program );
  2556. _currentProgram = program.id;
  2557. refreshProgram = true;
  2558. refreshMaterial = true;
  2559. refreshLights = true;
  2560. }
  2561. if ( material.id !== _currentMaterialId ) {
  2562. if ( _currentMaterialId === -1 ) refreshLights = true;
  2563. _currentMaterialId = material.id;
  2564. refreshMaterial = true;
  2565. }
  2566. if ( refreshProgram || camera !== _currentCamera ) {
  2567. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  2568. if ( _logarithmicDepthBuffer ) {
  2569. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  2570. }
  2571. if ( camera !== _currentCamera ) _currentCamera = camera;
  2572. // load material specific uniforms
  2573. // (shader material also gets them for the sake of genericity)
  2574. if ( material instanceof THREE.ShaderMaterial ||
  2575. material instanceof THREE.MeshPhongMaterial ||
  2576. material.envMap ) {
  2577. if ( p_uniforms.cameraPosition !== null ) {
  2578. _vector3.setFromMatrixPosition( camera.matrixWorld );
  2579. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  2580. }
  2581. }
  2582. if ( material instanceof THREE.MeshPhongMaterial ||
  2583. material instanceof THREE.MeshLambertMaterial ||
  2584. material instanceof THREE.MeshBasicMaterial ||
  2585. material instanceof THREE.ShaderMaterial ||
  2586. material.skinning ) {
  2587. if ( p_uniforms.viewMatrix !== null ) {
  2588. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  2589. }
  2590. }
  2591. }
  2592. // skinning uniforms must be set even if material didn't change
  2593. // auto-setting of texture unit for bone texture must go before other textures
  2594. // not sure why, but otherwise weird things happen
  2595. if ( material.skinning ) {
  2596. if ( object.bindMatrix && p_uniforms.bindMatrix !== null ) {
  2597. _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
  2598. }
  2599. if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== null ) {
  2600. _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
  2601. }
  2602. if ( _supportsBoneTextures && object.skeleton && object.skeleton.useVertexTexture ) {
  2603. if ( p_uniforms.boneTexture !== null ) {
  2604. var textureUnit = getTextureUnit();
  2605. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  2606. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  2607. }
  2608. if ( p_uniforms.boneTextureWidth !== null ) {
  2609. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  2610. }
  2611. if ( p_uniforms.boneTextureHeight !== null ) {
  2612. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  2613. }
  2614. } else if ( object.skeleton && object.skeleton.boneMatrices ) {
  2615. if ( p_uniforms.boneGlobalMatrices !== null ) {
  2616. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  2617. }
  2618. }
  2619. }
  2620. if ( refreshMaterial ) {
  2621. // refresh uniforms common to several materials
  2622. if ( fog && material.fog ) {
  2623. refreshUniformsFog( m_uniforms, fog );
  2624. }
  2625. if ( material instanceof THREE.MeshPhongMaterial ||
  2626. material instanceof THREE.MeshLambertMaterial ||
  2627. material.lights ) {
  2628. if ( _lightsNeedUpdate ) {
  2629. refreshLights = true;
  2630. setupLights( lights );
  2631. _lightsNeedUpdate = false;
  2632. }
  2633. if ( refreshLights ) {
  2634. refreshUniformsLights( m_uniforms, _lights );
  2635. markUniformsLightsNeedsUpdate( m_uniforms, true );
  2636. } else {
  2637. markUniformsLightsNeedsUpdate( m_uniforms, false );
  2638. }
  2639. }
  2640. if ( material instanceof THREE.MeshBasicMaterial ||
  2641. material instanceof THREE.MeshLambertMaterial ||
  2642. material instanceof THREE.MeshPhongMaterial ) {
  2643. refreshUniformsCommon( m_uniforms, material );
  2644. }
  2645. // refresh single material specific uniforms
  2646. if ( material instanceof THREE.LineBasicMaterial ) {
  2647. refreshUniformsLine( m_uniforms, material );
  2648. } else if ( material instanceof THREE.LineDashedMaterial ) {
  2649. refreshUniformsLine( m_uniforms, material );
  2650. refreshUniformsDash( m_uniforms, material );
  2651. } else if ( material instanceof THREE.PointCloudMaterial ) {
  2652. refreshUniformsParticle( m_uniforms, material );
  2653. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  2654. refreshUniformsPhong( m_uniforms, material );
  2655. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  2656. refreshUniformsLambert( m_uniforms, material );
  2657. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  2658. m_uniforms.mNear.value = camera.near;
  2659. m_uniforms.mFar.value = camera.far;
  2660. m_uniforms.opacity.value = material.opacity;
  2661. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  2662. m_uniforms.opacity.value = material.opacity;
  2663. }
  2664. if ( object.receiveShadow && ! material._shadowPass ) {
  2665. refreshUniformsShadow( m_uniforms, lights );
  2666. }
  2667. // load common uniforms
  2668. loadUniformsGeneric( material.uniformsList );
  2669. }
  2670. loadUniformsMatrices( p_uniforms, object );
  2671. if ( p_uniforms.modelMatrix !== null ) {
  2672. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  2673. }
  2674. return program;
  2675. }
  2676. // Uniforms (refresh uniforms objects)
  2677. function refreshUniformsCommon ( uniforms, material ) {
  2678. uniforms.opacity.value = material.opacity;
  2679. uniforms.diffuse.value = material.color;
  2680. uniforms.map.value = material.map;
  2681. uniforms.lightMap.value = material.lightMap;
  2682. uniforms.specularMap.value = material.specularMap;
  2683. uniforms.alphaMap.value = material.alphaMap;
  2684. if ( material.bumpMap ) {
  2685. uniforms.bumpMap.value = material.bumpMap;
  2686. uniforms.bumpScale.value = material.bumpScale;
  2687. }
  2688. if ( material.normalMap ) {
  2689. uniforms.normalMap.value = material.normalMap;
  2690. uniforms.normalScale.value.copy( material.normalScale );
  2691. }
  2692. // uv repeat and offset setting priorities
  2693. // 1. color map
  2694. // 2. specular map
  2695. // 3. normal map
  2696. // 4. bump map
  2697. // 5. alpha map
  2698. var uvScaleMap;
  2699. if ( material.map ) {
  2700. uvScaleMap = material.map;
  2701. } else if ( material.specularMap ) {
  2702. uvScaleMap = material.specularMap;
  2703. } else if ( material.normalMap ) {
  2704. uvScaleMap = material.normalMap;
  2705. } else if ( material.bumpMap ) {
  2706. uvScaleMap = material.bumpMap;
  2707. } else if ( material.alphaMap ) {
  2708. uvScaleMap = material.alphaMap;
  2709. }
  2710. if ( uvScaleMap !== undefined ) {
  2711. var offset = uvScaleMap.offset;
  2712. var repeat = uvScaleMap.repeat;
  2713. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  2714. }
  2715. uniforms.envMap.value = material.envMap;
  2716. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  2717. uniforms.reflectivity.value = material.reflectivity;
  2718. uniforms.refractionRatio.value = material.refractionRatio;
  2719. }
  2720. function refreshUniformsLine ( uniforms, material ) {
  2721. uniforms.diffuse.value = material.color;
  2722. uniforms.opacity.value = material.opacity;
  2723. }
  2724. function refreshUniformsDash ( uniforms, material ) {
  2725. uniforms.dashSize.value = material.dashSize;
  2726. uniforms.totalSize.value = material.dashSize + material.gapSize;
  2727. uniforms.scale.value = material.scale;
  2728. }
  2729. function refreshUniformsParticle ( uniforms, material ) {
  2730. uniforms.psColor.value = material.color;
  2731. uniforms.opacity.value = material.opacity;
  2732. uniforms.size.value = material.size;
  2733. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  2734. uniforms.map.value = material.map;
  2735. }
  2736. function refreshUniformsFog ( uniforms, fog ) {
  2737. uniforms.fogColor.value = fog.color;
  2738. if ( fog instanceof THREE.Fog ) {
  2739. uniforms.fogNear.value = fog.near;
  2740. uniforms.fogFar.value = fog.far;
  2741. } else if ( fog instanceof THREE.FogExp2 ) {
  2742. uniforms.fogDensity.value = fog.density;
  2743. }
  2744. }
  2745. function refreshUniformsPhong ( uniforms, material ) {
  2746. uniforms.shininess.value = material.shininess;
  2747. uniforms.emissive.value = material.emissive;
  2748. uniforms.specular.value = material.specular;
  2749. if ( material.wrapAround ) {
  2750. uniforms.wrapRGB.value.copy( material.wrapRGB );
  2751. }
  2752. }
  2753. function refreshUniformsLambert ( uniforms, material ) {
  2754. uniforms.emissive.value = material.emissive;
  2755. if ( material.wrapAround ) {
  2756. uniforms.wrapRGB.value.copy( material.wrapRGB );
  2757. }
  2758. }
  2759. function refreshUniformsLights ( uniforms, lights ) {
  2760. uniforms.ambientLightColor.value = lights.ambient;
  2761. uniforms.directionalLightColor.value = lights.directional.colors;
  2762. uniforms.directionalLightDirection.value = lights.directional.positions;
  2763. uniforms.pointLightColor.value = lights.point.colors;
  2764. uniforms.pointLightPosition.value = lights.point.positions;
  2765. uniforms.pointLightDistance.value = lights.point.distances;
  2766. uniforms.pointLightDecay.value = lights.point.decays;
  2767. uniforms.spotLightColor.value = lights.spot.colors;
  2768. uniforms.spotLightPosition.value = lights.spot.positions;
  2769. uniforms.spotLightDistance.value = lights.spot.distances;
  2770. uniforms.spotLightDirection.value = lights.spot.directions;
  2771. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  2772. uniforms.spotLightExponent.value = lights.spot.exponents;
  2773. uniforms.spotLightDecay.value = lights.spot.decays;
  2774. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  2775. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  2776. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  2777. }
  2778. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  2779. function markUniformsLightsNeedsUpdate ( uniforms, boolean ) {
  2780. uniforms.ambientLightColor.needsUpdate = boolean;
  2781. uniforms.directionalLightColor.needsUpdate = boolean;
  2782. uniforms.directionalLightDirection.needsUpdate = boolean;
  2783. uniforms.pointLightColor.needsUpdate = boolean;
  2784. uniforms.pointLightPosition.needsUpdate = boolean;
  2785. uniforms.pointLightDistance.needsUpdate = boolean;
  2786. uniforms.pointLightDecay.needsUpdate = boolean;
  2787. uniforms.spotLightColor.needsUpdate = boolean;
  2788. uniforms.spotLightPosition.needsUpdate = boolean;
  2789. uniforms.spotLightDistance.needsUpdate = boolean;
  2790. uniforms.spotLightDirection.needsUpdate = boolean;
  2791. uniforms.spotLightAngleCos.needsUpdate = boolean;
  2792. uniforms.spotLightExponent.needsUpdate = boolean;
  2793. uniforms.spotLightDecay.needsUpdate = boolean;
  2794. uniforms.hemisphereLightSkyColor.needsUpdate = boolean;
  2795. uniforms.hemisphereLightGroundColor.needsUpdate = boolean;
  2796. uniforms.hemisphereLightDirection.needsUpdate = boolean;
  2797. }
  2798. function refreshUniformsShadow ( uniforms, lights ) {
  2799. if ( uniforms.shadowMatrix ) {
  2800. var j = 0;
  2801. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  2802. var light = lights[ i ];
  2803. if ( ! light.castShadow ) continue;
  2804. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  2805. uniforms.shadowMap.value[ j ] = light.shadowMap;
  2806. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  2807. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  2808. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  2809. uniforms.shadowBias.value[ j ] = light.shadowBias;
  2810. j ++;
  2811. }
  2812. }
  2813. }
  2814. }
  2815. // Uniforms (load to GPU)
  2816. function loadUniformsMatrices ( uniforms, object ) {
  2817. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  2818. if ( uniforms.normalMatrix ) {
  2819. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  2820. }
  2821. }
  2822. function getTextureUnit() {
  2823. var textureUnit = _usedTextureUnits;
  2824. if ( textureUnit >= _maxTextures ) {
  2825. THREE.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + _maxTextures );
  2826. }
  2827. _usedTextureUnits += 1;
  2828. return textureUnit;
  2829. }
  2830. function loadUniformsGeneric ( uniforms ) {
  2831. var texture, textureUnit, offset;
  2832. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  2833. var uniform = uniforms[ j ][ 0 ];
  2834. // needsUpdate property is not added to all uniforms.
  2835. if ( uniform.needsUpdate === false ) continue;
  2836. var type = uniform.type;
  2837. var value = uniform.value;
  2838. var location = uniforms[ j ][ 1 ];
  2839. switch ( type ) {
  2840. case '1i':
  2841. _gl.uniform1i( location, value );
  2842. break;
  2843. case '1f':
  2844. _gl.uniform1f( location, value );
  2845. break;
  2846. case '2f':
  2847. _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
  2848. break;
  2849. case '3f':
  2850. _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
  2851. break;
  2852. case '4f':
  2853. _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
  2854. break;
  2855. case '1iv':
  2856. _gl.uniform1iv( location, value );
  2857. break;
  2858. case '3iv':
  2859. _gl.uniform3iv( location, value );
  2860. break;
  2861. case '1fv':
  2862. _gl.uniform1fv( location, value );
  2863. break;
  2864. case '2fv':
  2865. _gl.uniform2fv( location, value );
  2866. break;
  2867. case '3fv':
  2868. _gl.uniform3fv( location, value );
  2869. break;
  2870. case '4fv':
  2871. _gl.uniform4fv( location, value );
  2872. break;
  2873. case 'Matrix3fv':
  2874. _gl.uniformMatrix3fv( location, false, value );
  2875. break;
  2876. case 'Matrix4fv':
  2877. _gl.uniformMatrix4fv( location, false, value );
  2878. break;
  2879. //
  2880. case 'i':
  2881. // single integer
  2882. _gl.uniform1i( location, value );
  2883. break;
  2884. case 'f':
  2885. // single float
  2886. _gl.uniform1f( location, value );
  2887. break;
  2888. case 'v2':
  2889. // single THREE.Vector2
  2890. _gl.uniform2f( location, value.x, value.y );
  2891. break;
  2892. case 'v3':
  2893. // single THREE.Vector3
  2894. _gl.uniform3f( location, value.x, value.y, value.z );
  2895. break;
  2896. case 'v4':
  2897. // single THREE.Vector4
  2898. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  2899. break;
  2900. case 'c':
  2901. // single THREE.Color
  2902. _gl.uniform3f( location, value.r, value.g, value.b );
  2903. break;
  2904. case 'iv1':
  2905. // flat array of integers (JS or typed array)
  2906. _gl.uniform1iv( location, value );
  2907. break;
  2908. case 'iv':
  2909. // flat array of integers with 3 x N size (JS or typed array)
  2910. _gl.uniform3iv( location, value );
  2911. break;
  2912. case 'fv1':
  2913. // flat array of floats (JS or typed array)
  2914. _gl.uniform1fv( location, value );
  2915. break;
  2916. case 'fv':
  2917. // flat array of floats with 3 x N size (JS or typed array)
  2918. _gl.uniform3fv( location, value );
  2919. break;
  2920. case 'v2v':
  2921. // array of THREE.Vector2
  2922. if ( uniform._array === undefined ) {
  2923. uniform._array = new Float32Array( 2 * value.length );
  2924. }
  2925. for ( var i = 0, il = value.length; i < il; i ++ ) {
  2926. offset = i * 2;
  2927. uniform._array[ offset ] = value[ i ].x;
  2928. uniform._array[ offset + 1 ] = value[ i ].y;
  2929. }
  2930. _gl.uniform2fv( location, uniform._array );
  2931. break;
  2932. case 'v3v':
  2933. // array of THREE.Vector3
  2934. if ( uniform._array === undefined ) {
  2935. uniform._array = new Float32Array( 3 * value.length );
  2936. }
  2937. for ( var i = 0, il = value.length; i < il; i ++ ) {
  2938. offset = i * 3;
  2939. uniform._array[ offset ] = value[ i ].x;
  2940. uniform._array[ offset + 1 ] = value[ i ].y;
  2941. uniform._array[ offset + 2 ] = value[ i ].z;
  2942. }
  2943. _gl.uniform3fv( location, uniform._array );
  2944. break;
  2945. case 'v4v':
  2946. // array of THREE.Vector4
  2947. if ( uniform._array === undefined ) {
  2948. uniform._array = new Float32Array( 4 * value.length );
  2949. }
  2950. for ( var i = 0, il = value.length; i < il; i ++ ) {
  2951. offset = i * 4;
  2952. uniform._array[ offset ] = value[ i ].x;
  2953. uniform._array[ offset + 1 ] = value[ i ].y;
  2954. uniform._array[ offset + 2 ] = value[ i ].z;
  2955. uniform._array[ offset + 3 ] = value[ i ].w;
  2956. }
  2957. _gl.uniform4fv( location, uniform._array );
  2958. break;
  2959. case 'm3':
  2960. // single THREE.Matrix3
  2961. _gl.uniformMatrix3fv( location, false, value.elements );
  2962. break;
  2963. case 'm3v':
  2964. // array of THREE.Matrix3
  2965. if ( uniform._array === undefined ) {
  2966. uniform._array = new Float32Array( 9 * value.length );
  2967. }
  2968. for ( var i = 0, il = value.length; i < il; i ++ ) {
  2969. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  2970. }
  2971. _gl.uniformMatrix3fv( location, false, uniform._array );
  2972. break;
  2973. case 'm4':
  2974. // single THREE.Matrix4
  2975. _gl.uniformMatrix4fv( location, false, value.elements );
  2976. break;
  2977. case 'm4v':
  2978. // array of THREE.Matrix4
  2979. if ( uniform._array === undefined ) {
  2980. uniform._array = new Float32Array( 16 * value.length );
  2981. }
  2982. for ( var i = 0, il = value.length; i < il; i ++ ) {
  2983. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  2984. }
  2985. _gl.uniformMatrix4fv( location, false, uniform._array );
  2986. break;
  2987. case 't':
  2988. // single THREE.Texture (2d or cube)
  2989. texture = value;
  2990. textureUnit = getTextureUnit();
  2991. _gl.uniform1i( location, textureUnit );
  2992. if ( ! texture ) continue;
  2993. if ( texture instanceof THREE.CubeTexture ||
  2994. ( texture.image instanceof Array && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/
  2995. setCubeTexture( texture, textureUnit );
  2996. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  2997. setCubeTextureDynamic( texture, textureUnit );
  2998. } else {
  2999. _this.setTexture( texture, textureUnit );
  3000. }
  3001. break;
  3002. case 'tv':
  3003. // array of THREE.Texture (2d)
  3004. if ( uniform._array === undefined ) {
  3005. uniform._array = [];
  3006. }
  3007. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  3008. uniform._array[ i ] = getTextureUnit();
  3009. }
  3010. _gl.uniform1iv( location, uniform._array );
  3011. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  3012. texture = uniform.value[ i ];
  3013. textureUnit = uniform._array[ i ];
  3014. if ( ! texture ) continue;
  3015. _this.setTexture( texture, textureUnit );
  3016. }
  3017. break;
  3018. default:
  3019. THREE.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  3020. }
  3021. }
  3022. }
  3023. function setupMatrices ( object, camera ) {
  3024. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  3025. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  3026. }
  3027. function setColorLinear( array, offset, color, intensity ) {
  3028. array[ offset ] = color.r * intensity;
  3029. array[ offset + 1 ] = color.g * intensity;
  3030. array[ offset + 2 ] = color.b * intensity;
  3031. }
  3032. function setupLights ( lights ) {
  3033. var l, ll, light, n,
  3034. r = 0, g = 0, b = 0,
  3035. color, skyColor, groundColor,
  3036. intensity, intensitySq,
  3037. position,
  3038. distance,
  3039. zlights = _lights,
  3040. dirColors = zlights.directional.colors,
  3041. dirPositions = zlights.directional.positions,
  3042. pointColors = zlights.point.colors,
  3043. pointPositions = zlights.point.positions,
  3044. pointDistances = zlights.point.distances,
  3045. pointDecays = zlights.point.decays,
  3046. spotColors = zlights.spot.colors,
  3047. spotPositions = zlights.spot.positions,
  3048. spotDistances = zlights.spot.distances,
  3049. spotDirections = zlights.spot.directions,
  3050. spotAnglesCos = zlights.spot.anglesCos,
  3051. spotExponents = zlights.spot.exponents,
  3052. spotDecays = zlights.spot.decays,
  3053. hemiSkyColors = zlights.hemi.skyColors,
  3054. hemiGroundColors = zlights.hemi.groundColors,
  3055. hemiPositions = zlights.hemi.positions,
  3056. dirLength = 0,
  3057. pointLength = 0,
  3058. spotLength = 0,
  3059. hemiLength = 0,
  3060. dirCount = 0,
  3061. pointCount = 0,
  3062. spotCount = 0,
  3063. hemiCount = 0,
  3064. dirOffset = 0,
  3065. pointOffset = 0,
  3066. spotOffset = 0,
  3067. hemiOffset = 0;
  3068. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  3069. light = lights[ l ];
  3070. if ( light.onlyShadow ) continue;
  3071. color = light.color;
  3072. intensity = light.intensity;
  3073. distance = light.distance;
  3074. if ( light instanceof THREE.AmbientLight ) {
  3075. if ( ! light.visible ) continue;
  3076. r += color.r;
  3077. g += color.g;
  3078. b += color.b;
  3079. } else if ( light instanceof THREE.DirectionalLight ) {
  3080. dirCount += 1;
  3081. if ( ! light.visible ) continue;
  3082. _direction.setFromMatrixPosition( light.matrixWorld );
  3083. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  3084. _direction.sub( _vector3 );
  3085. _direction.normalize();
  3086. dirOffset = dirLength * 3;
  3087. dirPositions[ dirOffset ] = _direction.x;
  3088. dirPositions[ dirOffset + 1 ] = _direction.y;
  3089. dirPositions[ dirOffset + 2 ] = _direction.z;
  3090. setColorLinear( dirColors, dirOffset, color, intensity );
  3091. dirLength += 1;
  3092. } else if ( light instanceof THREE.PointLight ) {
  3093. pointCount += 1;
  3094. if ( ! light.visible ) continue;
  3095. pointOffset = pointLength * 3;
  3096. setColorLinear( pointColors, pointOffset, color, intensity );
  3097. _vector3.setFromMatrixPosition( light.matrixWorld );
  3098. pointPositions[ pointOffset ] = _vector3.x;
  3099. pointPositions[ pointOffset + 1 ] = _vector3.y;
  3100. pointPositions[ pointOffset + 2 ] = _vector3.z;
  3101. // distance is 0 if decay is 0, because there is no attenuation at all.
  3102. pointDistances[ pointLength ] = distance;
  3103. pointDecays[ pointLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  3104. pointLength += 1;
  3105. } else if ( light instanceof THREE.SpotLight ) {
  3106. spotCount += 1;
  3107. if ( ! light.visible ) continue;
  3108. spotOffset = spotLength * 3;
  3109. setColorLinear( spotColors, spotOffset, color, intensity );
  3110. _direction.setFromMatrixPosition( light.matrixWorld );
  3111. spotPositions[ spotOffset ] = _direction.x;
  3112. spotPositions[ spotOffset + 1 ] = _direction.y;
  3113. spotPositions[ spotOffset + 2 ] = _direction.z;
  3114. spotDistances[ spotLength ] = distance;
  3115. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  3116. _direction.sub( _vector3 );
  3117. _direction.normalize();
  3118. spotDirections[ spotOffset ] = _direction.x;
  3119. spotDirections[ spotOffset + 1 ] = _direction.y;
  3120. spotDirections[ spotOffset + 2 ] = _direction.z;
  3121. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  3122. spotExponents[ spotLength ] = light.exponent;
  3123. spotDecays[ spotLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  3124. spotLength += 1;
  3125. } else if ( light instanceof THREE.HemisphereLight ) {
  3126. hemiCount += 1;
  3127. if ( ! light.visible ) continue;
  3128. _direction.setFromMatrixPosition( light.matrixWorld );
  3129. _direction.normalize();
  3130. hemiOffset = hemiLength * 3;
  3131. hemiPositions[ hemiOffset ] = _direction.x;
  3132. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  3133. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  3134. skyColor = light.color;
  3135. groundColor = light.groundColor;
  3136. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  3137. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  3138. hemiLength += 1;
  3139. }
  3140. }
  3141. // null eventual remains from removed lights
  3142. // (this is to avoid if in shader)
  3143. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  3144. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  3145. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  3146. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  3147. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  3148. zlights.directional.length = dirLength;
  3149. zlights.point.length = pointLength;
  3150. zlights.spot.length = spotLength;
  3151. zlights.hemi.length = hemiLength;
  3152. zlights.ambient[ 0 ] = r;
  3153. zlights.ambient[ 1 ] = g;
  3154. zlights.ambient[ 2 ] = b;
  3155. }
  3156. // GL state setting
  3157. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  3158. if ( cullFace === THREE.CullFaceNone ) {
  3159. _gl.disable( _gl.CULL_FACE );
  3160. } else {
  3161. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  3162. _gl.frontFace( _gl.CW );
  3163. } else {
  3164. _gl.frontFace( _gl.CCW );
  3165. }
  3166. if ( cullFace === THREE.CullFaceBack ) {
  3167. _gl.cullFace( _gl.BACK );
  3168. } else if ( cullFace === THREE.CullFaceFront ) {
  3169. _gl.cullFace( _gl.FRONT );
  3170. } else {
  3171. _gl.cullFace( _gl.FRONT_AND_BACK );
  3172. }
  3173. _gl.enable( _gl.CULL_FACE );
  3174. }
  3175. };
  3176. this.setMaterialFaces = function ( material ) {
  3177. var doubleSided = material.side === THREE.DoubleSide;
  3178. var flipSided = material.side === THREE.BackSide;
  3179. if ( _oldDoubleSided !== doubleSided ) {
  3180. if ( doubleSided ) {
  3181. _gl.disable( _gl.CULL_FACE );
  3182. } else {
  3183. _gl.enable( _gl.CULL_FACE );
  3184. }
  3185. _oldDoubleSided = doubleSided;
  3186. }
  3187. if ( _oldFlipSided !== flipSided ) {
  3188. if ( flipSided ) {
  3189. _gl.frontFace( _gl.CW );
  3190. } else {
  3191. _gl.frontFace( _gl.CCW );
  3192. }
  3193. _oldFlipSided = flipSided;
  3194. }
  3195. };
  3196. this.setDepthTest = function ( depthTest ) {
  3197. if ( _oldDepthTest !== depthTest ) {
  3198. if ( depthTest ) {
  3199. _gl.enable( _gl.DEPTH_TEST );
  3200. } else {
  3201. _gl.disable( _gl.DEPTH_TEST );
  3202. }
  3203. _oldDepthTest = depthTest;
  3204. }
  3205. };
  3206. this.setDepthWrite = function ( depthWrite ) {
  3207. if ( _oldDepthWrite !== depthWrite ) {
  3208. _gl.depthMask( depthWrite );
  3209. _oldDepthWrite = depthWrite;
  3210. }
  3211. };
  3212. function setLineWidth ( width ) {
  3213. width *= pixelRatio;
  3214. if ( width !== _oldLineWidth ) {
  3215. _gl.lineWidth( width );
  3216. _oldLineWidth = width;
  3217. }
  3218. }
  3219. function setPolygonOffset ( polygonoffset, factor, units ) {
  3220. if ( _oldPolygonOffset !== polygonoffset ) {
  3221. if ( polygonoffset ) {
  3222. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  3223. } else {
  3224. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  3225. }
  3226. _oldPolygonOffset = polygonoffset;
  3227. }
  3228. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  3229. _gl.polygonOffset( factor, units );
  3230. _oldPolygonOffsetFactor = factor;
  3231. _oldPolygonOffsetUnits = units;
  3232. }
  3233. }
  3234. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha ) {
  3235. if ( blending !== _oldBlending ) {
  3236. if ( blending === THREE.NoBlending ) {
  3237. _gl.disable( _gl.BLEND );
  3238. } else if ( blending === THREE.AdditiveBlending ) {
  3239. _gl.enable( _gl.BLEND );
  3240. _gl.blendEquation( _gl.FUNC_ADD );
  3241. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  3242. } else if ( blending === THREE.SubtractiveBlending ) {
  3243. // TODO: Find blendFuncSeparate() combination
  3244. _gl.enable( _gl.BLEND );
  3245. _gl.blendEquation( _gl.FUNC_ADD );
  3246. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  3247. } else if ( blending === THREE.MultiplyBlending ) {
  3248. // TODO: Find blendFuncSeparate() combination
  3249. _gl.enable( _gl.BLEND );
  3250. _gl.blendEquation( _gl.FUNC_ADD );
  3251. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  3252. } else if ( blending === THREE.CustomBlending ) {
  3253. _gl.enable( _gl.BLEND );
  3254. } else {
  3255. _gl.enable( _gl.BLEND );
  3256. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  3257. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  3258. }
  3259. _oldBlending = blending;
  3260. }
  3261. if ( blending === THREE.CustomBlending ) {
  3262. blendEquationAlpha = blendEquationAlpha || blendEquation;
  3263. blendSrcAlpha = blendSrcAlpha || blendSrc;
  3264. blendDstAlpha = blendDstAlpha || blendDst;
  3265. if ( blendEquation !== _oldBlendEquation || blendEquationAlpha !== _oldBlendEquationAlpha ) {
  3266. _gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  3267. _oldBlendEquation = blendEquation;
  3268. _oldBlendEquationAlpha = blendEquationAlpha;
  3269. }
  3270. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst || blendSrcAlpha !== _oldBlendSrcAlpha || blendDstAlpha !== _oldBlendDstAlpha ) {
  3271. _gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  3272. _oldBlendSrc = blendSrc;
  3273. _oldBlendDst = blendDst;
  3274. _oldBlendSrcAlpha = blendSrcAlpha;
  3275. _oldBlendDstAlpha = blendDstAlpha;
  3276. }
  3277. } else {
  3278. _oldBlendEquation = null;
  3279. _oldBlendSrc = null;
  3280. _oldBlendDst = null;
  3281. _oldBlendEquationAlpha = null;
  3282. _oldBlendSrcAlpha = null;
  3283. _oldBlendDstAlpha = null;
  3284. }
  3285. };
  3286. // Textures
  3287. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  3288. var extension;
  3289. if ( isImagePowerOfTwo ) {
  3290. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  3291. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  3292. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  3293. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  3294. } else {
  3295. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  3296. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  3297. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  3298. THREE.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping. ( ' + texture.sourceFile + ' )' );
  3299. }
  3300. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  3301. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  3302. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  3303. THREE.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter. ( ' + texture.sourceFile + ' )' );
  3304. }
  3305. }
  3306. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  3307. if ( extension && texture.type !== THREE.FloatType && texture.type !== THREE.HalfFloatType ) {
  3308. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  3309. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  3310. texture.__oldAnisotropy = texture.anisotropy;
  3311. }
  3312. }
  3313. }
  3314. this.uploadTexture = function ( texture ) {
  3315. if ( texture.__webglInit === undefined ) {
  3316. texture.__webglInit = true;
  3317. texture.addEventListener( 'dispose', onTextureDispose );
  3318. texture.__webglTexture = _gl.createTexture();
  3319. _this.info.memory.textures ++;
  3320. }
  3321. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  3322. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  3323. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  3324. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  3325. texture.image = clampToMaxSize( texture.image, _maxTextureSize );
  3326. var image = texture.image,
  3327. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  3328. glFormat = paramThreeToGL( texture.format ),
  3329. glType = paramThreeToGL( texture.type );
  3330. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  3331. var mipmap, mipmaps = texture.mipmaps;
  3332. if ( texture instanceof THREE.DataTexture ) {
  3333. // use manually created mipmaps if available
  3334. // if there are no manual mipmaps
  3335. // set 0 level mipmap and then use GL to generate other mipmap levels
  3336. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  3337. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3338. mipmap = mipmaps[ i ];
  3339. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  3340. }
  3341. texture.generateMipmaps = false;
  3342. } else {
  3343. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  3344. }
  3345. } else if ( texture instanceof THREE.CompressedTexture ) {
  3346. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3347. mipmap = mipmaps[ i ];
  3348. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  3349. if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) {
  3350. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  3351. } else {
  3352. THREE.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  3353. }
  3354. } else {
  3355. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  3356. }
  3357. }
  3358. } else { // regular Texture (image, video, canvas)
  3359. // use manually created mipmaps if available
  3360. // if there are no manual mipmaps
  3361. // set 0 level mipmap and then use GL to generate other mipmap levels
  3362. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  3363. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3364. mipmap = mipmaps[ i ];
  3365. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  3366. }
  3367. texture.generateMipmaps = false;
  3368. } else {
  3369. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  3370. }
  3371. }
  3372. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  3373. texture.needsUpdate = false;
  3374. if ( texture.onUpdate ) texture.onUpdate();
  3375. };
  3376. this.setTexture = function ( texture, slot ) {
  3377. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3378. if ( texture.needsUpdate ) {
  3379. _this.uploadTexture( texture );
  3380. } else {
  3381. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  3382. }
  3383. };
  3384. function clampToMaxSize ( image, maxSize ) {
  3385. if ( image.width > maxSize || image.height > maxSize ) {
  3386. // Warning: Scaling through the canvas will only work with images that use
  3387. // premultiplied alpha.
  3388. var scale = maxSize / Math.max( image.width, image.height );
  3389. var canvas = document.createElement( 'canvas' );
  3390. canvas.width = Math.floor( image.width * scale );
  3391. canvas.height = Math.floor( image.height * scale );
  3392. var context = canvas.getContext( '2d' );
  3393. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  3394. THREE.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  3395. return canvas;
  3396. }
  3397. return image;
  3398. }
  3399. function setCubeTexture ( texture, slot ) {
  3400. if ( texture.image.length === 6 ) {
  3401. if ( texture.needsUpdate ) {
  3402. if ( ! texture.image.__webglTextureCube ) {
  3403. texture.addEventListener( 'dispose', onTextureDispose );
  3404. texture.image.__webglTextureCube = _gl.createTexture();
  3405. _this.info.memory.textures ++;
  3406. }
  3407. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3408. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  3409. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  3410. var isCompressed = texture instanceof THREE.CompressedTexture;
  3411. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  3412. var cubeImage = [];
  3413. for ( var i = 0; i < 6; i ++ ) {
  3414. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  3415. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  3416. } else {
  3417. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  3418. }
  3419. }
  3420. var image = cubeImage[ 0 ],
  3421. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  3422. glFormat = paramThreeToGL( texture.format ),
  3423. glType = paramThreeToGL( texture.type );
  3424. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  3425. for ( var i = 0; i < 6; i ++ ) {
  3426. if ( ! isCompressed ) {
  3427. if ( isDataTexture ) {
  3428. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  3429. } else {
  3430. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  3431. }
  3432. } else {
  3433. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  3434. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  3435. mipmap = mipmaps[ j ];
  3436. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  3437. if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) {
  3438. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  3439. } else {
  3440. THREE.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  3441. }
  3442. } else {
  3443. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  3444. }
  3445. }
  3446. }
  3447. }
  3448. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  3449. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  3450. }
  3451. texture.needsUpdate = false;
  3452. if ( texture.onUpdate ) texture.onUpdate();
  3453. } else {
  3454. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3455. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  3456. }
  3457. }
  3458. }
  3459. function setCubeTextureDynamic ( texture, slot ) {
  3460. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3461. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  3462. }
  3463. // Render targets
  3464. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  3465. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  3466. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  3467. }
  3468. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  3469. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  3470. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  3471. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  3472. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  3473. /* For some reason this is not working. Defaulting to RGBA4.
  3474. } else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  3475. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  3476. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  3477. */
  3478. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  3479. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  3480. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  3481. } else {
  3482. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  3483. }
  3484. }
  3485. this.setRenderTarget = function ( renderTarget ) {
  3486. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  3487. if ( renderTarget && renderTarget.__webglFramebuffer === undefined ) {
  3488. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  3489. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  3490. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  3491. renderTarget.__webglTexture = _gl.createTexture();
  3492. _this.info.memory.textures ++;
  3493. // Setup texture, create render and frame buffers
  3494. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  3495. glFormat = paramThreeToGL( renderTarget.format ),
  3496. glType = paramThreeToGL( renderTarget.type );
  3497. if ( isCube ) {
  3498. renderTarget.__webglFramebuffer = [];
  3499. renderTarget.__webglRenderbuffer = [];
  3500. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  3501. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  3502. for ( var i = 0; i < 6; i ++ ) {
  3503. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  3504. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  3505. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  3506. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  3507. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  3508. }
  3509. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  3510. } else {
  3511. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  3512. if ( renderTarget.shareDepthFrom ) {
  3513. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  3514. } else {
  3515. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  3516. }
  3517. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  3518. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  3519. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  3520. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  3521. if ( renderTarget.shareDepthFrom ) {
  3522. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  3523. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  3524. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  3525. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  3526. }
  3527. } else {
  3528. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  3529. }
  3530. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  3531. }
  3532. // Release everything
  3533. if ( isCube ) {
  3534. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  3535. } else {
  3536. _gl.bindTexture( _gl.TEXTURE_2D, null );
  3537. }
  3538. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  3539. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  3540. }
  3541. var framebuffer, width, height, vx, vy;
  3542. if ( renderTarget ) {
  3543. if ( isCube ) {
  3544. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  3545. } else {
  3546. framebuffer = renderTarget.__webglFramebuffer;
  3547. }
  3548. width = renderTarget.width;
  3549. height = renderTarget.height;
  3550. vx = 0;
  3551. vy = 0;
  3552. } else {
  3553. framebuffer = null;
  3554. width = _viewportWidth;
  3555. height = _viewportHeight;
  3556. vx = _viewportX;
  3557. vy = _viewportY;
  3558. }
  3559. if ( framebuffer !== _currentFramebuffer ) {
  3560. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  3561. _gl.viewport( vx, vy, width, height );
  3562. _currentFramebuffer = framebuffer;
  3563. }
  3564. _currentWidth = width;
  3565. _currentHeight = height;
  3566. };
  3567. this.readRenderTargetPixels = function( renderTarget, x, y, width, height, buffer ) {
  3568. if ( ! ( renderTarget instanceof THREE.WebGLRenderTarget ) ) {
  3569. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  3570. return;
  3571. }
  3572. if ( renderTarget.__webglFramebuffer ) {
  3573. if ( renderTarget.format !== THREE.RGBAFormat ) {
  3574. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA format. readPixels can read only RGBA format.' );
  3575. return;
  3576. }
  3577. var restore = false;
  3578. if ( renderTarget.__webglFramebuffer !== _currentFramebuffer ) {
  3579. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTarget.__webglFramebuffer );
  3580. restore = true;
  3581. }
  3582. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  3583. _gl.readPixels( x, y, width, height, _gl.RGBA, _gl.UNSIGNED_BYTE, buffer );
  3584. } else {
  3585. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  3586. }
  3587. if ( restore ) {
  3588. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  3589. }
  3590. }
  3591. };
  3592. function updateRenderTargetMipmap ( renderTarget ) {
  3593. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  3594. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  3595. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  3596. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  3597. } else {
  3598. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  3599. _gl.generateMipmap( _gl.TEXTURE_2D );
  3600. _gl.bindTexture( _gl.TEXTURE_2D, null );
  3601. }
  3602. }
  3603. // Fallback filters for non-power-of-2 textures
  3604. function filterFallback ( f ) {
  3605. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  3606. return _gl.NEAREST;
  3607. }
  3608. return _gl.LINEAR;
  3609. }
  3610. // Map three.js constants to WebGL constants
  3611. function paramThreeToGL ( p ) {
  3612. var extension;
  3613. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  3614. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  3615. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  3616. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  3617. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  3618. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  3619. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  3620. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  3621. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  3622. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  3623. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  3624. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  3625. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  3626. if ( p === THREE.ByteType ) return _gl.BYTE;
  3627. if ( p === THREE.ShortType ) return _gl.SHORT;
  3628. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  3629. if ( p === THREE.IntType ) return _gl.INT;
  3630. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  3631. if ( p === THREE.FloatType ) return _gl.FLOAT;
  3632. extension = extensions.get( 'OES_texture_half_float' );
  3633. if ( extension !== null ) {
  3634. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  3635. }
  3636. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  3637. if ( p === THREE.RGBFormat ) return _gl.RGB;
  3638. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  3639. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  3640. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  3641. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  3642. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  3643. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  3644. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  3645. if ( p === THREE.OneFactor ) return _gl.ONE;
  3646. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  3647. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  3648. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  3649. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  3650. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  3651. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  3652. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  3653. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  3654. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  3655. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  3656. if ( extension !== null ) {
  3657. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  3658. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3659. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3660. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3661. }
  3662. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  3663. if ( extension !== null ) {
  3664. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  3665. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  3666. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  3667. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  3668. }
  3669. extension = extensions.get( 'EXT_blend_minmax' );
  3670. if ( extension !== null ) {
  3671. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  3672. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  3673. }
  3674. return 0;
  3675. }
  3676. // Allocations
  3677. function allocateBones ( object ) {
  3678. if ( _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  3679. return 1024;
  3680. } else {
  3681. // default for when object is not specified
  3682. // ( for example when prebuilding shader
  3683. // to be used with multiple objects )
  3684. //
  3685. // - leave some extra space for other uniforms
  3686. // - limit here is ANGLE's 254 max uniform vectors
  3687. // (up to 54 should be safe)
  3688. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  3689. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  3690. var maxBones = nVertexMatrices;
  3691. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  3692. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  3693. if ( maxBones < object.skeleton.bones.length ) {
  3694. THREE.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  3695. }
  3696. }
  3697. return maxBones;
  3698. }
  3699. }
  3700. function allocateLights( lights ) {
  3701. var dirLights = 0;
  3702. var pointLights = 0;
  3703. var spotLights = 0;
  3704. var hemiLights = 0;
  3705. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  3706. var light = lights[ l ];
  3707. if ( light.onlyShadow || light.visible === false ) continue;
  3708. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  3709. if ( light instanceof THREE.PointLight ) pointLights ++;
  3710. if ( light instanceof THREE.SpotLight ) spotLights ++;
  3711. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  3712. }
  3713. return { 'directional': dirLights, 'point': pointLights, 'spot': spotLights, 'hemi': hemiLights };
  3714. }
  3715. function allocateShadows( lights ) {
  3716. var maxShadows = 0;
  3717. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  3718. var light = lights[ l ];
  3719. if ( ! light.castShadow ) continue;
  3720. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  3721. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  3722. }
  3723. return maxShadows;
  3724. }
  3725. // DEPRECATED
  3726. this.initMaterial = function () {
  3727. THREE.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  3728. };
  3729. this.addPrePlugin = function () {
  3730. THREE.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  3731. };
  3732. this.addPostPlugin = function () {
  3733. THREE.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  3734. };
  3735. this.updateShadowMap = function () {
  3736. THREE.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  3737. };
  3738. };