babylon.2.4.max.js 3.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. })();
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. return Color3;
  211. })();
  212. BABYLON.Color3 = Color3;
  213. var Color4 = (function () {
  214. function Color4(r, g, b, a) {
  215. this.r = r;
  216. this.g = g;
  217. this.b = b;
  218. this.a = a;
  219. }
  220. // Operators
  221. Color4.prototype.addInPlace = function (right) {
  222. this.r += right.r;
  223. this.g += right.g;
  224. this.b += right.b;
  225. this.a += right.a;
  226. return this;
  227. };
  228. Color4.prototype.asArray = function () {
  229. var result = [];
  230. this.toArray(result, 0);
  231. return result;
  232. };
  233. Color4.prototype.toArray = function (array, index) {
  234. if (index === undefined) {
  235. index = 0;
  236. }
  237. array[index] = this.r;
  238. array[index + 1] = this.g;
  239. array[index + 2] = this.b;
  240. array[index + 3] = this.a;
  241. return this;
  242. };
  243. Color4.prototype.add = function (right) {
  244. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  245. };
  246. Color4.prototype.subtract = function (right) {
  247. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  248. };
  249. Color4.prototype.subtractToRef = function (right, result) {
  250. result.r = this.r - right.r;
  251. result.g = this.g - right.g;
  252. result.b = this.b - right.b;
  253. result.a = this.a - right.a;
  254. return this;
  255. };
  256. Color4.prototype.scale = function (scale) {
  257. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  258. };
  259. Color4.prototype.scaleToRef = function (scale, result) {
  260. result.r = this.r * scale;
  261. result.g = this.g * scale;
  262. result.b = this.b * scale;
  263. result.a = this.a * scale;
  264. return this;
  265. };
  266. /**
  267. * Multipy an RGBA Color4 value by another and return a new Color4 object
  268. * @param color The Color4 (RGBA) value to multiply by
  269. * @returns A new Color4.
  270. */
  271. Color4.prototype.multiply = function (color) {
  272. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  273. };
  274. /**
  275. * Multipy an RGBA Color4 value by another and push the result in a reference value
  276. * @param color The Color4 (RGBA) value to multiply by
  277. * @param result The Color4 (RGBA) to fill the result in
  278. * @returns the result Color4.
  279. */
  280. Color4.prototype.multiplyToRef = function (color, result) {
  281. result.r = this.r * color.r;
  282. result.g = this.g * color.g;
  283. result.b = this.b * color.b;
  284. result.a = this.a * color.a;
  285. return result;
  286. };
  287. Color4.prototype.toString = function () {
  288. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  289. };
  290. Color4.prototype.getClassName = function () {
  291. return "Color4";
  292. };
  293. Color4.prototype.getHashCode = function () {
  294. var hash = this.r || 0;
  295. hash = (hash * 397) ^ (this.g || 0);
  296. hash = (hash * 397) ^ (this.b || 0);
  297. hash = (hash * 397) ^ (this.a || 0);
  298. return hash;
  299. };
  300. Color4.prototype.clone = function () {
  301. return new Color4(this.r, this.g, this.b, this.a);
  302. };
  303. Color4.prototype.copyFrom = function (source) {
  304. this.r = source.r;
  305. this.g = source.g;
  306. this.b = source.b;
  307. this.a = source.a;
  308. return this;
  309. };
  310. Color4.prototype.toHexString = function () {
  311. var intR = (this.r * 255) | 0;
  312. var intG = (this.g * 255) | 0;
  313. var intB = (this.b * 255) | 0;
  314. var intA = (this.a * 255) | 0;
  315. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  316. };
  317. // Statics
  318. Color4.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  320. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  321. return new Color4(0, 0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. var a = parseInt(hex.substring(7, 9), 16);
  327. return Color4.FromInts(r, g, b, a);
  328. };
  329. Color4.Lerp = function (left, right, amount) {
  330. var result = new Color4(0, 0, 0, 0);
  331. Color4.LerpToRef(left, right, amount, result);
  332. return result;
  333. };
  334. Color4.LerpToRef = function (left, right, amount, result) {
  335. result.r = left.r + (right.r - left.r) * amount;
  336. result.g = left.g + (right.g - left.g) * amount;
  337. result.b = left.b + (right.b - left.b) * amount;
  338. result.a = left.a + (right.a - left.a) * amount;
  339. };
  340. Color4.FromArray = function (array, offset) {
  341. if (offset === void 0) { offset = 0; }
  342. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  343. };
  344. Color4.FromInts = function (r, g, b, a) {
  345. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  346. };
  347. Color4.CheckColors4 = function (colors, count) {
  348. // Check if color3 was used
  349. if (colors.length === count * 3) {
  350. var colors4 = [];
  351. for (var index = 0; index < colors.length; index += 3) {
  352. var newIndex = (index / 3) * 4;
  353. colors4[newIndex] = colors[index];
  354. colors4[newIndex + 1] = colors[index + 1];
  355. colors4[newIndex + 2] = colors[index + 2];
  356. colors4[newIndex + 3] = 1.0;
  357. }
  358. return colors4;
  359. }
  360. return colors;
  361. };
  362. return Color4;
  363. })();
  364. BABYLON.Color4 = Color4;
  365. var Vector2 = (function () {
  366. function Vector2(x, y) {
  367. this.x = x;
  368. this.y = y;
  369. }
  370. Vector2.prototype.toString = function () {
  371. return "{X: " + this.x + " Y:" + this.y + "}";
  372. };
  373. Vector2.prototype.getClassName = function () {
  374. return "Vector2";
  375. };
  376. Vector2.prototype.getHashCode = function () {
  377. var hash = this.x || 0;
  378. hash = (hash * 397) ^ (this.y || 0);
  379. return hash;
  380. };
  381. // Operators
  382. Vector2.prototype.toArray = function (array, index) {
  383. if (index === void 0) { index = 0; }
  384. array[index] = this.x;
  385. array[index + 1] = this.y;
  386. return this;
  387. };
  388. Vector2.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. Vector2.prototype.copyFrom = function (source) {
  394. this.x = source.x;
  395. this.y = source.y;
  396. return this;
  397. };
  398. Vector2.prototype.copyFromFloats = function (x, y) {
  399. this.x = x;
  400. this.y = y;
  401. return this;
  402. };
  403. Vector2.prototype.add = function (otherVector) {
  404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  405. };
  406. Vector2.prototype.addToRef = function (otherVector, result) {
  407. result.x = this.x + otherVector.x;
  408. result.y = this.y + otherVector.y;
  409. return this;
  410. };
  411. Vector2.prototype.addVector3 = function (otherVector) {
  412. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  413. };
  414. Vector2.prototype.subtract = function (otherVector) {
  415. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  416. };
  417. Vector2.prototype.subtractToRef = function (otherVector, result) {
  418. result.x = this.x - otherVector.x;
  419. result.y = this.y - otherVector.y;
  420. return this;
  421. };
  422. Vector2.prototype.subtractInPlace = function (otherVector) {
  423. this.x -= otherVector.x;
  424. this.y -= otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.multiplyInPlace = function (otherVector) {
  428. this.x *= otherVector.x;
  429. this.y *= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiply = function (otherVector) {
  433. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  434. };
  435. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  436. result.x = this.x * otherVector.x;
  437. result.y = this.y * otherVector.y;
  438. return this;
  439. };
  440. Vector2.prototype.multiplyByFloats = function (x, y) {
  441. return new Vector2(this.x * x, this.y * y);
  442. };
  443. Vector2.prototype.divide = function (otherVector) {
  444. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  445. };
  446. Vector2.prototype.divideToRef = function (otherVector, result) {
  447. result.x = this.x / otherVector.x;
  448. result.y = this.y / otherVector.y;
  449. return this;
  450. };
  451. Vector2.prototype.negate = function () {
  452. return new Vector2(-this.x, -this.y);
  453. };
  454. Vector2.prototype.scaleInPlace = function (scale) {
  455. this.x *= scale;
  456. this.y *= scale;
  457. return this;
  458. };
  459. Vector2.prototype.scale = function (scale) {
  460. return new Vector2(this.x * scale, this.y * scale);
  461. };
  462. Vector2.prototype.equals = function (otherVector) {
  463. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  464. };
  465. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  466. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  467. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  468. };
  469. // Properties
  470. Vector2.prototype.length = function () {
  471. return Math.sqrt(this.x * this.x + this.y * this.y);
  472. };
  473. Vector2.prototype.lengthSquared = function () {
  474. return (this.x * this.x + this.y * this.y);
  475. };
  476. // Methods
  477. Vector2.prototype.normalize = function () {
  478. var len = this.length();
  479. if (len === 0)
  480. return this;
  481. var num = 1.0 / len;
  482. this.x *= num;
  483. this.y *= num;
  484. return this;
  485. };
  486. Vector2.prototype.clone = function () {
  487. return new Vector2(this.x, this.y);
  488. };
  489. // Statics
  490. Vector2.Zero = function () {
  491. return new Vector2(0, 0);
  492. };
  493. Vector2.FromArray = function (array, offset) {
  494. if (offset === void 0) { offset = 0; }
  495. return new Vector2(array[offset], array[offset + 1]);
  496. };
  497. Vector2.FromArrayToRef = function (array, offset, result) {
  498. result.x = array[offset];
  499. result.y = array[offset + 1];
  500. };
  501. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  502. var squared = amount * amount;
  503. var cubed = amount * squared;
  504. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  505. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  506. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  507. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  508. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  509. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  510. return new Vector2(x, y);
  511. };
  512. Vector2.Clamp = function (value, min, max) {
  513. var x = value.x;
  514. x = (x > max.x) ? max.x : x;
  515. x = (x < min.x) ? min.x : x;
  516. var y = value.y;
  517. y = (y > max.y) ? max.y : y;
  518. y = (y < min.y) ? min.y : y;
  519. return new Vector2(x, y);
  520. };
  521. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  522. var squared = amount * amount;
  523. var cubed = amount * squared;
  524. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  525. var part2 = (-2.0 * cubed) + (3.0 * squared);
  526. var part3 = (cubed - (2.0 * squared)) + amount;
  527. var part4 = cubed - squared;
  528. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  529. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  530. return new Vector2(x, y);
  531. };
  532. Vector2.Lerp = function (start, end, amount) {
  533. var x = start.x + ((end.x - start.x) * amount);
  534. var y = start.y + ((end.y - start.y) * amount);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Dot = function (left, right) {
  538. return left.x * right.x + left.y * right.y;
  539. };
  540. Vector2.Normalize = function (vector) {
  541. var newVector = vector.clone();
  542. newVector.normalize();
  543. return newVector;
  544. };
  545. Vector2.Minimize = function (left, right) {
  546. var x = (left.x < right.x) ? left.x : right.x;
  547. var y = (left.y < right.y) ? left.y : right.y;
  548. return new Vector2(x, y);
  549. };
  550. Vector2.Maximize = function (left, right) {
  551. var x = (left.x > right.x) ? left.x : right.x;
  552. var y = (left.y > right.y) ? left.y : right.y;
  553. return new Vector2(x, y);
  554. };
  555. Vector2.Transform = function (vector, transformation) {
  556. var r = Vector2.Zero();
  557. Vector2.TransformToRef(vector, transformation, r);
  558. return r;
  559. };
  560. Vector2.TransformToRef = function (vector, transformation, result) {
  561. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  562. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  563. result.x = x;
  564. result.y = y;
  565. };
  566. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  567. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  568. var sign = a < 0 ? -1 : 1;
  569. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  570. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  571. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  572. };
  573. Vector2.Distance = function (value1, value2) {
  574. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  575. };
  576. Vector2.DistanceSquared = function (value1, value2) {
  577. var x = value1.x - value2.x;
  578. var y = value1.y - value2.y;
  579. return (x * x) + (y * y);
  580. };
  581. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  582. var l2 = Vector2.DistanceSquared(segA, segB);
  583. if (l2 === 0.0) {
  584. return Vector2.Distance(p, segA);
  585. }
  586. var v = segB.subtract(segA);
  587. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  588. var proj = segA.add(v.multiplyByFloats(t, t));
  589. return Vector2.Distance(p, proj);
  590. };
  591. return Vector2;
  592. })();
  593. BABYLON.Vector2 = Vector2;
  594. var Vector3 = (function () {
  595. function Vector3(x, y, z) {
  596. this.x = x;
  597. this.y = y;
  598. this.z = z;
  599. }
  600. Vector3.prototype.toString = function () {
  601. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  602. };
  603. Vector3.prototype.getClassName = function () {
  604. return "Vector3";
  605. };
  606. Vector3.prototype.getHashCode = function () {
  607. var hash = this.x || 0;
  608. hash = (hash * 397) ^ (this.y || 0);
  609. hash = (hash * 397) ^ (this.z || 0);
  610. return hash;
  611. };
  612. // Operators
  613. Vector3.prototype.asArray = function () {
  614. var result = [];
  615. this.toArray(result, 0);
  616. return result;
  617. };
  618. Vector3.prototype.toArray = function (array, index) {
  619. if (index === void 0) { index = 0; }
  620. array[index] = this.x;
  621. array[index + 1] = this.y;
  622. array[index + 2] = this.z;
  623. return this;
  624. };
  625. Vector3.prototype.toQuaternion = function () {
  626. var result = new Quaternion(0, 0, 0, 1);
  627. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  628. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  629. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  630. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  631. var cosy = Math.cos(this.y * 0.5);
  632. var siny = Math.sin(this.y * 0.5);
  633. result.x = coszMinusx * siny;
  634. result.y = -sinzMinusx * siny;
  635. result.z = sinxPlusz * cosy;
  636. result.w = cosxPlusz * cosy;
  637. return result;
  638. };
  639. Vector3.prototype.addInPlace = function (otherVector) {
  640. this.x += otherVector.x;
  641. this.y += otherVector.y;
  642. this.z += otherVector.z;
  643. return this;
  644. };
  645. Vector3.prototype.add = function (otherVector) {
  646. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  647. };
  648. Vector3.prototype.addToRef = function (otherVector, result) {
  649. result.x = this.x + otherVector.x;
  650. result.y = this.y + otherVector.y;
  651. result.z = this.z + otherVector.z;
  652. return this;
  653. };
  654. Vector3.prototype.subtractInPlace = function (otherVector) {
  655. this.x -= otherVector.x;
  656. this.y -= otherVector.y;
  657. this.z -= otherVector.z;
  658. return this;
  659. };
  660. Vector3.prototype.subtract = function (otherVector) {
  661. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  662. };
  663. Vector3.prototype.subtractToRef = function (otherVector, result) {
  664. result.x = this.x - otherVector.x;
  665. result.y = this.y - otherVector.y;
  666. result.z = this.z - otherVector.z;
  667. return this;
  668. };
  669. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  670. return new Vector3(this.x - x, this.y - y, this.z - z);
  671. };
  672. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  673. result.x = this.x - x;
  674. result.y = this.y - y;
  675. result.z = this.z - z;
  676. return this;
  677. };
  678. Vector3.prototype.negate = function () {
  679. return new Vector3(-this.x, -this.y, -this.z);
  680. };
  681. Vector3.prototype.scaleInPlace = function (scale) {
  682. this.x *= scale;
  683. this.y *= scale;
  684. this.z *= scale;
  685. return this;
  686. };
  687. Vector3.prototype.scale = function (scale) {
  688. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  689. };
  690. Vector3.prototype.scaleToRef = function (scale, result) {
  691. result.x = this.x * scale;
  692. result.y = this.y * scale;
  693. result.z = this.z * scale;
  694. };
  695. Vector3.prototype.equals = function (otherVector) {
  696. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  697. };
  698. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  699. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  700. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  701. };
  702. Vector3.prototype.equalsToFloats = function (x, y, z) {
  703. return this.x === x && this.y === y && this.z === z;
  704. };
  705. Vector3.prototype.multiplyInPlace = function (otherVector) {
  706. this.x *= otherVector.x;
  707. this.y *= otherVector.y;
  708. this.z *= otherVector.z;
  709. return this;
  710. };
  711. Vector3.prototype.multiply = function (otherVector) {
  712. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  713. };
  714. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  715. result.x = this.x * otherVector.x;
  716. result.y = this.y * otherVector.y;
  717. result.z = this.z * otherVector.z;
  718. return this;
  719. };
  720. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  721. return new Vector3(this.x * x, this.y * y, this.z * z);
  722. };
  723. Vector3.prototype.divide = function (otherVector) {
  724. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  725. };
  726. Vector3.prototype.divideToRef = function (otherVector, result) {
  727. result.x = this.x / otherVector.x;
  728. result.y = this.y / otherVector.y;
  729. result.z = this.z / otherVector.z;
  730. return this;
  731. };
  732. Vector3.prototype.MinimizeInPlace = function (other) {
  733. if (other.x < this.x)
  734. this.x = other.x;
  735. if (other.y < this.y)
  736. this.y = other.y;
  737. if (other.z < this.z)
  738. this.z = other.z;
  739. return this;
  740. };
  741. Vector3.prototype.MaximizeInPlace = function (other) {
  742. if (other.x > this.x)
  743. this.x = other.x;
  744. if (other.y > this.y)
  745. this.y = other.y;
  746. if (other.z > this.z)
  747. this.z = other.z;
  748. return this;
  749. };
  750. // Properties
  751. Vector3.prototype.length = function () {
  752. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  753. };
  754. Vector3.prototype.lengthSquared = function () {
  755. return (this.x * this.x + this.y * this.y + this.z * this.z);
  756. };
  757. // Methods
  758. Vector3.prototype.normalize = function () {
  759. var len = this.length();
  760. if (len === 0 || len === 1.0)
  761. return this;
  762. var num = 1.0 / len;
  763. this.x *= num;
  764. this.y *= num;
  765. this.z *= num;
  766. return this;
  767. };
  768. Vector3.prototype.clone = function () {
  769. return new Vector3(this.x, this.y, this.z);
  770. };
  771. Vector3.prototype.copyFrom = function (source) {
  772. this.x = source.x;
  773. this.y = source.y;
  774. this.z = source.z;
  775. return this;
  776. };
  777. Vector3.prototype.copyFromFloats = function (x, y, z) {
  778. this.x = x;
  779. this.y = y;
  780. this.z = z;
  781. return this;
  782. };
  783. // Statics
  784. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  785. var d0 = Vector3.Dot(vector0, axis) - size;
  786. var d1 = Vector3.Dot(vector1, axis) - size;
  787. var s = d0 / (d0 - d1);
  788. return s;
  789. };
  790. Vector3.FromArray = function (array, offset) {
  791. if (!offset) {
  792. offset = 0;
  793. }
  794. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  795. };
  796. Vector3.FromFloatArray = function (array, offset) {
  797. if (!offset) {
  798. offset = 0;
  799. }
  800. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  801. };
  802. Vector3.FromArrayToRef = function (array, offset, result) {
  803. result.x = array[offset];
  804. result.y = array[offset + 1];
  805. result.z = array[offset + 2];
  806. };
  807. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  808. result.x = array[offset];
  809. result.y = array[offset + 1];
  810. result.z = array[offset + 2];
  811. };
  812. Vector3.FromFloatsToRef = function (x, y, z, result) {
  813. result.x = x;
  814. result.y = y;
  815. result.z = z;
  816. };
  817. Vector3.Zero = function () {
  818. return new Vector3(0, 0, 0);
  819. };
  820. Vector3.Up = function () {
  821. return new Vector3(0, 1.0, 0);
  822. };
  823. Vector3.TransformCoordinates = function (vector, transformation) {
  824. var result = Vector3.Zero();
  825. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  826. return result;
  827. };
  828. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  829. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  830. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  831. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  832. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  833. result.x = x / w;
  834. result.y = y / w;
  835. result.z = z / w;
  836. };
  837. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  838. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  839. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  840. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  841. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  842. result.x = rx / rw;
  843. result.y = ry / rw;
  844. result.z = rz / rw;
  845. };
  846. Vector3.TransformNormal = function (vector, transformation) {
  847. var result = Vector3.Zero();
  848. Vector3.TransformNormalToRef(vector, transformation, result);
  849. return result;
  850. };
  851. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  852. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  853. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  854. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  855. };
  856. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  857. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  858. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  859. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  860. };
  861. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  862. var squared = amount * amount;
  863. var cubed = amount * squared;
  864. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  865. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  866. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  867. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  868. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  869. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  870. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  871. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  872. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  873. return new Vector3(x, y, z);
  874. };
  875. Vector3.Clamp = function (value, min, max) {
  876. var x = value.x;
  877. x = (x > max.x) ? max.x : x;
  878. x = (x < min.x) ? min.x : x;
  879. var y = value.y;
  880. y = (y > max.y) ? max.y : y;
  881. y = (y < min.y) ? min.y : y;
  882. var z = value.z;
  883. z = (z > max.z) ? max.z : z;
  884. z = (z < min.z) ? min.z : z;
  885. return new Vector3(x, y, z);
  886. };
  887. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  888. var squared = amount * amount;
  889. var cubed = amount * squared;
  890. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  891. var part2 = (-2.0 * cubed) + (3.0 * squared);
  892. var part3 = (cubed - (2.0 * squared)) + amount;
  893. var part4 = cubed - squared;
  894. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  895. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  896. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  897. return new Vector3(x, y, z);
  898. };
  899. Vector3.Lerp = function (start, end, amount) {
  900. var x = start.x + ((end.x - start.x) * amount);
  901. var y = start.y + ((end.y - start.y) * amount);
  902. var z = start.z + ((end.z - start.z) * amount);
  903. return new Vector3(x, y, z);
  904. };
  905. Vector3.Dot = function (left, right) {
  906. return (left.x * right.x + left.y * right.y + left.z * right.z);
  907. };
  908. Vector3.Cross = function (left, right) {
  909. var result = Vector3.Zero();
  910. Vector3.CrossToRef(left, right, result);
  911. return result;
  912. };
  913. Vector3.CrossToRef = function (left, right, result) {
  914. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  915. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  916. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  917. result.copyFrom(Tmp.Vector3[0]);
  918. };
  919. Vector3.Normalize = function (vector) {
  920. var result = Vector3.Zero();
  921. Vector3.NormalizeToRef(vector, result);
  922. return result;
  923. };
  924. Vector3.NormalizeToRef = function (vector, result) {
  925. result.copyFrom(vector);
  926. result.normalize();
  927. };
  928. Vector3.Project = function (vector, world, transform, viewport) {
  929. var cw = viewport.width;
  930. var ch = viewport.height;
  931. var cx = viewport.x;
  932. var cy = viewport.y;
  933. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  934. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  935. return Vector3.TransformCoordinates(vector, finalMatrix);
  936. };
  937. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  938. var matrix = world.multiply(transform);
  939. matrix.invert();
  940. source.x = source.x / viewportWidth * 2 - 1;
  941. source.y = -(source.y / viewportHeight * 2 - 1);
  942. var vector = Vector3.TransformCoordinates(source, matrix);
  943. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  944. if (MathTools.WithinEpsilon(num, 1.0)) {
  945. vector = vector.scale(1.0 / num);
  946. }
  947. return vector;
  948. };
  949. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  950. var matrix = world.multiply(view).multiply(projection);
  951. matrix.invert();
  952. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  953. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  954. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  955. if (MathTools.WithinEpsilon(num, 1.0)) {
  956. vector = vector.scale(1.0 / num);
  957. }
  958. return vector;
  959. };
  960. Vector3.Minimize = function (left, right) {
  961. var min = left.clone();
  962. min.MinimizeInPlace(right);
  963. return min;
  964. };
  965. Vector3.Maximize = function (left, right) {
  966. var max = left.clone();
  967. max.MaximizeInPlace(right);
  968. return max;
  969. };
  970. Vector3.Distance = function (value1, value2) {
  971. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  972. };
  973. Vector3.DistanceSquared = function (value1, value2) {
  974. var x = value1.x - value2.x;
  975. var y = value1.y - value2.y;
  976. var z = value1.z - value2.z;
  977. return (x * x) + (y * y) + (z * z);
  978. };
  979. Vector3.Center = function (value1, value2) {
  980. var center = value1.add(value2);
  981. center.scaleInPlace(0.5);
  982. return center;
  983. };
  984. /**
  985. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  986. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  987. * to something in order to rotate it from its local system to the given target system.
  988. */
  989. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  990. var rotation = Vector3.Zero();
  991. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  992. return rotation;
  993. };
  994. /**
  995. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  996. */
  997. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  998. var u = axis1.normalize();
  999. var w = axis3.normalize();
  1000. // world axis
  1001. var X = Axis.X;
  1002. var Y = Axis.Y;
  1003. // equation unknowns and vars
  1004. var yaw = 0.0;
  1005. var pitch = 0.0;
  1006. var roll = 0.0;
  1007. var x = 0.0;
  1008. var y = 0.0;
  1009. var z = 0.0;
  1010. var t = 0.0;
  1011. var sign = -1.0;
  1012. var nbRevert = 0;
  1013. var cross = Tmp.Vector3[0];
  1014. var dot = 0.0;
  1015. // step 1 : rotation around w
  1016. // Rv3(u) = u1, and u1 belongs to plane xOz
  1017. // Rv3(w) = w1 = w invariant
  1018. var u1 = Tmp.Vector3[1];
  1019. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1020. z = 1.0;
  1021. }
  1022. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1023. x = 1.0;
  1024. }
  1025. else {
  1026. t = w.z / w.x;
  1027. x = -t * Math.sqrt(1 / (1 + t * t));
  1028. z = Math.sqrt(1 / (1 + t * t));
  1029. }
  1030. u1.x = x;
  1031. u1.y = y;
  1032. u1.z = z;
  1033. u1.normalize();
  1034. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1035. cross.normalize();
  1036. if (Vector3.Dot(w, cross) < 0) {
  1037. sign = 1.0;
  1038. }
  1039. dot = Vector3.Dot(u, u1);
  1040. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1041. roll = Math.acos(dot) * sign;
  1042. if (Vector3.Dot(u1, X) < 0) {
  1043. roll = Math.PI + roll;
  1044. u1 = u1.scaleInPlace(-1);
  1045. nbRevert++;
  1046. }
  1047. // step 2 : rotate around u1
  1048. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1049. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1050. var w2 = Tmp.Vector3[2];
  1051. var v2 = Tmp.Vector3[3];
  1052. x = 0.0;
  1053. y = 0.0;
  1054. z = 0.0;
  1055. sign = -1.0;
  1056. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1057. x = 1.0;
  1058. }
  1059. else {
  1060. t = u1.z / u1.x;
  1061. x = -t * Math.sqrt(1 / (1 + t * t));
  1062. z = Math.sqrt(1 / (1 + t * t));
  1063. }
  1064. w2.x = x;
  1065. w2.y = y;
  1066. w2.z = z;
  1067. w2.normalize();
  1068. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1069. v2.normalize();
  1070. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1071. cross.normalize();
  1072. if (Vector3.Dot(u1, cross) < 0) {
  1073. sign = 1.0;
  1074. }
  1075. dot = Vector3.Dot(w, w2);
  1076. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1077. pitch = Math.acos(dot) * sign;
  1078. if (Vector3.Dot(v2, Y) < 0) {
  1079. pitch = Math.PI + pitch;
  1080. nbRevert++;
  1081. }
  1082. // step 3 : rotate around v2
  1083. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1084. sign = -1.0;
  1085. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1086. cross.normalize();
  1087. if (Vector3.Dot(cross, Y) < 0) {
  1088. sign = 1.0;
  1089. }
  1090. dot = Vector3.Dot(u1, X);
  1091. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1092. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1093. if (dot < 0 && nbRevert < 2) {
  1094. yaw = Math.PI + yaw;
  1095. }
  1096. ref.x = pitch;
  1097. ref.y = yaw;
  1098. ref.z = roll;
  1099. };
  1100. return Vector3;
  1101. })();
  1102. BABYLON.Vector3 = Vector3;
  1103. //Vector4 class created for EulerAngle class conversion to Quaternion
  1104. var Vector4 = (function () {
  1105. function Vector4(x, y, z, w) {
  1106. this.x = x;
  1107. this.y = y;
  1108. this.z = z;
  1109. this.w = w;
  1110. }
  1111. Vector4.prototype.toString = function () {
  1112. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1113. };
  1114. Vector4.prototype.getClassName = function () {
  1115. return "Vector4";
  1116. };
  1117. Vector4.prototype.getHashCode = function () {
  1118. var hash = this.x || 0;
  1119. hash = (hash * 397) ^ (this.y || 0);
  1120. hash = (hash * 397) ^ (this.z || 0);
  1121. hash = (hash * 397) ^ (this.w || 0);
  1122. return hash;
  1123. };
  1124. // Operators
  1125. Vector4.prototype.asArray = function () {
  1126. var result = [];
  1127. this.toArray(result, 0);
  1128. return result;
  1129. };
  1130. Vector4.prototype.toArray = function (array, index) {
  1131. if (index === undefined) {
  1132. index = 0;
  1133. }
  1134. array[index] = this.x;
  1135. array[index + 1] = this.y;
  1136. array[index + 2] = this.z;
  1137. array[index + 3] = this.w;
  1138. return this;
  1139. };
  1140. Vector4.prototype.addInPlace = function (otherVector) {
  1141. this.x += otherVector.x;
  1142. this.y += otherVector.y;
  1143. this.z += otherVector.z;
  1144. this.w += otherVector.w;
  1145. return this;
  1146. };
  1147. Vector4.prototype.add = function (otherVector) {
  1148. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1149. };
  1150. Vector4.prototype.addToRef = function (otherVector, result) {
  1151. result.x = this.x + otherVector.x;
  1152. result.y = this.y + otherVector.y;
  1153. result.z = this.z + otherVector.z;
  1154. result.w = this.w + otherVector.w;
  1155. return this;
  1156. };
  1157. Vector4.prototype.subtractInPlace = function (otherVector) {
  1158. this.x -= otherVector.x;
  1159. this.y -= otherVector.y;
  1160. this.z -= otherVector.z;
  1161. this.w -= otherVector.w;
  1162. return this;
  1163. };
  1164. Vector4.prototype.subtract = function (otherVector) {
  1165. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1166. };
  1167. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1168. result.x = this.x - otherVector.x;
  1169. result.y = this.y - otherVector.y;
  1170. result.z = this.z - otherVector.z;
  1171. result.w = this.w - otherVector.w;
  1172. return this;
  1173. };
  1174. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1175. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1176. };
  1177. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1178. result.x = this.x - x;
  1179. result.y = this.y - y;
  1180. result.z = this.z - z;
  1181. result.w = this.w - w;
  1182. return this;
  1183. };
  1184. Vector4.prototype.negate = function () {
  1185. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1186. };
  1187. Vector4.prototype.scaleInPlace = function (scale) {
  1188. this.x *= scale;
  1189. this.y *= scale;
  1190. this.z *= scale;
  1191. this.w *= scale;
  1192. return this;
  1193. };
  1194. Vector4.prototype.scale = function (scale) {
  1195. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1196. };
  1197. Vector4.prototype.scaleToRef = function (scale, result) {
  1198. result.x = this.x * scale;
  1199. result.y = this.y * scale;
  1200. result.z = this.z * scale;
  1201. result.w = this.w * scale;
  1202. };
  1203. Vector4.prototype.equals = function (otherVector) {
  1204. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1205. };
  1206. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1207. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1208. return otherVector
  1209. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1210. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1211. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1212. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1213. };
  1214. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1215. return this.x === x && this.y === y && this.z === z && this.w === w;
  1216. };
  1217. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1218. this.x *= otherVector.x;
  1219. this.y *= otherVector.y;
  1220. this.z *= otherVector.z;
  1221. this.w *= otherVector.w;
  1222. return this;
  1223. };
  1224. Vector4.prototype.multiply = function (otherVector) {
  1225. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1226. };
  1227. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1228. result.x = this.x * otherVector.x;
  1229. result.y = this.y * otherVector.y;
  1230. result.z = this.z * otherVector.z;
  1231. result.w = this.w * otherVector.w;
  1232. return this;
  1233. };
  1234. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1235. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1236. };
  1237. Vector4.prototype.divide = function (otherVector) {
  1238. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1239. };
  1240. Vector4.prototype.divideToRef = function (otherVector, result) {
  1241. result.x = this.x / otherVector.x;
  1242. result.y = this.y / otherVector.y;
  1243. result.z = this.z / otherVector.z;
  1244. result.w = this.w / otherVector.w;
  1245. return this;
  1246. };
  1247. Vector4.prototype.MinimizeInPlace = function (other) {
  1248. if (other.x < this.x)
  1249. this.x = other.x;
  1250. if (other.y < this.y)
  1251. this.y = other.y;
  1252. if (other.z < this.z)
  1253. this.z = other.z;
  1254. if (other.w < this.w)
  1255. this.w = other.w;
  1256. return this;
  1257. };
  1258. Vector4.prototype.MaximizeInPlace = function (other) {
  1259. if (other.x > this.x)
  1260. this.x = other.x;
  1261. if (other.y > this.y)
  1262. this.y = other.y;
  1263. if (other.z > this.z)
  1264. this.z = other.z;
  1265. if (other.w > this.w)
  1266. this.w = other.w;
  1267. return this;
  1268. };
  1269. // Properties
  1270. Vector4.prototype.length = function () {
  1271. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1272. };
  1273. Vector4.prototype.lengthSquared = function () {
  1274. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1275. };
  1276. // Methods
  1277. Vector4.prototype.normalize = function () {
  1278. var len = this.length();
  1279. if (len === 0)
  1280. return this;
  1281. var num = 1.0 / len;
  1282. this.x *= num;
  1283. this.y *= num;
  1284. this.z *= num;
  1285. this.w *= num;
  1286. return this;
  1287. };
  1288. Vector4.prototype.toVector3 = function () {
  1289. return new Vector3(this.x, this.y, this.z);
  1290. };
  1291. Vector4.prototype.clone = function () {
  1292. return new Vector4(this.x, this.y, this.z, this.w);
  1293. };
  1294. Vector4.prototype.copyFrom = function (source) {
  1295. this.x = source.x;
  1296. this.y = source.y;
  1297. this.z = source.z;
  1298. this.w = source.w;
  1299. return this;
  1300. };
  1301. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1302. this.x = x;
  1303. this.y = y;
  1304. this.z = z;
  1305. this.w = w;
  1306. return this;
  1307. };
  1308. // Statics
  1309. Vector4.FromArray = function (array, offset) {
  1310. if (!offset) {
  1311. offset = 0;
  1312. }
  1313. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1314. };
  1315. Vector4.FromArrayToRef = function (array, offset, result) {
  1316. result.x = array[offset];
  1317. result.y = array[offset + 1];
  1318. result.z = array[offset + 2];
  1319. result.w = array[offset + 3];
  1320. };
  1321. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1322. result.x = array[offset];
  1323. result.y = array[offset + 1];
  1324. result.z = array[offset + 2];
  1325. result.w = array[offset + 3];
  1326. };
  1327. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1328. result.x = x;
  1329. result.y = y;
  1330. result.z = z;
  1331. result.w = w;
  1332. };
  1333. Vector4.Zero = function () {
  1334. return new Vector4(0, 0, 0, 0);
  1335. };
  1336. Vector4.Normalize = function (vector) {
  1337. var result = Vector4.Zero();
  1338. Vector4.NormalizeToRef(vector, result);
  1339. return result;
  1340. };
  1341. Vector4.NormalizeToRef = function (vector, result) {
  1342. result.copyFrom(vector);
  1343. result.normalize();
  1344. };
  1345. Vector4.Minimize = function (left, right) {
  1346. var min = left.clone();
  1347. min.MinimizeInPlace(right);
  1348. return min;
  1349. };
  1350. Vector4.Maximize = function (left, right) {
  1351. var max = left.clone();
  1352. max.MaximizeInPlace(right);
  1353. return max;
  1354. };
  1355. Vector4.Distance = function (value1, value2) {
  1356. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1357. };
  1358. Vector4.DistanceSquared = function (value1, value2) {
  1359. var x = value1.x - value2.x;
  1360. var y = value1.y - value2.y;
  1361. var z = value1.z - value2.z;
  1362. var w = value1.w - value2.w;
  1363. return (x * x) + (y * y) + (z * z) + (w * w);
  1364. };
  1365. Vector4.Center = function (value1, value2) {
  1366. var center = value1.add(value2);
  1367. center.scaleInPlace(0.5);
  1368. return center;
  1369. };
  1370. return Vector4;
  1371. })();
  1372. BABYLON.Vector4 = Vector4;
  1373. var Size = (function () {
  1374. function Size(width, height) {
  1375. this.width = width;
  1376. this.height = height;
  1377. }
  1378. Size.prototype.toString = function () {
  1379. return "{W: " + this.width + ", H: " + this.height + "}";
  1380. };
  1381. Size.prototype.getClassName = function () {
  1382. return "Size";
  1383. };
  1384. Size.prototype.getHashCode = function () {
  1385. var hash = this.width || 0;
  1386. hash = (hash * 397) ^ (this.height || 0);
  1387. return hash;
  1388. };
  1389. Size.prototype.copyFrom = function (src) {
  1390. this.width = src.width;
  1391. this.height = src.height;
  1392. };
  1393. Size.prototype.clone = function () {
  1394. return new Size(this.width, this.height);
  1395. };
  1396. Size.prototype.equals = function (other) {
  1397. if (!other) {
  1398. return false;
  1399. }
  1400. return (this.width === other.width) && (this.height === other.height);
  1401. };
  1402. Object.defineProperty(Size.prototype, "surface", {
  1403. get: function () {
  1404. return this.width * this.height;
  1405. },
  1406. enumerable: true,
  1407. configurable: true
  1408. });
  1409. Size.Zero = function () {
  1410. return new Size(0, 0);
  1411. };
  1412. Size.prototype.add = function (otherSize) {
  1413. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1414. return r;
  1415. };
  1416. Size.prototype.substract = function (otherSize) {
  1417. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1418. return r;
  1419. };
  1420. Size.Lerp = function (start, end, amount) {
  1421. var w = start.width + ((end.width - start.width) * amount);
  1422. var h = start.height + ((end.height - start.height) * amount);
  1423. return new Size(w, h);
  1424. };
  1425. return Size;
  1426. })();
  1427. BABYLON.Size = Size;
  1428. var Quaternion = (function () {
  1429. function Quaternion(x, y, z, w) {
  1430. if (x === void 0) { x = 0; }
  1431. if (y === void 0) { y = 0; }
  1432. if (z === void 0) { z = 0; }
  1433. if (w === void 0) { w = 1; }
  1434. this.x = x;
  1435. this.y = y;
  1436. this.z = z;
  1437. this.w = w;
  1438. }
  1439. Quaternion.prototype.toString = function () {
  1440. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1441. };
  1442. Quaternion.prototype.getClassName = function () {
  1443. return "Quaternion";
  1444. };
  1445. Quaternion.prototype.getHashCode = function () {
  1446. var hash = this.x || 0;
  1447. hash = (hash * 397) ^ (this.y || 0);
  1448. hash = (hash * 397) ^ (this.z || 0);
  1449. hash = (hash * 397) ^ (this.w || 0);
  1450. return hash;
  1451. };
  1452. Quaternion.prototype.asArray = function () {
  1453. return [this.x, this.y, this.z, this.w];
  1454. };
  1455. Quaternion.prototype.equals = function (otherQuaternion) {
  1456. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1457. };
  1458. Quaternion.prototype.clone = function () {
  1459. return new Quaternion(this.x, this.y, this.z, this.w);
  1460. };
  1461. Quaternion.prototype.copyFrom = function (other) {
  1462. this.x = other.x;
  1463. this.y = other.y;
  1464. this.z = other.z;
  1465. this.w = other.w;
  1466. return this;
  1467. };
  1468. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1469. this.x = x;
  1470. this.y = y;
  1471. this.z = z;
  1472. this.w = w;
  1473. return this;
  1474. };
  1475. Quaternion.prototype.add = function (other) {
  1476. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1477. };
  1478. Quaternion.prototype.subtract = function (other) {
  1479. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1480. };
  1481. Quaternion.prototype.scale = function (value) {
  1482. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1483. };
  1484. Quaternion.prototype.multiply = function (q1) {
  1485. var result = new Quaternion(0, 0, 0, 1.0);
  1486. this.multiplyToRef(q1, result);
  1487. return result;
  1488. };
  1489. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1490. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1491. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1492. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1493. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1494. result.copyFromFloats(x, y, z, w);
  1495. return this;
  1496. };
  1497. Quaternion.prototype.multiplyInPlace = function (q1) {
  1498. this.multiplyToRef(q1, this);
  1499. return this;
  1500. };
  1501. Quaternion.prototype.conjugateToRef = function (ref) {
  1502. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1503. return this;
  1504. };
  1505. Quaternion.prototype.conjugateInPlace = function () {
  1506. this.x *= -1;
  1507. this.y *= -1;
  1508. this.z *= -1;
  1509. return this;
  1510. };
  1511. Quaternion.prototype.conjugate = function () {
  1512. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1513. return result;
  1514. };
  1515. Quaternion.prototype.length = function () {
  1516. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1517. };
  1518. Quaternion.prototype.normalize = function () {
  1519. var length = 1.0 / this.length();
  1520. this.x *= length;
  1521. this.y *= length;
  1522. this.z *= length;
  1523. this.w *= length;
  1524. return this;
  1525. };
  1526. Quaternion.prototype.toEulerAngles = function (order) {
  1527. if (order === void 0) { order = "YZX"; }
  1528. var result = Vector3.Zero();
  1529. this.toEulerAnglesToRef(result, order);
  1530. return result;
  1531. };
  1532. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1533. if (order === void 0) { order = "YZX"; }
  1534. var heading, attitude, bank;
  1535. var x = this.x, y = this.y, z = this.z, w = this.w;
  1536. switch (order) {
  1537. case "YZX":
  1538. var test = x * y + z * w;
  1539. if (test > 0.499) {
  1540. heading = 2 * Math.atan2(x, w);
  1541. attitude = Math.PI / 2;
  1542. bank = 0;
  1543. }
  1544. if (test < -0.499) {
  1545. heading = -2 * Math.atan2(x, w);
  1546. attitude = -Math.PI / 2;
  1547. bank = 0;
  1548. }
  1549. if (isNaN(heading)) {
  1550. var sqx = x * x;
  1551. var sqy = y * y;
  1552. var sqz = z * z;
  1553. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1554. attitude = Math.asin(2 * test); // attitude
  1555. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1556. }
  1557. break;
  1558. default:
  1559. throw new Error("Euler order " + order + " not supported yet.");
  1560. }
  1561. result.y = heading;
  1562. result.z = attitude;
  1563. result.x = bank;
  1564. return this;
  1565. };
  1566. ;
  1567. Quaternion.prototype.toRotationMatrix = function (result) {
  1568. var xx = this.x * this.x;
  1569. var yy = this.y * this.y;
  1570. var zz = this.z * this.z;
  1571. var xy = this.x * this.y;
  1572. var zw = this.z * this.w;
  1573. var zx = this.z * this.x;
  1574. var yw = this.y * this.w;
  1575. var yz = this.y * this.z;
  1576. var xw = this.x * this.w;
  1577. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1578. result.m[1] = 2.0 * (xy + zw);
  1579. result.m[2] = 2.0 * (zx - yw);
  1580. result.m[3] = 0;
  1581. result.m[4] = 2.0 * (xy - zw);
  1582. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1583. result.m[6] = 2.0 * (yz + xw);
  1584. result.m[7] = 0;
  1585. result.m[8] = 2.0 * (zx + yw);
  1586. result.m[9] = 2.0 * (yz - xw);
  1587. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1588. result.m[11] = 0;
  1589. result.m[12] = 0;
  1590. result.m[13] = 0;
  1591. result.m[14] = 0;
  1592. result.m[15] = 1.0;
  1593. return this;
  1594. };
  1595. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1596. Quaternion.FromRotationMatrixToRef(matrix, this);
  1597. return this;
  1598. };
  1599. // Statics
  1600. Quaternion.FromRotationMatrix = function (matrix) {
  1601. var result = new Quaternion();
  1602. Quaternion.FromRotationMatrixToRef(matrix, result);
  1603. return result;
  1604. };
  1605. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1606. var data = matrix.m;
  1607. var m11 = data[0], m12 = data[4], m13 = data[8];
  1608. var m21 = data[1], m22 = data[5], m23 = data[9];
  1609. var m31 = data[2], m32 = data[6], m33 = data[10];
  1610. var trace = m11 + m22 + m33;
  1611. var s;
  1612. if (trace > 0) {
  1613. s = 0.5 / Math.sqrt(trace + 1.0);
  1614. result.w = 0.25 / s;
  1615. result.x = (m32 - m23) * s;
  1616. result.y = (m13 - m31) * s;
  1617. result.z = (m21 - m12) * s;
  1618. }
  1619. else if (m11 > m22 && m11 > m33) {
  1620. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1621. result.w = (m32 - m23) / s;
  1622. result.x = 0.25 * s;
  1623. result.y = (m12 + m21) / s;
  1624. result.z = (m13 + m31) / s;
  1625. }
  1626. else if (m22 > m33) {
  1627. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1628. result.w = (m13 - m31) / s;
  1629. result.x = (m12 + m21) / s;
  1630. result.y = 0.25 * s;
  1631. result.z = (m23 + m32) / s;
  1632. }
  1633. else {
  1634. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1635. result.w = (m21 - m12) / s;
  1636. result.x = (m13 + m31) / s;
  1637. result.y = (m23 + m32) / s;
  1638. result.z = 0.25 * s;
  1639. }
  1640. };
  1641. Quaternion.Inverse = function (q) {
  1642. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1643. };
  1644. Quaternion.Identity = function () {
  1645. return new Quaternion(0, 0, 0, 1);
  1646. };
  1647. Quaternion.RotationAxis = function (axis, angle) {
  1648. var result = new Quaternion();
  1649. var sin = Math.sin(angle / 2);
  1650. axis.normalize();
  1651. result.w = Math.cos(angle / 2);
  1652. result.x = axis.x * sin;
  1653. result.y = axis.y * sin;
  1654. result.z = axis.z * sin;
  1655. return result;
  1656. };
  1657. Quaternion.FromArray = function (array, offset) {
  1658. if (!offset) {
  1659. offset = 0;
  1660. }
  1661. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1662. };
  1663. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1664. var result = new Quaternion();
  1665. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1666. return result;
  1667. };
  1668. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1669. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1670. var halfRoll = roll * 0.5;
  1671. var halfPitch = pitch * 0.5;
  1672. var halfYaw = yaw * 0.5;
  1673. var sinRoll = Math.sin(halfRoll);
  1674. var cosRoll = Math.cos(halfRoll);
  1675. var sinPitch = Math.sin(halfPitch);
  1676. var cosPitch = Math.cos(halfPitch);
  1677. var sinYaw = Math.sin(halfYaw);
  1678. var cosYaw = Math.cos(halfYaw);
  1679. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1680. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1681. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1682. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1683. };
  1684. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1685. var result = new Quaternion();
  1686. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1687. return result;
  1688. };
  1689. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1690. // Produces a quaternion from Euler angles in the z-x-z orientation
  1691. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1692. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1693. var halfBeta = beta * 0.5;
  1694. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1695. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1696. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1697. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1698. };
  1699. Quaternion.Slerp = function (left, right, amount) {
  1700. var num2;
  1701. var num3;
  1702. var num = amount;
  1703. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1704. var flag = false;
  1705. if (num4 < 0) {
  1706. flag = true;
  1707. num4 = -num4;
  1708. }
  1709. if (num4 > 0.999999) {
  1710. num3 = 1 - num;
  1711. num2 = flag ? -num : num;
  1712. }
  1713. else {
  1714. var num5 = Math.acos(num4);
  1715. var num6 = (1.0 / Math.sin(num5));
  1716. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1717. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1718. }
  1719. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1720. };
  1721. return Quaternion;
  1722. })();
  1723. BABYLON.Quaternion = Quaternion;
  1724. var Matrix = (function () {
  1725. function Matrix() {
  1726. this.m = new Float32Array(16);
  1727. }
  1728. // Properties
  1729. Matrix.prototype.isIdentity = function () {
  1730. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1731. return false;
  1732. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1733. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1734. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1735. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1736. return false;
  1737. return true;
  1738. };
  1739. Matrix.prototype.determinant = function () {
  1740. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1741. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1742. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1743. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1744. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1745. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1746. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1747. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1748. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1749. };
  1750. // Methods
  1751. Matrix.prototype.toArray = function () {
  1752. return this.m;
  1753. };
  1754. Matrix.prototype.asArray = function () {
  1755. return this.toArray();
  1756. };
  1757. Matrix.prototype.invert = function () {
  1758. this.invertToRef(this);
  1759. return this;
  1760. };
  1761. Matrix.prototype.reset = function () {
  1762. for (var index = 0; index < 16; index++) {
  1763. this.m[index] = 0;
  1764. }
  1765. return this;
  1766. };
  1767. Matrix.prototype.add = function (other) {
  1768. var result = new Matrix();
  1769. this.addToRef(other, result);
  1770. return result;
  1771. };
  1772. Matrix.prototype.addToRef = function (other, result) {
  1773. for (var index = 0; index < 16; index++) {
  1774. result.m[index] = this.m[index] + other.m[index];
  1775. }
  1776. return this;
  1777. };
  1778. Matrix.prototype.addToSelf = function (other) {
  1779. for (var index = 0; index < 16; index++) {
  1780. this.m[index] += other.m[index];
  1781. }
  1782. return this;
  1783. };
  1784. Matrix.prototype.invertToRef = function (other) {
  1785. var l1 = this.m[0];
  1786. var l2 = this.m[1];
  1787. var l3 = this.m[2];
  1788. var l4 = this.m[3];
  1789. var l5 = this.m[4];
  1790. var l6 = this.m[5];
  1791. var l7 = this.m[6];
  1792. var l8 = this.m[7];
  1793. var l9 = this.m[8];
  1794. var l10 = this.m[9];
  1795. var l11 = this.m[10];
  1796. var l12 = this.m[11];
  1797. var l13 = this.m[12];
  1798. var l14 = this.m[13];
  1799. var l15 = this.m[14];
  1800. var l16 = this.m[15];
  1801. var l17 = (l11 * l16) - (l12 * l15);
  1802. var l18 = (l10 * l16) - (l12 * l14);
  1803. var l19 = (l10 * l15) - (l11 * l14);
  1804. var l20 = (l9 * l16) - (l12 * l13);
  1805. var l21 = (l9 * l15) - (l11 * l13);
  1806. var l22 = (l9 * l14) - (l10 * l13);
  1807. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1808. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1809. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1810. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1811. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1812. var l28 = (l7 * l16) - (l8 * l15);
  1813. var l29 = (l6 * l16) - (l8 * l14);
  1814. var l30 = (l6 * l15) - (l7 * l14);
  1815. var l31 = (l5 * l16) - (l8 * l13);
  1816. var l32 = (l5 * l15) - (l7 * l13);
  1817. var l33 = (l5 * l14) - (l6 * l13);
  1818. var l34 = (l7 * l12) - (l8 * l11);
  1819. var l35 = (l6 * l12) - (l8 * l10);
  1820. var l36 = (l6 * l11) - (l7 * l10);
  1821. var l37 = (l5 * l12) - (l8 * l9);
  1822. var l38 = (l5 * l11) - (l7 * l9);
  1823. var l39 = (l5 * l10) - (l6 * l9);
  1824. other.m[0] = l23 * l27;
  1825. other.m[4] = l24 * l27;
  1826. other.m[8] = l25 * l27;
  1827. other.m[12] = l26 * l27;
  1828. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1829. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1830. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1831. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1832. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1833. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1834. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1835. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1836. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1837. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1838. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1839. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1840. return this;
  1841. };
  1842. Matrix.prototype.setTranslation = function (vector3) {
  1843. this.m[12] = vector3.x;
  1844. this.m[13] = vector3.y;
  1845. this.m[14] = vector3.z;
  1846. return this;
  1847. };
  1848. Matrix.prototype.getTranslation = function () {
  1849. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1850. };
  1851. Matrix.prototype.multiply = function (other) {
  1852. var result = new Matrix();
  1853. this.multiplyToRef(other, result);
  1854. return result;
  1855. };
  1856. Matrix.prototype.copyFrom = function (other) {
  1857. for (var index = 0; index < 16; index++) {
  1858. this.m[index] = other.m[index];
  1859. }
  1860. return this;
  1861. };
  1862. Matrix.prototype.copyToArray = function (array, offset) {
  1863. if (offset === void 0) { offset = 0; }
  1864. for (var index = 0; index < 16; index++) {
  1865. array[offset + index] = this.m[index];
  1866. }
  1867. return this;
  1868. };
  1869. Matrix.prototype.multiplyToRef = function (other, result) {
  1870. this.multiplyToArray(other, result.m, 0);
  1871. return this;
  1872. };
  1873. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1874. var tm0 = this.m[0];
  1875. var tm1 = this.m[1];
  1876. var tm2 = this.m[2];
  1877. var tm3 = this.m[3];
  1878. var tm4 = this.m[4];
  1879. var tm5 = this.m[5];
  1880. var tm6 = this.m[6];
  1881. var tm7 = this.m[7];
  1882. var tm8 = this.m[8];
  1883. var tm9 = this.m[9];
  1884. var tm10 = this.m[10];
  1885. var tm11 = this.m[11];
  1886. var tm12 = this.m[12];
  1887. var tm13 = this.m[13];
  1888. var tm14 = this.m[14];
  1889. var tm15 = this.m[15];
  1890. var om0 = other.m[0];
  1891. var om1 = other.m[1];
  1892. var om2 = other.m[2];
  1893. var om3 = other.m[3];
  1894. var om4 = other.m[4];
  1895. var om5 = other.m[5];
  1896. var om6 = other.m[6];
  1897. var om7 = other.m[7];
  1898. var om8 = other.m[8];
  1899. var om9 = other.m[9];
  1900. var om10 = other.m[10];
  1901. var om11 = other.m[11];
  1902. var om12 = other.m[12];
  1903. var om13 = other.m[13];
  1904. var om14 = other.m[14];
  1905. var om15 = other.m[15];
  1906. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1907. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1908. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1909. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1910. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1911. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1912. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1913. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1914. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1915. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1916. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1917. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1918. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1919. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1920. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1921. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1922. return this;
  1923. };
  1924. Matrix.prototype.equals = function (value) {
  1925. return value &&
  1926. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1927. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1928. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1929. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1930. };
  1931. Matrix.prototype.clone = function () {
  1932. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1933. };
  1934. Matrix.prototype.getClassName = function () {
  1935. return "Matrix";
  1936. };
  1937. Matrix.prototype.getHashCode = function () {
  1938. var hash = this.m[0] || 0;
  1939. for (var i = 1; i < 16; i++) {
  1940. hash = (hash * 397) ^ (this.m[i] || 0);
  1941. }
  1942. return hash;
  1943. };
  1944. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1945. translation.x = this.m[12];
  1946. translation.y = this.m[13];
  1947. translation.z = this.m[14];
  1948. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1949. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1950. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1951. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1952. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1953. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1954. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1955. rotation.x = 0;
  1956. rotation.y = 0;
  1957. rotation.z = 0;
  1958. rotation.w = 1;
  1959. return false;
  1960. }
  1961. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1962. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1963. return true;
  1964. };
  1965. // Statics
  1966. Matrix.FromArray = function (array, offset) {
  1967. var result = new Matrix();
  1968. if (!offset) {
  1969. offset = 0;
  1970. }
  1971. Matrix.FromArrayToRef(array, offset, result);
  1972. return result;
  1973. };
  1974. Matrix.FromArrayToRef = function (array, offset, result) {
  1975. for (var index = 0; index < 16; index++) {
  1976. result.m[index] = array[index + offset];
  1977. }
  1978. };
  1979. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1980. for (var index = 0; index < 16; index++) {
  1981. result.m[index] = array[index + offset] * scale;
  1982. }
  1983. };
  1984. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1985. result.m[0] = initialM11;
  1986. result.m[1] = initialM12;
  1987. result.m[2] = initialM13;
  1988. result.m[3] = initialM14;
  1989. result.m[4] = initialM21;
  1990. result.m[5] = initialM22;
  1991. result.m[6] = initialM23;
  1992. result.m[7] = initialM24;
  1993. result.m[8] = initialM31;
  1994. result.m[9] = initialM32;
  1995. result.m[10] = initialM33;
  1996. result.m[11] = initialM34;
  1997. result.m[12] = initialM41;
  1998. result.m[13] = initialM42;
  1999. result.m[14] = initialM43;
  2000. result.m[15] = initialM44;
  2001. };
  2002. Matrix.prototype.getRow = function (index) {
  2003. if (index < 0 || index > 3) {
  2004. return null;
  2005. }
  2006. var i = index * 4;
  2007. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2008. };
  2009. Matrix.prototype.setRow = function (index, row) {
  2010. if (index < 0 || index > 3) {
  2011. return this;
  2012. }
  2013. var i = index * 4;
  2014. this.m[i + 0] = row.x;
  2015. this.m[i + 1] = row.y;
  2016. this.m[i + 2] = row.z;
  2017. this.m[i + 3] = row.w;
  2018. return this;
  2019. };
  2020. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2021. var result = new Matrix();
  2022. result.m[0] = initialM11;
  2023. result.m[1] = initialM12;
  2024. result.m[2] = initialM13;
  2025. result.m[3] = initialM14;
  2026. result.m[4] = initialM21;
  2027. result.m[5] = initialM22;
  2028. result.m[6] = initialM23;
  2029. result.m[7] = initialM24;
  2030. result.m[8] = initialM31;
  2031. result.m[9] = initialM32;
  2032. result.m[10] = initialM33;
  2033. result.m[11] = initialM34;
  2034. result.m[12] = initialM41;
  2035. result.m[13] = initialM42;
  2036. result.m[14] = initialM43;
  2037. result.m[15] = initialM44;
  2038. return result;
  2039. };
  2040. Matrix.Compose = function (scale, rotation, translation) {
  2041. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2042. var rotationMatrix = Matrix.Identity();
  2043. rotation.toRotationMatrix(rotationMatrix);
  2044. result = result.multiply(rotationMatrix);
  2045. result.setTranslation(translation);
  2046. return result;
  2047. };
  2048. Matrix.Identity = function () {
  2049. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2050. };
  2051. Matrix.IdentityToRef = function (result) {
  2052. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2053. };
  2054. Matrix.Zero = function () {
  2055. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2056. };
  2057. Matrix.RotationX = function (angle) {
  2058. var result = new Matrix();
  2059. Matrix.RotationXToRef(angle, result);
  2060. return result;
  2061. };
  2062. Matrix.Invert = function (source) {
  2063. var result = new Matrix();
  2064. source.invertToRef(result);
  2065. return result;
  2066. };
  2067. Matrix.RotationXToRef = function (angle, result) {
  2068. var s = Math.sin(angle);
  2069. var c = Math.cos(angle);
  2070. result.m[0] = 1.0;
  2071. result.m[15] = 1.0;
  2072. result.m[5] = c;
  2073. result.m[10] = c;
  2074. result.m[9] = -s;
  2075. result.m[6] = s;
  2076. result.m[1] = 0;
  2077. result.m[2] = 0;
  2078. result.m[3] = 0;
  2079. result.m[4] = 0;
  2080. result.m[7] = 0;
  2081. result.m[8] = 0;
  2082. result.m[11] = 0;
  2083. result.m[12] = 0;
  2084. result.m[13] = 0;
  2085. result.m[14] = 0;
  2086. };
  2087. Matrix.RotationY = function (angle) {
  2088. var result = new Matrix();
  2089. Matrix.RotationYToRef(angle, result);
  2090. return result;
  2091. };
  2092. Matrix.RotationYToRef = function (angle, result) {
  2093. var s = Math.sin(angle);
  2094. var c = Math.cos(angle);
  2095. result.m[5] = 1.0;
  2096. result.m[15] = 1.0;
  2097. result.m[0] = c;
  2098. result.m[2] = -s;
  2099. result.m[8] = s;
  2100. result.m[10] = c;
  2101. result.m[1] = 0;
  2102. result.m[3] = 0;
  2103. result.m[4] = 0;
  2104. result.m[6] = 0;
  2105. result.m[7] = 0;
  2106. result.m[9] = 0;
  2107. result.m[11] = 0;
  2108. result.m[12] = 0;
  2109. result.m[13] = 0;
  2110. result.m[14] = 0;
  2111. };
  2112. Matrix.RotationZ = function (angle) {
  2113. var result = new Matrix();
  2114. Matrix.RotationZToRef(angle, result);
  2115. return result;
  2116. };
  2117. Matrix.RotationZToRef = function (angle, result) {
  2118. var s = Math.sin(angle);
  2119. var c = Math.cos(angle);
  2120. result.m[10] = 1.0;
  2121. result.m[15] = 1.0;
  2122. result.m[0] = c;
  2123. result.m[1] = s;
  2124. result.m[4] = -s;
  2125. result.m[5] = c;
  2126. result.m[2] = 0;
  2127. result.m[3] = 0;
  2128. result.m[6] = 0;
  2129. result.m[7] = 0;
  2130. result.m[8] = 0;
  2131. result.m[9] = 0;
  2132. result.m[11] = 0;
  2133. result.m[12] = 0;
  2134. result.m[13] = 0;
  2135. result.m[14] = 0;
  2136. };
  2137. Matrix.RotationAxis = function (axis, angle) {
  2138. var result = Matrix.Zero();
  2139. Matrix.RotationAxisToRef(axis, angle, result);
  2140. return result;
  2141. };
  2142. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2143. var s = Math.sin(-angle);
  2144. var c = Math.cos(-angle);
  2145. var c1 = 1 - c;
  2146. axis.normalize();
  2147. result.m[0] = (axis.x * axis.x) * c1 + c;
  2148. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2149. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2150. result.m[3] = 0.0;
  2151. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2152. result.m[5] = (axis.y * axis.y) * c1 + c;
  2153. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2154. result.m[7] = 0.0;
  2155. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2156. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2157. result.m[10] = (axis.z * axis.z) * c1 + c;
  2158. result.m[11] = 0.0;
  2159. result.m[15] = 1.0;
  2160. };
  2161. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2162. var result = new Matrix();
  2163. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2164. return result;
  2165. };
  2166. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2167. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2168. this._tempQuaternion.toRotationMatrix(result);
  2169. };
  2170. Matrix.Scaling = function (x, y, z) {
  2171. var result = Matrix.Zero();
  2172. Matrix.ScalingToRef(x, y, z, result);
  2173. return result;
  2174. };
  2175. Matrix.ScalingToRef = function (x, y, z, result) {
  2176. result.m[0] = x;
  2177. result.m[1] = 0;
  2178. result.m[2] = 0;
  2179. result.m[3] = 0;
  2180. result.m[4] = 0;
  2181. result.m[5] = y;
  2182. result.m[6] = 0;
  2183. result.m[7] = 0;
  2184. result.m[8] = 0;
  2185. result.m[9] = 0;
  2186. result.m[10] = z;
  2187. result.m[11] = 0;
  2188. result.m[12] = 0;
  2189. result.m[13] = 0;
  2190. result.m[14] = 0;
  2191. result.m[15] = 1.0;
  2192. };
  2193. Matrix.Translation = function (x, y, z) {
  2194. var result = Matrix.Identity();
  2195. Matrix.TranslationToRef(x, y, z, result);
  2196. return result;
  2197. };
  2198. Matrix.TranslationToRef = function (x, y, z, result) {
  2199. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2200. };
  2201. Matrix.Lerp = function (startValue, endValue, gradient) {
  2202. var result = Matrix.Zero();
  2203. for (var index = 0; index < 16; index++) {
  2204. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2205. }
  2206. return result;
  2207. };
  2208. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2209. var startScale = new Vector3(0, 0, 0);
  2210. var startRotation = new Quaternion();
  2211. var startTranslation = new Vector3(0, 0, 0);
  2212. startValue.decompose(startScale, startRotation, startTranslation);
  2213. var endScale = new Vector3(0, 0, 0);
  2214. var endRotation = new Quaternion();
  2215. var endTranslation = new Vector3(0, 0, 0);
  2216. endValue.decompose(endScale, endRotation, endTranslation);
  2217. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2218. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2219. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2220. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2221. };
  2222. Matrix.LookAtLH = function (eye, target, up) {
  2223. var result = Matrix.Zero();
  2224. Matrix.LookAtLHToRef(eye, target, up, result);
  2225. return result;
  2226. };
  2227. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2228. // Z axis
  2229. target.subtractToRef(eye, this._zAxis);
  2230. this._zAxis.normalize();
  2231. // X axis
  2232. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2233. if (this._xAxis.lengthSquared() === 0) {
  2234. this._xAxis.x = 1.0;
  2235. }
  2236. else {
  2237. this._xAxis.normalize();
  2238. }
  2239. // Y axis
  2240. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2241. this._yAxis.normalize();
  2242. // Eye angles
  2243. var ex = -Vector3.Dot(this._xAxis, eye);
  2244. var ey = -Vector3.Dot(this._yAxis, eye);
  2245. var ez = -Vector3.Dot(this._zAxis, eye);
  2246. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2247. };
  2248. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2249. var matrix = Matrix.Zero();
  2250. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2251. return matrix;
  2252. };
  2253. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2254. var hw = 2.0 / width;
  2255. var hh = 2.0 / height;
  2256. var id = 1.0 / (zfar - znear);
  2257. var nid = znear / (znear - zfar);
  2258. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2259. };
  2260. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2261. var matrix = Matrix.Zero();
  2262. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2263. return matrix;
  2264. };
  2265. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2266. result.m[0] = 2.0 / (right - left);
  2267. result.m[1] = result.m[2] = result.m[3] = 0;
  2268. result.m[5] = 2.0 / (top - bottom);
  2269. result.m[4] = result.m[6] = result.m[7] = 0;
  2270. result.m[10] = -1.0 / (znear - zfar);
  2271. result.m[8] = result.m[9] = result.m[11] = 0;
  2272. result.m[12] = (left + right) / (left - right);
  2273. result.m[13] = (top + bottom) / (bottom - top);
  2274. result.m[14] = znear / (znear - zfar);
  2275. result.m[15] = 1.0;
  2276. };
  2277. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2278. var matrix = Matrix.Zero();
  2279. matrix.m[0] = (2.0 * znear) / width;
  2280. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2281. matrix.m[5] = (2.0 * znear) / height;
  2282. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2283. matrix.m[10] = -zfar / (znear - zfar);
  2284. matrix.m[8] = matrix.m[9] = 0.0;
  2285. matrix.m[11] = 1.0;
  2286. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2287. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2288. return matrix;
  2289. };
  2290. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2291. var matrix = Matrix.Zero();
  2292. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2293. return matrix;
  2294. };
  2295. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2296. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2297. var tan = 1.0 / (Math.tan(fov * 0.5));
  2298. if (isVerticalFovFixed) {
  2299. result.m[0] = tan / aspect;
  2300. }
  2301. else {
  2302. result.m[0] = tan;
  2303. }
  2304. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2305. if (isVerticalFovFixed) {
  2306. result.m[5] = tan;
  2307. }
  2308. else {
  2309. result.m[5] = tan * aspect;
  2310. }
  2311. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2312. result.m[8] = result.m[9] = 0.0;
  2313. result.m[10] = -zfar / (znear - zfar);
  2314. result.m[11] = 1.0;
  2315. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2316. result.m[14] = (znear * zfar) / (znear - zfar);
  2317. };
  2318. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2319. var cw = viewport.width;
  2320. var ch = viewport.height;
  2321. var cx = viewport.x;
  2322. var cy = viewport.y;
  2323. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2324. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2325. };
  2326. Matrix.GetAsMatrix2x2 = function (matrix) {
  2327. return new Float32Array([
  2328. matrix.m[0], matrix.m[1],
  2329. matrix.m[4], matrix.m[5]
  2330. ]);
  2331. };
  2332. Matrix.GetAsMatrix3x3 = function (matrix) {
  2333. return new Float32Array([
  2334. matrix.m[0], matrix.m[1], matrix.m[2],
  2335. matrix.m[4], matrix.m[5], matrix.m[6],
  2336. matrix.m[8], matrix.m[9], matrix.m[10]
  2337. ]);
  2338. };
  2339. Matrix.Transpose = function (matrix) {
  2340. var result = new Matrix();
  2341. result.m[0] = matrix.m[0];
  2342. result.m[1] = matrix.m[4];
  2343. result.m[2] = matrix.m[8];
  2344. result.m[3] = matrix.m[12];
  2345. result.m[4] = matrix.m[1];
  2346. result.m[5] = matrix.m[5];
  2347. result.m[6] = matrix.m[9];
  2348. result.m[7] = matrix.m[13];
  2349. result.m[8] = matrix.m[2];
  2350. result.m[9] = matrix.m[6];
  2351. result.m[10] = matrix.m[10];
  2352. result.m[11] = matrix.m[14];
  2353. result.m[12] = matrix.m[3];
  2354. result.m[13] = matrix.m[7];
  2355. result.m[14] = matrix.m[11];
  2356. result.m[15] = matrix.m[15];
  2357. return result;
  2358. };
  2359. Matrix.Reflection = function (plane) {
  2360. var matrix = new Matrix();
  2361. Matrix.ReflectionToRef(plane, matrix);
  2362. return matrix;
  2363. };
  2364. Matrix.ReflectionToRef = function (plane, result) {
  2365. plane.normalize();
  2366. var x = plane.normal.x;
  2367. var y = plane.normal.y;
  2368. var z = plane.normal.z;
  2369. var temp = -2 * x;
  2370. var temp2 = -2 * y;
  2371. var temp3 = -2 * z;
  2372. result.m[0] = (temp * x) + 1;
  2373. result.m[1] = temp2 * x;
  2374. result.m[2] = temp3 * x;
  2375. result.m[3] = 0.0;
  2376. result.m[4] = temp * y;
  2377. result.m[5] = (temp2 * y) + 1;
  2378. result.m[6] = temp3 * y;
  2379. result.m[7] = 0.0;
  2380. result.m[8] = temp * z;
  2381. result.m[9] = temp2 * z;
  2382. result.m[10] = (temp3 * z) + 1;
  2383. result.m[11] = 0.0;
  2384. result.m[12] = temp * plane.d;
  2385. result.m[13] = temp2 * plane.d;
  2386. result.m[14] = temp3 * plane.d;
  2387. result.m[15] = 1.0;
  2388. };
  2389. Matrix._tempQuaternion = new Quaternion();
  2390. Matrix._xAxis = Vector3.Zero();
  2391. Matrix._yAxis = Vector3.Zero();
  2392. Matrix._zAxis = Vector3.Zero();
  2393. return Matrix;
  2394. })();
  2395. BABYLON.Matrix = Matrix;
  2396. var Plane = (function () {
  2397. function Plane(a, b, c, d) {
  2398. this.normal = new Vector3(a, b, c);
  2399. this.d = d;
  2400. }
  2401. Plane.prototype.asArray = function () {
  2402. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2403. };
  2404. // Methods
  2405. Plane.prototype.clone = function () {
  2406. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2407. };
  2408. Plane.prototype.getClassName = function () {
  2409. return "Plane";
  2410. };
  2411. Plane.prototype.getHashCode = function () {
  2412. var hash = this.normal.getHashCode();
  2413. hash = (hash * 397) ^ (this.d || 0);
  2414. return hash;
  2415. };
  2416. Plane.prototype.normalize = function () {
  2417. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2418. var magnitude = 0;
  2419. if (norm !== 0) {
  2420. magnitude = 1.0 / norm;
  2421. }
  2422. this.normal.x *= magnitude;
  2423. this.normal.y *= magnitude;
  2424. this.normal.z *= magnitude;
  2425. this.d *= magnitude;
  2426. return this;
  2427. };
  2428. Plane.prototype.transform = function (transformation) {
  2429. var transposedMatrix = Matrix.Transpose(transformation);
  2430. var x = this.normal.x;
  2431. var y = this.normal.y;
  2432. var z = this.normal.z;
  2433. var d = this.d;
  2434. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2435. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2436. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2437. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2438. return new Plane(normalX, normalY, normalZ, finalD);
  2439. };
  2440. Plane.prototype.dotCoordinate = function (point) {
  2441. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2442. };
  2443. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2444. var x1 = point2.x - point1.x;
  2445. var y1 = point2.y - point1.y;
  2446. var z1 = point2.z - point1.z;
  2447. var x2 = point3.x - point1.x;
  2448. var y2 = point3.y - point1.y;
  2449. var z2 = point3.z - point1.z;
  2450. var yz = (y1 * z2) - (z1 * y2);
  2451. var xz = (z1 * x2) - (x1 * z2);
  2452. var xy = (x1 * y2) - (y1 * x2);
  2453. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2454. var invPyth;
  2455. if (pyth !== 0) {
  2456. invPyth = 1.0 / pyth;
  2457. }
  2458. else {
  2459. invPyth = 0;
  2460. }
  2461. this.normal.x = yz * invPyth;
  2462. this.normal.y = xz * invPyth;
  2463. this.normal.z = xy * invPyth;
  2464. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2465. return this;
  2466. };
  2467. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2468. var dot = Vector3.Dot(this.normal, direction);
  2469. return (dot <= epsilon);
  2470. };
  2471. Plane.prototype.signedDistanceTo = function (point) {
  2472. return Vector3.Dot(point, this.normal) + this.d;
  2473. };
  2474. // Statics
  2475. Plane.FromArray = function (array) {
  2476. return new Plane(array[0], array[1], array[2], array[3]);
  2477. };
  2478. Plane.FromPoints = function (point1, point2, point3) {
  2479. var result = new Plane(0, 0, 0, 0);
  2480. result.copyFromPoints(point1, point2, point3);
  2481. return result;
  2482. };
  2483. Plane.FromPositionAndNormal = function (origin, normal) {
  2484. var result = new Plane(0, 0, 0, 0);
  2485. normal.normalize();
  2486. result.normal = normal;
  2487. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2488. return result;
  2489. };
  2490. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2491. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2492. return Vector3.Dot(point, normal) + d;
  2493. };
  2494. return Plane;
  2495. })();
  2496. BABYLON.Plane = Plane;
  2497. var Viewport = (function () {
  2498. function Viewport(x, y, width, height) {
  2499. this.x = x;
  2500. this.y = y;
  2501. this.width = width;
  2502. this.height = height;
  2503. }
  2504. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2505. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2506. };
  2507. return Viewport;
  2508. })();
  2509. BABYLON.Viewport = Viewport;
  2510. var Frustum = (function () {
  2511. function Frustum() {
  2512. }
  2513. Frustum.GetPlanes = function (transform) {
  2514. var frustumPlanes = [];
  2515. for (var index = 0; index < 6; index++) {
  2516. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2517. }
  2518. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2519. return frustumPlanes;
  2520. };
  2521. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2522. // Near
  2523. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2524. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2525. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2526. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2527. frustumPlanes[0].normalize();
  2528. // Far
  2529. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2530. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2531. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2532. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2533. frustumPlanes[1].normalize();
  2534. // Left
  2535. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2536. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2537. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2538. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2539. frustumPlanes[2].normalize();
  2540. // Right
  2541. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2542. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2543. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2544. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2545. frustumPlanes[3].normalize();
  2546. // Top
  2547. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2548. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2549. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2550. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2551. frustumPlanes[4].normalize();
  2552. // Bottom
  2553. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2554. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2555. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2556. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2557. frustumPlanes[5].normalize();
  2558. };
  2559. return Frustum;
  2560. })();
  2561. BABYLON.Frustum = Frustum;
  2562. (function (Space) {
  2563. Space[Space["LOCAL"] = 0] = "LOCAL";
  2564. Space[Space["WORLD"] = 1] = "WORLD";
  2565. })(BABYLON.Space || (BABYLON.Space = {}));
  2566. var Space = BABYLON.Space;
  2567. var Axis = (function () {
  2568. function Axis() {
  2569. }
  2570. Axis.X = new Vector3(1, 0, 0);
  2571. Axis.Y = new Vector3(0, 1, 0);
  2572. Axis.Z = new Vector3(0, 0, 1);
  2573. return Axis;
  2574. })();
  2575. BABYLON.Axis = Axis;
  2576. ;
  2577. var BezierCurve = (function () {
  2578. function BezierCurve() {
  2579. }
  2580. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2581. // Extract X (which is equal to time here)
  2582. var f0 = 1 - 3 * x2 + 3 * x1;
  2583. var f1 = 3 * x2 - 6 * x1;
  2584. var f2 = 3 * x1;
  2585. var refinedT = t;
  2586. for (var i = 0; i < 5; i++) {
  2587. var refinedT2 = refinedT * refinedT;
  2588. var refinedT3 = refinedT2 * refinedT;
  2589. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2590. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2591. refinedT -= (x - t) * slope;
  2592. refinedT = Math.min(1, Math.max(0, refinedT));
  2593. }
  2594. // Resolve cubic bezier for the given x
  2595. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2596. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2597. Math.pow(refinedT, 3);
  2598. };
  2599. return BezierCurve;
  2600. })();
  2601. BABYLON.BezierCurve = BezierCurve;
  2602. (function (Orientation) {
  2603. Orientation[Orientation["CW"] = 0] = "CW";
  2604. Orientation[Orientation["CCW"] = 1] = "CCW";
  2605. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2606. var Orientation = BABYLON.Orientation;
  2607. var Angle = (function () {
  2608. function Angle(radians) {
  2609. var _this = this;
  2610. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2611. this.radians = function () { return _this._radians; };
  2612. this._radians = radians;
  2613. if (this._radians < 0)
  2614. this._radians += (2 * Math.PI);
  2615. }
  2616. Angle.BetweenTwoPoints = function (a, b) {
  2617. var delta = b.subtract(a);
  2618. var theta = Math.atan2(delta.y, delta.x);
  2619. return new Angle(theta);
  2620. };
  2621. Angle.FromRadians = function (radians) {
  2622. return new Angle(radians);
  2623. };
  2624. Angle.FromDegrees = function (degrees) {
  2625. return new Angle(degrees * Math.PI / 180);
  2626. };
  2627. return Angle;
  2628. })();
  2629. BABYLON.Angle = Angle;
  2630. var Arc2 = (function () {
  2631. function Arc2(startPoint, midPoint, endPoint) {
  2632. this.startPoint = startPoint;
  2633. this.midPoint = midPoint;
  2634. this.endPoint = endPoint;
  2635. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2636. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2637. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2638. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2639. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2640. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2641. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2642. var a1 = this.startAngle.degrees();
  2643. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2644. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2645. // angles correction
  2646. if (a2 - a1 > +180.0)
  2647. a2 -= 360.0;
  2648. if (a2 - a1 < -180.0)
  2649. a2 += 360.0;
  2650. if (a3 - a2 > +180.0)
  2651. a3 -= 360.0;
  2652. if (a3 - a2 < -180.0)
  2653. a3 += 360.0;
  2654. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2655. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2656. }
  2657. return Arc2;
  2658. })();
  2659. BABYLON.Arc2 = Arc2;
  2660. var Path2 = (function () {
  2661. function Path2(x, y) {
  2662. this._points = new Array();
  2663. this._length = 0;
  2664. this.closed = false;
  2665. this._points.push(new Vector2(x, y));
  2666. }
  2667. Path2.prototype.addLineTo = function (x, y) {
  2668. if (closed) {
  2669. //Tools.Error("cannot add lines to closed paths");
  2670. return this;
  2671. }
  2672. var newPoint = new Vector2(x, y);
  2673. var previousPoint = this._points[this._points.length - 1];
  2674. this._points.push(newPoint);
  2675. this._length += newPoint.subtract(previousPoint).length();
  2676. return this;
  2677. };
  2678. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2679. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2680. if (closed) {
  2681. //Tools.Error("cannot add arcs to closed paths");
  2682. return this;
  2683. }
  2684. var startPoint = this._points[this._points.length - 1];
  2685. var midPoint = new Vector2(midX, midY);
  2686. var endPoint = new Vector2(endX, endY);
  2687. var arc = new Arc2(startPoint, midPoint, endPoint);
  2688. var increment = arc.angle.radians() / numberOfSegments;
  2689. if (arc.orientation === Orientation.CW)
  2690. increment *= -1;
  2691. var currentAngle = arc.startAngle.radians() + increment;
  2692. for (var i = 0; i < numberOfSegments; i++) {
  2693. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2694. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2695. this.addLineTo(x, y);
  2696. currentAngle += increment;
  2697. }
  2698. return this;
  2699. };
  2700. Path2.prototype.close = function () {
  2701. this.closed = true;
  2702. return this;
  2703. };
  2704. Path2.prototype.length = function () {
  2705. var result = this._length;
  2706. if (!this.closed) {
  2707. var lastPoint = this._points[this._points.length - 1];
  2708. var firstPoint = this._points[0];
  2709. result += (firstPoint.subtract(lastPoint).length());
  2710. }
  2711. return result;
  2712. };
  2713. Path2.prototype.getPoints = function () {
  2714. return this._points;
  2715. };
  2716. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2717. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2718. //Tools.Error("normalized length position should be between 0 and 1.");
  2719. return Vector2.Zero();
  2720. }
  2721. var lengthPosition = normalizedLengthPosition * this.length();
  2722. var previousOffset = 0;
  2723. for (var i = 0; i < this._points.length; i++) {
  2724. var j = (i + 1) % this._points.length;
  2725. var a = this._points[i];
  2726. var b = this._points[j];
  2727. var bToA = b.subtract(a);
  2728. var nextOffset = (bToA.length() + previousOffset);
  2729. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2730. var dir = bToA.normalize();
  2731. var localOffset = lengthPosition - previousOffset;
  2732. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2733. }
  2734. previousOffset = nextOffset;
  2735. }
  2736. //Tools.Error("internal error");
  2737. return Vector2.Zero();
  2738. };
  2739. Path2.StartingAt = function (x, y) {
  2740. return new Path2(x, y);
  2741. };
  2742. return Path2;
  2743. })();
  2744. BABYLON.Path2 = Path2;
  2745. var Path3D = (function () {
  2746. /**
  2747. * new Path3D(path, normal, raw)
  2748. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2749. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2750. * path : an array of Vector3, the curve axis of the Path3D
  2751. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2752. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2753. */
  2754. function Path3D(path, firstNormal, raw) {
  2755. this.path = path;
  2756. this._curve = new Array();
  2757. this._distances = new Array();
  2758. this._tangents = new Array();
  2759. this._normals = new Array();
  2760. this._binormals = new Array();
  2761. for (var p = 0; p < path.length; p++) {
  2762. this._curve[p] = path[p].clone(); // hard copy
  2763. }
  2764. this._raw = raw || false;
  2765. this._compute(firstNormal);
  2766. }
  2767. /**
  2768. * Returns the Path3D array of successive Vector3 designing its curve.
  2769. */
  2770. Path3D.prototype.getCurve = function () {
  2771. return this._curve;
  2772. };
  2773. /**
  2774. * Returns an array populated with tangent vectors on each Path3D curve point.
  2775. */
  2776. Path3D.prototype.getTangents = function () {
  2777. return this._tangents;
  2778. };
  2779. /**
  2780. * Returns an array populated with normal vectors on each Path3D curve point.
  2781. */
  2782. Path3D.prototype.getNormals = function () {
  2783. return this._normals;
  2784. };
  2785. /**
  2786. * Returns an array populated with binormal vectors on each Path3D curve point.
  2787. */
  2788. Path3D.prototype.getBinormals = function () {
  2789. return this._binormals;
  2790. };
  2791. /**
  2792. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2793. */
  2794. Path3D.prototype.getDistances = function () {
  2795. return this._distances;
  2796. };
  2797. /**
  2798. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2799. * Returns the same object updated.
  2800. */
  2801. Path3D.prototype.update = function (path, firstNormal) {
  2802. for (var p = 0; p < path.length; p++) {
  2803. this._curve[p].x = path[p].x;
  2804. this._curve[p].y = path[p].y;
  2805. this._curve[p].z = path[p].z;
  2806. }
  2807. this._compute(firstNormal);
  2808. return this;
  2809. };
  2810. // private function compute() : computes tangents, normals and binormals
  2811. Path3D.prototype._compute = function (firstNormal) {
  2812. var l = this._curve.length;
  2813. // first and last tangents
  2814. this._tangents[0] = this._getFirstNonNullVector(0);
  2815. if (!this._raw) {
  2816. this._tangents[0].normalize();
  2817. }
  2818. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2819. if (!this._raw) {
  2820. this._tangents[l - 1].normalize();
  2821. }
  2822. // normals and binormals at first point : arbitrary vector with _normalVector()
  2823. var tg0 = this._tangents[0];
  2824. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2825. this._normals[0] = pp0;
  2826. if (!this._raw) {
  2827. this._normals[0].normalize();
  2828. }
  2829. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2830. if (!this._raw) {
  2831. this._binormals[0].normalize();
  2832. }
  2833. this._distances[0] = 0;
  2834. // normals and binormals : next points
  2835. var prev; // previous vector (segment)
  2836. var cur; // current vector (segment)
  2837. var curTang; // current tangent
  2838. // previous normal
  2839. var prevBinor; // previous binormal
  2840. for (var i = 1; i < l; i++) {
  2841. // tangents
  2842. prev = this._getLastNonNullVector(i);
  2843. if (i < l - 1) {
  2844. cur = this._getFirstNonNullVector(i);
  2845. this._tangents[i] = prev.add(cur);
  2846. this._tangents[i].normalize();
  2847. }
  2848. this._distances[i] = this._distances[i - 1] + prev.length();
  2849. // normals and binormals
  2850. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2851. curTang = this._tangents[i];
  2852. prevBinor = this._binormals[i - 1];
  2853. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2854. if (!this._raw) {
  2855. this._normals[i].normalize();
  2856. }
  2857. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2858. if (!this._raw) {
  2859. this._binormals[i].normalize();
  2860. }
  2861. }
  2862. };
  2863. // private function getFirstNonNullVector(index)
  2864. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2865. Path3D.prototype._getFirstNonNullVector = function (index) {
  2866. var i = 1;
  2867. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2868. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2869. i++;
  2870. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2871. }
  2872. return nNVector;
  2873. };
  2874. // private function getLastNonNullVector(index)
  2875. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2876. Path3D.prototype._getLastNonNullVector = function (index) {
  2877. var i = 1;
  2878. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2879. while (nLVector.length() === 0 && index > i + 1) {
  2880. i++;
  2881. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2882. }
  2883. return nLVector;
  2884. };
  2885. // private function normalVector(v0, vt, va) :
  2886. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2887. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2888. Path3D.prototype._normalVector = function (v0, vt, va) {
  2889. var normal0;
  2890. if (va === undefined || va === null) {
  2891. var point;
  2892. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2893. point = new Vector3(0, -1, 0);
  2894. }
  2895. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2896. point = new Vector3(1, 0, 0);
  2897. }
  2898. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2899. point = new Vector3(0, 0, 1);
  2900. }
  2901. normal0 = Vector3.Cross(vt, point);
  2902. }
  2903. else {
  2904. normal0 = Vector3.Cross(vt, va);
  2905. Vector3.CrossToRef(normal0, vt, normal0);
  2906. }
  2907. normal0.normalize();
  2908. return normal0;
  2909. };
  2910. return Path3D;
  2911. })();
  2912. BABYLON.Path3D = Path3D;
  2913. var Curve3 = (function () {
  2914. /**
  2915. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2916. * A Curve3 is designed from a series of successive Vector3.
  2917. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2918. */
  2919. function Curve3(points) {
  2920. this._length = 0;
  2921. this._points = points;
  2922. this._length = this._computeLength(points);
  2923. }
  2924. /**
  2925. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2926. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2927. * @param v1 (Vector3) the control point
  2928. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2929. * @param nbPoints (integer) the wanted number of points in the curve
  2930. */
  2931. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2932. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2933. var bez = new Array();
  2934. var equation = function (t, val0, val1, val2) {
  2935. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2936. return res;
  2937. };
  2938. for (var i = 0; i <= nbPoints; i++) {
  2939. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2940. }
  2941. return new Curve3(bez);
  2942. };
  2943. /**
  2944. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2945. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2946. * @param v1 (Vector3) the first control point
  2947. * @param v2 (Vector3) the second control point
  2948. * @param v3 (Vector3) the end point of the Cubic Bezier
  2949. * @param nbPoints (integer) the wanted number of points in the curve
  2950. */
  2951. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2952. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2953. var bez = new Array();
  2954. var equation = function (t, val0, val1, val2, val3) {
  2955. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2956. return res;
  2957. };
  2958. for (var i = 0; i <= nbPoints; i++) {
  2959. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2960. }
  2961. return new Curve3(bez);
  2962. };
  2963. /**
  2964. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2965. * @param p1 (Vector3) the origin point of the Hermite Spline
  2966. * @param t1 (Vector3) the tangent vector at the origin point
  2967. * @param p2 (Vector3) the end point of the Hermite Spline
  2968. * @param t2 (Vector3) the tangent vector at the end point
  2969. * @param nbPoints (integer) the wanted number of points in the curve
  2970. */
  2971. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2972. var hermite = new Array();
  2973. var step = 1 / nbPoints;
  2974. for (var i = 0; i <= nbPoints; i++) {
  2975. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2976. }
  2977. return new Curve3(hermite);
  2978. };
  2979. /**
  2980. * Returns the Curve3 stored array of successive Vector3
  2981. */
  2982. Curve3.prototype.getPoints = function () {
  2983. return this._points;
  2984. };
  2985. /**
  2986. * Returns the computed length (float) of the curve.
  2987. */
  2988. Curve3.prototype.length = function () {
  2989. return this._length;
  2990. };
  2991. /**
  2992. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  2993. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  2994. * curveA and curveB keep unchanged.
  2995. */
  2996. Curve3.prototype.continue = function (curve) {
  2997. var lastPoint = this._points[this._points.length - 1];
  2998. var continuedPoints = this._points.slice();
  2999. var curvePoints = curve.getPoints();
  3000. for (var i = 1; i < curvePoints.length; i++) {
  3001. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3002. }
  3003. var continuedCurve = new Curve3(continuedPoints);
  3004. return continuedCurve;
  3005. };
  3006. Curve3.prototype._computeLength = function (path) {
  3007. var l = 0;
  3008. for (var i = 1; i < path.length; i++) {
  3009. l += (path[i].subtract(path[i - 1])).length();
  3010. }
  3011. return l;
  3012. };
  3013. return Curve3;
  3014. })();
  3015. BABYLON.Curve3 = Curve3;
  3016. // SphericalHarmonics
  3017. var SphericalHarmonics = (function () {
  3018. function SphericalHarmonics() {
  3019. this.L00 = Vector3.Zero();
  3020. this.L1_1 = Vector3.Zero();
  3021. this.L10 = Vector3.Zero();
  3022. this.L11 = Vector3.Zero();
  3023. this.L2_2 = Vector3.Zero();
  3024. this.L2_1 = Vector3.Zero();
  3025. this.L20 = Vector3.Zero();
  3026. this.L21 = Vector3.Zero();
  3027. this.L22 = Vector3.Zero();
  3028. }
  3029. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3030. var colorVector = new Vector3(color.r, color.g, color.b);
  3031. var c = colorVector.scale(deltaSolidAngle);
  3032. this.L00 = this.L00.add(c.scale(0.282095));
  3033. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3034. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3035. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3036. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3037. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3038. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3039. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3040. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3041. };
  3042. SphericalHarmonics.prototype.scale = function (scale) {
  3043. this.L00 = this.L00.scale(scale);
  3044. this.L1_1 = this.L1_1.scale(scale);
  3045. this.L10 = this.L10.scale(scale);
  3046. this.L11 = this.L11.scale(scale);
  3047. this.L2_2 = this.L2_2.scale(scale);
  3048. this.L2_1 = this.L2_1.scale(scale);
  3049. this.L20 = this.L20.scale(scale);
  3050. this.L21 = this.L21.scale(scale);
  3051. this.L22 = this.L22.scale(scale);
  3052. };
  3053. return SphericalHarmonics;
  3054. })();
  3055. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3056. // SphericalPolynomial
  3057. var SphericalPolynomial = (function () {
  3058. function SphericalPolynomial() {
  3059. this.x = Vector3.Zero();
  3060. this.y = Vector3.Zero();
  3061. this.z = Vector3.Zero();
  3062. this.xx = Vector3.Zero();
  3063. this.yy = Vector3.Zero();
  3064. this.zz = Vector3.Zero();
  3065. this.xy = Vector3.Zero();
  3066. this.yz = Vector3.Zero();
  3067. this.zx = Vector3.Zero();
  3068. }
  3069. SphericalPolynomial.prototype.addAmbient = function (color) {
  3070. var colorVector = new Vector3(color.r, color.g, color.b);
  3071. this.xx = this.xx.add(colorVector);
  3072. this.yy = this.yy.add(colorVector);
  3073. this.zz = this.zz.add(colorVector);
  3074. };
  3075. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3076. var result = new SphericalPolynomial();
  3077. result.x = harmonics.L11.scale(1.02333);
  3078. result.y = harmonics.L1_1.scale(1.02333);
  3079. result.z = harmonics.L10.scale(1.02333);
  3080. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3081. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3082. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3083. result.yz = harmonics.L2_1.scale(0.858086);
  3084. result.zx = harmonics.L21.scale(0.858086);
  3085. result.xy = harmonics.L2_2.scale(0.858086);
  3086. return result;
  3087. };
  3088. return SphericalPolynomial;
  3089. })();
  3090. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3091. // Vertex formats
  3092. var PositionNormalVertex = (function () {
  3093. function PositionNormalVertex(position, normal) {
  3094. if (position === void 0) { position = Vector3.Zero(); }
  3095. if (normal === void 0) { normal = Vector3.Up(); }
  3096. this.position = position;
  3097. this.normal = normal;
  3098. }
  3099. PositionNormalVertex.prototype.clone = function () {
  3100. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3101. };
  3102. return PositionNormalVertex;
  3103. })();
  3104. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3105. var PositionNormalTextureVertex = (function () {
  3106. function PositionNormalTextureVertex(position, normal, uv) {
  3107. if (position === void 0) { position = Vector3.Zero(); }
  3108. if (normal === void 0) { normal = Vector3.Up(); }
  3109. if (uv === void 0) { uv = Vector2.Zero(); }
  3110. this.position = position;
  3111. this.normal = normal;
  3112. this.uv = uv;
  3113. }
  3114. PositionNormalTextureVertex.prototype.clone = function () {
  3115. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3116. };
  3117. return PositionNormalTextureVertex;
  3118. })();
  3119. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3120. // Temporary pre-allocated objects for engine internal use
  3121. // usage in any internal function :
  3122. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3123. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3124. var Tmp = (function () {
  3125. function Tmp() {
  3126. }
  3127. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3128. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3129. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3130. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3131. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3132. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3133. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3134. Matrix.Zero(), Matrix.Zero(),
  3135. Matrix.Zero(), Matrix.Zero(),
  3136. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3137. return Tmp;
  3138. })();
  3139. BABYLON.Tmp = Tmp;
  3140. })(BABYLON || (BABYLON = {}));
  3141. var BABYLON;
  3142. (function (BABYLON) {
  3143. function generateSerializableMember(type, sourceName) {
  3144. return function (target, propertyKey) {
  3145. if (!target.__serializableMembers) {
  3146. target.__serializableMembers = {};
  3147. }
  3148. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3149. };
  3150. }
  3151. function serialize(sourceName) {
  3152. return generateSerializableMember(0, sourceName); // value member
  3153. }
  3154. BABYLON.serialize = serialize;
  3155. function serializeAsTexture(sourceName) {
  3156. return generateSerializableMember(1, sourceName); // texture member
  3157. }
  3158. BABYLON.serializeAsTexture = serializeAsTexture;
  3159. function serializeAsColor3(sourceName) {
  3160. return generateSerializableMember(2, sourceName); // color3 member
  3161. }
  3162. BABYLON.serializeAsColor3 = serializeAsColor3;
  3163. function serializeAsFresnelParameters(sourceName) {
  3164. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3165. }
  3166. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3167. function serializeAsVector2(sourceName) {
  3168. return generateSerializableMember(4, sourceName); // vector2 member
  3169. }
  3170. BABYLON.serializeAsVector2 = serializeAsVector2;
  3171. function serializeAsVector3(sourceName) {
  3172. return generateSerializableMember(5, sourceName); // vector3 member
  3173. }
  3174. BABYLON.serializeAsVector3 = serializeAsVector3;
  3175. function serializeAsMeshReference(sourceName) {
  3176. return generateSerializableMember(6, sourceName); // mesh reference member
  3177. }
  3178. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3179. function serializeAsColorCurves(sourceName) {
  3180. return generateSerializableMember(7, sourceName); // color curves
  3181. }
  3182. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3183. var SerializationHelper = (function () {
  3184. function SerializationHelper() {
  3185. }
  3186. SerializationHelper.Serialize = function (entity, serializationObject) {
  3187. if (!serializationObject) {
  3188. serializationObject = {};
  3189. }
  3190. // Tags
  3191. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3192. // Properties
  3193. for (var property in entity.__serializableMembers) {
  3194. var propertyDescriptor = entity.__serializableMembers[property];
  3195. var targetPropertyName = propertyDescriptor.sourceName || property;
  3196. var propertyType = propertyDescriptor.type;
  3197. var sourceProperty = entity[property];
  3198. if (sourceProperty !== undefined && sourceProperty !== null) {
  3199. switch (propertyType) {
  3200. case 0:
  3201. serializationObject[targetPropertyName] = sourceProperty;
  3202. break;
  3203. case 1:
  3204. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3205. break;
  3206. case 2:
  3207. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3208. break;
  3209. case 3:
  3210. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3211. break;
  3212. case 4:
  3213. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3214. break;
  3215. case 5:
  3216. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3217. break;
  3218. case 6:
  3219. serializationObject[targetPropertyName] = sourceProperty.id;
  3220. break;
  3221. case 7:
  3222. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3223. break;
  3224. }
  3225. }
  3226. }
  3227. return serializationObject;
  3228. };
  3229. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3230. var destination = creationFunction();
  3231. // Tags
  3232. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3233. // Properties
  3234. for (var property in destination.__serializableMembers) {
  3235. var propertyDescriptor = destination.__serializableMembers[property];
  3236. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3237. var propertyType = propertyDescriptor.type;
  3238. if (sourceProperty !== undefined && sourceProperty !== null) {
  3239. switch (propertyType) {
  3240. case 0:
  3241. destination[property] = sourceProperty;
  3242. break;
  3243. case 1:
  3244. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3245. break;
  3246. case 2:
  3247. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3248. break;
  3249. case 3:
  3250. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3251. break;
  3252. case 4:
  3253. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3254. break;
  3255. case 5:
  3256. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3257. break;
  3258. case 6:
  3259. destination[property] = scene.getLastMeshByID(sourceProperty);
  3260. break;
  3261. case 7:
  3262. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3263. break;
  3264. }
  3265. }
  3266. }
  3267. return destination;
  3268. };
  3269. SerializationHelper.Clone = function (creationFunction, source) {
  3270. var destination = creationFunction();
  3271. // Tags
  3272. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3273. // Properties
  3274. for (var property in destination.__serializableMembers) {
  3275. var propertyDescriptor = destination.__serializableMembers[property];
  3276. var sourceProperty = source[property];
  3277. var propertyType = propertyDescriptor.type;
  3278. if (sourceProperty !== undefined && sourceProperty !== null) {
  3279. switch (propertyType) {
  3280. case 0: // Value
  3281. case 6:
  3282. destination[property] = sourceProperty;
  3283. break;
  3284. case 1: // Texture
  3285. case 2: // Color3
  3286. case 3: // FresnelParameters
  3287. case 4: // Vector2
  3288. case 5: // Vector3
  3289. case 7:
  3290. destination[property] = sourceProperty.clone();
  3291. break;
  3292. }
  3293. }
  3294. }
  3295. return destination;
  3296. };
  3297. return SerializationHelper;
  3298. })();
  3299. BABYLON.SerializationHelper = SerializationHelper;
  3300. })(BABYLON || (BABYLON = {}));
  3301. var BABYLON;
  3302. (function (BABYLON) {
  3303. /**
  3304. * A class serves as a medium between the observable and its observers
  3305. */
  3306. var EventState = (function () {
  3307. /**
  3308. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3309. */
  3310. function EventState(mask, skipNextObservers) {
  3311. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3312. this.mask = mask;
  3313. this.skipNextObservers = skipNextObservers;
  3314. }
  3315. return EventState;
  3316. })();
  3317. BABYLON.EventState = EventState;
  3318. /**
  3319. * Represent an Observer registered to a given Observable object.
  3320. */
  3321. var Observer = (function () {
  3322. function Observer(callback, mask) {
  3323. this.callback = callback;
  3324. this.mask = mask;
  3325. }
  3326. return Observer;
  3327. })();
  3328. BABYLON.Observer = Observer;
  3329. /**
  3330. * The Observable class is a simple implementation of the Observable pattern.
  3331. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  3332. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3333. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  3334. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  3335. */
  3336. var Observable = (function () {
  3337. function Observable() {
  3338. this._observers = new Array();
  3339. }
  3340. /**
  3341. * Create a new Observer with the specified callback
  3342. * @param callback the callback that will be executed for that Observer
  3343. * @param mask the mask used to filter observers
  3344. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  3345. */
  3346. Observable.prototype.add = function (callback, mask, insertFirst) {
  3347. if (mask === void 0) { mask = -1; }
  3348. if (insertFirst === void 0) { insertFirst = false; }
  3349. if (!callback) {
  3350. return null;
  3351. }
  3352. var observer = new Observer(callback, mask);
  3353. if (insertFirst) {
  3354. this._observers.unshift(observer);
  3355. }
  3356. else {
  3357. this._observers.push(observer);
  3358. }
  3359. return observer;
  3360. };
  3361. /**
  3362. * Remove an Observer from the Observable object
  3363. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3364. */
  3365. Observable.prototype.remove = function (observer) {
  3366. var index = this._observers.indexOf(observer);
  3367. if (index !== -1) {
  3368. this._observers.splice(index, 1);
  3369. return true;
  3370. }
  3371. return false;
  3372. };
  3373. /**
  3374. * Remove a callback from the Observable object
  3375. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3376. */
  3377. Observable.prototype.removeCallback = function (callback) {
  3378. for (var index = 0; index < this._observers.length; index++) {
  3379. if (this._observers[index].callback === callback) {
  3380. this._observers.splice(index, 1);
  3381. return true;
  3382. }
  3383. }
  3384. return false;
  3385. };
  3386. /**
  3387. * Notify all Observers by calling their respective callback with the given data
  3388. * @param eventData
  3389. * @param mask
  3390. */
  3391. Observable.prototype.notifyObservers = function (eventData, mask) {
  3392. if (mask === void 0) { mask = -1; }
  3393. var state = new EventState(mask);
  3394. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3395. var obs = _a[_i];
  3396. if (obs.mask & mask) {
  3397. obs.callback(eventData, state);
  3398. }
  3399. if (state.skipNextObservers) {
  3400. break;
  3401. }
  3402. }
  3403. };
  3404. /**
  3405. * return true is the Observable has at least one Observer registered
  3406. */
  3407. Observable.prototype.hasObservers = function () {
  3408. return this._observers.length > 0;
  3409. };
  3410. /**
  3411. * Clear the list of observers
  3412. */
  3413. Observable.prototype.clear = function () {
  3414. this._observers = new Array();
  3415. };
  3416. /**
  3417. * Clone the current observable
  3418. */
  3419. Observable.prototype.clone = function () {
  3420. var result = new Observable();
  3421. result._observers = this._observers.slice(0);
  3422. return result;
  3423. };
  3424. return Observable;
  3425. })();
  3426. BABYLON.Observable = Observable;
  3427. })(BABYLON || (BABYLON = {}));
  3428. var BABYLON;
  3429. (function (BABYLON) {
  3430. var Database = (function () {
  3431. function Database(urlToScene, callbackManifestChecked) {
  3432. // Handling various flavors of prefixed version of IndexedDB
  3433. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3434. this.callbackManifestChecked = callbackManifestChecked;
  3435. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3436. this.db = null;
  3437. this.enableSceneOffline = false;
  3438. this.enableTexturesOffline = false;
  3439. this.manifestVersionFound = 0;
  3440. this.mustUpdateRessources = false;
  3441. this.hasReachedQuota = false;
  3442. if (!Database.IDBStorageEnabled) {
  3443. this.callbackManifestChecked(true);
  3444. }
  3445. else {
  3446. this.checkManifestFile();
  3447. }
  3448. }
  3449. Database.prototype.checkManifestFile = function () {
  3450. var _this = this;
  3451. function noManifestFile() {
  3452. that.enableSceneOffline = false;
  3453. that.enableTexturesOffline = false;
  3454. that.callbackManifestChecked(false);
  3455. }
  3456. var that = this;
  3457. var timeStampUsed = false;
  3458. var manifestURL = this.currentSceneUrl + ".manifest";
  3459. var xhr = new XMLHttpRequest();
  3460. if (navigator.onLine) {
  3461. // Adding a timestamp to by-pass browsers' cache
  3462. timeStampUsed = true;
  3463. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3464. }
  3465. xhr.open("GET", manifestURL, true);
  3466. xhr.addEventListener("load", function () {
  3467. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3468. try {
  3469. var manifestFile = JSON.parse(xhr.response);
  3470. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3471. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3472. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3473. _this.manifestVersionFound = manifestFile.version;
  3474. }
  3475. if (_this.callbackManifestChecked) {
  3476. _this.callbackManifestChecked(true);
  3477. }
  3478. }
  3479. catch (ex) {
  3480. noManifestFile();
  3481. }
  3482. }
  3483. else {
  3484. noManifestFile();
  3485. }
  3486. }, false);
  3487. xhr.addEventListener("error", function (event) {
  3488. if (timeStampUsed) {
  3489. timeStampUsed = false;
  3490. // Let's retry without the timeStamp
  3491. // It could fail when coupled with HTML5 Offline API
  3492. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3493. xhr.open("GET", retryManifestURL, true);
  3494. xhr.send();
  3495. }
  3496. else {
  3497. noManifestFile();
  3498. }
  3499. }, false);
  3500. try {
  3501. xhr.send();
  3502. }
  3503. catch (ex) {
  3504. BABYLON.Tools.Error("Error on XHR send request.");
  3505. that.callbackManifestChecked(false);
  3506. }
  3507. };
  3508. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3509. var _this = this;
  3510. function handleError() {
  3511. that.isSupported = false;
  3512. if (errorCallback)
  3513. errorCallback();
  3514. }
  3515. var that = this;
  3516. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3517. // Your browser doesn't support IndexedDB
  3518. this.isSupported = false;
  3519. if (errorCallback)
  3520. errorCallback();
  3521. }
  3522. else {
  3523. // If the DB hasn't been opened or created yet
  3524. if (!this.db) {
  3525. this.hasReachedQuota = false;
  3526. this.isSupported = true;
  3527. var request = this.idbFactory.open("babylonjs", 1);
  3528. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3529. request.onerror = function (event) {
  3530. handleError();
  3531. };
  3532. // executes when a version change transaction cannot complete due to other active transactions
  3533. request.onblocked = function (event) {
  3534. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3535. handleError();
  3536. };
  3537. // DB has been opened successfully
  3538. request.onsuccess = function (event) {
  3539. _this.db = request.result;
  3540. successCallback();
  3541. };
  3542. // Initialization of the DB. Creating Scenes & Textures stores
  3543. request.onupgradeneeded = function (event) {
  3544. _this.db = (event.target).result;
  3545. try {
  3546. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3547. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3548. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3549. }
  3550. catch (ex) {
  3551. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3552. handleError();
  3553. }
  3554. };
  3555. }
  3556. else {
  3557. if (successCallback)
  3558. successCallback();
  3559. }
  3560. }
  3561. };
  3562. Database.prototype.loadImageFromDB = function (url, image) {
  3563. var _this = this;
  3564. var completeURL = Database.ReturnFullUrlLocation(url);
  3565. var saveAndLoadImage = function () {
  3566. if (!_this.hasReachedQuota && _this.db !== null) {
  3567. // the texture is not yet in the DB, let's try to save it
  3568. _this._saveImageIntoDBAsync(completeURL, image);
  3569. }
  3570. else {
  3571. image.src = url;
  3572. }
  3573. };
  3574. if (!this.mustUpdateRessources) {
  3575. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3576. }
  3577. else {
  3578. saveAndLoadImage();
  3579. }
  3580. };
  3581. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3582. if (this.isSupported && this.db !== null) {
  3583. var texture;
  3584. var transaction = this.db.transaction(["textures"]);
  3585. transaction.onabort = function (event) {
  3586. image.src = url;
  3587. };
  3588. transaction.oncomplete = function (event) {
  3589. var blobTextureURL;
  3590. if (texture) {
  3591. var URL = window.URL || window.webkitURL;
  3592. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3593. image.onerror = function () {
  3594. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3595. image.src = url;
  3596. };
  3597. image.src = blobTextureURL;
  3598. }
  3599. else {
  3600. notInDBCallback();
  3601. }
  3602. };
  3603. var getRequest = transaction.objectStore("textures").get(url);
  3604. getRequest.onsuccess = function (event) {
  3605. texture = (event.target).result;
  3606. };
  3607. getRequest.onerror = function (event) {
  3608. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3609. image.src = url;
  3610. };
  3611. }
  3612. else {
  3613. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3614. image.src = url;
  3615. }
  3616. };
  3617. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3618. var _this = this;
  3619. if (this.isSupported) {
  3620. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3621. var generateBlobUrl = function () {
  3622. var blobTextureURL;
  3623. if (blob) {
  3624. var URL = window.URL || window.webkitURL;
  3625. try {
  3626. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3627. }
  3628. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3629. catch (ex) {
  3630. blobTextureURL = URL.createObjectURL(blob);
  3631. }
  3632. }
  3633. image.src = blobTextureURL;
  3634. };
  3635. if (Database.IsUASupportingBlobStorage) {
  3636. var xhr = new XMLHttpRequest(), blob;
  3637. xhr.open("GET", url, true);
  3638. xhr.responseType = "blob";
  3639. xhr.addEventListener("load", function () {
  3640. if (xhr.status === 200) {
  3641. // Blob as response (XHR2)
  3642. blob = xhr.response;
  3643. var transaction = _this.db.transaction(["textures"], "readwrite");
  3644. // the transaction could abort because of a QuotaExceededError error
  3645. transaction.onabort = function (event) {
  3646. try {
  3647. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3648. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3649. this.hasReachedQuota = true;
  3650. }
  3651. }
  3652. catch (ex) { }
  3653. generateBlobUrl();
  3654. };
  3655. transaction.oncomplete = function (event) {
  3656. generateBlobUrl();
  3657. };
  3658. var newTexture = { textureUrl: url, data: blob };
  3659. try {
  3660. // Put the blob into the dabase
  3661. var addRequest = transaction.objectStore("textures").put(newTexture);
  3662. addRequest.onsuccess = function (event) {
  3663. };
  3664. addRequest.onerror = function (event) {
  3665. generateBlobUrl();
  3666. };
  3667. }
  3668. catch (ex) {
  3669. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3670. if (ex.code === 25) {
  3671. Database.IsUASupportingBlobStorage = false;
  3672. }
  3673. image.src = url;
  3674. }
  3675. }
  3676. else {
  3677. image.src = url;
  3678. }
  3679. }, false);
  3680. xhr.addEventListener("error", function (event) {
  3681. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3682. image.src = url;
  3683. }, false);
  3684. xhr.send();
  3685. }
  3686. else {
  3687. image.src = url;
  3688. }
  3689. }
  3690. else {
  3691. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3692. image.src = url;
  3693. }
  3694. };
  3695. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3696. var _this = this;
  3697. var updateVersion = function (event) {
  3698. // the version is not yet in the DB or we need to update it
  3699. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3700. };
  3701. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3702. };
  3703. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3704. var _this = this;
  3705. if (this.isSupported) {
  3706. var version;
  3707. try {
  3708. var transaction = this.db.transaction(["versions"]);
  3709. transaction.oncomplete = function (event) {
  3710. if (version) {
  3711. // If the version in the JSON file is > than the version in DB
  3712. if (_this.manifestVersionFound > version.data) {
  3713. _this.mustUpdateRessources = true;
  3714. updateInDBCallback();
  3715. }
  3716. else {
  3717. callback(version.data);
  3718. }
  3719. }
  3720. else {
  3721. _this.mustUpdateRessources = true;
  3722. updateInDBCallback();
  3723. }
  3724. };
  3725. transaction.onabort = function (event) {
  3726. callback(-1);
  3727. };
  3728. var getRequest = transaction.objectStore("versions").get(url);
  3729. getRequest.onsuccess = function (event) {
  3730. version = (event.target).result;
  3731. };
  3732. getRequest.onerror = function (event) {
  3733. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3734. callback(-1);
  3735. };
  3736. }
  3737. catch (ex) {
  3738. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3739. callback(-1);
  3740. }
  3741. }
  3742. else {
  3743. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3744. callback(-1);
  3745. }
  3746. };
  3747. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3748. var _this = this;
  3749. if (this.isSupported && !this.hasReachedQuota) {
  3750. try {
  3751. // Open a transaction to the database
  3752. var transaction = this.db.transaction(["versions"], "readwrite");
  3753. // the transaction could abort because of a QuotaExceededError error
  3754. transaction.onabort = function (event) {
  3755. try {
  3756. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3757. _this.hasReachedQuota = true;
  3758. }
  3759. }
  3760. catch (ex) { }
  3761. callback(-1);
  3762. };
  3763. transaction.oncomplete = function (event) {
  3764. callback(_this.manifestVersionFound);
  3765. };
  3766. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3767. // Put the scene into the database
  3768. var addRequest = transaction.objectStore("versions").put(newVersion);
  3769. addRequest.onsuccess = function (event) {
  3770. };
  3771. addRequest.onerror = function (event) {
  3772. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3773. };
  3774. }
  3775. catch (ex) {
  3776. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3777. callback(-1);
  3778. }
  3779. }
  3780. else {
  3781. callback(-1);
  3782. }
  3783. };
  3784. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3785. var _this = this;
  3786. var completeUrl = Database.ReturnFullUrlLocation(url);
  3787. var saveAndLoadFile = function (event) {
  3788. // the scene is not yet in the DB, let's try to save it
  3789. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3790. };
  3791. this._checkVersionFromDB(completeUrl, function (version) {
  3792. if (version !== -1) {
  3793. if (!_this.mustUpdateRessources) {
  3794. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3795. }
  3796. else {
  3797. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3798. }
  3799. }
  3800. else {
  3801. errorCallback();
  3802. }
  3803. });
  3804. };
  3805. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3806. if (this.isSupported) {
  3807. var targetStore;
  3808. if (url.indexOf(".babylon") !== -1) {
  3809. targetStore = "scenes";
  3810. }
  3811. else {
  3812. targetStore = "textures";
  3813. }
  3814. var file;
  3815. var transaction = this.db.transaction([targetStore]);
  3816. transaction.oncomplete = function (event) {
  3817. if (file) {
  3818. callback(file.data);
  3819. }
  3820. else {
  3821. notInDBCallback();
  3822. }
  3823. };
  3824. transaction.onabort = function (event) {
  3825. notInDBCallback();
  3826. };
  3827. var getRequest = transaction.objectStore(targetStore).get(url);
  3828. getRequest.onsuccess = function (event) {
  3829. file = (event.target).result;
  3830. };
  3831. getRequest.onerror = function (event) {
  3832. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3833. notInDBCallback();
  3834. };
  3835. }
  3836. else {
  3837. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3838. callback();
  3839. }
  3840. };
  3841. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3842. var _this = this;
  3843. if (this.isSupported) {
  3844. var targetStore;
  3845. if (url.indexOf(".babylon") !== -1) {
  3846. targetStore = "scenes";
  3847. }
  3848. else {
  3849. targetStore = "textures";
  3850. }
  3851. // Create XHR
  3852. var xhr = new XMLHttpRequest(), fileData;
  3853. xhr.open("GET", url, true);
  3854. if (useArrayBuffer) {
  3855. xhr.responseType = "arraybuffer";
  3856. }
  3857. xhr.onprogress = progressCallback;
  3858. xhr.addEventListener("load", function () {
  3859. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3860. // Blob as response (XHR2)
  3861. //fileData = xhr.responseText;
  3862. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3863. if (!_this.hasReachedQuota) {
  3864. // Open a transaction to the database
  3865. var transaction = _this.db.transaction([targetStore], "readwrite");
  3866. // the transaction could abort because of a QuotaExceededError error
  3867. transaction.onabort = function (event) {
  3868. try {
  3869. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3870. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3871. this.hasReachedQuota = true;
  3872. }
  3873. }
  3874. catch (ex) { }
  3875. callback(fileData);
  3876. };
  3877. transaction.oncomplete = function (event) {
  3878. callback(fileData);
  3879. };
  3880. var newFile;
  3881. if (targetStore === "scenes") {
  3882. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3883. }
  3884. else {
  3885. newFile = { textureUrl: url, data: fileData };
  3886. }
  3887. try {
  3888. // Put the scene into the database
  3889. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3890. addRequest.onsuccess = function (event) {
  3891. };
  3892. addRequest.onerror = function (event) {
  3893. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3894. };
  3895. }
  3896. catch (ex) {
  3897. callback(fileData);
  3898. }
  3899. }
  3900. else {
  3901. callback(fileData);
  3902. }
  3903. }
  3904. else {
  3905. callback();
  3906. }
  3907. }, false);
  3908. xhr.addEventListener("error", function (event) {
  3909. BABYLON.Tools.Error("error on XHR request.");
  3910. callback();
  3911. }, false);
  3912. xhr.send();
  3913. }
  3914. else {
  3915. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3916. callback();
  3917. }
  3918. };
  3919. Database.IsUASupportingBlobStorage = true;
  3920. Database.IDBStorageEnabled = true;
  3921. Database.parseURL = function (url) {
  3922. var a = document.createElement('a');
  3923. a.href = url;
  3924. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3925. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3926. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3927. return absLocation;
  3928. };
  3929. Database.ReturnFullUrlLocation = function (url) {
  3930. if (url.indexOf("http:/") === -1) {
  3931. return (Database.parseURL(window.location.href) + url);
  3932. }
  3933. else {
  3934. return url;
  3935. }
  3936. };
  3937. return Database;
  3938. })();
  3939. BABYLON.Database = Database;
  3940. })(BABYLON || (BABYLON = {}));
  3941. var BABYLON;
  3942. (function (BABYLON) {
  3943. var Internals;
  3944. (function (Internals) {
  3945. /*
  3946. * Based on jsTGALoader - Javascript loader for TGA file
  3947. * By Vincent Thibault
  3948. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3949. */
  3950. var TGATools = (function () {
  3951. function TGATools() {
  3952. }
  3953. TGATools.GetTGAHeader = function (data) {
  3954. var offset = 0;
  3955. var header = {
  3956. id_length: data[offset++],
  3957. colormap_type: data[offset++],
  3958. image_type: data[offset++],
  3959. colormap_index: data[offset++] | data[offset++] << 8,
  3960. colormap_length: data[offset++] | data[offset++] << 8,
  3961. colormap_size: data[offset++],
  3962. origin: [
  3963. data[offset++] | data[offset++] << 8,
  3964. data[offset++] | data[offset++] << 8
  3965. ],
  3966. width: data[offset++] | data[offset++] << 8,
  3967. height: data[offset++] | data[offset++] << 8,
  3968. pixel_size: data[offset++],
  3969. flags: data[offset++]
  3970. };
  3971. return header;
  3972. };
  3973. TGATools.UploadContent = function (gl, data) {
  3974. // Not enough data to contain header ?
  3975. if (data.length < 19) {
  3976. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3977. return;
  3978. }
  3979. // Read Header
  3980. var offset = 18;
  3981. var header = TGATools.GetTGAHeader(data);
  3982. // Assume it's a valid Targa file.
  3983. if (header.id_length + offset > data.length) {
  3984. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3985. return;
  3986. }
  3987. // Skip not needed data
  3988. offset += header.id_length;
  3989. var use_rle = false;
  3990. var use_pal = false;
  3991. var use_rgb = false;
  3992. var use_grey = false;
  3993. // Get some informations.
  3994. switch (header.image_type) {
  3995. case TGATools._TYPE_RLE_INDEXED:
  3996. use_rle = true;
  3997. case TGATools._TYPE_INDEXED:
  3998. use_pal = true;
  3999. break;
  4000. case TGATools._TYPE_RLE_RGB:
  4001. use_rle = true;
  4002. case TGATools._TYPE_RGB:
  4003. use_rgb = true;
  4004. break;
  4005. case TGATools._TYPE_RLE_GREY:
  4006. use_rle = true;
  4007. case TGATools._TYPE_GREY:
  4008. use_grey = true;
  4009. break;
  4010. }
  4011. var pixel_data;
  4012. var numAlphaBits = header.flags & 0xf;
  4013. var pixel_size = header.pixel_size >> 3;
  4014. var pixel_total = header.width * header.height * pixel_size;
  4015. // Read palettes
  4016. var palettes;
  4017. if (use_pal) {
  4018. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4019. }
  4020. // Read LRE
  4021. if (use_rle) {
  4022. pixel_data = new Uint8Array(pixel_total);
  4023. var c, count, i;
  4024. var localOffset = 0;
  4025. var pixels = new Uint8Array(pixel_size);
  4026. while (offset < pixel_total && localOffset < pixel_total) {
  4027. c = data[offset++];
  4028. count = (c & 0x7f) + 1;
  4029. // RLE pixels
  4030. if (c & 0x80) {
  4031. // Bind pixel tmp array
  4032. for (i = 0; i < pixel_size; ++i) {
  4033. pixels[i] = data[offset++];
  4034. }
  4035. // Copy pixel array
  4036. for (i = 0; i < count; ++i) {
  4037. pixel_data.set(pixels, localOffset + i * pixel_size);
  4038. }
  4039. localOffset += pixel_size * count;
  4040. }
  4041. else {
  4042. count *= pixel_size;
  4043. for (i = 0; i < count; ++i) {
  4044. pixel_data[localOffset + i] = data[offset++];
  4045. }
  4046. localOffset += count;
  4047. }
  4048. }
  4049. }
  4050. else {
  4051. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4052. }
  4053. // Load to texture
  4054. var x_start, y_start, x_step, y_step, y_end, x_end;
  4055. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4056. default:
  4057. case TGATools._ORIGIN_UL:
  4058. x_start = 0;
  4059. x_step = 1;
  4060. x_end = header.width;
  4061. y_start = 0;
  4062. y_step = 1;
  4063. y_end = header.height;
  4064. break;
  4065. case TGATools._ORIGIN_BL:
  4066. x_start = 0;
  4067. x_step = 1;
  4068. x_end = header.width;
  4069. y_start = header.height - 1;
  4070. y_step = -1;
  4071. y_end = -1;
  4072. break;
  4073. case TGATools._ORIGIN_UR:
  4074. x_start = header.width - 1;
  4075. x_step = -1;
  4076. x_end = -1;
  4077. y_start = 0;
  4078. y_step = 1;
  4079. y_end = header.height;
  4080. break;
  4081. case TGATools._ORIGIN_BR:
  4082. x_start = header.width - 1;
  4083. x_step = -1;
  4084. x_end = -1;
  4085. y_start = header.height - 1;
  4086. y_step = -1;
  4087. y_end = -1;
  4088. break;
  4089. }
  4090. // Load the specify method
  4091. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4092. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4093. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4094. };
  4095. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4096. var image = pixel_data, colormap = palettes;
  4097. var width = header.width, height = header.height;
  4098. var color, i = 0, x, y;
  4099. var imageData = new Uint8Array(width * height * 4);
  4100. for (y = y_start; y !== y_end; y += y_step) {
  4101. for (x = x_start; x !== x_end; x += x_step, i++) {
  4102. color = image[i];
  4103. imageData[(x + width * y) * 4 + 3] = 255;
  4104. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4105. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4106. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4107. }
  4108. }
  4109. return imageData;
  4110. };
  4111. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4112. var image = pixel_data;
  4113. var width = header.width, height = header.height;
  4114. var color, i = 0, x, y;
  4115. var imageData = new Uint8Array(width * height * 4);
  4116. for (y = y_start; y !== y_end; y += y_step) {
  4117. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4118. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4119. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4120. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4121. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4122. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4123. }
  4124. }
  4125. return imageData;
  4126. };
  4127. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4128. var image = pixel_data;
  4129. var width = header.width, height = header.height;
  4130. var i = 0, x, y;
  4131. var imageData = new Uint8Array(width * height * 4);
  4132. for (y = y_start; y !== y_end; y += y_step) {
  4133. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4134. imageData[(x + width * y) * 4 + 3] = 255;
  4135. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4136. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4137. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4138. }
  4139. }
  4140. return imageData;
  4141. };
  4142. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4143. var image = pixel_data;
  4144. var width = header.width, height = header.height;
  4145. var i = 0, x, y;
  4146. var imageData = new Uint8Array(width * height * 4);
  4147. for (y = y_start; y !== y_end; y += y_step) {
  4148. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4149. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4150. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4151. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4152. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4153. }
  4154. }
  4155. return imageData;
  4156. };
  4157. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4158. var image = pixel_data;
  4159. var width = header.width, height = header.height;
  4160. var color, i = 0, x, y;
  4161. var imageData = new Uint8Array(width * height * 4);
  4162. for (y = y_start; y !== y_end; y += y_step) {
  4163. for (x = x_start; x !== x_end; x += x_step, i++) {
  4164. color = image[i];
  4165. imageData[(x + width * y) * 4 + 0] = color;
  4166. imageData[(x + width * y) * 4 + 1] = color;
  4167. imageData[(x + width * y) * 4 + 2] = color;
  4168. imageData[(x + width * y) * 4 + 3] = 255;
  4169. }
  4170. }
  4171. return imageData;
  4172. };
  4173. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4174. var image = pixel_data;
  4175. var width = header.width, height = header.height;
  4176. var i = 0, x, y;
  4177. var imageData = new Uint8Array(width * height * 4);
  4178. for (y = y_start; y !== y_end; y += y_step) {
  4179. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4180. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4181. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4182. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4183. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4184. }
  4185. }
  4186. return imageData;
  4187. };
  4188. TGATools._TYPE_NO_DATA = 0;
  4189. TGATools._TYPE_INDEXED = 1;
  4190. TGATools._TYPE_RGB = 2;
  4191. TGATools._TYPE_GREY = 3;
  4192. TGATools._TYPE_RLE_INDEXED = 9;
  4193. TGATools._TYPE_RLE_RGB = 10;
  4194. TGATools._TYPE_RLE_GREY = 11;
  4195. TGATools._ORIGIN_MASK = 0x30;
  4196. TGATools._ORIGIN_SHIFT = 0x04;
  4197. TGATools._ORIGIN_BL = 0x00;
  4198. TGATools._ORIGIN_BR = 0x01;
  4199. TGATools._ORIGIN_UL = 0x02;
  4200. TGATools._ORIGIN_UR = 0x03;
  4201. return TGATools;
  4202. })();
  4203. Internals.TGATools = TGATools;
  4204. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4205. })(BABYLON || (BABYLON = {}));
  4206. var BABYLON;
  4207. (function (BABYLON) {
  4208. var SmartArray = (function () {
  4209. function SmartArray(capacity) {
  4210. this.length = 0;
  4211. this._duplicateId = 0;
  4212. this.data = new Array(capacity);
  4213. this._id = SmartArray._GlobalId++;
  4214. }
  4215. SmartArray.prototype.push = function (value) {
  4216. this.data[this.length++] = value;
  4217. if (this.length > this.data.length) {
  4218. this.data.length *= 2;
  4219. }
  4220. if (!value.__smartArrayFlags) {
  4221. value.__smartArrayFlags = {};
  4222. }
  4223. value.__smartArrayFlags[this._id] = this._duplicateId;
  4224. };
  4225. SmartArray.prototype.pushNoDuplicate = function (value) {
  4226. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4227. return false;
  4228. }
  4229. this.push(value);
  4230. return true;
  4231. };
  4232. SmartArray.prototype.sort = function (compareFn) {
  4233. this.data.sort(compareFn);
  4234. };
  4235. SmartArray.prototype.reset = function () {
  4236. this.length = 0;
  4237. this._duplicateId++;
  4238. };
  4239. SmartArray.prototype.concat = function (array) {
  4240. if (array.length === 0) {
  4241. return;
  4242. }
  4243. if (this.length + array.length > this.data.length) {
  4244. this.data.length = (this.length + array.length) * 2;
  4245. }
  4246. for (var index = 0; index < array.length; index++) {
  4247. this.data[this.length++] = (array.data || array)[index];
  4248. }
  4249. };
  4250. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4251. if (array.length === 0) {
  4252. return;
  4253. }
  4254. if (this.length + array.length > this.data.length) {
  4255. this.data.length = (this.length + array.length) * 2;
  4256. }
  4257. for (var index = 0; index < array.length; index++) {
  4258. var item = (array.data || array)[index];
  4259. this.pushNoDuplicate(item);
  4260. }
  4261. };
  4262. SmartArray.prototype.indexOf = function (value) {
  4263. var position = this.data.indexOf(value);
  4264. if (position >= this.length) {
  4265. return -1;
  4266. }
  4267. return position;
  4268. };
  4269. // Statics
  4270. SmartArray._GlobalId = 0;
  4271. return SmartArray;
  4272. })();
  4273. BABYLON.SmartArray = SmartArray;
  4274. })(BABYLON || (BABYLON = {}));
  4275. var BABYLON;
  4276. (function (BABYLON) {
  4277. /**
  4278. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4279. * The underlying implementation relies on an associative array to ensure the best performances.
  4280. * The value can be anything including 'null' but except 'undefined'
  4281. */
  4282. var StringDictionary = (function () {
  4283. function StringDictionary() {
  4284. this._count = 0;
  4285. this._data = {};
  4286. }
  4287. /**
  4288. * Get a value based from its key
  4289. * @param key the given key to get the matching value from
  4290. * @return the value if found, otherwise undefined is returned
  4291. */
  4292. StringDictionary.prototype.get = function (key) {
  4293. var val = this._data[key];
  4294. if (val !== undefined) {
  4295. return val;
  4296. }
  4297. return undefined;
  4298. };
  4299. /**
  4300. * Get a value from its key or add it if it doesn't exist.
  4301. * This method will ensure you that a given key/data will be present in the dictionary.
  4302. * @param key the given key to get the matching value from
  4303. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4304. * The factory will only be invoked if there's no data for the given key.
  4305. * @return the value corresponding to the key.
  4306. */
  4307. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4308. var val = this.get(key);
  4309. if (val !== undefined) {
  4310. return val;
  4311. }
  4312. val = factory(key);
  4313. if (val) {
  4314. this.add(key, val);
  4315. }
  4316. return val;
  4317. };
  4318. /**
  4319. * Get a value from its key if present in the dictionary otherwise add it
  4320. * @param key the key to get the value from
  4321. * @param val if there's no such key/value pair in the dictionary add it with this value
  4322. * @return the value corresponding to the key
  4323. */
  4324. StringDictionary.prototype.getOrAdd = function (key, val) {
  4325. var curVal = this.get(key);
  4326. if (curVal !== undefined) {
  4327. return curVal;
  4328. }
  4329. this.add(key, val);
  4330. return val;
  4331. };
  4332. /**
  4333. * Check if there's a given key in the dictionary
  4334. * @param key the key to check for
  4335. * @return true if the key is present, false otherwise
  4336. */
  4337. StringDictionary.prototype.contains = function (key) {
  4338. return this._data[key] !== undefined;
  4339. };
  4340. /**
  4341. * Add a new key and its corresponding value
  4342. * @param key the key to add
  4343. * @param value the value corresponding to the key
  4344. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  4345. */
  4346. StringDictionary.prototype.add = function (key, value) {
  4347. if (this._data[key] !== undefined) {
  4348. return false;
  4349. }
  4350. this._data[key] = value;
  4351. ++this._count;
  4352. return true;
  4353. };
  4354. StringDictionary.prototype.set = function (key, value) {
  4355. if (this._data[key] === undefined) {
  4356. return false;
  4357. }
  4358. this._data[key] = value;
  4359. return true;
  4360. };
  4361. /**
  4362. * Remove a key/value from the dictionary.
  4363. * @param key the key to remove
  4364. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4365. */
  4366. StringDictionary.prototype.remove = function (key) {
  4367. if (this.contains(key)) {
  4368. delete this._data[key];
  4369. --this._count;
  4370. return true;
  4371. }
  4372. return false;
  4373. };
  4374. /**
  4375. * Clear the whole content of the dictionary
  4376. */
  4377. StringDictionary.prototype.clear = function () {
  4378. this._data = {};
  4379. this._count = 0;
  4380. };
  4381. Object.defineProperty(StringDictionary.prototype, "count", {
  4382. get: function () {
  4383. return this._count;
  4384. },
  4385. enumerable: true,
  4386. configurable: true
  4387. });
  4388. /**
  4389. * Execute a callback on each key/val of the dictionary.
  4390. * Note that you can remove any element in this dictionary in the callback implementation
  4391. * @param callback the callback to execute on a given key/value pair
  4392. */
  4393. StringDictionary.prototype.forEach = function (callback) {
  4394. for (var cur in this._data) {
  4395. var val = this._data[cur];
  4396. callback(cur, val);
  4397. }
  4398. };
  4399. /**
  4400. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4401. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4402. * Note that you can remove any element in this dictionary in the callback implementation
  4403. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4404. */
  4405. StringDictionary.prototype.first = function (callback) {
  4406. for (var cur in this._data) {
  4407. var val = this._data[cur];
  4408. var res = callback(cur, val);
  4409. if (res) {
  4410. return res;
  4411. }
  4412. }
  4413. return null;
  4414. };
  4415. return StringDictionary;
  4416. })();
  4417. BABYLON.StringDictionary = StringDictionary;
  4418. })(BABYLON || (BABYLON = {}));
  4419. var BABYLON;
  4420. (function (BABYLON) {
  4421. // Screenshots
  4422. var screenshotCanvas;
  4423. var cloneValue = function (source, destinationObject) {
  4424. if (!source)
  4425. return null;
  4426. if (source instanceof BABYLON.Mesh) {
  4427. return null;
  4428. }
  4429. if (source instanceof BABYLON.SubMesh) {
  4430. return source.clone(destinationObject);
  4431. }
  4432. else if (source.clone) {
  4433. return source.clone();
  4434. }
  4435. return null;
  4436. };
  4437. var Tools = (function () {
  4438. function Tools() {
  4439. }
  4440. Tools.Instantiate = function (className) {
  4441. var arr = className.split(".");
  4442. var fn = (window || this);
  4443. for (var i = 0, len = arr.length; i < len; i++) {
  4444. fn = fn[arr[i]];
  4445. }
  4446. if (typeof fn !== "function") {
  4447. return null;
  4448. }
  4449. return fn;
  4450. };
  4451. Tools.SetImmediate = function (action) {
  4452. if (window.setImmediate) {
  4453. window.setImmediate(action);
  4454. }
  4455. else {
  4456. setTimeout(action, 1);
  4457. }
  4458. };
  4459. Tools.IsExponentOfTwo = function (value) {
  4460. var count = 1;
  4461. do {
  4462. count *= 2;
  4463. } while (count < value);
  4464. return count === value;
  4465. };
  4466. Tools.GetExponentOfTwo = function (value, max) {
  4467. var count = 1;
  4468. do {
  4469. count *= 2;
  4470. } while (count < value);
  4471. if (count > max)
  4472. count = max;
  4473. return count;
  4474. };
  4475. Tools.GetFilename = function (path) {
  4476. var index = path.lastIndexOf("/");
  4477. if (index < 0)
  4478. return path;
  4479. return path.substring(index + 1);
  4480. };
  4481. Tools.GetDOMTextContent = function (element) {
  4482. var result = "";
  4483. var child = element.firstChild;
  4484. while (child) {
  4485. if (child.nodeType === 3) {
  4486. result += child.textContent;
  4487. }
  4488. child = child.nextSibling;
  4489. }
  4490. return result;
  4491. };
  4492. Tools.ToDegrees = function (angle) {
  4493. return angle * 180 / Math.PI;
  4494. };
  4495. Tools.ToRadians = function (angle) {
  4496. return angle * Math.PI / 180;
  4497. };
  4498. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4499. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4500. var output = "";
  4501. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4502. var i = 0;
  4503. var bytes = new Uint8Array(buffer);
  4504. while (i < bytes.length) {
  4505. chr1 = bytes[i++];
  4506. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4507. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4508. enc1 = chr1 >> 2;
  4509. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4510. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4511. enc4 = chr3 & 63;
  4512. if (isNaN(chr2)) {
  4513. enc3 = enc4 = 64;
  4514. }
  4515. else if (isNaN(chr3)) {
  4516. enc4 = 64;
  4517. }
  4518. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4519. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4520. }
  4521. return "data:image/png;base64," + output;
  4522. };
  4523. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4524. if (bias === void 0) { bias = null; }
  4525. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4526. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4527. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4528. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4529. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4530. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4531. }
  4532. if (bias) {
  4533. minimum.x -= minimum.x * bias.x + bias.y;
  4534. minimum.y -= minimum.y * bias.x + bias.y;
  4535. minimum.z -= minimum.z * bias.x + bias.y;
  4536. maximum.x += maximum.x * bias.x + bias.y;
  4537. maximum.y += maximum.y * bias.x + bias.y;
  4538. maximum.z += maximum.z * bias.x + bias.y;
  4539. }
  4540. return {
  4541. minimum: minimum,
  4542. maximum: maximum
  4543. };
  4544. };
  4545. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4546. if (bias === void 0) { bias = null; }
  4547. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4548. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4549. if (!stride) {
  4550. stride = 3;
  4551. }
  4552. for (var index = start; index < start + count; index++) {
  4553. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4554. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4555. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4556. }
  4557. if (bias) {
  4558. minimum.x -= minimum.x * bias.x + bias.y;
  4559. minimum.y -= minimum.y * bias.x + bias.y;
  4560. minimum.z -= minimum.z * bias.x + bias.y;
  4561. maximum.x += maximum.x * bias.x + bias.y;
  4562. maximum.y += maximum.y * bias.x + bias.y;
  4563. maximum.z += maximum.z * bias.x + bias.y;
  4564. }
  4565. return {
  4566. minimum: minimum,
  4567. maximum: maximum
  4568. };
  4569. };
  4570. Tools.Vector2ArrayFeeder = function (array) {
  4571. return function (index) {
  4572. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4573. var length = isFloatArray ? array.length / 2 : array.length;
  4574. if (index >= length) {
  4575. return null;
  4576. }
  4577. if (isFloatArray) {
  4578. var fa = array;
  4579. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4580. }
  4581. var a = array;
  4582. return a[index];
  4583. };
  4584. };
  4585. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4586. if (bias === void 0) { bias = null; }
  4587. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4588. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4589. var i = 0;
  4590. var cur = feeder(i++);
  4591. while (cur) {
  4592. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4593. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4594. cur = feeder(i++);
  4595. }
  4596. if (bias) {
  4597. minimum.x -= minimum.x * bias.x + bias.y;
  4598. minimum.y -= minimum.y * bias.x + bias.y;
  4599. maximum.x += maximum.x * bias.x + bias.y;
  4600. maximum.y += maximum.y * bias.x + bias.y;
  4601. }
  4602. return {
  4603. minimum: minimum,
  4604. maximum: maximum
  4605. };
  4606. };
  4607. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4608. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4609. return undefined;
  4610. return Array.isArray(obj) ? obj : [obj];
  4611. };
  4612. // Misc.
  4613. Tools.GetPointerPrefix = function () {
  4614. var eventPrefix = "pointer";
  4615. // Check if pointer events are supported
  4616. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4617. eventPrefix = "mouse";
  4618. }
  4619. return eventPrefix;
  4620. };
  4621. Tools.QueueNewFrame = function (func) {
  4622. if (window.requestAnimationFrame)
  4623. window.requestAnimationFrame(func);
  4624. else if (window.msRequestAnimationFrame)
  4625. window.msRequestAnimationFrame(func);
  4626. else if (window.webkitRequestAnimationFrame)
  4627. window.webkitRequestAnimationFrame(func);
  4628. else if (window.mozRequestAnimationFrame)
  4629. window.mozRequestAnimationFrame(func);
  4630. else if (window.oRequestAnimationFrame)
  4631. window.oRequestAnimationFrame(func);
  4632. else {
  4633. window.setTimeout(func, 16);
  4634. }
  4635. };
  4636. Tools.RequestFullscreen = function (element, options) {
  4637. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4638. if (!requestFunction)
  4639. return;
  4640. requestFunction.call(element, options);
  4641. };
  4642. Tools.ExitFullscreen = function () {
  4643. if (document.exitFullscreen) {
  4644. document.exitFullscreen();
  4645. }
  4646. else if (document.mozCancelFullScreen) {
  4647. document.mozCancelFullScreen();
  4648. }
  4649. else if (document.webkitCancelFullScreen) {
  4650. document.webkitCancelFullScreen();
  4651. }
  4652. else if (document.msCancelFullScreen) {
  4653. document.msCancelFullScreen();
  4654. }
  4655. };
  4656. // External files
  4657. Tools.CleanUrl = function (url) {
  4658. url = url.replace(/#/mg, "%23");
  4659. return url;
  4660. };
  4661. Tools.LoadImage = function (url, onload, onerror, database) {
  4662. if (url instanceof ArrayBuffer) {
  4663. url = Tools.EncodeArrayBufferTobase64(url);
  4664. }
  4665. url = Tools.CleanUrl(url);
  4666. var img = new Image();
  4667. if (url.substr(0, 5) !== "data:") {
  4668. if (Tools.CorsBehavior) {
  4669. switch (typeof (Tools.CorsBehavior)) {
  4670. case "function":
  4671. var result = Tools.CorsBehavior(url);
  4672. if (result) {
  4673. img.crossOrigin = result;
  4674. }
  4675. break;
  4676. case "string":
  4677. default:
  4678. img.crossOrigin = Tools.CorsBehavior;
  4679. break;
  4680. }
  4681. }
  4682. }
  4683. img.onload = function () {
  4684. onload(img);
  4685. };
  4686. img.onerror = function (err) {
  4687. Tools.Error("Error while trying to load texture: " + url);
  4688. if (Tools.UseFallbackTexture) {
  4689. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4690. onload(img);
  4691. }
  4692. else {
  4693. onerror();
  4694. }
  4695. };
  4696. var noIndexedDB = function () {
  4697. img.src = url;
  4698. };
  4699. var loadFromIndexedDB = function () {
  4700. database.loadImageFromDB(url, img);
  4701. };
  4702. //ANY database to do!
  4703. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4704. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4705. }
  4706. else {
  4707. if (url.indexOf("file:") === -1) {
  4708. noIndexedDB();
  4709. }
  4710. else {
  4711. try {
  4712. var textureName = url.substring(5).toLowerCase();
  4713. var blobURL;
  4714. try {
  4715. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4716. }
  4717. catch (ex) {
  4718. // Chrome doesn't support oneTimeOnly parameter
  4719. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4720. }
  4721. img.src = blobURL;
  4722. }
  4723. catch (e) {
  4724. img.src = null;
  4725. }
  4726. }
  4727. }
  4728. return img;
  4729. };
  4730. //ANY
  4731. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4732. url = Tools.CleanUrl(url);
  4733. var noIndexedDB = function () {
  4734. var request = new XMLHttpRequest();
  4735. var loadUrl = Tools.BaseUrl + url;
  4736. request.open('GET', loadUrl, true);
  4737. if (useArrayBuffer) {
  4738. request.responseType = "arraybuffer";
  4739. }
  4740. request.onprogress = progressCallBack;
  4741. request.onreadystatechange = function () {
  4742. if (request.readyState === 4) {
  4743. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4744. callback(!useArrayBuffer ? request.responseText : request.response);
  4745. }
  4746. else {
  4747. if (onError) {
  4748. onError();
  4749. }
  4750. else {
  4751. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4752. }
  4753. }
  4754. }
  4755. };
  4756. request.send(null);
  4757. };
  4758. var loadFromIndexedDB = function () {
  4759. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4760. };
  4761. if (url.indexOf("file:") !== -1) {
  4762. var fileName = url.substring(5).toLowerCase();
  4763. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4764. }
  4765. else {
  4766. // Caching all files
  4767. if (database && database.enableSceneOffline) {
  4768. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4769. }
  4770. else {
  4771. noIndexedDB();
  4772. }
  4773. }
  4774. };
  4775. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4776. var reader = new FileReader();
  4777. reader.onload = function (e) {
  4778. //target doesn't have result from ts 1.3
  4779. callback(e.target['result']);
  4780. };
  4781. reader.onprogress = progressCallback;
  4782. reader.readAsDataURL(fileToLoad);
  4783. };
  4784. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4785. var reader = new FileReader();
  4786. reader.onerror = function (e) {
  4787. Tools.Log("Error while reading file: " + fileToLoad.name);
  4788. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4789. };
  4790. reader.onload = function (e) {
  4791. //target doesn't have result from ts 1.3
  4792. callback(e.target['result']);
  4793. };
  4794. reader.onprogress = progressCallBack;
  4795. if (!useArrayBuffer) {
  4796. // Asynchronous read
  4797. reader.readAsText(fileToLoad);
  4798. }
  4799. else {
  4800. reader.readAsArrayBuffer(fileToLoad);
  4801. }
  4802. };
  4803. //returns a downloadable url to a file content.
  4804. Tools.FileAsURL = function (content) {
  4805. var fileBlob = new Blob([content]);
  4806. var url = window.URL || window.webkitURL;
  4807. var link = url.createObjectURL(fileBlob);
  4808. return link;
  4809. };
  4810. // Misc.
  4811. Tools.Format = function (value, decimals) {
  4812. if (decimals === void 0) { decimals = 2; }
  4813. return value.toFixed(decimals);
  4814. };
  4815. Tools.CheckExtends = function (v, min, max) {
  4816. if (v.x < min.x)
  4817. min.x = v.x;
  4818. if (v.y < min.y)
  4819. min.y = v.y;
  4820. if (v.z < min.z)
  4821. min.z = v.z;
  4822. if (v.x > max.x)
  4823. max.x = v.x;
  4824. if (v.y > max.y)
  4825. max.y = v.y;
  4826. if (v.z > max.z)
  4827. max.z = v.z;
  4828. };
  4829. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4830. for (var prop in source) {
  4831. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4832. continue;
  4833. }
  4834. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4835. continue;
  4836. }
  4837. var sourceValue = source[prop];
  4838. var typeOfSourceValue = typeof sourceValue;
  4839. if (typeOfSourceValue === "function") {
  4840. continue;
  4841. }
  4842. if (typeOfSourceValue === "object") {
  4843. if (sourceValue instanceof Array) {
  4844. destination[prop] = [];
  4845. if (sourceValue.length > 0) {
  4846. if (typeof sourceValue[0] == "object") {
  4847. for (var index = 0; index < sourceValue.length; index++) {
  4848. var clonedValue = cloneValue(sourceValue[index], destination);
  4849. if (destination[prop].indexOf(clonedValue) === -1) {
  4850. destination[prop].push(clonedValue);
  4851. }
  4852. }
  4853. }
  4854. else {
  4855. destination[prop] = sourceValue.slice(0);
  4856. }
  4857. }
  4858. }
  4859. else {
  4860. destination[prop] = cloneValue(sourceValue, destination);
  4861. }
  4862. }
  4863. else {
  4864. destination[prop] = sourceValue;
  4865. }
  4866. }
  4867. };
  4868. Tools.IsEmpty = function (obj) {
  4869. for (var i in obj) {
  4870. return false;
  4871. }
  4872. return true;
  4873. };
  4874. Tools.RegisterTopRootEvents = function (events) {
  4875. for (var index = 0; index < events.length; index++) {
  4876. var event = events[index];
  4877. window.addEventListener(event.name, event.handler, false);
  4878. try {
  4879. if (window.parent) {
  4880. window.parent.addEventListener(event.name, event.handler, false);
  4881. }
  4882. }
  4883. catch (e) {
  4884. }
  4885. }
  4886. };
  4887. Tools.UnregisterTopRootEvents = function (events) {
  4888. for (var index = 0; index < events.length; index++) {
  4889. var event = events[index];
  4890. window.removeEventListener(event.name, event.handler);
  4891. try {
  4892. if (window.parent) {
  4893. window.parent.removeEventListener(event.name, event.handler);
  4894. }
  4895. }
  4896. catch (e) {
  4897. }
  4898. }
  4899. };
  4900. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4901. // Read the contents of the framebuffer
  4902. var numberOfChannelsByLine = width * 4;
  4903. var halfHeight = height / 2;
  4904. //Reading datas from WebGL
  4905. var data = engine.readPixels(0, 0, width, height);
  4906. //To flip image on Y axis.
  4907. for (var i = 0; i < halfHeight; i++) {
  4908. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4909. var currentCell = j + i * numberOfChannelsByLine;
  4910. var targetLine = height - i - 1;
  4911. var targetCell = j + targetLine * numberOfChannelsByLine;
  4912. var temp = data[currentCell];
  4913. data[currentCell] = data[targetCell];
  4914. data[targetCell] = temp;
  4915. }
  4916. }
  4917. // Create a 2D canvas to store the result
  4918. if (!screenshotCanvas) {
  4919. screenshotCanvas = document.createElement('canvas');
  4920. }
  4921. screenshotCanvas.width = width;
  4922. screenshotCanvas.height = height;
  4923. var context = screenshotCanvas.getContext('2d');
  4924. // Copy the pixels to a 2D canvas
  4925. var imageData = context.createImageData(width, height);
  4926. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4927. var castData = imageData.data;
  4928. castData.set(data);
  4929. context.putImageData(imageData, 0, 0);
  4930. var base64Image = screenshotCanvas.toDataURL();
  4931. if (successCallback) {
  4932. successCallback(base64Image);
  4933. }
  4934. else {
  4935. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4936. if (("download" in document.createElement("a"))) {
  4937. var a = window.document.createElement("a");
  4938. a.href = base64Image;
  4939. var date = new Date();
  4940. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4941. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4942. window.document.body.appendChild(a);
  4943. a.addEventListener("click", function () {
  4944. a.parentElement.removeChild(a);
  4945. });
  4946. a.click();
  4947. }
  4948. else {
  4949. var newWindow = window.open("");
  4950. var img = newWindow.document.createElement("img");
  4951. img.src = base64Image;
  4952. newWindow.document.body.appendChild(img);
  4953. }
  4954. }
  4955. };
  4956. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4957. var width;
  4958. var height;
  4959. //If a precision value is specified
  4960. if (size.precision) {
  4961. width = Math.round(engine.getRenderWidth() * size.precision);
  4962. height = Math.round(width / engine.getAspectRatio(camera));
  4963. size = { width: width, height: height };
  4964. }
  4965. else if (size.width && size.height) {
  4966. width = size.width;
  4967. height = size.height;
  4968. }
  4969. else if (size.width && !size.height) {
  4970. width = size.width;
  4971. height = Math.round(width / engine.getAspectRatio(camera));
  4972. size = { width: width, height: height };
  4973. }
  4974. else if (size.height && !size.width) {
  4975. height = size.height;
  4976. width = Math.round(height * engine.getAspectRatio(camera));
  4977. size = { width: width, height: height };
  4978. }
  4979. else if (!isNaN(size)) {
  4980. height = size;
  4981. width = size;
  4982. }
  4983. else {
  4984. Tools.Error("Invalid 'size' parameter !");
  4985. return;
  4986. }
  4987. var scene = camera.getScene();
  4988. var previousCamera = null;
  4989. if (scene.activeCamera !== camera) {
  4990. previousCamera = scene.activeCamera;
  4991. scene.activeCamera = camera;
  4992. }
  4993. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4994. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4995. texture.renderList = scene.meshes;
  4996. texture.onAfterRenderObservable.add(function () {
  4997. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4998. });
  4999. scene.incrementRenderId();
  5000. scene.resetCachedMaterial();
  5001. texture.render(true);
  5002. texture.dispose();
  5003. if (previousCamera) {
  5004. scene.activeCamera = previousCamera;
  5005. }
  5006. camera.getProjectionMatrix(true); // Force cache refresh;
  5007. };
  5008. // XHR response validator for local file scenario
  5009. Tools.ValidateXHRData = function (xhr, dataType) {
  5010. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5011. if (dataType === void 0) { dataType = 7; }
  5012. try {
  5013. if (dataType & 1) {
  5014. if (xhr.responseText && xhr.responseText.length > 0) {
  5015. return true;
  5016. }
  5017. else if (dataType === 1) {
  5018. return false;
  5019. }
  5020. }
  5021. if (dataType & 2) {
  5022. // Check header width and height since there is no "TGA" magic number
  5023. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5024. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5025. return true;
  5026. }
  5027. else if (dataType === 2) {
  5028. return false;
  5029. }
  5030. }
  5031. if (dataType & 4) {
  5032. // Check for the "DDS" magic number
  5033. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5034. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5035. return true;
  5036. }
  5037. else {
  5038. return false;
  5039. }
  5040. }
  5041. }
  5042. catch (e) {
  5043. }
  5044. return false;
  5045. };
  5046. Object.defineProperty(Tools, "NoneLogLevel", {
  5047. get: function () {
  5048. return Tools._NoneLogLevel;
  5049. },
  5050. enumerable: true,
  5051. configurable: true
  5052. });
  5053. Object.defineProperty(Tools, "MessageLogLevel", {
  5054. get: function () {
  5055. return Tools._MessageLogLevel;
  5056. },
  5057. enumerable: true,
  5058. configurable: true
  5059. });
  5060. Object.defineProperty(Tools, "WarningLogLevel", {
  5061. get: function () {
  5062. return Tools._WarningLogLevel;
  5063. },
  5064. enumerable: true,
  5065. configurable: true
  5066. });
  5067. Object.defineProperty(Tools, "ErrorLogLevel", {
  5068. get: function () {
  5069. return Tools._ErrorLogLevel;
  5070. },
  5071. enumerable: true,
  5072. configurable: true
  5073. });
  5074. Object.defineProperty(Tools, "AllLogLevel", {
  5075. get: function () {
  5076. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5077. },
  5078. enumerable: true,
  5079. configurable: true
  5080. });
  5081. Tools._AddLogEntry = function (entry) {
  5082. Tools._LogCache = entry + Tools._LogCache;
  5083. if (Tools.OnNewCacheEntry) {
  5084. Tools.OnNewCacheEntry(entry);
  5085. }
  5086. };
  5087. Tools._FormatMessage = function (message) {
  5088. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5089. var date = new Date();
  5090. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5091. };
  5092. Tools._LogDisabled = function (message) {
  5093. // nothing to do
  5094. };
  5095. Tools._LogEnabled = function (message) {
  5096. var formattedMessage = Tools._FormatMessage(message);
  5097. console.log("BJS - " + formattedMessage);
  5098. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5099. Tools._AddLogEntry(entry);
  5100. };
  5101. Tools._WarnDisabled = function (message) {
  5102. // nothing to do
  5103. };
  5104. Tools._WarnEnabled = function (message) {
  5105. var formattedMessage = Tools._FormatMessage(message);
  5106. console.warn("BJS - " + formattedMessage);
  5107. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5108. Tools._AddLogEntry(entry);
  5109. };
  5110. Tools._ErrorDisabled = function (message) {
  5111. // nothing to do
  5112. };
  5113. Tools._ErrorEnabled = function (message) {
  5114. Tools.errorsCount++;
  5115. var formattedMessage = Tools._FormatMessage(message);
  5116. console.error("BJS - " + formattedMessage);
  5117. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5118. Tools._AddLogEntry(entry);
  5119. };
  5120. Object.defineProperty(Tools, "LogCache", {
  5121. get: function () {
  5122. return Tools._LogCache;
  5123. },
  5124. enumerable: true,
  5125. configurable: true
  5126. });
  5127. Tools.ClearLogCache = function () {
  5128. Tools._LogCache = "";
  5129. Tools.errorsCount = 0;
  5130. };
  5131. Object.defineProperty(Tools, "LogLevels", {
  5132. set: function (level) {
  5133. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5134. Tools.Log = Tools._LogEnabled;
  5135. }
  5136. else {
  5137. Tools.Log = Tools._LogDisabled;
  5138. }
  5139. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5140. Tools.Warn = Tools._WarnEnabled;
  5141. }
  5142. else {
  5143. Tools.Warn = Tools._WarnDisabled;
  5144. }
  5145. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5146. Tools.Error = Tools._ErrorEnabled;
  5147. }
  5148. else {
  5149. Tools.Error = Tools._ErrorDisabled;
  5150. }
  5151. },
  5152. enumerable: true,
  5153. configurable: true
  5154. });
  5155. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5156. get: function () {
  5157. return Tools._PerformanceNoneLogLevel;
  5158. },
  5159. enumerable: true,
  5160. configurable: true
  5161. });
  5162. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5163. get: function () {
  5164. return Tools._PerformanceUserMarkLogLevel;
  5165. },
  5166. enumerable: true,
  5167. configurable: true
  5168. });
  5169. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5170. get: function () {
  5171. return Tools._PerformanceConsoleLogLevel;
  5172. },
  5173. enumerable: true,
  5174. configurable: true
  5175. });
  5176. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5177. set: function (level) {
  5178. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5179. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5180. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5181. return;
  5182. }
  5183. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5184. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5185. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5186. return;
  5187. }
  5188. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5189. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5190. },
  5191. enumerable: true,
  5192. configurable: true
  5193. });
  5194. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5195. };
  5196. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5197. };
  5198. Tools._StartUserMark = function (counterName, condition) {
  5199. if (condition === void 0) { condition = true; }
  5200. if (!condition || !Tools._performance.mark) {
  5201. return;
  5202. }
  5203. Tools._performance.mark(counterName + "-Begin");
  5204. };
  5205. Tools._EndUserMark = function (counterName, condition) {
  5206. if (condition === void 0) { condition = true; }
  5207. if (!condition || !Tools._performance.mark) {
  5208. return;
  5209. }
  5210. Tools._performance.mark(counterName + "-End");
  5211. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5212. };
  5213. Tools._StartPerformanceConsole = function (counterName, condition) {
  5214. if (condition === void 0) { condition = true; }
  5215. if (!condition) {
  5216. return;
  5217. }
  5218. Tools._StartUserMark(counterName, condition);
  5219. if (console.time) {
  5220. console.time(counterName);
  5221. }
  5222. };
  5223. Tools._EndPerformanceConsole = function (counterName, condition) {
  5224. if (condition === void 0) { condition = true; }
  5225. if (!condition) {
  5226. return;
  5227. }
  5228. Tools._EndUserMark(counterName, condition);
  5229. if (console.time) {
  5230. console.timeEnd(counterName);
  5231. }
  5232. };
  5233. Object.defineProperty(Tools, "Now", {
  5234. get: function () {
  5235. if (window.performance && window.performance.now) {
  5236. return window.performance.now();
  5237. }
  5238. return new Date().getTime();
  5239. },
  5240. enumerable: true,
  5241. configurable: true
  5242. });
  5243. /**
  5244. * This method will return the name of the class used to create the instance of the given object.
  5245. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5246. * @param object the object to get the class name from
  5247. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5248. */
  5249. Tools.getClassName = function (object, isType) {
  5250. if (isType === void 0) { isType = false; }
  5251. var name = null;
  5252. if (!isType && object.getClassName) {
  5253. name = object.getClassName();
  5254. }
  5255. else {
  5256. if (object instanceof Object) {
  5257. var classObj = isType ? object : Object.getPrototypeOf(object);
  5258. name = classObj.constructor["__bjsclassName__"];
  5259. }
  5260. if (!name) {
  5261. name = typeof object;
  5262. }
  5263. }
  5264. return name;
  5265. };
  5266. Tools.first = function (array, predicate) {
  5267. for (var _i = 0; _i < array.length; _i++) {
  5268. var el = array[_i];
  5269. if (predicate(el)) {
  5270. return el;
  5271. }
  5272. }
  5273. };
  5274. /**
  5275. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  5276. * @param array
  5277. */
  5278. Tools.arrayOrStringFeeder = function (array) {
  5279. return function (index) {
  5280. if (index >= array.length) {
  5281. return null;
  5282. }
  5283. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5284. if (val && val.getHashCode) {
  5285. val = val.getHashCode();
  5286. }
  5287. if (typeof val === "string") {
  5288. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5289. }
  5290. return val;
  5291. };
  5292. };
  5293. /**
  5294. * Compute the hashCode of a stream of number
  5295. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5296. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5297. * @return the hash code computed
  5298. */
  5299. Tools.hashCodeFromStream = function (feeder) {
  5300. // Based from here: http://stackoverflow.com/a/7616484/802124
  5301. var hash = 0;
  5302. var index = 0;
  5303. var chr = feeder(index++);
  5304. while (chr != null) {
  5305. hash = ((hash << 5) - hash) + chr;
  5306. hash |= 0; // Convert to 32bit integer
  5307. chr = feeder(index++);
  5308. }
  5309. return hash;
  5310. };
  5311. Tools.BaseUrl = "";
  5312. Tools.CorsBehavior = "anonymous";
  5313. Tools.UseFallbackTexture = true;
  5314. // Logs
  5315. Tools._NoneLogLevel = 0;
  5316. Tools._MessageLogLevel = 1;
  5317. Tools._WarningLogLevel = 2;
  5318. Tools._ErrorLogLevel = 4;
  5319. Tools._LogCache = "";
  5320. Tools.errorsCount = 0;
  5321. Tools.Log = Tools._LogEnabled;
  5322. Tools.Warn = Tools._WarnEnabled;
  5323. Tools.Error = Tools._ErrorEnabled;
  5324. // Performances
  5325. Tools._PerformanceNoneLogLevel = 0;
  5326. Tools._PerformanceUserMarkLogLevel = 1;
  5327. Tools._PerformanceConsoleLogLevel = 2;
  5328. Tools._performance = window.performance;
  5329. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5330. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5331. return Tools;
  5332. })();
  5333. BABYLON.Tools = Tools;
  5334. /**
  5335. * Use this className as a decorator on a given class definition to add it a name.
  5336. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5337. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5338. * @param name
  5339. */
  5340. function className(name) {
  5341. return function (target) {
  5342. target["__bjsclassName__"] = name;
  5343. };
  5344. }
  5345. BABYLON.className = className;
  5346. /**
  5347. * An implementation of a loop for asynchronous functions.
  5348. */
  5349. var AsyncLoop = (function () {
  5350. /**
  5351. * Constroctor.
  5352. * @param iterations the number of iterations.
  5353. * @param _fn the function to run each iteration
  5354. * @param _successCallback the callback that will be called upon succesful execution
  5355. * @param offset starting offset.
  5356. */
  5357. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5358. if (offset === void 0) { offset = 0; }
  5359. this.iterations = iterations;
  5360. this._fn = _fn;
  5361. this._successCallback = _successCallback;
  5362. this.index = offset - 1;
  5363. this._done = false;
  5364. }
  5365. /**
  5366. * Execute the next iteration. Must be called after the last iteration was finished.
  5367. */
  5368. AsyncLoop.prototype.executeNext = function () {
  5369. if (!this._done) {
  5370. if (this.index + 1 < this.iterations) {
  5371. ++this.index;
  5372. this._fn(this);
  5373. }
  5374. else {
  5375. this.breakLoop();
  5376. }
  5377. }
  5378. };
  5379. /**
  5380. * Break the loop and run the success callback.
  5381. */
  5382. AsyncLoop.prototype.breakLoop = function () {
  5383. this._done = true;
  5384. this._successCallback();
  5385. };
  5386. /**
  5387. * Helper function
  5388. */
  5389. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5390. if (offset === void 0) { offset = 0; }
  5391. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5392. loop.executeNext();
  5393. return loop;
  5394. };
  5395. /**
  5396. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5397. * @param iterations total number of iterations
  5398. * @param syncedIterations number of synchronous iterations in each async iteration.
  5399. * @param fn the function to call each iteration.
  5400. * @param callback a success call back that will be called when iterating stops.
  5401. * @param breakFunction a break condition (optional)
  5402. * @param timeout timeout settings for the setTimeout function. default - 0.
  5403. * @constructor
  5404. */
  5405. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5406. if (timeout === void 0) { timeout = 0; }
  5407. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5408. if (breakFunction && breakFunction())
  5409. loop.breakLoop();
  5410. else {
  5411. setTimeout(function () {
  5412. for (var i = 0; i < syncedIterations; ++i) {
  5413. var iteration = (loop.index * syncedIterations) + i;
  5414. if (iteration >= iterations)
  5415. break;
  5416. fn(iteration);
  5417. if (breakFunction && breakFunction()) {
  5418. loop.breakLoop();
  5419. break;
  5420. }
  5421. }
  5422. loop.executeNext();
  5423. }, timeout);
  5424. }
  5425. }, callback);
  5426. };
  5427. return AsyncLoop;
  5428. })();
  5429. BABYLON.AsyncLoop = AsyncLoop;
  5430. })(BABYLON || (BABYLON = {}));
  5431. var BABYLON;
  5432. (function (BABYLON) {
  5433. var Internals;
  5434. (function (Internals) {
  5435. var _AlphaState = (function () {
  5436. function _AlphaState() {
  5437. this._isAlphaBlendDirty = false;
  5438. this._isBlendFunctionParametersDirty = false;
  5439. this._alphaBlend = false;
  5440. this._blendFunctionParameters = new Array(4);
  5441. }
  5442. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5443. get: function () {
  5444. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5445. },
  5446. enumerable: true,
  5447. configurable: true
  5448. });
  5449. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5450. get: function () {
  5451. return this._alphaBlend;
  5452. },
  5453. set: function (value) {
  5454. if (this._alphaBlend === value) {
  5455. return;
  5456. }
  5457. this._alphaBlend = value;
  5458. this._isAlphaBlendDirty = true;
  5459. },
  5460. enumerable: true,
  5461. configurable: true
  5462. });
  5463. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5464. if (this._blendFunctionParameters[0] === value0 &&
  5465. this._blendFunctionParameters[1] === value1 &&
  5466. this._blendFunctionParameters[2] === value2 &&
  5467. this._blendFunctionParameters[3] === value3) {
  5468. return;
  5469. }
  5470. this._blendFunctionParameters[0] = value0;
  5471. this._blendFunctionParameters[1] = value1;
  5472. this._blendFunctionParameters[2] = value2;
  5473. this._blendFunctionParameters[3] = value3;
  5474. this._isBlendFunctionParametersDirty = true;
  5475. };
  5476. _AlphaState.prototype.reset = function () {
  5477. this._alphaBlend = false;
  5478. this._blendFunctionParameters[0] = null;
  5479. this._blendFunctionParameters[1] = null;
  5480. this._blendFunctionParameters[2] = null;
  5481. this._blendFunctionParameters[3] = null;
  5482. this._isAlphaBlendDirty = true;
  5483. this._isBlendFunctionParametersDirty = false;
  5484. };
  5485. _AlphaState.prototype.apply = function (gl) {
  5486. if (!this.isDirty) {
  5487. return;
  5488. }
  5489. // Alpha blend
  5490. if (this._isAlphaBlendDirty) {
  5491. if (this._alphaBlend) {
  5492. gl.enable(gl.BLEND);
  5493. }
  5494. else {
  5495. gl.disable(gl.BLEND);
  5496. }
  5497. this._isAlphaBlendDirty = false;
  5498. }
  5499. // Alpha function
  5500. if (this._isBlendFunctionParametersDirty) {
  5501. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5502. this._isBlendFunctionParametersDirty = false;
  5503. }
  5504. };
  5505. return _AlphaState;
  5506. })();
  5507. Internals._AlphaState = _AlphaState;
  5508. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5509. })(BABYLON || (BABYLON = {}));
  5510. var BABYLON;
  5511. (function (BABYLON) {
  5512. var Internals;
  5513. (function (Internals) {
  5514. var _DepthCullingState = (function () {
  5515. function _DepthCullingState() {
  5516. this._isDepthTestDirty = false;
  5517. this._isDepthMaskDirty = false;
  5518. this._isDepthFuncDirty = false;
  5519. this._isCullFaceDirty = false;
  5520. this._isCullDirty = false;
  5521. this._isZOffsetDirty = false;
  5522. }
  5523. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5524. get: function () {
  5525. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5526. },
  5527. enumerable: true,
  5528. configurable: true
  5529. });
  5530. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5531. get: function () {
  5532. return this._zOffset;
  5533. },
  5534. set: function (value) {
  5535. if (this._zOffset === value) {
  5536. return;
  5537. }
  5538. this._zOffset = value;
  5539. this._isZOffsetDirty = true;
  5540. },
  5541. enumerable: true,
  5542. configurable: true
  5543. });
  5544. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5545. get: function () {
  5546. return this._cullFace;
  5547. },
  5548. set: function (value) {
  5549. if (this._cullFace === value) {
  5550. return;
  5551. }
  5552. this._cullFace = value;
  5553. this._isCullFaceDirty = true;
  5554. },
  5555. enumerable: true,
  5556. configurable: true
  5557. });
  5558. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5559. get: function () {
  5560. return this._cull;
  5561. },
  5562. set: function (value) {
  5563. if (this._cull === value) {
  5564. return;
  5565. }
  5566. this._cull = value;
  5567. this._isCullDirty = true;
  5568. },
  5569. enumerable: true,
  5570. configurable: true
  5571. });
  5572. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5573. get: function () {
  5574. return this._depthFunc;
  5575. },
  5576. set: function (value) {
  5577. if (this._depthFunc === value) {
  5578. return;
  5579. }
  5580. this._depthFunc = value;
  5581. this._isDepthFuncDirty = true;
  5582. },
  5583. enumerable: true,
  5584. configurable: true
  5585. });
  5586. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5587. get: function () {
  5588. return this._depthMask;
  5589. },
  5590. set: function (value) {
  5591. if (this._depthMask === value) {
  5592. return;
  5593. }
  5594. this._depthMask = value;
  5595. this._isDepthMaskDirty = true;
  5596. },
  5597. enumerable: true,
  5598. configurable: true
  5599. });
  5600. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5601. get: function () {
  5602. return this._depthTest;
  5603. },
  5604. set: function (value) {
  5605. if (this._depthTest === value) {
  5606. return;
  5607. }
  5608. this._depthTest = value;
  5609. this._isDepthTestDirty = true;
  5610. },
  5611. enumerable: true,
  5612. configurable: true
  5613. });
  5614. _DepthCullingState.prototype.reset = function () {
  5615. this._depthMask = true;
  5616. this._depthTest = true;
  5617. this._depthFunc = null;
  5618. this._cullFace = null;
  5619. this._cull = null;
  5620. this._zOffset = 0;
  5621. this._isDepthTestDirty = true;
  5622. this._isDepthMaskDirty = true;
  5623. this._isDepthFuncDirty = false;
  5624. this._isCullFaceDirty = false;
  5625. this._isCullDirty = false;
  5626. this._isZOffsetDirty = false;
  5627. };
  5628. _DepthCullingState.prototype.apply = function (gl) {
  5629. if (!this.isDirty) {
  5630. return;
  5631. }
  5632. // Cull
  5633. if (this._isCullDirty) {
  5634. if (this.cull) {
  5635. gl.enable(gl.CULL_FACE);
  5636. }
  5637. else {
  5638. gl.disable(gl.CULL_FACE);
  5639. }
  5640. this._isCullDirty = false;
  5641. }
  5642. // Cull face
  5643. if (this._isCullFaceDirty) {
  5644. gl.cullFace(this.cullFace);
  5645. this._isCullFaceDirty = false;
  5646. }
  5647. // Depth mask
  5648. if (this._isDepthMaskDirty) {
  5649. gl.depthMask(this.depthMask);
  5650. this._isDepthMaskDirty = false;
  5651. }
  5652. // Depth test
  5653. if (this._isDepthTestDirty) {
  5654. if (this.depthTest) {
  5655. gl.enable(gl.DEPTH_TEST);
  5656. }
  5657. else {
  5658. gl.disable(gl.DEPTH_TEST);
  5659. }
  5660. this._isDepthTestDirty = false;
  5661. }
  5662. // Depth func
  5663. if (this._isDepthFuncDirty) {
  5664. gl.depthFunc(this.depthFunc);
  5665. this._isDepthFuncDirty = false;
  5666. }
  5667. // zOffset
  5668. if (this._isZOffsetDirty) {
  5669. if (this.zOffset) {
  5670. gl.enable(gl.POLYGON_OFFSET_FILL);
  5671. gl.polygonOffset(this.zOffset, 0);
  5672. }
  5673. else {
  5674. gl.disable(gl.POLYGON_OFFSET_FILL);
  5675. }
  5676. this._isZOffsetDirty = false;
  5677. }
  5678. };
  5679. return _DepthCullingState;
  5680. })();
  5681. Internals._DepthCullingState = _DepthCullingState;
  5682. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5683. })(BABYLON || (BABYLON = {}));
  5684. var BABYLON;
  5685. (function (BABYLON) {
  5686. var compileShader = function (gl, source, type, defines) {
  5687. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5688. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5689. gl.compileShader(shader);
  5690. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5691. throw new Error(gl.getShaderInfoLog(shader));
  5692. }
  5693. return shader;
  5694. };
  5695. var getWebGLTextureType = function (gl, type) {
  5696. var textureType = gl.UNSIGNED_BYTE;
  5697. if (type === Engine.TEXTURETYPE_FLOAT)
  5698. textureType = gl.FLOAT;
  5699. return textureType;
  5700. };
  5701. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5702. var magFilter = gl.NEAREST;
  5703. var minFilter = gl.NEAREST;
  5704. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5705. magFilter = gl.LINEAR;
  5706. if (generateMipMaps) {
  5707. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5708. }
  5709. else {
  5710. minFilter = gl.LINEAR;
  5711. }
  5712. }
  5713. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5714. magFilter = gl.LINEAR;
  5715. if (generateMipMaps) {
  5716. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5717. }
  5718. else {
  5719. minFilter = gl.LINEAR;
  5720. }
  5721. }
  5722. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5723. magFilter = gl.NEAREST;
  5724. if (generateMipMaps) {
  5725. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5726. }
  5727. else {
  5728. minFilter = gl.NEAREST;
  5729. }
  5730. }
  5731. return {
  5732. min: minFilter,
  5733. mag: magFilter
  5734. };
  5735. };
  5736. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5737. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5738. var engine = scene.getEngine();
  5739. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5740. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5741. gl.bindTexture(gl.TEXTURE_2D, texture);
  5742. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5743. texture._baseWidth = width;
  5744. texture._baseHeight = height;
  5745. texture._width = potWidth;
  5746. texture._height = potHeight;
  5747. texture.isReady = true;
  5748. processFunction(potWidth, potHeight);
  5749. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5750. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5751. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5752. if (!noMipmap && !isCompressed) {
  5753. gl.generateMipmap(gl.TEXTURE_2D);
  5754. }
  5755. gl.bindTexture(gl.TEXTURE_2D, null);
  5756. engine.resetTextureCache();
  5757. scene._removePendingData(texture);
  5758. if (onLoad) {
  5759. onLoad();
  5760. }
  5761. };
  5762. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5763. var img;
  5764. var onload = function () {
  5765. loadedImages[index] = img;
  5766. loadedImages._internalCount++;
  5767. scene._removePendingData(img);
  5768. if (loadedImages._internalCount === 6) {
  5769. onfinish(loadedImages);
  5770. }
  5771. };
  5772. var onerror = function () {
  5773. scene._removePendingData(img);
  5774. };
  5775. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5776. scene._addPendingData(img);
  5777. };
  5778. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5779. var loadedImages = [];
  5780. loadedImages._internalCount = 0;
  5781. for (var index = 0; index < 6; index++) {
  5782. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5783. }
  5784. };
  5785. var InstancingAttributeInfo = (function () {
  5786. function InstancingAttributeInfo() {
  5787. }
  5788. return InstancingAttributeInfo;
  5789. })();
  5790. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  5791. var EngineCapabilities = (function () {
  5792. function EngineCapabilities() {
  5793. }
  5794. return EngineCapabilities;
  5795. })();
  5796. BABYLON.EngineCapabilities = EngineCapabilities;
  5797. /**
  5798. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5799. */
  5800. var Engine = (function () {
  5801. /**
  5802. * @constructor
  5803. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5804. * @param {boolean} [antialias] - enable antialias
  5805. * @param options - further options to be sent to the getContext function
  5806. */
  5807. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5808. var _this = this;
  5809. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5810. // Public members
  5811. this.isFullscreen = false;
  5812. this.isPointerLock = false;
  5813. this.cullBackFaces = true;
  5814. this.renderEvenInBackground = true;
  5815. // To enable/disable IDB support and avoid XHR on .manifest
  5816. this.enableOfflineSupport = true;
  5817. this.scenes = new Array();
  5818. this._windowIsBackground = false;
  5819. this._webGLVersion = "1.0";
  5820. this._drawCalls = 0;
  5821. this._renderingQueueLaunched = false;
  5822. this._activeRenderLoops = [];
  5823. // FPS
  5824. this.fpsRange = 60;
  5825. this.previousFramesDuration = [];
  5826. this.fps = 60;
  5827. this.deltaTime = 0;
  5828. // States
  5829. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5830. this._alphaState = new BABYLON.Internals._AlphaState();
  5831. this._alphaMode = Engine.ALPHA_DISABLE;
  5832. // Cache
  5833. this._loadedTexturesCache = new Array();
  5834. this._maxTextureChannels = 16;
  5835. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5836. this._compiledEffects = {};
  5837. this._uintIndicesCurrentlySet = false;
  5838. this._currentBoundBuffer = new Array();
  5839. this._currentInstanceLocations = new Array();
  5840. this._currentInstanceBuffers = new Array();
  5841. this._renderingCanvas = canvas;
  5842. this._externalData = new BABYLON.StringDictionary();
  5843. options = options || {};
  5844. options.antialias = antialias;
  5845. if (options.preserveDrawingBuffer === undefined) {
  5846. options.preserveDrawingBuffer = false;
  5847. }
  5848. // GL
  5849. //try {
  5850. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5851. // if (this._gl) {
  5852. // this._webGLVersion = "2.0";
  5853. // }
  5854. //} catch (e) {
  5855. // // Do nothing
  5856. //}
  5857. if (!this._gl) {
  5858. try {
  5859. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5860. }
  5861. catch (e) {
  5862. throw new Error("WebGL not supported");
  5863. }
  5864. }
  5865. if (!this._gl) {
  5866. throw new Error("WebGL not supported");
  5867. }
  5868. this._onBlur = function () {
  5869. _this._windowIsBackground = true;
  5870. };
  5871. this._onFocus = function () {
  5872. _this._windowIsBackground = false;
  5873. };
  5874. window.addEventListener("blur", this._onBlur);
  5875. window.addEventListener("focus", this._onFocus);
  5876. // Viewport
  5877. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5878. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5879. this.resize();
  5880. // Caps
  5881. this._caps = new EngineCapabilities();
  5882. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5883. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5884. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5885. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5886. // Infos
  5887. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5888. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5889. if (rendererInfo != null) {
  5890. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5891. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5892. }
  5893. if (!this._glVendor) {
  5894. this._glVendor = "Unknown vendor";
  5895. }
  5896. if (!this._glRenderer) {
  5897. this._glRenderer = "Unknown renderer";
  5898. }
  5899. // Extensions
  5900. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5901. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5902. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5903. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  5904. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5905. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5906. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5907. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5908. this._caps.highPrecisionShaderSupported = true;
  5909. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5910. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5911. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5912. if (this._gl.getShaderPrecisionFormat) {
  5913. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5914. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5915. }
  5916. // Depth buffer
  5917. this.setDepthBuffer(true);
  5918. this.setDepthFunctionToLessOrEqual();
  5919. this.setDepthWrite(true);
  5920. // Fullscreen
  5921. this._onFullscreenChange = function () {
  5922. if (document.fullscreen !== undefined) {
  5923. _this.isFullscreen = document.fullscreen;
  5924. }
  5925. else if (document.mozFullScreen !== undefined) {
  5926. _this.isFullscreen = document.mozFullScreen;
  5927. }
  5928. else if (document.webkitIsFullScreen !== undefined) {
  5929. _this.isFullscreen = document.webkitIsFullScreen;
  5930. }
  5931. else if (document.msIsFullScreen !== undefined) {
  5932. _this.isFullscreen = document.msIsFullScreen;
  5933. }
  5934. // Pointer lock
  5935. if (_this.isFullscreen && _this._pointerLockRequested) {
  5936. canvas.requestPointerLock = canvas.requestPointerLock ||
  5937. canvas.msRequestPointerLock ||
  5938. canvas.mozRequestPointerLock ||
  5939. canvas.webkitRequestPointerLock;
  5940. if (canvas.requestPointerLock) {
  5941. canvas.requestPointerLock();
  5942. }
  5943. }
  5944. };
  5945. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5946. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5947. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5948. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5949. // Pointer lock
  5950. this._onPointerLockChange = function () {
  5951. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5952. document.webkitPointerLockElement === canvas ||
  5953. document.msPointerLockElement === canvas ||
  5954. document.pointerLockElement === canvas);
  5955. };
  5956. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5957. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5958. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5959. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5960. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5961. Engine.audioEngine = new BABYLON.AudioEngine();
  5962. }
  5963. //default loading screen
  5964. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5965. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5966. }
  5967. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5968. get: function () {
  5969. return Engine._ALPHA_DISABLE;
  5970. },
  5971. enumerable: true,
  5972. configurable: true
  5973. });
  5974. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5975. get: function () {
  5976. return Engine._ALPHA_ONEONE;
  5977. },
  5978. enumerable: true,
  5979. configurable: true
  5980. });
  5981. Object.defineProperty(Engine, "ALPHA_ADD", {
  5982. get: function () {
  5983. return Engine._ALPHA_ADD;
  5984. },
  5985. enumerable: true,
  5986. configurable: true
  5987. });
  5988. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5989. get: function () {
  5990. return Engine._ALPHA_COMBINE;
  5991. },
  5992. enumerable: true,
  5993. configurable: true
  5994. });
  5995. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5996. get: function () {
  5997. return Engine._ALPHA_SUBTRACT;
  5998. },
  5999. enumerable: true,
  6000. configurable: true
  6001. });
  6002. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6003. get: function () {
  6004. return Engine._ALPHA_MULTIPLY;
  6005. },
  6006. enumerable: true,
  6007. configurable: true
  6008. });
  6009. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6010. get: function () {
  6011. return Engine._ALPHA_MAXIMIZED;
  6012. },
  6013. enumerable: true,
  6014. configurable: true
  6015. });
  6016. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6017. get: function () {
  6018. return Engine._DELAYLOADSTATE_NONE;
  6019. },
  6020. enumerable: true,
  6021. configurable: true
  6022. });
  6023. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6024. get: function () {
  6025. return Engine._DELAYLOADSTATE_LOADED;
  6026. },
  6027. enumerable: true,
  6028. configurable: true
  6029. });
  6030. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6031. get: function () {
  6032. return Engine._DELAYLOADSTATE_LOADING;
  6033. },
  6034. enumerable: true,
  6035. configurable: true
  6036. });
  6037. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6038. get: function () {
  6039. return Engine._DELAYLOADSTATE_NOTLOADED;
  6040. },
  6041. enumerable: true,
  6042. configurable: true
  6043. });
  6044. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6045. get: function () {
  6046. return Engine._TEXTUREFORMAT_ALPHA;
  6047. },
  6048. enumerable: true,
  6049. configurable: true
  6050. });
  6051. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6052. get: function () {
  6053. return Engine._TEXTUREFORMAT_LUMINANCE;
  6054. },
  6055. enumerable: true,
  6056. configurable: true
  6057. });
  6058. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6059. get: function () {
  6060. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6061. },
  6062. enumerable: true,
  6063. configurable: true
  6064. });
  6065. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6066. get: function () {
  6067. return Engine._TEXTUREFORMAT_RGB;
  6068. },
  6069. enumerable: true,
  6070. configurable: true
  6071. });
  6072. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6073. get: function () {
  6074. return Engine._TEXTUREFORMAT_RGBA;
  6075. },
  6076. enumerable: true,
  6077. configurable: true
  6078. });
  6079. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6080. get: function () {
  6081. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6082. },
  6083. enumerable: true,
  6084. configurable: true
  6085. });
  6086. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6087. get: function () {
  6088. return Engine._TEXTURETYPE_FLOAT;
  6089. },
  6090. enumerable: true,
  6091. configurable: true
  6092. });
  6093. Object.defineProperty(Engine, "Version", {
  6094. get: function () {
  6095. return "2.4.0";
  6096. },
  6097. enumerable: true,
  6098. configurable: true
  6099. });
  6100. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6101. get: function () {
  6102. return this._webGLVersion;
  6103. },
  6104. enumerable: true,
  6105. configurable: true
  6106. });
  6107. Engine.prototype._prepareWorkingCanvas = function () {
  6108. if (this._workingCanvas) {
  6109. return;
  6110. }
  6111. this._workingCanvas = document.createElement("canvas");
  6112. this._workingContext = this._workingCanvas.getContext("2d");
  6113. };
  6114. Engine.prototype.resetTextureCache = function () {
  6115. for (var index = 0; index < this._maxTextureChannels; index++) {
  6116. this._activeTexturesCache[index] = null;
  6117. }
  6118. };
  6119. Engine.prototype.getGlInfo = function () {
  6120. return {
  6121. vendor: this._glVendor,
  6122. renderer: this._glRenderer,
  6123. version: this._glVersion
  6124. };
  6125. };
  6126. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6127. if (useScreen === void 0) { useScreen = false; }
  6128. var viewport = camera.viewport;
  6129. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6130. };
  6131. Engine.prototype.getRenderWidth = function (useScreen) {
  6132. if (useScreen === void 0) { useScreen = false; }
  6133. if (!useScreen && this._currentRenderTarget) {
  6134. return this._currentRenderTarget._width;
  6135. }
  6136. return this._renderingCanvas.width;
  6137. };
  6138. Engine.prototype.getRenderHeight = function (useScreen) {
  6139. if (useScreen === void 0) { useScreen = false; }
  6140. if (!useScreen && this._currentRenderTarget) {
  6141. return this._currentRenderTarget._height;
  6142. }
  6143. return this._renderingCanvas.height;
  6144. };
  6145. Engine.prototype.getRenderingCanvas = function () {
  6146. return this._renderingCanvas;
  6147. };
  6148. Engine.prototype.getRenderingCanvasClientRect = function () {
  6149. return this._renderingCanvas.getBoundingClientRect();
  6150. };
  6151. Engine.prototype.setHardwareScalingLevel = function (level) {
  6152. this._hardwareScalingLevel = level;
  6153. this.resize();
  6154. };
  6155. Engine.prototype.getHardwareScalingLevel = function () {
  6156. return this._hardwareScalingLevel;
  6157. };
  6158. Engine.prototype.getLoadedTexturesCache = function () {
  6159. return this._loadedTexturesCache;
  6160. };
  6161. Engine.prototype.getCaps = function () {
  6162. return this._caps;
  6163. };
  6164. Object.defineProperty(Engine.prototype, "drawCalls", {
  6165. get: function () {
  6166. return this._drawCalls;
  6167. },
  6168. enumerable: true,
  6169. configurable: true
  6170. });
  6171. // Methods
  6172. Engine.prototype.resetDrawCalls = function () {
  6173. this._drawCalls = 0;
  6174. };
  6175. Engine.prototype.getDepthFunction = function () {
  6176. return this._depthCullingState.depthFunc;
  6177. };
  6178. Engine.prototype.setDepthFunction = function (depthFunc) {
  6179. this._depthCullingState.depthFunc = depthFunc;
  6180. };
  6181. Engine.prototype.setDepthFunctionToGreater = function () {
  6182. this._depthCullingState.depthFunc = this._gl.GREATER;
  6183. };
  6184. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6185. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6186. };
  6187. Engine.prototype.setDepthFunctionToLess = function () {
  6188. this._depthCullingState.depthFunc = this._gl.LESS;
  6189. };
  6190. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6191. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6192. };
  6193. /**
  6194. * stop executing a render loop function and remove it from the execution array
  6195. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6196. */
  6197. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6198. if (!renderFunction) {
  6199. this._activeRenderLoops = [];
  6200. return;
  6201. }
  6202. var index = this._activeRenderLoops.indexOf(renderFunction);
  6203. if (index >= 0) {
  6204. this._activeRenderLoops.splice(index, 1);
  6205. }
  6206. };
  6207. Engine.prototype._renderLoop = function () {
  6208. var shouldRender = true;
  6209. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6210. shouldRender = false;
  6211. }
  6212. if (shouldRender) {
  6213. // Start new frame
  6214. this.beginFrame();
  6215. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6216. var renderFunction = this._activeRenderLoops[index];
  6217. renderFunction();
  6218. }
  6219. // Present
  6220. this.endFrame();
  6221. }
  6222. if (this._activeRenderLoops.length > 0) {
  6223. // Register new frame
  6224. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6225. }
  6226. else {
  6227. this._renderingQueueLaunched = false;
  6228. }
  6229. };
  6230. /**
  6231. * Register and execute a render loop. The engine can have more than one render function.
  6232. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6233. * @example
  6234. * engine.runRenderLoop(function () {
  6235. * scene.render()
  6236. * })
  6237. */
  6238. Engine.prototype.runRenderLoop = function (renderFunction) {
  6239. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6240. return;
  6241. }
  6242. this._activeRenderLoops.push(renderFunction);
  6243. if (!this._renderingQueueLaunched) {
  6244. this._renderingQueueLaunched = true;
  6245. this._bindedRenderFunction = this._renderLoop.bind(this);
  6246. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6247. }
  6248. };
  6249. /**
  6250. * Toggle full screen mode.
  6251. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6252. * @param {any} options - an options object to be sent to the requestFullscreen function
  6253. */
  6254. Engine.prototype.switchFullscreen = function (requestPointerLock, options) {
  6255. if (this.isFullscreen) {
  6256. BABYLON.Tools.ExitFullscreen();
  6257. }
  6258. else {
  6259. this._pointerLockRequested = requestPointerLock;
  6260. BABYLON.Tools.RequestFullscreen(this._renderingCanvas, options);
  6261. }
  6262. };
  6263. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  6264. this.applyStates();
  6265. if (backBuffer) {
  6266. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6267. }
  6268. if (depthStencil && this._depthCullingState.depthMask) {
  6269. this._gl.clearDepth(1.0);
  6270. }
  6271. var mode = 0;
  6272. if (backBuffer) {
  6273. mode |= this._gl.COLOR_BUFFER_BIT;
  6274. }
  6275. if (depthStencil && this._depthCullingState.depthMask) {
  6276. mode |= this._gl.DEPTH_BUFFER_BIT;
  6277. }
  6278. this._gl.clear(mode);
  6279. };
  6280. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  6281. var gl = this._gl;
  6282. // Save state
  6283. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  6284. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  6285. // Change state
  6286. gl.enable(gl.SCISSOR_TEST);
  6287. gl.scissor(x, y, width, height);
  6288. // Clear
  6289. this.clear(clearColor, true, true);
  6290. // Restore state
  6291. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  6292. if (curScissor === true) {
  6293. gl.enable(gl.SCISSOR_TEST);
  6294. }
  6295. else {
  6296. gl.disable(gl.SCISSOR_TEST);
  6297. }
  6298. };
  6299. /**
  6300. * Set the WebGL's viewport
  6301. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6302. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6303. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6304. */
  6305. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6306. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6307. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6308. var x = viewport.x || 0;
  6309. var y = viewport.y || 0;
  6310. this._cachedViewport = viewport;
  6311. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6312. };
  6313. /**
  6314. * Directly set the WebGL Viewport
  6315. * The x, y, width & height are directly passed to the WebGL call
  6316. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  6317. */
  6318. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6319. var currentViewport = this._cachedViewport;
  6320. this._cachedViewport = null;
  6321. this._gl.viewport(x, y, width, height);
  6322. return currentViewport;
  6323. };
  6324. Engine.prototype.beginFrame = function () {
  6325. this._measureFps();
  6326. };
  6327. Engine.prototype.endFrame = function () {
  6328. //this.flushFramebuffer();
  6329. };
  6330. /**
  6331. * resize the view according to the canvas' size.
  6332. * @example
  6333. * window.addEventListener("resize", function () {
  6334. * engine.resize();
  6335. * });
  6336. */
  6337. Engine.prototype.resize = function () {
  6338. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6339. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6340. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6341. for (var index = 0; index < this.scenes.length; index++) {
  6342. var scene = this.scenes[index];
  6343. if (scene.debugLayer.isVisible()) {
  6344. scene.debugLayer._syncPositions();
  6345. }
  6346. }
  6347. };
  6348. /**
  6349. * force a specific size of the canvas
  6350. * @param {number} width - the new canvas' width
  6351. * @param {number} height - the new canvas' height
  6352. */
  6353. Engine.prototype.setSize = function (width, height) {
  6354. this._renderingCanvas.width = width;
  6355. this._renderingCanvas.height = height;
  6356. for (var index = 0; index < this.scenes.length; index++) {
  6357. var scene = this.scenes[index];
  6358. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6359. var cam = scene.cameras[camIndex];
  6360. cam._currentRenderId = 0;
  6361. }
  6362. }
  6363. };
  6364. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6365. this._currentRenderTarget = texture;
  6366. var gl = this._gl;
  6367. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  6368. if (texture.isCube) {
  6369. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6370. }
  6371. else {
  6372. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6373. }
  6374. this._gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6375. this.wipeCaches();
  6376. };
  6377. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6378. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6379. this._currentRenderTarget = null;
  6380. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6381. var gl = this._gl;
  6382. gl.bindTexture(gl.TEXTURE_2D, texture);
  6383. gl.generateMipmap(gl.TEXTURE_2D);
  6384. gl.bindTexture(gl.TEXTURE_2D, null);
  6385. }
  6386. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  6387. };
  6388. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6389. if (texture.generateMipMaps) {
  6390. var gl = this._gl;
  6391. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6392. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6393. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6394. }
  6395. };
  6396. Engine.prototype.flushFramebuffer = function () {
  6397. this._gl.flush();
  6398. };
  6399. Engine.prototype.restoreDefaultFramebuffer = function () {
  6400. this._currentRenderTarget = null;
  6401. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  6402. this.setViewport(this._cachedViewport);
  6403. this.wipeCaches();
  6404. };
  6405. // VBOs
  6406. Engine.prototype._resetVertexBufferBinding = function () {
  6407. this.bindBuffer(null, this._gl.ARRAY_BUFFER);
  6408. this._cachedVertexBuffers = null;
  6409. };
  6410. Engine.prototype.createVertexBuffer = function (vertices) {
  6411. var vbo = this._gl.createBuffer();
  6412. this.bindBuffer(vbo, this._gl.ARRAY_BUFFER);
  6413. if (vertices instanceof Float32Array) {
  6414. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6415. }
  6416. else {
  6417. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6418. }
  6419. this._resetVertexBufferBinding();
  6420. vbo.references = 1;
  6421. return vbo;
  6422. };
  6423. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  6424. var vbo = this._gl.createBuffer();
  6425. this.bindBuffer(vbo, this._gl.ARRAY_BUFFER);
  6426. if (vertices instanceof Float32Array) {
  6427. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  6428. }
  6429. else {
  6430. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  6431. }
  6432. this._resetVertexBufferBinding();
  6433. vbo.references = 1;
  6434. return vbo;
  6435. };
  6436. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  6437. this.bindBuffer(vertexBuffer, this._gl.ARRAY_BUFFER);
  6438. if (offset === undefined) {
  6439. offset = 0;
  6440. }
  6441. if (count === undefined) {
  6442. if (vertices instanceof Float32Array) {
  6443. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6444. }
  6445. else {
  6446. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6447. }
  6448. }
  6449. else {
  6450. if (vertices instanceof Float32Array) {
  6451. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  6452. }
  6453. else {
  6454. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  6455. }
  6456. }
  6457. this._resetVertexBufferBinding();
  6458. };
  6459. Engine.prototype._resetIndexBufferBinding = function () {
  6460. this.bindBuffer(null, this._gl.ELEMENT_ARRAY_BUFFER);
  6461. this._cachedIndexBuffer = null;
  6462. };
  6463. Engine.prototype.createIndexBuffer = function (indices) {
  6464. var vbo = this._gl.createBuffer();
  6465. this.bindBuffer(vbo, this._gl.ELEMENT_ARRAY_BUFFER);
  6466. // Check for 32 bits indices
  6467. var arrayBuffer;
  6468. var need32Bits = false;
  6469. if (this._caps.uintIndices) {
  6470. for (var index = 0; index < indices.length; index++) {
  6471. if (indices[index] > 65535) {
  6472. need32Bits = true;
  6473. break;
  6474. }
  6475. }
  6476. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6477. }
  6478. else {
  6479. arrayBuffer = new Uint16Array(indices);
  6480. }
  6481. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6482. this._resetIndexBufferBinding();
  6483. vbo.references = 1;
  6484. vbo.is32Bits = need32Bits;
  6485. return vbo;
  6486. };
  6487. Engine.prototype.bindArrayBuffer = function (buffer) {
  6488. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  6489. };
  6490. Engine.prototype.updateArrayBuffer = function (data) {
  6491. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6492. };
  6493. Engine.prototype.bindBuffer = function (buffer, target) {
  6494. if (this._currentBoundBuffer[target] !== buffer) {
  6495. this._gl.bindBuffer(target, buffer);
  6496. this._currentBoundBuffer[target] = buffer;
  6497. }
  6498. };
  6499. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6500. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6501. this._cachedVertexBuffers = vertexBuffer;
  6502. this._cachedEffectForVertexBuffers = effect;
  6503. this.bindBuffer(vertexBuffer, this._gl.ARRAY_BUFFER);
  6504. var offset = 0;
  6505. for (var index = 0; index < vertexDeclaration.length; index++) {
  6506. var order = effect.getAttributeLocation(index);
  6507. if (order >= 0) {
  6508. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6509. }
  6510. offset += vertexDeclaration[index] * 4;
  6511. }
  6512. }
  6513. if (this._cachedIndexBuffer !== indexBuffer) {
  6514. this._cachedIndexBuffer = indexBuffer;
  6515. this.bindBuffer(indexBuffer, this._gl.ELEMENT_ARRAY_BUFFER);
  6516. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6517. }
  6518. };
  6519. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  6520. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6521. this._cachedVertexBuffers = vertexBuffers;
  6522. this._cachedEffectForVertexBuffers = effect;
  6523. var attributes = effect.getAttributesNames();
  6524. for (var index = 0; index < attributes.length; index++) {
  6525. var order = effect.getAttributeLocation(index);
  6526. if (order >= 0) {
  6527. var vertexBuffer = vertexBuffers[attributes[index]];
  6528. if (!vertexBuffer) {
  6529. continue;
  6530. }
  6531. var buffer = vertexBuffer.getBuffer();
  6532. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  6533. this._gl.vertexAttribPointer(order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  6534. if (vertexBuffer.getIsInstanced()) {
  6535. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  6536. this._currentInstanceLocations.push(order);
  6537. this._currentInstanceBuffers.push(buffer);
  6538. }
  6539. }
  6540. }
  6541. }
  6542. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6543. this._cachedIndexBuffer = indexBuffer;
  6544. this.bindBuffer(indexBuffer, this._gl.ELEMENT_ARRAY_BUFFER);
  6545. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6546. }
  6547. };
  6548. Engine.prototype.unbindInstanceAttributes = function () {
  6549. var boundBuffer;
  6550. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  6551. var instancesBuffer = this._currentInstanceBuffers[i];
  6552. if (boundBuffer != instancesBuffer) {
  6553. boundBuffer = instancesBuffer;
  6554. this.bindBuffer(instancesBuffer, this._gl.ARRAY_BUFFER);
  6555. }
  6556. var offsetLocation = this._currentInstanceLocations[i];
  6557. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6558. }
  6559. this._currentInstanceBuffers.length = 0;
  6560. this._currentInstanceLocations.length = 0;
  6561. };
  6562. Engine.prototype._releaseBuffer = function (buffer) {
  6563. buffer.references--;
  6564. if (buffer.references === 0) {
  6565. this._gl.deleteBuffer(buffer);
  6566. return true;
  6567. }
  6568. return false;
  6569. };
  6570. Engine.prototype.createInstancesBuffer = function (capacity) {
  6571. var buffer = this._gl.createBuffer();
  6572. buffer.capacity = capacity;
  6573. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  6574. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6575. return buffer;
  6576. };
  6577. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6578. this._gl.deleteBuffer(buffer);
  6579. };
  6580. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6581. this.bindBuffer(instancesBuffer, this._gl.ARRAY_BUFFER);
  6582. if (data) {
  6583. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6584. }
  6585. if (offsetLocations[0].index !== undefined) {
  6586. var stride = 0;
  6587. for (var i = 0; i < offsetLocations.length; i++) {
  6588. var ai = offsetLocations[i];
  6589. stride += ai.attributeSize * 4;
  6590. }
  6591. for (var i = 0; i < offsetLocations.length; i++) {
  6592. var ai = offsetLocations[i];
  6593. this._gl.enableVertexAttribArray(ai.index);
  6594. this._gl.vertexAttribPointer(ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  6595. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  6596. this._currentInstanceLocations.push(ai.index);
  6597. this._currentInstanceBuffers.push(instancesBuffer);
  6598. }
  6599. }
  6600. else {
  6601. for (var index = 0; index < 4; index++) {
  6602. var offsetLocation = offsetLocations[index];
  6603. this._gl.enableVertexAttribArray(offsetLocation);
  6604. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6605. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6606. this._currentInstanceLocations.push(offsetLocation);
  6607. this._currentInstanceBuffers.push(instancesBuffer);
  6608. }
  6609. }
  6610. };
  6611. Engine.prototype.applyStates = function () {
  6612. this._depthCullingState.apply(this._gl);
  6613. this._alphaState.apply(this._gl);
  6614. };
  6615. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6616. // Apply states
  6617. this.applyStates();
  6618. this._drawCalls++;
  6619. // Render
  6620. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6621. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6622. if (instancesCount) {
  6623. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6624. return;
  6625. }
  6626. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6627. };
  6628. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6629. // Apply states
  6630. this.applyStates();
  6631. this._drawCalls++;
  6632. if (instancesCount) {
  6633. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6634. return;
  6635. }
  6636. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6637. };
  6638. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6639. // Apply states
  6640. this.applyStates();
  6641. this._drawCalls++;
  6642. if (instancesCount) {
  6643. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6644. return;
  6645. }
  6646. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6647. };
  6648. // Shaders
  6649. Engine.prototype._releaseEffect = function (effect) {
  6650. if (this._compiledEffects[effect._key]) {
  6651. delete this._compiledEffects[effect._key];
  6652. if (effect.getProgram()) {
  6653. this._gl.deleteProgram(effect.getProgram());
  6654. }
  6655. }
  6656. };
  6657. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  6658. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6659. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6660. var name = vertex + "+" + fragment + "@" + defines;
  6661. if (this._compiledEffects[name]) {
  6662. return this._compiledEffects[name];
  6663. }
  6664. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  6665. effect._key = name;
  6666. this._compiledEffects[name] = effect;
  6667. return effect;
  6668. };
  6669. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6670. if (uniformsNames === void 0) { uniformsNames = []; }
  6671. if (samplers === void 0) { samplers = []; }
  6672. if (defines === void 0) { defines = ""; }
  6673. return this.createEffect({
  6674. vertex: "particles",
  6675. fragmentElement: fragmentName
  6676. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6677. };
  6678. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6679. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6680. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6681. var shaderProgram = this._gl.createProgram();
  6682. this._gl.attachShader(shaderProgram, vertexShader);
  6683. this._gl.attachShader(shaderProgram, fragmentShader);
  6684. this._gl.linkProgram(shaderProgram);
  6685. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6686. if (!linked) {
  6687. var error = this._gl.getProgramInfoLog(shaderProgram);
  6688. if (error) {
  6689. throw new Error(error);
  6690. }
  6691. }
  6692. this._gl.deleteShader(vertexShader);
  6693. this._gl.deleteShader(fragmentShader);
  6694. return shaderProgram;
  6695. };
  6696. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6697. var results = [];
  6698. for (var index = 0; index < uniformsNames.length; index++) {
  6699. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6700. }
  6701. return results;
  6702. };
  6703. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6704. var results = [];
  6705. for (var index = 0; index < attributesNames.length; index++) {
  6706. try {
  6707. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6708. }
  6709. catch (e) {
  6710. results.push(-1);
  6711. }
  6712. }
  6713. return results;
  6714. };
  6715. Engine.prototype.enableEffect = function (effect) {
  6716. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6717. if (effect && effect.onBind) {
  6718. effect.onBind(effect);
  6719. }
  6720. return;
  6721. }
  6722. this._vertexAttribArraysToUse = this._vertexAttribArraysToUse || [];
  6723. this._vertexAttribArraysEnabled = this._vertexAttribArraysEnabled || [];
  6724. // Use program
  6725. this._gl.useProgram(effect.getProgram());
  6726. var i, ul;
  6727. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  6728. this._vertexAttribArraysToUse[i] = false;
  6729. }
  6730. var attributesCount = effect.getAttributesCount();
  6731. for (i = 0; i < attributesCount; i++) {
  6732. // Attributes
  6733. var order = effect.getAttributeLocation(i);
  6734. if (order >= 0) {
  6735. this._vertexAttribArraysToUse[order] = true;
  6736. }
  6737. }
  6738. for (i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  6739. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i] || this._vertexAttribArraysToUse[i]) {
  6740. continue;
  6741. }
  6742. this._vertexAttribArraysEnabled[i] = false;
  6743. this._gl.disableVertexAttribArray(i);
  6744. }
  6745. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  6746. if (this._vertexAttribArraysToUse[i] && !this._vertexAttribArraysEnabled[i]) {
  6747. this._vertexAttribArraysEnabled[i] = true;
  6748. this._gl.enableVertexAttribArray(i);
  6749. }
  6750. }
  6751. this._currentEffect = effect;
  6752. if (effect.onBind) {
  6753. effect.onBind(effect);
  6754. }
  6755. };
  6756. Engine.prototype.setArray = function (uniform, array) {
  6757. if (!uniform)
  6758. return;
  6759. this._gl.uniform1fv(uniform, array);
  6760. };
  6761. Engine.prototype.setArray2 = function (uniform, array) {
  6762. if (!uniform || array.length % 2 !== 0)
  6763. return;
  6764. this._gl.uniform2fv(uniform, array);
  6765. };
  6766. Engine.prototype.setArray3 = function (uniform, array) {
  6767. if (!uniform || array.length % 3 !== 0)
  6768. return;
  6769. this._gl.uniform3fv(uniform, array);
  6770. };
  6771. Engine.prototype.setArray4 = function (uniform, array) {
  6772. if (!uniform || array.length % 4 !== 0)
  6773. return;
  6774. this._gl.uniform4fv(uniform, array);
  6775. };
  6776. Engine.prototype.setMatrices = function (uniform, matrices) {
  6777. if (!uniform)
  6778. return;
  6779. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6780. };
  6781. Engine.prototype.setMatrix = function (uniform, matrix) {
  6782. if (!uniform)
  6783. return;
  6784. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6785. };
  6786. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6787. if (!uniform)
  6788. return;
  6789. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6790. };
  6791. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6792. if (!uniform)
  6793. return;
  6794. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6795. };
  6796. Engine.prototype.setFloat = function (uniform, value) {
  6797. if (!uniform)
  6798. return;
  6799. this._gl.uniform1f(uniform, value);
  6800. };
  6801. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6802. if (!uniform)
  6803. return;
  6804. this._gl.uniform2f(uniform, x, y);
  6805. };
  6806. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6807. if (!uniform)
  6808. return;
  6809. this._gl.uniform3f(uniform, x, y, z);
  6810. };
  6811. Engine.prototype.setBool = function (uniform, bool) {
  6812. if (!uniform)
  6813. return;
  6814. this._gl.uniform1i(uniform, bool);
  6815. };
  6816. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6817. if (!uniform)
  6818. return;
  6819. this._gl.uniform4f(uniform, x, y, z, w);
  6820. };
  6821. Engine.prototype.setColor3 = function (uniform, color3) {
  6822. if (!uniform)
  6823. return;
  6824. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6825. };
  6826. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6827. if (!uniform)
  6828. return;
  6829. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6830. };
  6831. // States
  6832. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6833. if (zOffset === void 0) { zOffset = 0; }
  6834. if (reverseSide === void 0) { reverseSide = false; }
  6835. // Culling
  6836. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6837. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6838. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6839. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6840. if (culling) {
  6841. this._depthCullingState.cullFace = cullFace;
  6842. this._depthCullingState.cull = true;
  6843. }
  6844. else {
  6845. this._depthCullingState.cull = false;
  6846. }
  6847. }
  6848. // Z offset
  6849. this._depthCullingState.zOffset = zOffset;
  6850. };
  6851. Engine.prototype.setDepthBuffer = function (enable) {
  6852. this._depthCullingState.depthTest = enable;
  6853. };
  6854. Engine.prototype.getDepthWrite = function () {
  6855. return this._depthCullingState.depthMask;
  6856. };
  6857. Engine.prototype.setDepthWrite = function (enable) {
  6858. this._depthCullingState.depthMask = enable;
  6859. };
  6860. Engine.prototype.setColorWrite = function (enable) {
  6861. this._gl.colorMask(enable, enable, enable, enable);
  6862. };
  6863. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  6864. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  6865. if (this._alphaMode === mode) {
  6866. return;
  6867. }
  6868. switch (mode) {
  6869. case Engine.ALPHA_DISABLE:
  6870. this._alphaState.alphaBlend = false;
  6871. break;
  6872. case Engine.ALPHA_COMBINE:
  6873. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6874. this._alphaState.alphaBlend = true;
  6875. break;
  6876. case Engine.ALPHA_ONEONE:
  6877. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6878. this._alphaState.alphaBlend = true;
  6879. break;
  6880. case Engine.ALPHA_ADD:
  6881. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6882. this._alphaState.alphaBlend = true;
  6883. break;
  6884. case Engine.ALPHA_SUBTRACT:
  6885. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6886. this._alphaState.alphaBlend = true;
  6887. break;
  6888. case Engine.ALPHA_MULTIPLY:
  6889. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6890. this._alphaState.alphaBlend = true;
  6891. break;
  6892. case Engine.ALPHA_MAXIMIZED:
  6893. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6894. this._alphaState.alphaBlend = true;
  6895. break;
  6896. }
  6897. if (!noDepthWriteChange) {
  6898. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  6899. }
  6900. this._alphaMode = mode;
  6901. };
  6902. Engine.prototype.getAlphaMode = function () {
  6903. return this._alphaMode;
  6904. };
  6905. Engine.prototype.setAlphaTesting = function (enable) {
  6906. this._alphaTest = enable;
  6907. };
  6908. Engine.prototype.getAlphaTesting = function () {
  6909. return this._alphaTest;
  6910. };
  6911. // Textures
  6912. Engine.prototype.wipeCaches = function () {
  6913. this.resetTextureCache();
  6914. this._currentEffect = null;
  6915. this._depthCullingState.reset();
  6916. this.setDepthFunctionToLessOrEqual();
  6917. this._alphaState.reset();
  6918. this._cachedVertexBuffers = null;
  6919. this._cachedIndexBuffer = null;
  6920. this._cachedEffectForVertexBuffers = null;
  6921. };
  6922. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6923. var gl = this._gl;
  6924. gl.bindTexture(gl.TEXTURE_2D, texture);
  6925. var magFilter = gl.NEAREST;
  6926. var minFilter = gl.NEAREST;
  6927. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6928. magFilter = gl.LINEAR;
  6929. minFilter = gl.LINEAR;
  6930. }
  6931. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6932. magFilter = gl.LINEAR;
  6933. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6934. }
  6935. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6936. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6937. gl.bindTexture(gl.TEXTURE_2D, null);
  6938. texture.samplingMode = samplingMode;
  6939. };
  6940. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6941. var _this = this;
  6942. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6943. if (onLoad === void 0) { onLoad = null; }
  6944. if (onError === void 0) { onError = null; }
  6945. if (buffer === void 0) { buffer = null; }
  6946. var texture = this._gl.createTexture();
  6947. var extension;
  6948. var fromData = false;
  6949. if (url.substr(0, 5) === "data:") {
  6950. fromData = true;
  6951. }
  6952. if (!fromData)
  6953. extension = url.substr(url.length - 4, 4).toLowerCase();
  6954. else {
  6955. var oldUrl = url;
  6956. fromData = oldUrl.split(':');
  6957. url = oldUrl;
  6958. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6959. }
  6960. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6961. var isTGA = (extension === ".tga");
  6962. scene._addPendingData(texture);
  6963. texture.url = url;
  6964. texture.noMipmap = noMipmap;
  6965. texture.references = 1;
  6966. texture.samplingMode = samplingMode;
  6967. this._loadedTexturesCache.push(texture);
  6968. var onerror = function () {
  6969. scene._removePendingData(texture);
  6970. if (onError) {
  6971. onError();
  6972. }
  6973. };
  6974. var callback;
  6975. if (isTGA) {
  6976. callback = function (arrayBuffer) {
  6977. var data = new Uint8Array(arrayBuffer);
  6978. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6979. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6980. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6981. }, onLoad, samplingMode);
  6982. };
  6983. if (!(fromData instanceof Array))
  6984. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6985. callback(arrayBuffer);
  6986. }, onerror, scene.database, true);
  6987. else
  6988. callback(buffer);
  6989. }
  6990. else if (isDDS) {
  6991. callback = function (data) {
  6992. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6993. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6994. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6995. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6996. }, onLoad, samplingMode);
  6997. };
  6998. if (!(fromData instanceof Array))
  6999. BABYLON.Tools.LoadFile(url, function (data) {
  7000. callback(data);
  7001. }, onerror, scene.database, true);
  7002. else
  7003. callback(buffer);
  7004. }
  7005. else {
  7006. var onload = function (img) {
  7007. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7008. var isPot = (img.width === potWidth && img.height === potHeight);
  7009. if (!isPot) {
  7010. _this._prepareWorkingCanvas();
  7011. _this._workingCanvas.width = potWidth;
  7012. _this._workingCanvas.height = potHeight;
  7013. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7014. _this._workingContext.imageSmoothingEnabled = false;
  7015. _this._workingContext.mozImageSmoothingEnabled = false;
  7016. _this._workingContext.oImageSmoothingEnabled = false;
  7017. _this._workingContext.webkitImageSmoothingEnabled = false;
  7018. _this._workingContext.msImageSmoothingEnabled = false;
  7019. }
  7020. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7021. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7022. _this._workingContext.imageSmoothingEnabled = true;
  7023. _this._workingContext.mozImageSmoothingEnabled = true;
  7024. _this._workingContext.oImageSmoothingEnabled = true;
  7025. _this._workingContext.webkitImageSmoothingEnabled = true;
  7026. _this._workingContext.msImageSmoothingEnabled = true;
  7027. }
  7028. }
  7029. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7030. }, onLoad, samplingMode);
  7031. };
  7032. if (!(fromData instanceof Array))
  7033. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7034. else
  7035. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7036. }
  7037. return texture;
  7038. };
  7039. Engine.prototype._getInternalFormat = function (format) {
  7040. var internalFormat = this._gl.RGBA;
  7041. switch (format) {
  7042. case Engine.TEXTUREFORMAT_ALPHA:
  7043. internalFormat = this._gl.ALPHA;
  7044. break;
  7045. case Engine.TEXTUREFORMAT_LUMINANCE:
  7046. internalFormat = this._gl.LUMINANCE;
  7047. break;
  7048. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7049. internalFormat = this._gl.LUMINANCE_ALPHA;
  7050. break;
  7051. case Engine.TEXTUREFORMAT_RGB:
  7052. internalFormat = this._gl.RGB;
  7053. break;
  7054. case Engine.TEXTUREFORMAT_RGBA:
  7055. internalFormat = this._gl.RGBA;
  7056. break;
  7057. }
  7058. return internalFormat;
  7059. };
  7060. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7061. if (compression === void 0) { compression = null; }
  7062. var internalFormat = this._getInternalFormat(format);
  7063. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7064. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7065. if (texture._width % 4 !== 0) {
  7066. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7067. }
  7068. if (compression) {
  7069. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7070. }
  7071. else {
  7072. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7073. }
  7074. if (texture.generateMipMaps) {
  7075. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7076. }
  7077. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7078. this.resetTextureCache();
  7079. texture.isReady = true;
  7080. };
  7081. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7082. if (compression === void 0) { compression = null; }
  7083. var texture = this._gl.createTexture();
  7084. texture._baseWidth = width;
  7085. texture._baseHeight = height;
  7086. texture._width = width;
  7087. texture._height = height;
  7088. texture.references = 1;
  7089. this.updateRawTexture(texture, data, format, invertY, compression);
  7090. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7091. // Filters
  7092. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7093. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7094. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7095. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7096. texture.samplingMode = samplingMode;
  7097. this._loadedTexturesCache.push(texture);
  7098. return texture;
  7099. };
  7100. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  7101. var texture = this._gl.createTexture();
  7102. texture._baseWidth = width;
  7103. texture._baseHeight = height;
  7104. if (generateMipMaps) {
  7105. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7106. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7107. }
  7108. this.resetTextureCache();
  7109. texture._width = width;
  7110. texture._height = height;
  7111. texture.isReady = false;
  7112. texture.generateMipMaps = generateMipMaps;
  7113. texture.references = 1;
  7114. texture.samplingMode = samplingMode;
  7115. this.updateTextureSamplingMode(samplingMode, texture);
  7116. this._loadedTexturesCache.push(texture);
  7117. return texture;
  7118. };
  7119. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7120. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7121. if (texture.isCube) {
  7122. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  7123. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7124. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7125. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7126. }
  7127. else {
  7128. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7129. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7130. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7131. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7132. }
  7133. };
  7134. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  7135. if (premulAlpha === void 0) { premulAlpha = false; }
  7136. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7137. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  7138. if (premulAlpha) {
  7139. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7140. }
  7141. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  7142. if (texture.generateMipMaps) {
  7143. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7144. }
  7145. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7146. this.resetTextureCache();
  7147. texture.isReady = true;
  7148. };
  7149. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  7150. if (texture._isDisabled) {
  7151. return;
  7152. }
  7153. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7154. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  7155. try {
  7156. // Testing video texture support
  7157. if (this._videoTextureSupported === undefined) {
  7158. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7159. if (this._gl.getError() !== 0) {
  7160. this._videoTextureSupported = false;
  7161. }
  7162. else {
  7163. this._videoTextureSupported = true;
  7164. }
  7165. }
  7166. // Copy video through the current working canvas if video texture is not supported
  7167. if (!this._videoTextureSupported) {
  7168. if (!texture._workingCanvas) {
  7169. texture._workingCanvas = document.createElement("canvas");
  7170. texture._workingContext = texture._workingCanvas.getContext("2d");
  7171. texture._workingCanvas.width = texture._width;
  7172. texture._workingCanvas.height = texture._height;
  7173. }
  7174. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  7175. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  7176. }
  7177. else {
  7178. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7179. }
  7180. if (texture.generateMipMaps) {
  7181. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7182. }
  7183. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7184. this.resetTextureCache();
  7185. texture.isReady = true;
  7186. }
  7187. catch (ex) {
  7188. // Something unexpected
  7189. // Let's disable the texture
  7190. texture._isDisabled = true;
  7191. }
  7192. };
  7193. Engine.prototype.createRenderTargetTexture = function (size, options) {
  7194. // old version had a "generateMipMaps" arg instead of options.
  7195. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  7196. // in the same way, generateDepthBuffer is defaulted to true
  7197. var generateMipMaps = false;
  7198. var generateDepthBuffer = true;
  7199. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7200. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7201. if (options !== undefined) {
  7202. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7203. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7204. type = options.type === undefined ? type : options.type;
  7205. if (options.samplingMode !== undefined) {
  7206. samplingMode = options.samplingMode;
  7207. }
  7208. if (type === Engine.TEXTURETYPE_FLOAT) {
  7209. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  7210. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7211. }
  7212. }
  7213. var gl = this._gl;
  7214. var texture = gl.createTexture();
  7215. gl.bindTexture(gl.TEXTURE_2D, texture);
  7216. var width = size.width || size;
  7217. var height = size.height || size;
  7218. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7219. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  7220. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7221. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  7222. }
  7223. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7224. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7225. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7226. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7227. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  7228. var depthBuffer;
  7229. // Create the depth buffer
  7230. if (generateDepthBuffer) {
  7231. depthBuffer = gl.createRenderbuffer();
  7232. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7233. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7234. }
  7235. // Create the framebuffer
  7236. var framebuffer = gl.createFramebuffer();
  7237. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  7238. if (generateDepthBuffer) {
  7239. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7240. }
  7241. if (generateMipMaps) {
  7242. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7243. }
  7244. // Unbind
  7245. gl.bindTexture(gl.TEXTURE_2D, null);
  7246. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7247. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  7248. texture._framebuffer = framebuffer;
  7249. if (generateDepthBuffer) {
  7250. texture._depthBuffer = depthBuffer;
  7251. }
  7252. texture._baseWidth = width;
  7253. texture._baseHeight = height;
  7254. texture._width = width;
  7255. texture._height = height;
  7256. texture.isReady = true;
  7257. texture.generateMipMaps = generateMipMaps;
  7258. texture.references = 1;
  7259. texture.samplingMode = samplingMode;
  7260. this.resetTextureCache();
  7261. this._loadedTexturesCache.push(texture);
  7262. return texture;
  7263. };
  7264. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  7265. var gl = this._gl;
  7266. var texture = gl.createTexture();
  7267. var generateMipMaps = true;
  7268. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7269. if (options !== undefined) {
  7270. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7271. if (options.samplingMode !== undefined) {
  7272. samplingMode = options.samplingMode;
  7273. }
  7274. }
  7275. texture.isCube = true;
  7276. texture.references = 1;
  7277. texture.generateMipMaps = generateMipMaps;
  7278. texture.references = 1;
  7279. texture.samplingMode = samplingMode;
  7280. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7281. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7282. for (var face = 0; face < 6; face++) {
  7283. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  7284. }
  7285. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  7286. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  7287. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7288. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7289. // Create the depth buffer
  7290. var depthBuffer = gl.createRenderbuffer();
  7291. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7292. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  7293. // Create the framebuffer
  7294. var framebuffer = gl.createFramebuffer();
  7295. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  7296. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7297. // Mipmaps
  7298. if (texture.generateMipMaps) {
  7299. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7300. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7301. }
  7302. // Unbind
  7303. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7304. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7305. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  7306. texture._framebuffer = framebuffer;
  7307. texture._depthBuffer = depthBuffer;
  7308. this.resetTextureCache();
  7309. texture._width = size;
  7310. texture._height = size;
  7311. texture.isReady = true;
  7312. return texture;
  7313. };
  7314. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  7315. var _this = this;
  7316. var gl = this._gl;
  7317. var texture = gl.createTexture();
  7318. texture.isCube = true;
  7319. texture.url = rootUrl;
  7320. texture.references = 1;
  7321. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  7322. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7323. if (isDDS) {
  7324. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  7325. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7326. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  7327. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7328. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  7329. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  7330. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  7331. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7332. }
  7333. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7334. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  7335. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7336. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7337. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7338. _this.resetTextureCache();
  7339. texture._width = info.width;
  7340. texture._height = info.height;
  7341. texture.isReady = true;
  7342. }, null, null, true);
  7343. }
  7344. else {
  7345. cascadeLoad(rootUrl, scene, function (imgs) {
  7346. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  7347. var height = width;
  7348. _this._prepareWorkingCanvas();
  7349. _this._workingCanvas.width = width;
  7350. _this._workingCanvas.height = height;
  7351. var faces = [
  7352. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7353. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7354. ];
  7355. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7356. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7357. for (var index = 0; index < faces.length; index++) {
  7358. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  7359. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  7360. }
  7361. if (!noMipmap) {
  7362. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7363. }
  7364. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7365. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7366. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7367. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7368. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7369. _this.resetTextureCache();
  7370. texture._width = width;
  7371. texture._height = height;
  7372. texture.isReady = true;
  7373. }, files);
  7374. }
  7375. return texture;
  7376. };
  7377. Engine.prototype.updateTextureSize = function (texture, width, height) {
  7378. texture._width = width;
  7379. texture._height = height;
  7380. texture._size = width * height;
  7381. texture._baseWidth = width;
  7382. texture._baseHeight = height;
  7383. };
  7384. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  7385. var _this = this;
  7386. var gl = this._gl;
  7387. var texture = gl.createTexture();
  7388. scene._addPendingData(texture);
  7389. texture.isCube = true;
  7390. texture.references = 1;
  7391. texture.url = url;
  7392. var internalFormat = this._getInternalFormat(format);
  7393. var textureType = gl.UNSIGNED_BYTE;
  7394. if (type === Engine.TEXTURETYPE_FLOAT) {
  7395. textureType = gl.FLOAT;
  7396. }
  7397. var width = size;
  7398. var height = width;
  7399. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7400. texture._width = width;
  7401. texture._height = height;
  7402. var onerror = function () {
  7403. scene._removePendingData(texture);
  7404. };
  7405. var internalCallback = function (data) {
  7406. var rgbeDataArrays = callback(data);
  7407. var facesIndex = [
  7408. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7409. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7410. ];
  7411. width = texture._width;
  7412. height = texture._height;
  7413. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7414. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7415. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7416. if (!noMipmap && isPot) {
  7417. if (mipmmapGenerator) {
  7418. var arrayTemp = [];
  7419. // Data are known to be in +X +Y +Z -X -Y -Z
  7420. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  7421. arrayTemp.push(rgbeDataArrays[0]); // +X
  7422. arrayTemp.push(rgbeDataArrays[3]); // -X
  7423. arrayTemp.push(rgbeDataArrays[1]); // +Y
  7424. arrayTemp.push(rgbeDataArrays[4]); // -Y
  7425. arrayTemp.push(rgbeDataArrays[2]); // +Z
  7426. arrayTemp.push(rgbeDataArrays[5]); // -Z
  7427. var mipData = mipmmapGenerator(arrayTemp);
  7428. for (var level = 0; level < mipData.length; level++) {
  7429. var mipSize = width >> level;
  7430. // mipData is order in +X -X +Y -Y +Z -Z
  7431. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  7432. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  7433. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  7434. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  7435. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  7436. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  7437. }
  7438. }
  7439. else {
  7440. // Data are known to be in +X +Y +Z -X -Y -Z
  7441. for (var index = 0; index < facesIndex.length; index++) {
  7442. var faceData = rgbeDataArrays[index];
  7443. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  7444. }
  7445. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7446. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  7447. // By following the webgl standard changes from Revision 7, 2014/11/24
  7448. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  7449. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  7450. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  7451. // Data are known to be in +X +Y +Z -X -Y -Z
  7452. for (var index = 0; index < facesIndex.length; index++) {
  7453. var faceData = rgbeDataArrays[index];
  7454. // Create a new RGBA Face.
  7455. var newFaceData = new Float32Array(width * height * 4);
  7456. for (var x = 0; x < width; x++) {
  7457. for (var y = 0; y < height; y++) {
  7458. var index_1 = (y * width + x) * 3;
  7459. var newIndex = (y * width + x) * 4;
  7460. // Map Old Value to new value.
  7461. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  7462. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  7463. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  7464. // Add fully opaque alpha channel.
  7465. newFaceData[newIndex + 3] = 1;
  7466. }
  7467. }
  7468. // Reupload the face.
  7469. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  7470. }
  7471. // Try to generate mipmap again.
  7472. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7473. }
  7474. }
  7475. }
  7476. else {
  7477. noMipmap = true;
  7478. }
  7479. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  7480. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7481. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7482. }
  7483. else {
  7484. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7485. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7486. }
  7487. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7488. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7489. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7490. texture.isReady = true;
  7491. _this.resetTextureCache();
  7492. scene._removePendingData(texture);
  7493. };
  7494. BABYLON.Tools.LoadFile(url, function (data) {
  7495. internalCallback(data);
  7496. }, onerror, scene.database, true);
  7497. return texture;
  7498. };
  7499. ;
  7500. Engine.prototype._releaseTexture = function (texture) {
  7501. var gl = this._gl;
  7502. if (texture._framebuffer) {
  7503. gl.deleteFramebuffer(texture._framebuffer);
  7504. }
  7505. if (texture._depthBuffer) {
  7506. gl.deleteRenderbuffer(texture._depthBuffer);
  7507. }
  7508. gl.deleteTexture(texture);
  7509. // Unbind channels
  7510. this.unbindAllTextures();
  7511. var index = this._loadedTexturesCache.indexOf(texture);
  7512. if (index !== -1) {
  7513. this._loadedTexturesCache.splice(index, 1);
  7514. }
  7515. };
  7516. Engine.prototype.bindSamplers = function (effect) {
  7517. this._gl.useProgram(effect.getProgram());
  7518. var samplers = effect.getSamplers();
  7519. for (var index = 0; index < samplers.length; index++) {
  7520. var uniform = effect.getUniform(samplers[index]);
  7521. this._gl.uniform1i(uniform, index);
  7522. }
  7523. this._currentEffect = null;
  7524. };
  7525. Engine.prototype._bindTexture = function (channel, texture) {
  7526. if (channel < 0) {
  7527. return;
  7528. }
  7529. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7530. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7531. this._activeTexturesCache[channel] = null;
  7532. };
  7533. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7534. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7535. };
  7536. Engine.prototype.unbindAllTextures = function () {
  7537. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7538. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7539. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7540. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7541. this._activeTexturesCache[channel] = null;
  7542. }
  7543. };
  7544. Engine.prototype.setTexture = function (channel, texture) {
  7545. if (channel < 0) {
  7546. return;
  7547. }
  7548. // Not ready?
  7549. if (!texture || !texture.isReady()) {
  7550. if (this._activeTexturesCache[channel] != null) {
  7551. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7552. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7553. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7554. this._activeTexturesCache[channel] = null;
  7555. }
  7556. return;
  7557. }
  7558. // Video
  7559. var alreadyActivated = false;
  7560. if (texture instanceof BABYLON.VideoTexture) {
  7561. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7562. alreadyActivated = true;
  7563. texture.update();
  7564. }
  7565. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7566. texture.delayLoad();
  7567. return;
  7568. }
  7569. if (this._activeTexturesCache[channel] === texture) {
  7570. return;
  7571. }
  7572. this._activeTexturesCache[channel] = texture;
  7573. var internalTexture = texture.getInternalTexture();
  7574. if (!alreadyActivated) {
  7575. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7576. }
  7577. if (internalTexture.isCube) {
  7578. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7579. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7580. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7581. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7582. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7583. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7584. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7585. }
  7586. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7587. }
  7588. else {
  7589. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7590. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7591. internalTexture._cachedWrapU = texture.wrapU;
  7592. switch (texture.wrapU) {
  7593. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7594. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7595. break;
  7596. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7597. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7598. break;
  7599. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7600. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7601. break;
  7602. }
  7603. }
  7604. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7605. internalTexture._cachedWrapV = texture.wrapV;
  7606. switch (texture.wrapV) {
  7607. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7608. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7609. break;
  7610. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7611. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7612. break;
  7613. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7614. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7615. break;
  7616. }
  7617. }
  7618. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7619. }
  7620. };
  7621. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7622. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7623. var value = texture.anisotropicFilteringLevel;
  7624. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7625. value = 1;
  7626. }
  7627. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7628. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7629. texture._cachedAnisotropicFilteringLevel = value;
  7630. }
  7631. };
  7632. Engine.prototype.readPixels = function (x, y, width, height) {
  7633. var data = new Uint8Array(height * width * 4);
  7634. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7635. return data;
  7636. };
  7637. /**
  7638. * Add an externaly attached data from its key.
  7639. * This method call will fail and return false, if such key already exists.
  7640. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  7641. * @param key the unique key that identifies the data
  7642. * @param data the data object to associate to the key for this Engine instance
  7643. * @return true if no such key were already present and the data was added successfully, false otherwise
  7644. */
  7645. Engine.prototype.addExternalData = function (key, data) {
  7646. return this._externalData.add(key, data);
  7647. };
  7648. /**
  7649. * Get an externaly attached data from its key
  7650. * @param key the unique key that identifies the data
  7651. * @return the associated data, if present (can be null), or undefined if not present
  7652. */
  7653. Engine.prototype.getExternalData = function (key) {
  7654. return this._externalData.get(key);
  7655. };
  7656. /**
  7657. * Get an externaly attached data from its key, create it using a factory if it's not already present
  7658. * @param key the unique key that identifies the data
  7659. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  7660. * @return the associated data, can be null if the factory returned null.
  7661. */
  7662. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  7663. return this._externalData.getOrAddWithFactory(key, factory);
  7664. };
  7665. /**
  7666. * Remove an externaly attached data from the Engine instance
  7667. * @param key the unique key that identifies the data
  7668. * @return true if the data was successfully removed, false if it doesn't exist
  7669. */
  7670. Engine.prototype.removeExternalData = function (key) {
  7671. return this._externalData.remove(key);
  7672. };
  7673. Engine.prototype.releaseInternalTexture = function (texture) {
  7674. if (!texture) {
  7675. return;
  7676. }
  7677. texture.references--;
  7678. // Final reference ?
  7679. if (texture.references === 0) {
  7680. var texturesCache = this.getLoadedTexturesCache();
  7681. var index = texturesCache.indexOf(texture);
  7682. if (index > -1) {
  7683. texturesCache.splice(index, 1);
  7684. }
  7685. this._releaseTexture(texture);
  7686. }
  7687. };
  7688. // Dispose
  7689. Engine.prototype.dispose = function () {
  7690. this.hideLoadingUI();
  7691. this.stopRenderLoop();
  7692. // Release scenes
  7693. while (this.scenes.length) {
  7694. this.scenes[0].dispose();
  7695. }
  7696. // Release audio engine
  7697. Engine.audioEngine.dispose();
  7698. // Release effects
  7699. for (var name in this._compiledEffects) {
  7700. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7701. }
  7702. // Unbind
  7703. if (this._vertexAttribArraysEnabled) {
  7704. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  7705. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i]) {
  7706. continue;
  7707. }
  7708. this._gl.disableVertexAttribArray(i);
  7709. }
  7710. }
  7711. this._gl = null;
  7712. // Events
  7713. window.removeEventListener("blur", this._onBlur);
  7714. window.removeEventListener("focus", this._onFocus);
  7715. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7716. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7717. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7718. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7719. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7720. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7721. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7722. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7723. };
  7724. // Loading screen
  7725. Engine.prototype.displayLoadingUI = function () {
  7726. this._loadingScreen.displayLoadingUI();
  7727. };
  7728. Engine.prototype.hideLoadingUI = function () {
  7729. this._loadingScreen.hideLoadingUI();
  7730. };
  7731. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7732. get: function () {
  7733. return this._loadingScreen;
  7734. },
  7735. set: function (loadingScreen) {
  7736. this._loadingScreen = loadingScreen;
  7737. },
  7738. enumerable: true,
  7739. configurable: true
  7740. });
  7741. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7742. set: function (text) {
  7743. this._loadingScreen.loadingUIText = text;
  7744. },
  7745. enumerable: true,
  7746. configurable: true
  7747. });
  7748. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7749. set: function (color) {
  7750. this._loadingScreen.loadingUIBackgroundColor = color;
  7751. },
  7752. enumerable: true,
  7753. configurable: true
  7754. });
  7755. // FPS
  7756. Engine.prototype.getFps = function () {
  7757. return this.fps;
  7758. };
  7759. Engine.prototype.getDeltaTime = function () {
  7760. return this.deltaTime;
  7761. };
  7762. Engine.prototype._measureFps = function () {
  7763. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7764. var length = this.previousFramesDuration.length;
  7765. if (length >= 2) {
  7766. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7767. }
  7768. if (length >= this.fpsRange) {
  7769. if (length > this.fpsRange) {
  7770. this.previousFramesDuration.splice(0, 1);
  7771. length = this.previousFramesDuration.length;
  7772. }
  7773. var sum = 0;
  7774. for (var id = 0; id < length - 1; id++) {
  7775. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7776. }
  7777. this.fps = 1000.0 / (sum / (length - 1));
  7778. }
  7779. };
  7780. // Statics
  7781. Engine.isSupported = function () {
  7782. try {
  7783. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7784. if (navigator.isCocoonJS) {
  7785. return true;
  7786. }
  7787. var tempcanvas = document.createElement("canvas");
  7788. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7789. return gl != null && !!window.WebGLRenderingContext;
  7790. }
  7791. catch (e) {
  7792. return false;
  7793. }
  7794. };
  7795. // Const statics
  7796. Engine._ALPHA_DISABLE = 0;
  7797. Engine._ALPHA_ADD = 1;
  7798. Engine._ALPHA_COMBINE = 2;
  7799. Engine._ALPHA_SUBTRACT = 3;
  7800. Engine._ALPHA_MULTIPLY = 4;
  7801. Engine._ALPHA_MAXIMIZED = 5;
  7802. Engine._ALPHA_ONEONE = 6;
  7803. Engine._DELAYLOADSTATE_NONE = 0;
  7804. Engine._DELAYLOADSTATE_LOADED = 1;
  7805. Engine._DELAYLOADSTATE_LOADING = 2;
  7806. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7807. Engine._TEXTUREFORMAT_ALPHA = 0;
  7808. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7809. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7810. Engine._TEXTUREFORMAT_RGB = 4;
  7811. Engine._TEXTUREFORMAT_RGBA = 5;
  7812. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7813. Engine._TEXTURETYPE_FLOAT = 1;
  7814. // Updatable statics so stick with vars here
  7815. Engine.CollisionsEpsilon = 0.001;
  7816. Engine.CodeRepository = "src/";
  7817. Engine.ShadersRepository = "src/Shaders/";
  7818. return Engine;
  7819. })();
  7820. BABYLON.Engine = Engine;
  7821. })(BABYLON || (BABYLON = {}));
  7822. var BABYLON;
  7823. (function (BABYLON) {
  7824. /**
  7825. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7826. */
  7827. var Node = (function () {
  7828. /**
  7829. * @constructor
  7830. * @param {string} name - the name and id to be given to this node
  7831. * @param {BABYLON.Scene} the scene this node will be added to
  7832. */
  7833. function Node(name, scene) {
  7834. this.state = "";
  7835. this.animations = new Array();
  7836. this._ranges = {};
  7837. this._childrenFlag = -1;
  7838. this._isEnabled = true;
  7839. this._isReady = true;
  7840. this._currentRenderId = -1;
  7841. this._parentRenderId = -1;
  7842. this.name = name;
  7843. this.id = name;
  7844. this._scene = scene;
  7845. this._initCache();
  7846. }
  7847. Object.defineProperty(Node.prototype, "parent", {
  7848. get: function () {
  7849. return this._parentNode;
  7850. },
  7851. set: function (parent) {
  7852. if (this._parentNode === parent) {
  7853. return;
  7854. }
  7855. if (this._parentNode) {
  7856. var index = this._parentNode._children.indexOf(this);
  7857. if (index !== -1) {
  7858. this._parentNode._children.splice(index, 1);
  7859. }
  7860. }
  7861. this._parentNode = parent;
  7862. if (this._parentNode) {
  7863. if (!this._parentNode._children) {
  7864. this._parentNode._children = new Array();
  7865. }
  7866. this._parentNode._children.push(this);
  7867. }
  7868. },
  7869. enumerable: true,
  7870. configurable: true
  7871. });
  7872. Node.prototype.getScene = function () {
  7873. return this._scene;
  7874. };
  7875. Node.prototype.getEngine = function () {
  7876. return this._scene.getEngine();
  7877. };
  7878. // override it in derived class
  7879. Node.prototype.getWorldMatrix = function () {
  7880. return BABYLON.Matrix.Identity();
  7881. };
  7882. // override it in derived class if you add new variables to the cache
  7883. // and call the parent class method
  7884. Node.prototype._initCache = function () {
  7885. this._cache = {};
  7886. this._cache.parent = undefined;
  7887. };
  7888. Node.prototype.updateCache = function (force) {
  7889. if (!force && this.isSynchronized())
  7890. return;
  7891. this._cache.parent = this.parent;
  7892. this._updateCache();
  7893. };
  7894. // override it in derived class if you add new variables to the cache
  7895. // and call the parent class method if !ignoreParentClass
  7896. Node.prototype._updateCache = function (ignoreParentClass) {
  7897. };
  7898. // override it in derived class if you add new variables to the cache
  7899. Node.prototype._isSynchronized = function () {
  7900. return true;
  7901. };
  7902. Node.prototype._markSyncedWithParent = function () {
  7903. this._parentRenderId = this.parent._currentRenderId;
  7904. };
  7905. Node.prototype.isSynchronizedWithParent = function () {
  7906. if (!this.parent) {
  7907. return true;
  7908. }
  7909. if (this._parentRenderId !== this.parent._currentRenderId) {
  7910. return false;
  7911. }
  7912. return this.parent.isSynchronized();
  7913. };
  7914. Node.prototype.isSynchronized = function (updateCache) {
  7915. var check = this.hasNewParent();
  7916. check = check || !this.isSynchronizedWithParent();
  7917. check = check || !this._isSynchronized();
  7918. if (updateCache)
  7919. this.updateCache(true);
  7920. return !check;
  7921. };
  7922. Node.prototype.hasNewParent = function (update) {
  7923. if (this._cache.parent === this.parent)
  7924. return false;
  7925. if (update)
  7926. this._cache.parent = this.parent;
  7927. return true;
  7928. };
  7929. /**
  7930. * Is this node ready to be used/rendered
  7931. * @return {boolean} is it ready
  7932. */
  7933. Node.prototype.isReady = function () {
  7934. return this._isReady;
  7935. };
  7936. /**
  7937. * Is this node enabled.
  7938. * If the node has a parent and is enabled, the parent will be inspected as well.
  7939. * @return {boolean} whether this node (and its parent) is enabled.
  7940. * @see setEnabled
  7941. */
  7942. Node.prototype.isEnabled = function () {
  7943. if (!this._isEnabled) {
  7944. return false;
  7945. }
  7946. if (this.parent) {
  7947. return this.parent.isEnabled();
  7948. }
  7949. return true;
  7950. };
  7951. /**
  7952. * Set the enabled state of this node.
  7953. * @param {boolean} value - the new enabled state
  7954. * @see isEnabled
  7955. */
  7956. Node.prototype.setEnabled = function (value) {
  7957. this._isEnabled = value;
  7958. };
  7959. /**
  7960. * Is this node a descendant of the given node.
  7961. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7962. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7963. * @see parent
  7964. */
  7965. Node.prototype.isDescendantOf = function (ancestor) {
  7966. if (this.parent) {
  7967. if (this.parent === ancestor) {
  7968. return true;
  7969. }
  7970. return this.parent.isDescendantOf(ancestor);
  7971. }
  7972. return false;
  7973. };
  7974. /**
  7975. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  7976. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7977. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7978. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7979. */
  7980. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  7981. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  7982. if (!this._children) {
  7983. return;
  7984. }
  7985. for (var index = 0; index < this._children.length; index++) {
  7986. var item = this._children[index];
  7987. if (!predicate || predicate(item)) {
  7988. results.push(item);
  7989. }
  7990. if (!directDescendantsOnly) {
  7991. item._getDescendants(results, false, predicate);
  7992. }
  7993. }
  7994. };
  7995. /**
  7996. * Will return all nodes that have this node as ascendant.
  7997. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7998. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7999. * @return {BABYLON.Node[]} all children nodes of all types.
  8000. */
  8001. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  8002. var results = [];
  8003. this._getDescendants(results, directDescendantsOnly, predicate);
  8004. return results;
  8005. };
  8006. /**
  8007. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  8008. * @Deprecated, legacy support.
  8009. * use getDecendants instead.
  8010. */
  8011. Node.prototype.getChildren = function (predicate) {
  8012. return this.getDescendants(true, predicate);
  8013. };
  8014. /**
  8015. * Get all child-meshes of this node.
  8016. */
  8017. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  8018. var results = [];
  8019. this._getDescendants(results, directDecendantsOnly, function (node) {
  8020. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  8021. });
  8022. return results;
  8023. };
  8024. Node.prototype._setReady = function (state) {
  8025. if (state === this._isReady) {
  8026. return;
  8027. }
  8028. if (!state) {
  8029. this._isReady = false;
  8030. return;
  8031. }
  8032. this._isReady = true;
  8033. if (this.onReady) {
  8034. this.onReady(this);
  8035. }
  8036. };
  8037. Node.prototype.getAnimationByName = function (name) {
  8038. for (var i = 0; i < this.animations.length; i++) {
  8039. var animation = this.animations[i];
  8040. if (animation.name === name) {
  8041. return animation;
  8042. }
  8043. }
  8044. return null;
  8045. };
  8046. Node.prototype.createAnimationRange = function (name, from, to) {
  8047. // check name not already in use
  8048. if (!this._ranges[name]) {
  8049. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  8050. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8051. if (this.animations[i]) {
  8052. this.animations[i].createRange(name, from, to);
  8053. }
  8054. }
  8055. }
  8056. };
  8057. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  8058. if (deleteFrames === void 0) { deleteFrames = true; }
  8059. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8060. if (this.animations[i]) {
  8061. this.animations[i].deleteRange(name, deleteFrames);
  8062. }
  8063. }
  8064. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  8065. };
  8066. Node.prototype.getAnimationRange = function (name) {
  8067. return this._ranges[name];
  8068. };
  8069. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  8070. var range = this.getAnimationRange(name);
  8071. if (!range) {
  8072. return null;
  8073. }
  8074. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  8075. };
  8076. Node.prototype.serializeAnimationRanges = function () {
  8077. var serializationRanges = [];
  8078. for (var name in this._ranges) {
  8079. var range = {};
  8080. range.name = name;
  8081. range.from = this._ranges[name].from;
  8082. range.to = this._ranges[name].to;
  8083. serializationRanges.push(range);
  8084. }
  8085. return serializationRanges;
  8086. };
  8087. Node.prototype.dispose = function () {
  8088. this.parent = null;
  8089. };
  8090. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  8091. if (parsedNode.ranges) {
  8092. for (var index = 0; index < parsedNode.ranges.length; index++) {
  8093. var data = parsedNode.ranges[index];
  8094. node.createAnimationRange(data.name, data.from, data.to);
  8095. }
  8096. }
  8097. };
  8098. __decorate([
  8099. BABYLON.serialize()
  8100. ], Node.prototype, "name", void 0);
  8101. __decorate([
  8102. BABYLON.serialize()
  8103. ], Node.prototype, "id", void 0);
  8104. __decorate([
  8105. BABYLON.serialize()
  8106. ], Node.prototype, "uniqueId", void 0);
  8107. __decorate([
  8108. BABYLON.serialize()
  8109. ], Node.prototype, "state", void 0);
  8110. return Node;
  8111. })();
  8112. BABYLON.Node = Node;
  8113. })(BABYLON || (BABYLON = {}));
  8114. var BABYLON;
  8115. (function (BABYLON) {
  8116. var FilesInput = (function () {
  8117. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  8118. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  8119. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  8120. this._engine = p_engine;
  8121. this._canvas = p_canvas;
  8122. this._currentScene = p_scene;
  8123. this._sceneLoadedCallback = p_sceneLoadedCallback;
  8124. this._progressCallback = p_progressCallback;
  8125. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  8126. this._textureLoadingCallback = p_textureLoadingCallback;
  8127. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  8128. }
  8129. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  8130. var _this = this;
  8131. if (p_elementToMonitor) {
  8132. this._elementToMonitor = p_elementToMonitor;
  8133. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  8134. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  8135. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  8136. }
  8137. };
  8138. FilesInput.prototype.renderFunction = function () {
  8139. if (this._additionnalRenderLoopLogicCallback) {
  8140. this._additionnalRenderLoopLogicCallback();
  8141. }
  8142. if (this._currentScene) {
  8143. if (this._textureLoadingCallback) {
  8144. var remaining = this._currentScene.getWaitingItemsCount();
  8145. if (remaining > 0) {
  8146. this._textureLoadingCallback(remaining);
  8147. }
  8148. }
  8149. this._currentScene.render();
  8150. }
  8151. };
  8152. FilesInput.prototype.drag = function (e) {
  8153. e.stopPropagation();
  8154. e.preventDefault();
  8155. };
  8156. FilesInput.prototype.drop = function (eventDrop) {
  8157. eventDrop.stopPropagation();
  8158. eventDrop.preventDefault();
  8159. this.loadFiles(eventDrop);
  8160. };
  8161. FilesInput.prototype.loadFiles = function (event) {
  8162. if (this._startingProcessingFilesCallback)
  8163. this._startingProcessingFilesCallback();
  8164. // Handling data transfer via drag'n'drop
  8165. if (event && event.dataTransfer && event.dataTransfer.files) {
  8166. this._filesToLoad = event.dataTransfer.files;
  8167. }
  8168. // Handling files from input files
  8169. if (event && event.target && event.target.files) {
  8170. this._filesToLoad = event.target.files;
  8171. }
  8172. if (this._filesToLoad && this._filesToLoad.length > 0) {
  8173. for (var i = 0; i < this._filesToLoad.length; i++) {
  8174. switch (this._filesToLoad[i].type) {
  8175. case "image/jpeg":
  8176. case "image/png":
  8177. case "image/bmp":
  8178. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8179. break;
  8180. case "image/targa":
  8181. case "image/vnd.ms-dds":
  8182. case "audio/wav":
  8183. case "audio/x-wav":
  8184. case "audio/mp3":
  8185. case "audio/mpeg":
  8186. case "audio/mpeg3":
  8187. case "audio/x-mpeg-3":
  8188. case "audio/ogg":
  8189. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8190. break;
  8191. default:
  8192. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  8193. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8194. }
  8195. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  8196. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  8197. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  8198. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  8199. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  8200. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  8201. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  8202. this._sceneFileToLoad = this._filesToLoad[i];
  8203. }
  8204. break;
  8205. }
  8206. }
  8207. this.reload();
  8208. }
  8209. };
  8210. FilesInput.prototype.reload = function () {
  8211. var _this = this;
  8212. var that = this;
  8213. // If a ".babylon" file has been provided
  8214. if (this._sceneFileToLoad) {
  8215. if (this._currentScene) {
  8216. if (BABYLON.Tools.errorsCount > 0) {
  8217. BABYLON.Tools.ClearLogCache();
  8218. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  8219. }
  8220. this._engine.stopRenderLoop();
  8221. this._currentScene.dispose();
  8222. }
  8223. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  8224. that._currentScene = newScene;
  8225. // Wait for textures and shaders to be ready
  8226. that._currentScene.executeWhenReady(function () {
  8227. // Attach camera to canvas inputs
  8228. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  8229. that._currentScene.createDefaultCameraOrLight();
  8230. }
  8231. that._currentScene.activeCamera.attachControl(that._canvas);
  8232. if (that._sceneLoadedCallback) {
  8233. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  8234. }
  8235. that._engine.runRenderLoop(function () { that.renderFunction(); });
  8236. });
  8237. }, function (progress) {
  8238. if (_this._progressCallback) {
  8239. _this._progressCallback(progress);
  8240. }
  8241. });
  8242. }
  8243. else {
  8244. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  8245. }
  8246. };
  8247. FilesInput.FilesTextures = new Array();
  8248. FilesInput.FilesToLoad = new Array();
  8249. return FilesInput;
  8250. })();
  8251. BABYLON.FilesInput = FilesInput;
  8252. })(BABYLON || (BABYLON = {}));
  8253. var BABYLON;
  8254. (function (BABYLON) {
  8255. var IntersectionInfo = (function () {
  8256. function IntersectionInfo(bu, bv, distance) {
  8257. this.bu = bu;
  8258. this.bv = bv;
  8259. this.distance = distance;
  8260. this.faceId = 0;
  8261. this.subMeshId = 0;
  8262. }
  8263. return IntersectionInfo;
  8264. })();
  8265. BABYLON.IntersectionInfo = IntersectionInfo;
  8266. var PickingInfo = (function () {
  8267. function PickingInfo() {
  8268. this.hit = false;
  8269. this.distance = 0;
  8270. this.pickedPoint = null;
  8271. this.pickedMesh = null;
  8272. this.bu = 0;
  8273. this.bv = 0;
  8274. this.faceId = -1;
  8275. this.subMeshId = 0;
  8276. this.pickedSprite = null;
  8277. }
  8278. // Methods
  8279. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  8280. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  8281. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  8282. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8283. return null;
  8284. }
  8285. var indices = this.pickedMesh.getIndices();
  8286. var result;
  8287. if (useVerticesNormals) {
  8288. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8289. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  8290. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  8291. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  8292. normal0 = normal0.scale(this.bu);
  8293. normal1 = normal1.scale(this.bv);
  8294. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  8295. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  8296. }
  8297. else {
  8298. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8299. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  8300. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  8301. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  8302. var p1p2 = vertex1.subtract(vertex2);
  8303. var p3p2 = vertex3.subtract(vertex2);
  8304. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  8305. }
  8306. if (useWorldCoordinates) {
  8307. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  8308. }
  8309. return BABYLON.Vector3.Normalize(result);
  8310. };
  8311. PickingInfo.prototype.getTextureCoordinates = function () {
  8312. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8313. return null;
  8314. }
  8315. var indices = this.pickedMesh.getIndices();
  8316. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8317. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  8318. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  8319. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  8320. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  8321. uv1 = uv1.scale(this.bu);
  8322. uv2 = uv2.scale(this.bv);
  8323. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  8324. };
  8325. return PickingInfo;
  8326. })();
  8327. BABYLON.PickingInfo = PickingInfo;
  8328. })(BABYLON || (BABYLON = {}));
  8329. var BABYLON;
  8330. (function (BABYLON) {
  8331. var BoundingSphere = (function () {
  8332. function BoundingSphere(minimum, maximum) {
  8333. this.minimum = minimum;
  8334. this.maximum = maximum;
  8335. this._tempRadiusVector = BABYLON.Vector3.Zero();
  8336. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  8337. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  8338. this.radius = distance * 0.5;
  8339. this.centerWorld = BABYLON.Vector3.Zero();
  8340. this._update(BABYLON.Matrix.Identity());
  8341. }
  8342. // Methods
  8343. BoundingSphere.prototype._update = function (world) {
  8344. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  8345. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  8346. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  8347. };
  8348. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  8349. for (var i = 0; i < 6; i++) {
  8350. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  8351. return false;
  8352. }
  8353. return true;
  8354. };
  8355. BoundingSphere.prototype.intersectsPoint = function (point) {
  8356. var x = this.centerWorld.x - point.x;
  8357. var y = this.centerWorld.y - point.y;
  8358. var z = this.centerWorld.z - point.z;
  8359. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8360. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  8361. return false;
  8362. return true;
  8363. };
  8364. // Statics
  8365. BoundingSphere.Intersects = function (sphere0, sphere1) {
  8366. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  8367. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  8368. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  8369. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8370. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  8371. return false;
  8372. return true;
  8373. };
  8374. return BoundingSphere;
  8375. })();
  8376. BABYLON.BoundingSphere = BoundingSphere;
  8377. })(BABYLON || (BABYLON = {}));
  8378. var BABYLON;
  8379. (function (BABYLON) {
  8380. var BoundingBox = (function () {
  8381. function BoundingBox(minimum, maximum) {
  8382. this.minimum = minimum;
  8383. this.maximum = maximum;
  8384. this.vectors = new Array();
  8385. this.vectorsWorld = new Array();
  8386. // Bounding vectors
  8387. this.vectors.push(this.minimum.clone());
  8388. this.vectors.push(this.maximum.clone());
  8389. this.vectors.push(this.minimum.clone());
  8390. this.vectors[2].x = this.maximum.x;
  8391. this.vectors.push(this.minimum.clone());
  8392. this.vectors[3].y = this.maximum.y;
  8393. this.vectors.push(this.minimum.clone());
  8394. this.vectors[4].z = this.maximum.z;
  8395. this.vectors.push(this.maximum.clone());
  8396. this.vectors[5].z = this.minimum.z;
  8397. this.vectors.push(this.maximum.clone());
  8398. this.vectors[6].x = this.minimum.x;
  8399. this.vectors.push(this.maximum.clone());
  8400. this.vectors[7].y = this.minimum.y;
  8401. // OBB
  8402. this.center = this.maximum.add(this.minimum).scale(0.5);
  8403. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  8404. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  8405. // World
  8406. for (var index = 0; index < this.vectors.length; index++) {
  8407. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  8408. }
  8409. this.minimumWorld = BABYLON.Vector3.Zero();
  8410. this.maximumWorld = BABYLON.Vector3.Zero();
  8411. this._update(BABYLON.Matrix.Identity());
  8412. }
  8413. // Methods
  8414. BoundingBox.prototype.getWorldMatrix = function () {
  8415. return this._worldMatrix;
  8416. };
  8417. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  8418. this._worldMatrix.copyFrom(matrix);
  8419. return this;
  8420. };
  8421. BoundingBox.prototype._update = function (world) {
  8422. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  8423. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  8424. for (var index = 0; index < this.vectors.length; index++) {
  8425. var v = this.vectorsWorld[index];
  8426. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  8427. if (v.x < this.minimumWorld.x)
  8428. this.minimumWorld.x = v.x;
  8429. if (v.y < this.minimumWorld.y)
  8430. this.minimumWorld.y = v.y;
  8431. if (v.z < this.minimumWorld.z)
  8432. this.minimumWorld.z = v.z;
  8433. if (v.x > this.maximumWorld.x)
  8434. this.maximumWorld.x = v.x;
  8435. if (v.y > this.maximumWorld.y)
  8436. this.maximumWorld.y = v.y;
  8437. if (v.z > this.maximumWorld.z)
  8438. this.maximumWorld.z = v.z;
  8439. }
  8440. // OBB
  8441. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  8442. this.center.scaleInPlace(0.5);
  8443. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  8444. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  8445. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  8446. this._worldMatrix = world;
  8447. };
  8448. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  8449. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  8450. };
  8451. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8452. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  8453. };
  8454. BoundingBox.prototype.intersectsPoint = function (point) {
  8455. var delta = -BABYLON.Epsilon;
  8456. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  8457. return false;
  8458. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  8459. return false;
  8460. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  8461. return false;
  8462. return true;
  8463. };
  8464. BoundingBox.prototype.intersectsSphere = function (sphere) {
  8465. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  8466. };
  8467. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  8468. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  8469. return false;
  8470. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  8471. return false;
  8472. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  8473. return false;
  8474. return true;
  8475. };
  8476. // Statics
  8477. BoundingBox.Intersects = function (box0, box1) {
  8478. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  8479. return false;
  8480. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  8481. return false;
  8482. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  8483. return false;
  8484. return true;
  8485. };
  8486. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  8487. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  8488. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  8489. return (num <= (sphereRadius * sphereRadius));
  8490. };
  8491. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  8492. for (var p = 0; p < 6; p++) {
  8493. for (var i = 0; i < 8; i++) {
  8494. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8495. return false;
  8496. }
  8497. }
  8498. }
  8499. return true;
  8500. };
  8501. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  8502. for (var p = 0; p < 6; p++) {
  8503. var inCount = 8;
  8504. for (var i = 0; i < 8; i++) {
  8505. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8506. --inCount;
  8507. }
  8508. else {
  8509. break;
  8510. }
  8511. }
  8512. if (inCount === 0)
  8513. return false;
  8514. }
  8515. return true;
  8516. };
  8517. return BoundingBox;
  8518. })();
  8519. BABYLON.BoundingBox = BoundingBox;
  8520. })(BABYLON || (BABYLON = {}));
  8521. var BABYLON;
  8522. (function (BABYLON) {
  8523. var computeBoxExtents = function (axis, box) {
  8524. var p = BABYLON.Vector3.Dot(box.center, axis);
  8525. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  8526. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  8527. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  8528. var r = r0 + r1 + r2;
  8529. return {
  8530. min: p - r,
  8531. max: p + r
  8532. };
  8533. };
  8534. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  8535. var axisOverlap = function (axis, box0, box1) {
  8536. var result0 = computeBoxExtents(axis, box0);
  8537. var result1 = computeBoxExtents(axis, box1);
  8538. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  8539. };
  8540. var BoundingInfo = (function () {
  8541. function BoundingInfo(minimum, maximum) {
  8542. this.minimum = minimum;
  8543. this.maximum = maximum;
  8544. this._isLocked = false;
  8545. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  8546. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  8547. }
  8548. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  8549. get: function () {
  8550. return this._isLocked;
  8551. },
  8552. set: function (value) {
  8553. this._isLocked = value;
  8554. },
  8555. enumerable: true,
  8556. configurable: true
  8557. });
  8558. // Methods
  8559. BoundingInfo.prototype.update = function (world) {
  8560. if (this._isLocked) {
  8561. return;
  8562. }
  8563. this.boundingBox._update(world);
  8564. this.boundingSphere._update(world);
  8565. };
  8566. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  8567. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  8568. return false;
  8569. return this.boundingBox.isInFrustum(frustumPlanes);
  8570. };
  8571. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8572. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  8573. };
  8574. BoundingInfo.prototype._checkCollision = function (collider) {
  8575. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  8576. };
  8577. BoundingInfo.prototype.intersectsPoint = function (point) {
  8578. if (!this.boundingSphere.centerWorld) {
  8579. return false;
  8580. }
  8581. if (!this.boundingSphere.intersectsPoint(point)) {
  8582. return false;
  8583. }
  8584. if (!this.boundingBox.intersectsPoint(point)) {
  8585. return false;
  8586. }
  8587. return true;
  8588. };
  8589. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  8590. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  8591. return false;
  8592. }
  8593. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  8594. return false;
  8595. }
  8596. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  8597. return false;
  8598. }
  8599. if (!precise) {
  8600. return true;
  8601. }
  8602. var box0 = this.boundingBox;
  8603. var box1 = boundingInfo.boundingBox;
  8604. if (!axisOverlap(box0.directions[0], box0, box1))
  8605. return false;
  8606. if (!axisOverlap(box0.directions[1], box0, box1))
  8607. return false;
  8608. if (!axisOverlap(box0.directions[2], box0, box1))
  8609. return false;
  8610. if (!axisOverlap(box1.directions[0], box0, box1))
  8611. return false;
  8612. if (!axisOverlap(box1.directions[1], box0, box1))
  8613. return false;
  8614. if (!axisOverlap(box1.directions[2], box0, box1))
  8615. return false;
  8616. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8617. return false;
  8618. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8619. return false;
  8620. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8621. return false;
  8622. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8623. return false;
  8624. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8625. return false;
  8626. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8627. return false;
  8628. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8629. return false;
  8630. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8631. return false;
  8632. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8633. return false;
  8634. return true;
  8635. };
  8636. return BoundingInfo;
  8637. })();
  8638. BABYLON.BoundingInfo = BoundingInfo;
  8639. })(BABYLON || (BABYLON = {}));
  8640. var BABYLON;
  8641. (function (BABYLON) {
  8642. var Ray = (function () {
  8643. function Ray(origin, direction, length) {
  8644. if (length === void 0) { length = Number.MAX_VALUE; }
  8645. this.origin = origin;
  8646. this.direction = direction;
  8647. this.length = length;
  8648. }
  8649. // Methods
  8650. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  8651. var d = 0.0;
  8652. var maxValue = Number.MAX_VALUE;
  8653. var inv;
  8654. var min;
  8655. var max;
  8656. var temp;
  8657. if (Math.abs(this.direction.x) < 0.0000001) {
  8658. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  8659. return false;
  8660. }
  8661. }
  8662. else {
  8663. inv = 1.0 / this.direction.x;
  8664. min = (minimum.x - this.origin.x) * inv;
  8665. max = (maximum.x - this.origin.x) * inv;
  8666. if (max === -Infinity) {
  8667. max = Infinity;
  8668. }
  8669. if (min > max) {
  8670. temp = min;
  8671. min = max;
  8672. max = temp;
  8673. }
  8674. d = Math.max(min, d);
  8675. maxValue = Math.min(max, maxValue);
  8676. if (d > maxValue) {
  8677. return false;
  8678. }
  8679. }
  8680. if (Math.abs(this.direction.y) < 0.0000001) {
  8681. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  8682. return false;
  8683. }
  8684. }
  8685. else {
  8686. inv = 1.0 / this.direction.y;
  8687. min = (minimum.y - this.origin.y) * inv;
  8688. max = (maximum.y - this.origin.y) * inv;
  8689. if (max === -Infinity) {
  8690. max = Infinity;
  8691. }
  8692. if (min > max) {
  8693. temp = min;
  8694. min = max;
  8695. max = temp;
  8696. }
  8697. d = Math.max(min, d);
  8698. maxValue = Math.min(max, maxValue);
  8699. if (d > maxValue) {
  8700. return false;
  8701. }
  8702. }
  8703. if (Math.abs(this.direction.z) < 0.0000001) {
  8704. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  8705. return false;
  8706. }
  8707. }
  8708. else {
  8709. inv = 1.0 / this.direction.z;
  8710. min = (minimum.z - this.origin.z) * inv;
  8711. max = (maximum.z - this.origin.z) * inv;
  8712. if (max === -Infinity) {
  8713. max = Infinity;
  8714. }
  8715. if (min > max) {
  8716. temp = min;
  8717. min = max;
  8718. max = temp;
  8719. }
  8720. d = Math.max(min, d);
  8721. maxValue = Math.min(max, maxValue);
  8722. if (d > maxValue) {
  8723. return false;
  8724. }
  8725. }
  8726. return true;
  8727. };
  8728. Ray.prototype.intersectsBox = function (box) {
  8729. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8730. };
  8731. Ray.prototype.intersectsSphere = function (sphere) {
  8732. var x = sphere.center.x - this.origin.x;
  8733. var y = sphere.center.y - this.origin.y;
  8734. var z = sphere.center.z - this.origin.z;
  8735. var pyth = (x * x) + (y * y) + (z * z);
  8736. var rr = sphere.radius * sphere.radius;
  8737. if (pyth <= rr) {
  8738. return true;
  8739. }
  8740. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8741. if (dot < 0.0) {
  8742. return false;
  8743. }
  8744. var temp = pyth - (dot * dot);
  8745. return temp <= rr;
  8746. };
  8747. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8748. if (!this._edge1) {
  8749. this._edge1 = BABYLON.Vector3.Zero();
  8750. this._edge2 = BABYLON.Vector3.Zero();
  8751. this._pvec = BABYLON.Vector3.Zero();
  8752. this._tvec = BABYLON.Vector3.Zero();
  8753. this._qvec = BABYLON.Vector3.Zero();
  8754. }
  8755. vertex1.subtractToRef(vertex0, this._edge1);
  8756. vertex2.subtractToRef(vertex0, this._edge2);
  8757. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  8758. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  8759. if (det === 0) {
  8760. return null;
  8761. }
  8762. var invdet = 1 / det;
  8763. this.origin.subtractToRef(vertex0, this._tvec);
  8764. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8765. if (bu < 0 || bu > 1.0) {
  8766. return null;
  8767. }
  8768. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8769. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8770. if (bv < 0 || bu + bv > 1.0) {
  8771. return null;
  8772. }
  8773. //check if the distance is longer than the predefined length.
  8774. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8775. if (distance > this.length) {
  8776. return null;
  8777. }
  8778. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8779. };
  8780. Ray.prototype.intersectsPlane = function (plane) {
  8781. var distance;
  8782. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  8783. if (Math.abs(result1) < 9.99999997475243E-07) {
  8784. return null;
  8785. }
  8786. else {
  8787. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  8788. distance = (-plane.d - result2) / result1;
  8789. if (distance < 0.0) {
  8790. if (distance < -9.99999997475243E-07) {
  8791. return null;
  8792. }
  8793. else {
  8794. return 0;
  8795. }
  8796. }
  8797. return distance;
  8798. }
  8799. };
  8800. /**
  8801. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  8802. * @param sega the first point of the segment to test the intersection against
  8803. * @param segb the second point of the segment to test the intersection against
  8804. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  8805. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  8806. */
  8807. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  8808. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  8809. var u = segb.subtract(sega);
  8810. var v = rsegb.subtract(this.origin);
  8811. var w = sega.subtract(this.origin);
  8812. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  8813. var b = BABYLON.Vector3.Dot(u, v);
  8814. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  8815. var d = BABYLON.Vector3.Dot(u, w);
  8816. var e = BABYLON.Vector3.Dot(v, w);
  8817. var D = a * c - b * b; // always >= 0
  8818. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  8819. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  8820. // compute the line parameters of the two closest points
  8821. if (D < Ray.smallnum) {
  8822. sN = 0.0; // force using point P0 on segment S1
  8823. sD = 1.0; // to prevent possible division by 0.0 later
  8824. tN = e;
  8825. tD = c;
  8826. }
  8827. else {
  8828. sN = (b * e - c * d);
  8829. tN = (a * e - b * d);
  8830. if (sN < 0.0) {
  8831. sN = 0.0;
  8832. tN = e;
  8833. tD = c;
  8834. }
  8835. else if (sN > sD) {
  8836. sN = sD;
  8837. tN = e + b;
  8838. tD = c;
  8839. }
  8840. }
  8841. if (tN < 0.0) {
  8842. tN = 0.0;
  8843. // recompute sc for this edge
  8844. if (-d < 0.0) {
  8845. sN = 0.0;
  8846. }
  8847. else if (-d > a)
  8848. sN = sD;
  8849. else {
  8850. sN = -d;
  8851. sD = a;
  8852. }
  8853. }
  8854. else if (tN > tD) {
  8855. tN = tD;
  8856. // recompute sc for this edge
  8857. if ((-d + b) < 0.0) {
  8858. sN = 0;
  8859. }
  8860. else if ((-d + b) > a) {
  8861. sN = sD;
  8862. }
  8863. else {
  8864. sN = (-d + b);
  8865. sD = a;
  8866. }
  8867. }
  8868. // finally do the division to get sc and tc
  8869. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  8870. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  8871. // get the difference of the two closest points
  8872. var qtc = v.multiplyByFloats(tc, tc, tc);
  8873. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  8874. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  8875. if (isIntersected) {
  8876. return qtc.length();
  8877. }
  8878. return -1;
  8879. };
  8880. // Statics
  8881. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8882. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8883. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8884. var direction = end.subtract(start);
  8885. direction.normalize();
  8886. return new Ray(start, direction);
  8887. };
  8888. /**
  8889. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  8890. * transformed to the given world matrix.
  8891. * @param origin The origin point
  8892. * @param end The end point
  8893. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8894. */
  8895. Ray.CreateNewFromTo = function (origin, end, world) {
  8896. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8897. var direction = end.subtract(origin);
  8898. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8899. direction.normalize();
  8900. return Ray.Transform(new Ray(origin, direction, length), world);
  8901. };
  8902. Ray.Transform = function (ray, matrix) {
  8903. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8904. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8905. newDirection.normalize();
  8906. return new Ray(newOrigin, newDirection, ray.length);
  8907. };
  8908. Ray.smallnum = 0.00000001;
  8909. Ray.rayl = 10e8;
  8910. return Ray;
  8911. })();
  8912. BABYLON.Ray = Ray;
  8913. })(BABYLON || (BABYLON = {}));
  8914. var BABYLON;
  8915. (function (BABYLON) {
  8916. var AbstractMesh = (function (_super) {
  8917. __extends(AbstractMesh, _super);
  8918. // Constructor
  8919. function AbstractMesh(name, scene) {
  8920. var _this = this;
  8921. _super.call(this, name, scene);
  8922. // Events
  8923. /**
  8924. * An event triggered when the mesh is disposed.
  8925. * @type {BABYLON.Observable}
  8926. */
  8927. this.onDisposeObservable = new BABYLON.Observable();
  8928. /**
  8929. * An event triggered when this mesh collides with another one
  8930. * @type {BABYLON.Observable}
  8931. */
  8932. this.onCollideObservable = new BABYLON.Observable();
  8933. /**
  8934. * An event triggered when the collision's position changes
  8935. * @type {BABYLON.Observable}
  8936. */
  8937. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  8938. /**
  8939. * An event triggered after the world matrix is updated
  8940. * @type {BABYLON.Observable}
  8941. */
  8942. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  8943. // Properties
  8944. this.definedFacingForward = true; // orientation for POV movement & rotation
  8945. this.position = new BABYLON.Vector3(0, 0, 0);
  8946. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8947. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8948. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8949. this.visibility = 1.0;
  8950. this.alphaIndex = Number.MAX_VALUE;
  8951. this.infiniteDistance = false;
  8952. this.isVisible = true;
  8953. this.isPickable = true;
  8954. this.showBoundingBox = false;
  8955. this.showSubMeshesBoundingBox = false;
  8956. this.isBlocker = false;
  8957. this.renderingGroupId = 0;
  8958. this.receiveShadows = false;
  8959. this.renderOutline = false;
  8960. this.outlineColor = BABYLON.Color3.Red();
  8961. this.outlineWidth = 0.02;
  8962. this.renderOverlay = false;
  8963. this.overlayColor = BABYLON.Color3.Red();
  8964. this.overlayAlpha = 0.5;
  8965. this.hasVertexAlpha = false;
  8966. this.useVertexColors = true;
  8967. this.applyFog = true;
  8968. this.computeBonesUsingShaders = true;
  8969. this.scalingDeterminant = 1;
  8970. this.numBoneInfluencers = 4;
  8971. this.useOctreeForRenderingSelection = true;
  8972. this.useOctreeForPicking = true;
  8973. this.useOctreeForCollisions = true;
  8974. this.layerMask = 0x0FFFFFFF;
  8975. this.alwaysSelectAsActiveMesh = false;
  8976. // Collisions
  8977. this._checkCollisions = false;
  8978. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8979. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8980. this._collider = new BABYLON.Collider();
  8981. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8982. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8983. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8984. // Edges
  8985. this.edgesWidth = 1;
  8986. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8987. // Cache
  8988. this._localWorld = BABYLON.Matrix.Zero();
  8989. this._worldMatrix = BABYLON.Matrix.Zero();
  8990. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8991. this._absolutePosition = BABYLON.Vector3.Zero();
  8992. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8993. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8994. this._isDirty = false;
  8995. this._pivotMatrix = BABYLON.Matrix.Identity();
  8996. this._isDisposed = false;
  8997. this._renderId = 0;
  8998. this._intersectionsInProgress = new Array();
  8999. this._isWorldMatrixFrozen = false;
  9000. this._unIndexed = false;
  9001. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9002. if (collidedMesh === void 0) { collidedMesh = null; }
  9003. //TODO move this to the collision coordinator!
  9004. if (_this.getScene().workerCollisions)
  9005. newPosition.multiplyInPlace(_this._collider.radius);
  9006. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  9007. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9008. _this.position.addInPlace(_this._diffPositionForCollisions);
  9009. }
  9010. if (collidedMesh) {
  9011. _this.onCollideObservable.notifyObservers(collidedMesh);
  9012. }
  9013. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  9014. };
  9015. scene.addMesh(this);
  9016. }
  9017. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9018. get: function () {
  9019. return AbstractMesh._BILLBOARDMODE_NONE;
  9020. },
  9021. enumerable: true,
  9022. configurable: true
  9023. });
  9024. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9025. get: function () {
  9026. return AbstractMesh._BILLBOARDMODE_X;
  9027. },
  9028. enumerable: true,
  9029. configurable: true
  9030. });
  9031. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9032. get: function () {
  9033. return AbstractMesh._BILLBOARDMODE_Y;
  9034. },
  9035. enumerable: true,
  9036. configurable: true
  9037. });
  9038. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9039. get: function () {
  9040. return AbstractMesh._BILLBOARDMODE_Z;
  9041. },
  9042. enumerable: true,
  9043. configurable: true
  9044. });
  9045. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9046. get: function () {
  9047. return AbstractMesh._BILLBOARDMODE_ALL;
  9048. },
  9049. enumerable: true,
  9050. configurable: true
  9051. });
  9052. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  9053. set: function (callback) {
  9054. if (this._onDisposeObserver) {
  9055. this.onDisposeObservable.remove(this._onDisposeObserver);
  9056. }
  9057. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9058. },
  9059. enumerable: true,
  9060. configurable: true
  9061. });
  9062. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  9063. set: function (callback) {
  9064. if (this._onCollideObserver) {
  9065. this.onCollideObservable.remove(this._onCollideObserver);
  9066. }
  9067. this._onCollideObserver = this.onCollideObservable.add(callback);
  9068. },
  9069. enumerable: true,
  9070. configurable: true
  9071. });
  9072. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  9073. set: function (callback) {
  9074. if (this._onCollisionPositionChangeObserver) {
  9075. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  9076. }
  9077. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  9078. },
  9079. enumerable: true,
  9080. configurable: true
  9081. });
  9082. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  9083. get: function () {
  9084. return this._skeleton;
  9085. },
  9086. set: function (value) {
  9087. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  9088. this._skeleton._unregisterMeshWithPoseMatrix(this);
  9089. }
  9090. if (value && value.needInitialSkinMatrix) {
  9091. value._registerMeshWithPoseMatrix(this);
  9092. }
  9093. this._skeleton = value;
  9094. if (!this._skeleton) {
  9095. this._bonesTransformMatrices = null;
  9096. }
  9097. },
  9098. enumerable: true,
  9099. configurable: true
  9100. });
  9101. /**
  9102. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9103. */
  9104. AbstractMesh.prototype.toString = function (fullDetails) {
  9105. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  9106. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  9107. if (this._skeleton) {
  9108. ret += ", skeleton: " + this._skeleton.name;
  9109. }
  9110. if (fullDetails) {
  9111. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  9112. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  9113. }
  9114. return ret;
  9115. };
  9116. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  9117. /**
  9118. * Getting the rotation object.
  9119. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  9120. */
  9121. get: function () {
  9122. return this._rotation;
  9123. },
  9124. set: function (newRotation) {
  9125. this._rotation = newRotation;
  9126. },
  9127. enumerable: true,
  9128. configurable: true
  9129. });
  9130. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  9131. get: function () {
  9132. return this._scaling;
  9133. },
  9134. set: function (newScaling) {
  9135. this._scaling = newScaling;
  9136. if (this.physicsImpostor) {
  9137. this.physicsImpostor.forceUpdate();
  9138. }
  9139. },
  9140. enumerable: true,
  9141. configurable: true
  9142. });
  9143. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  9144. get: function () {
  9145. return this._rotationQuaternion;
  9146. },
  9147. set: function (quaternion) {
  9148. this._rotationQuaternion = quaternion;
  9149. //reset the rotation vector.
  9150. if (quaternion && this.rotation.length()) {
  9151. this.rotation.copyFromFloats(0, 0, 0);
  9152. }
  9153. },
  9154. enumerable: true,
  9155. configurable: true
  9156. });
  9157. // Methods
  9158. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  9159. this._poseMatrix.copyFrom(matrix);
  9160. };
  9161. AbstractMesh.prototype.getPoseMatrix = function () {
  9162. return this._poseMatrix;
  9163. };
  9164. AbstractMesh.prototype.disableEdgesRendering = function () {
  9165. if (this._edgesRenderer !== undefined) {
  9166. this._edgesRenderer.dispose();
  9167. this._edgesRenderer = undefined;
  9168. }
  9169. };
  9170. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  9171. if (epsilon === void 0) { epsilon = 0.95; }
  9172. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  9173. this.disableEdgesRendering();
  9174. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  9175. };
  9176. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9177. get: function () {
  9178. return false;
  9179. },
  9180. enumerable: true,
  9181. configurable: true
  9182. });
  9183. AbstractMesh.prototype.getLOD = function (camera) {
  9184. return this;
  9185. };
  9186. AbstractMesh.prototype.getTotalVertices = function () {
  9187. return 0;
  9188. };
  9189. AbstractMesh.prototype.getIndices = function () {
  9190. return null;
  9191. };
  9192. AbstractMesh.prototype.getVerticesData = function (kind) {
  9193. return null;
  9194. };
  9195. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9196. return false;
  9197. };
  9198. AbstractMesh.prototype.getBoundingInfo = function () {
  9199. if (this._masterMesh) {
  9200. return this._masterMesh.getBoundingInfo();
  9201. }
  9202. if (!this._boundingInfo) {
  9203. this._updateBoundingInfo();
  9204. }
  9205. return this._boundingInfo;
  9206. };
  9207. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9208. get: function () {
  9209. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9210. },
  9211. enumerable: true,
  9212. configurable: true
  9213. });
  9214. AbstractMesh.prototype._preActivate = function () {
  9215. };
  9216. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  9217. };
  9218. AbstractMesh.prototype._activate = function (renderId) {
  9219. this._renderId = renderId;
  9220. };
  9221. AbstractMesh.prototype.getWorldMatrix = function () {
  9222. if (this._masterMesh) {
  9223. return this._masterMesh.getWorldMatrix();
  9224. }
  9225. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9226. this.computeWorldMatrix();
  9227. }
  9228. return this._worldMatrix;
  9229. };
  9230. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9231. get: function () {
  9232. return this._worldMatrix;
  9233. },
  9234. enumerable: true,
  9235. configurable: true
  9236. });
  9237. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9238. get: function () {
  9239. return this._absolutePosition;
  9240. },
  9241. enumerable: true,
  9242. configurable: true
  9243. });
  9244. AbstractMesh.prototype.freezeWorldMatrix = function () {
  9245. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  9246. this.computeWorldMatrix(true);
  9247. this._isWorldMatrixFrozen = true;
  9248. };
  9249. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  9250. this._isWorldMatrixFrozen = false;
  9251. this.computeWorldMatrix(true);
  9252. };
  9253. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  9254. get: function () {
  9255. return this._isWorldMatrixFrozen;
  9256. },
  9257. enumerable: true,
  9258. configurable: true
  9259. });
  9260. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9261. axis.normalize();
  9262. if (!this.rotationQuaternion) {
  9263. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9264. this.rotation = BABYLON.Vector3.Zero();
  9265. }
  9266. var rotationQuaternion;
  9267. if (!space || space === BABYLON.Space.LOCAL) {
  9268. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9269. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9270. }
  9271. else {
  9272. if (this.parent) {
  9273. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9274. invertParentWorldMatrix.invert();
  9275. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9276. }
  9277. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9278. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9279. }
  9280. };
  9281. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9282. var displacementVector = axis.scale(distance);
  9283. if (!space || space === BABYLON.Space.LOCAL) {
  9284. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9285. this.setPositionWithLocalVector(tempV3);
  9286. }
  9287. else {
  9288. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9289. }
  9290. };
  9291. AbstractMesh.prototype.getAbsolutePosition = function () {
  9292. this.computeWorldMatrix();
  9293. return this._absolutePosition;
  9294. };
  9295. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9296. if (!absolutePosition) {
  9297. return;
  9298. }
  9299. var absolutePositionX;
  9300. var absolutePositionY;
  9301. var absolutePositionZ;
  9302. if (absolutePosition.x === undefined) {
  9303. if (arguments.length < 3) {
  9304. return;
  9305. }
  9306. absolutePositionX = arguments[0];
  9307. absolutePositionY = arguments[1];
  9308. absolutePositionZ = arguments[2];
  9309. }
  9310. else {
  9311. absolutePositionX = absolutePosition.x;
  9312. absolutePositionY = absolutePosition.y;
  9313. absolutePositionZ = absolutePosition.z;
  9314. }
  9315. if (this.parent) {
  9316. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9317. invertParentWorldMatrix.invert();
  9318. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9319. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9320. }
  9321. else {
  9322. this.position.x = absolutePositionX;
  9323. this.position.y = absolutePositionY;
  9324. this.position.z = absolutePositionZ;
  9325. }
  9326. };
  9327. // ================================== Point of View Movement =================================
  9328. /**
  9329. * Perform relative position change from the point of view of behind the front of the mesh.
  9330. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9331. * Supports definition of mesh facing forward or backward.
  9332. * @param {number} amountRight
  9333. * @param {number} amountUp
  9334. * @param {number} amountForward
  9335. */
  9336. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9337. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9338. };
  9339. /**
  9340. * Calculate relative position change from the point of view of behind the front of the mesh.
  9341. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9342. * Supports definition of mesh facing forward or backward.
  9343. * @param {number} amountRight
  9344. * @param {number} amountUp
  9345. * @param {number} amountForward
  9346. */
  9347. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9348. var rotMatrix = new BABYLON.Matrix();
  9349. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9350. rotQuaternion.toRotationMatrix(rotMatrix);
  9351. var translationDelta = BABYLON.Vector3.Zero();
  9352. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9353. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9354. return translationDelta;
  9355. };
  9356. // ================================== Point of View Rotation =================================
  9357. /**
  9358. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9359. * Supports definition of mesh facing forward or backward.
  9360. * @param {number} flipBack
  9361. * @param {number} twirlClockwise
  9362. * @param {number} tiltRight
  9363. */
  9364. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9365. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9366. };
  9367. /**
  9368. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9369. * Supports definition of mesh facing forward or backward.
  9370. * @param {number} flipBack
  9371. * @param {number} twirlClockwise
  9372. * @param {number} tiltRight
  9373. */
  9374. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9375. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9376. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9377. };
  9378. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9379. this._pivotMatrix = matrix;
  9380. this._cache.pivotMatrixUpdated = true;
  9381. };
  9382. AbstractMesh.prototype.getPivotMatrix = function () {
  9383. return this._pivotMatrix;
  9384. };
  9385. AbstractMesh.prototype._isSynchronized = function () {
  9386. if (this._isDirty) {
  9387. return false;
  9388. }
  9389. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9390. return false;
  9391. if (this._cache.pivotMatrixUpdated) {
  9392. return false;
  9393. }
  9394. if (this.infiniteDistance) {
  9395. return false;
  9396. }
  9397. if (!this._cache.position.equals(this.position))
  9398. return false;
  9399. if (this.rotationQuaternion) {
  9400. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9401. return false;
  9402. }
  9403. else {
  9404. if (!this._cache.rotation.equals(this.rotation))
  9405. return false;
  9406. }
  9407. if (!this._cache.scaling.equals(this.scaling))
  9408. return false;
  9409. return true;
  9410. };
  9411. AbstractMesh.prototype._initCache = function () {
  9412. _super.prototype._initCache.call(this);
  9413. this._cache.localMatrixUpdated = false;
  9414. this._cache.position = BABYLON.Vector3.Zero();
  9415. this._cache.scaling = BABYLON.Vector3.Zero();
  9416. this._cache.rotation = BABYLON.Vector3.Zero();
  9417. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9418. this._cache.billboardMode = -1;
  9419. };
  9420. AbstractMesh.prototype.markAsDirty = function (property) {
  9421. if (property === "rotation") {
  9422. this.rotationQuaternion = null;
  9423. }
  9424. this._currentRenderId = Number.MAX_VALUE;
  9425. this._isDirty = true;
  9426. };
  9427. AbstractMesh.prototype._updateBoundingInfo = function () {
  9428. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9429. this._boundingInfo.update(this.worldMatrixFromCache);
  9430. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9431. };
  9432. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9433. if (!this.subMeshes) {
  9434. return;
  9435. }
  9436. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9437. var subMesh = this.subMeshes[subIndex];
  9438. if (!subMesh.IsGlobal) {
  9439. subMesh.updateBoundingInfo(matrix);
  9440. }
  9441. }
  9442. };
  9443. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9444. if (this._isWorldMatrixFrozen) {
  9445. return this._worldMatrix;
  9446. }
  9447. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  9448. this._currentRenderId = this.getScene().getRenderId();
  9449. return this._worldMatrix;
  9450. }
  9451. this._cache.position.copyFrom(this.position);
  9452. this._cache.scaling.copyFrom(this.scaling);
  9453. this._cache.pivotMatrixUpdated = false;
  9454. this._cache.billboardMode = this.billboardMode;
  9455. this._currentRenderId = this.getScene().getRenderId();
  9456. this._isDirty = false;
  9457. // Scaling
  9458. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  9459. // Rotation
  9460. //rotate, if quaternion is set and rotation was used
  9461. if (this.rotationQuaternion) {
  9462. var len = this.rotation.length();
  9463. if (len) {
  9464. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  9465. this.rotation.copyFromFloats(0, 0, 0);
  9466. }
  9467. }
  9468. if (this.rotationQuaternion) {
  9469. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  9470. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9471. }
  9472. else {
  9473. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  9474. this._cache.rotation.copyFrom(this.rotation);
  9475. }
  9476. // Translation
  9477. if (this.infiniteDistance && !this.parent) {
  9478. var camera = this.getScene().activeCamera;
  9479. if (camera) {
  9480. var cameraWorldMatrix = camera.getWorldMatrix();
  9481. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9482. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  9483. }
  9484. }
  9485. else {
  9486. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  9487. }
  9488. // Composing transformations
  9489. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  9490. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  9491. // Billboarding
  9492. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9493. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  9494. var localPosition = BABYLON.Tmp.Vector3[0];
  9495. if (this.parent && this.parent.getWorldMatrix) {
  9496. this._markSyncedWithParent();
  9497. var parentMatrix;
  9498. if (this._meshToBoneReferal) {
  9499. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9500. parentMatrix = BABYLON.Tmp.Matrix[6];
  9501. }
  9502. else {
  9503. parentMatrix = this.parent.getWorldMatrix();
  9504. }
  9505. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  9506. localPosition = BABYLON.Tmp.Vector3[1];
  9507. }
  9508. var zero = this.getScene().activeCamera.globalPosition.clone();
  9509. if (this.parent && this.parent.position) {
  9510. localPosition.addInPlace(this.parent.position);
  9511. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  9512. }
  9513. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  9514. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  9515. zero.x = localPosition.x + BABYLON.Epsilon;
  9516. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  9517. zero.y = localPosition.y + BABYLON.Epsilon;
  9518. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  9519. zero.z = localPosition.z + BABYLON.Epsilon;
  9520. }
  9521. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  9522. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  9523. BABYLON.Tmp.Matrix[3].invert();
  9524. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  9525. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  9526. }
  9527. // Local world
  9528. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  9529. // Parent
  9530. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  9531. this._markSyncedWithParent();
  9532. if (this._meshToBoneReferal) {
  9533. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9534. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  9535. }
  9536. else {
  9537. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9538. }
  9539. }
  9540. else {
  9541. this._worldMatrix.copyFrom(this._localWorld);
  9542. }
  9543. // Bounding info
  9544. this._updateBoundingInfo();
  9545. // Absolute position
  9546. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9547. // Callbacks
  9548. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  9549. if (!this._poseMatrix) {
  9550. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  9551. }
  9552. return this._worldMatrix;
  9553. };
  9554. /**
  9555. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9556. * @param func: callback function to add
  9557. */
  9558. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9559. this.onAfterWorldMatrixUpdateObservable.add(func);
  9560. };
  9561. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9562. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  9563. };
  9564. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9565. this.computeWorldMatrix();
  9566. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9567. };
  9568. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9569. this.computeWorldMatrix();
  9570. var invLocalWorldMatrix = this._localWorld.clone();
  9571. invLocalWorldMatrix.invert();
  9572. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9573. };
  9574. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9575. this.computeWorldMatrix(true);
  9576. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9577. };
  9578. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9579. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9580. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  9581. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9582. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9583. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9584. /// <returns>Mesh oriented towards targetMesh</returns>
  9585. yawCor = yawCor || 0; // default to zero if undefined
  9586. pitchCor = pitchCor || 0;
  9587. rollCor = rollCor || 0;
  9588. var dv = targetPoint.subtract(this.position);
  9589. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9590. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9591. var pitch = Math.atan2(dv.y, len);
  9592. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9593. };
  9594. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  9595. this._meshToBoneReferal = affectedMesh;
  9596. this.parent = bone;
  9597. if (bone.getWorldMatrix().determinant() < 0) {
  9598. this.scalingDeterminant *= -1;
  9599. }
  9600. };
  9601. AbstractMesh.prototype.detachFromBone = function () {
  9602. if (this.parent.getWorldMatrix().determinant() < 0) {
  9603. this.scalingDeterminant *= -1;
  9604. }
  9605. this._meshToBoneReferal = null;
  9606. this.parent = null;
  9607. };
  9608. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9609. return this._boundingInfo.isInFrustum(frustumPlanes);
  9610. };
  9611. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9612. if (!camera) {
  9613. camera = this.getScene().activeCamera;
  9614. }
  9615. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9616. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9617. return false;
  9618. }
  9619. return true;
  9620. };
  9621. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9622. if (!this._boundingInfo || !mesh._boundingInfo) {
  9623. return false;
  9624. }
  9625. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9626. };
  9627. AbstractMesh.prototype.intersectsPoint = function (point) {
  9628. if (!this._boundingInfo) {
  9629. return false;
  9630. }
  9631. return this._boundingInfo.intersectsPoint(point);
  9632. };
  9633. // Physics
  9634. /**
  9635. * @Deprecated. Use new PhysicsImpostor instead.
  9636. * */
  9637. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9638. //legacy support
  9639. if (impostor.impostor) {
  9640. options = impostor;
  9641. impostor = impostor.impostor;
  9642. }
  9643. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  9644. return this.physicsImpostor.physicsBody;
  9645. };
  9646. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9647. return this.physicsImpostor;
  9648. };
  9649. /**
  9650. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  9651. */
  9652. AbstractMesh.prototype.getPhysicsMass = function () {
  9653. return this.physicsImpostor.getParam("mass");
  9654. };
  9655. /**
  9656. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  9657. */
  9658. AbstractMesh.prototype.getPhysicsFriction = function () {
  9659. return this.physicsImpostor.getParam("friction");
  9660. };
  9661. /**
  9662. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  9663. */
  9664. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9665. return this.physicsImpostor.getParam("resitution");
  9666. };
  9667. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9668. if (!camera) {
  9669. camera = this.getScene().activeCamera;
  9670. }
  9671. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9672. };
  9673. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9674. if (!camera) {
  9675. camera = this.getScene().activeCamera;
  9676. }
  9677. return this.absolutePosition.subtract(camera.position).length();
  9678. };
  9679. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9680. if (!this.physicsImpostor) {
  9681. return;
  9682. }
  9683. this.physicsImpostor.applyImpulse(force, contactPoint);
  9684. };
  9685. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9686. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  9687. return;
  9688. }
  9689. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  9690. mainPivot: pivot1,
  9691. connectedPivot: pivot2,
  9692. nativeParams: options
  9693. });
  9694. };
  9695. /**
  9696. * @Deprecated
  9697. */
  9698. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9699. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  9700. this.updatePhysicsBody();
  9701. };
  9702. /**
  9703. * @Deprecated
  9704. * Calling this function is not needed anymore.
  9705. * The physics engine takes care of transofmration automatically.
  9706. */
  9707. AbstractMesh.prototype.updatePhysicsBody = function () {
  9708. //Unneeded
  9709. };
  9710. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  9711. // Collisions
  9712. get: function () {
  9713. return this._checkCollisions;
  9714. },
  9715. set: function (collisionEnabled) {
  9716. this._checkCollisions = collisionEnabled;
  9717. if (this.getScene().workerCollisions) {
  9718. this.getScene().collisionCoordinator.onMeshUpdated(this);
  9719. }
  9720. },
  9721. enumerable: true,
  9722. configurable: true
  9723. });
  9724. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9725. var globalPosition = this.getAbsolutePosition();
  9726. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9727. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9728. this._collider.radius = this.ellipsoid;
  9729. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  9730. };
  9731. // Submeshes octree
  9732. /**
  9733. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9734. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9735. */
  9736. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9737. if (maxCapacity === void 0) { maxCapacity = 64; }
  9738. if (maxDepth === void 0) { maxDepth = 2; }
  9739. if (!this._submeshesOctree) {
  9740. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9741. }
  9742. this.computeWorldMatrix(true);
  9743. // Update octree
  9744. var bbox = this.getBoundingInfo().boundingBox;
  9745. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9746. return this._submeshesOctree;
  9747. };
  9748. // Collisions
  9749. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9750. this._generatePointsArray();
  9751. // Transformation
  9752. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9753. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9754. subMesh._lastColliderWorldVertices = [];
  9755. subMesh._trianglePlanes = [];
  9756. var start = subMesh.verticesStart;
  9757. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9758. for (var i = start; i < end; i++) {
  9759. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9760. }
  9761. }
  9762. // Collide
  9763. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  9764. if (collider.collisionFound) {
  9765. collider.collidedMesh = this;
  9766. }
  9767. };
  9768. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9769. var subMeshes;
  9770. var len;
  9771. // Octrees
  9772. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9773. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9774. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9775. len = intersections.length;
  9776. subMeshes = intersections.data;
  9777. }
  9778. else {
  9779. subMeshes = this.subMeshes;
  9780. len = subMeshes.length;
  9781. }
  9782. for (var index = 0; index < len; index++) {
  9783. var subMesh = subMeshes[index];
  9784. // Bounding test
  9785. if (len > 1 && !subMesh._checkCollision(collider))
  9786. continue;
  9787. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9788. }
  9789. };
  9790. AbstractMesh.prototype._checkCollision = function (collider) {
  9791. // Bounding box test
  9792. if (!this._boundingInfo._checkCollision(collider))
  9793. return;
  9794. // Transformation matrix
  9795. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9796. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9797. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9798. };
  9799. // Picking
  9800. AbstractMesh.prototype._generatePointsArray = function () {
  9801. return false;
  9802. };
  9803. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9804. var pickingInfo = new BABYLON.PickingInfo();
  9805. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9806. return pickingInfo;
  9807. }
  9808. if (!this._generatePointsArray()) {
  9809. return pickingInfo;
  9810. }
  9811. var intersectInfo = null;
  9812. // Octrees
  9813. var subMeshes;
  9814. var len;
  9815. if (this._submeshesOctree && this.useOctreeForPicking) {
  9816. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9817. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9818. len = intersections.length;
  9819. subMeshes = intersections.data;
  9820. }
  9821. else {
  9822. subMeshes = this.subMeshes;
  9823. len = subMeshes.length;
  9824. }
  9825. for (var index = 0; index < len; index++) {
  9826. var subMesh = subMeshes[index];
  9827. // Bounding test
  9828. if (len > 1 && !subMesh.canIntersects(ray))
  9829. continue;
  9830. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9831. if (currentIntersectInfo) {
  9832. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9833. intersectInfo = currentIntersectInfo;
  9834. intersectInfo.subMeshId = index;
  9835. if (fastCheck) {
  9836. break;
  9837. }
  9838. }
  9839. }
  9840. }
  9841. if (intersectInfo) {
  9842. // Get picked point
  9843. var world = this.getWorldMatrix();
  9844. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9845. var direction = ray.direction.clone();
  9846. direction = direction.scale(intersectInfo.distance);
  9847. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9848. var pickedPoint = worldOrigin.add(worldDirection);
  9849. // Return result
  9850. pickingInfo.hit = true;
  9851. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9852. pickingInfo.pickedPoint = pickedPoint;
  9853. pickingInfo.pickedMesh = this;
  9854. pickingInfo.bu = intersectInfo.bu;
  9855. pickingInfo.bv = intersectInfo.bv;
  9856. pickingInfo.faceId = intersectInfo.faceId;
  9857. pickingInfo.subMeshId = intersectInfo.subMeshId;
  9858. return pickingInfo;
  9859. }
  9860. return pickingInfo;
  9861. };
  9862. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9863. return null;
  9864. };
  9865. AbstractMesh.prototype.releaseSubMeshes = function () {
  9866. if (this.subMeshes) {
  9867. while (this.subMeshes.length) {
  9868. this.subMeshes[0].dispose();
  9869. }
  9870. }
  9871. else {
  9872. this.subMeshes = new Array();
  9873. }
  9874. };
  9875. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9876. var _this = this;
  9877. var index;
  9878. // Action manager
  9879. if (this.actionManager) {
  9880. this.actionManager.dispose();
  9881. this.actionManager = null;
  9882. }
  9883. // Skeleton
  9884. this.skeleton = null;
  9885. // Animations
  9886. this.getScene().stopAnimation(this);
  9887. // Physics
  9888. if (this.physicsImpostor) {
  9889. this.physicsImpostor.dispose();
  9890. }
  9891. // Intersections in progress
  9892. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9893. var other = this._intersectionsInProgress[index];
  9894. var pos = other._intersectionsInProgress.indexOf(this);
  9895. other._intersectionsInProgress.splice(pos, 1);
  9896. }
  9897. this._intersectionsInProgress = [];
  9898. // Lights
  9899. var lights = this.getScene().lights;
  9900. lights.forEach(function (light) {
  9901. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  9902. if (meshIndex !== -1) {
  9903. light.includedOnlyMeshes.splice(meshIndex, 1);
  9904. }
  9905. meshIndex = light.excludedMeshes.indexOf(_this);
  9906. if (meshIndex !== -1) {
  9907. light.excludedMeshes.splice(meshIndex, 1);
  9908. }
  9909. });
  9910. // Edges
  9911. if (this._edgesRenderer) {
  9912. this._edgesRenderer.dispose();
  9913. this._edgesRenderer = null;
  9914. }
  9915. // SubMeshes
  9916. this.releaseSubMeshes();
  9917. // Remove from scene
  9918. this.getScene().removeMesh(this);
  9919. if (!doNotRecurse) {
  9920. // Particles
  9921. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9922. if (this.getScene().particleSystems[index].emitter === this) {
  9923. this.getScene().particleSystems[index].dispose();
  9924. index--;
  9925. }
  9926. }
  9927. // Children
  9928. var objects = this.getDescendants(true);
  9929. for (index = 0; index < objects.length; index++) {
  9930. objects[index].dispose();
  9931. }
  9932. }
  9933. else {
  9934. var childMeshes = this.getChildMeshes(true);
  9935. for (index = 0; index < childMeshes.length; index++) {
  9936. var child = childMeshes[index];
  9937. child.parent = null;
  9938. child.computeWorldMatrix(true);
  9939. }
  9940. }
  9941. _super.prototype.dispose.call(this);
  9942. this.onAfterWorldMatrixUpdateObservable.clear();
  9943. this.onCollideObservable.clear();
  9944. this.onCollisionPositionChangeObservable.clear();
  9945. this._isDisposed = true;
  9946. // Callback
  9947. this.onDisposeObservable.notifyObservers(this);
  9948. this.onDisposeObservable.clear();
  9949. };
  9950. // Statics
  9951. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9952. AbstractMesh._BILLBOARDMODE_X = 1;
  9953. AbstractMesh._BILLBOARDMODE_Y = 2;
  9954. AbstractMesh._BILLBOARDMODE_Z = 4;
  9955. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9956. return AbstractMesh;
  9957. })(BABYLON.Node);
  9958. BABYLON.AbstractMesh = AbstractMesh;
  9959. })(BABYLON || (BABYLON = {}));
  9960. var BABYLON;
  9961. (function (BABYLON) {
  9962. var Light = (function (_super) {
  9963. __extends(Light, _super);
  9964. function Light(name, scene) {
  9965. _super.call(this, name, scene);
  9966. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9967. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9968. this.intensity = 1.0;
  9969. this.range = Number.MAX_VALUE;
  9970. this.includeOnlyWithLayerMask = 0;
  9971. this.includedOnlyMeshes = new Array();
  9972. this.excludedMeshes = new Array();
  9973. this.excludeWithLayerMask = 0;
  9974. // PBR Properties.
  9975. this.radius = 0.00001;
  9976. this._excludedMeshesIds = new Array();
  9977. this._includedOnlyMeshesIds = new Array();
  9978. scene.addLight(this);
  9979. }
  9980. /**
  9981. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9982. */
  9983. Light.prototype.toString = function (fullDetails) {
  9984. var ret = "Name: " + this.name;
  9985. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9986. if (this.animations) {
  9987. for (var i = 0; i < this.animations.length; i++) {
  9988. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9989. }
  9990. }
  9991. if (fullDetails) {
  9992. }
  9993. return ret;
  9994. };
  9995. Light.prototype.getShadowGenerator = function () {
  9996. return this._shadowGenerator;
  9997. };
  9998. Light.prototype.getAbsolutePosition = function () {
  9999. return BABYLON.Vector3.Zero();
  10000. };
  10001. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  10002. };
  10003. Light.prototype._getWorldMatrix = function () {
  10004. return BABYLON.Matrix.Identity();
  10005. };
  10006. Light.prototype.canAffectMesh = function (mesh) {
  10007. if (!mesh) {
  10008. return true;
  10009. }
  10010. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  10011. return false;
  10012. }
  10013. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  10014. return false;
  10015. }
  10016. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  10017. return false;
  10018. }
  10019. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  10020. return false;
  10021. }
  10022. return true;
  10023. };
  10024. Light.prototype.getWorldMatrix = function () {
  10025. this._currentRenderId = this.getScene().getRenderId();
  10026. var worldMatrix = this._getWorldMatrix();
  10027. if (this.parent && this.parent.getWorldMatrix) {
  10028. if (!this._parentedWorldMatrix) {
  10029. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  10030. }
  10031. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  10032. this._markSyncedWithParent();
  10033. return this._parentedWorldMatrix;
  10034. }
  10035. return worldMatrix;
  10036. };
  10037. Light.prototype.dispose = function () {
  10038. if (this._shadowGenerator) {
  10039. this._shadowGenerator.dispose();
  10040. this._shadowGenerator = null;
  10041. }
  10042. // Animations
  10043. this.getScene().stopAnimation(this);
  10044. // Remove from scene
  10045. this.getScene().removeLight(this);
  10046. _super.prototype.dispose.call(this);
  10047. };
  10048. Light.prototype.getTypeID = function () {
  10049. return 0;
  10050. };
  10051. Light.prototype.clone = function (name) {
  10052. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  10053. };
  10054. Light.prototype.serialize = function () {
  10055. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10056. // Type
  10057. serializationObject.type = this.getTypeID();
  10058. // Parent
  10059. if (this.parent) {
  10060. serializationObject.parentId = this.parent.id;
  10061. }
  10062. // Inclusion / exclusions
  10063. if (this.excludedMeshes.length > 0) {
  10064. serializationObject.excludedMeshesIds = [];
  10065. this.excludedMeshes.forEach(function (mesh) {
  10066. serializationObject.excludedMeshesIds.push(mesh.id);
  10067. });
  10068. }
  10069. if (this.includedOnlyMeshes.length > 0) {
  10070. serializationObject.includedOnlyMeshesIds = [];
  10071. this.includedOnlyMeshes.forEach(function (mesh) {
  10072. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  10073. });
  10074. }
  10075. // Animations
  10076. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10077. serializationObject.ranges = this.serializeAnimationRanges();
  10078. return serializationObject;
  10079. };
  10080. Light.GetConstructorFromName = function (type, name, scene) {
  10081. switch (type) {
  10082. case 0:
  10083. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  10084. case 1:
  10085. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  10086. case 2:
  10087. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  10088. case 3:
  10089. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  10090. }
  10091. };
  10092. Light.Parse = function (parsedLight, scene) {
  10093. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  10094. // Inclusion / exclusions
  10095. if (parsedLight.excludedMeshesIds) {
  10096. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  10097. }
  10098. if (parsedLight.includedOnlyMeshesIds) {
  10099. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  10100. }
  10101. // Parent
  10102. if (parsedLight.parentId) {
  10103. light._waitingParentId = parsedLight.parentId;
  10104. }
  10105. // Animations
  10106. if (parsedLight.animations) {
  10107. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  10108. var parsedAnimation = parsedLight.animations[animationIndex];
  10109. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10110. }
  10111. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  10112. }
  10113. if (parsedLight.autoAnimate) {
  10114. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  10115. }
  10116. return light;
  10117. };
  10118. __decorate([
  10119. BABYLON.serializeAsColor3()
  10120. ], Light.prototype, "diffuse", void 0);
  10121. __decorate([
  10122. BABYLON.serializeAsColor3()
  10123. ], Light.prototype, "specular", void 0);
  10124. __decorate([
  10125. BABYLON.serialize()
  10126. ], Light.prototype, "intensity", void 0);
  10127. __decorate([
  10128. BABYLON.serialize()
  10129. ], Light.prototype, "range", void 0);
  10130. __decorate([
  10131. BABYLON.serialize()
  10132. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  10133. __decorate([
  10134. BABYLON.serialize()
  10135. ], Light.prototype, "excludeWithLayerMask", void 0);
  10136. __decorate([
  10137. BABYLON.serialize()
  10138. ], Light.prototype, "radius", void 0);
  10139. return Light;
  10140. })(BABYLON.Node);
  10141. BABYLON.Light = Light;
  10142. })(BABYLON || (BABYLON = {}));
  10143. var BABYLON;
  10144. (function (BABYLON) {
  10145. var PointLight = (function (_super) {
  10146. __extends(PointLight, _super);
  10147. function PointLight(name, position, scene) {
  10148. _super.call(this, name, scene);
  10149. this.position = position;
  10150. }
  10151. PointLight.prototype.getAbsolutePosition = function () {
  10152. return this.transformedPosition ? this.transformedPosition : this.position;
  10153. };
  10154. PointLight.prototype.computeTransformedPosition = function () {
  10155. if (this.parent && this.parent.getWorldMatrix) {
  10156. if (!this.transformedPosition) {
  10157. this.transformedPosition = BABYLON.Vector3.Zero();
  10158. }
  10159. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10160. return true;
  10161. }
  10162. return false;
  10163. };
  10164. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  10165. if (this.parent && this.parent.getWorldMatrix) {
  10166. this.computeTransformedPosition();
  10167. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  10168. return;
  10169. }
  10170. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  10171. };
  10172. PointLight.prototype.needCube = function () {
  10173. return true;
  10174. };
  10175. PointLight.prototype.supportsVSM = function () {
  10176. return false;
  10177. };
  10178. PointLight.prototype.needRefreshPerFrame = function () {
  10179. return false;
  10180. };
  10181. PointLight.prototype.getShadowDirection = function (faceIndex) {
  10182. switch (faceIndex) {
  10183. case 0:
  10184. return new BABYLON.Vector3(1, 0, 0);
  10185. case 1:
  10186. return new BABYLON.Vector3(-1, 0, 0);
  10187. case 2:
  10188. return new BABYLON.Vector3(0, -1, 0);
  10189. case 3:
  10190. return new BABYLON.Vector3(0, 1, 0);
  10191. case 4:
  10192. return new BABYLON.Vector3(0, 0, 1);
  10193. case 5:
  10194. return new BABYLON.Vector3(0, 0, -1);
  10195. }
  10196. return BABYLON.Vector3.Zero();
  10197. };
  10198. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10199. var activeCamera = this.getScene().activeCamera;
  10200. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10201. };
  10202. PointLight.prototype._getWorldMatrix = function () {
  10203. if (!this._worldMatrix) {
  10204. this._worldMatrix = BABYLON.Matrix.Identity();
  10205. }
  10206. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10207. return this._worldMatrix;
  10208. };
  10209. PointLight.prototype.getTypeID = function () {
  10210. return 0;
  10211. };
  10212. __decorate([
  10213. BABYLON.serializeAsVector3()
  10214. ], PointLight.prototype, "position", void 0);
  10215. return PointLight;
  10216. })(BABYLON.Light);
  10217. BABYLON.PointLight = PointLight;
  10218. })(BABYLON || (BABYLON = {}));
  10219. var BABYLON;
  10220. (function (BABYLON) {
  10221. var SpotLight = (function (_super) {
  10222. __extends(SpotLight, _super);
  10223. function SpotLight(name, position, direction, angle, exponent, scene) {
  10224. _super.call(this, name, scene);
  10225. this.position = position;
  10226. this.direction = direction;
  10227. this.angle = angle;
  10228. this.exponent = exponent;
  10229. }
  10230. SpotLight.prototype.getAbsolutePosition = function () {
  10231. return this.transformedPosition ? this.transformedPosition : this.position;
  10232. };
  10233. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10234. var activeCamera = this.getScene().activeCamera;
  10235. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10236. };
  10237. SpotLight.prototype.needCube = function () {
  10238. return false;
  10239. };
  10240. SpotLight.prototype.supportsVSM = function () {
  10241. return true;
  10242. };
  10243. SpotLight.prototype.needRefreshPerFrame = function () {
  10244. return false;
  10245. };
  10246. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  10247. return this.direction;
  10248. };
  10249. SpotLight.prototype.setDirectionToTarget = function (target) {
  10250. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10251. return this.direction;
  10252. };
  10253. SpotLight.prototype.computeTransformedPosition = function () {
  10254. if (this.parent && this.parent.getWorldMatrix) {
  10255. if (!this.transformedPosition) {
  10256. this.transformedPosition = BABYLON.Vector3.Zero();
  10257. }
  10258. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10259. return true;
  10260. }
  10261. return false;
  10262. };
  10263. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  10264. var normalizeDirection;
  10265. if (this.parent && this.parent.getWorldMatrix) {
  10266. if (!this._transformedDirection) {
  10267. this._transformedDirection = BABYLON.Vector3.Zero();
  10268. }
  10269. this.computeTransformedPosition();
  10270. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10271. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  10272. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  10273. }
  10274. else {
  10275. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  10276. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10277. }
  10278. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  10279. };
  10280. SpotLight.prototype._getWorldMatrix = function () {
  10281. if (!this._worldMatrix) {
  10282. this._worldMatrix = BABYLON.Matrix.Identity();
  10283. }
  10284. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10285. return this._worldMatrix;
  10286. };
  10287. SpotLight.prototype.getTypeID = function () {
  10288. return 2;
  10289. };
  10290. __decorate([
  10291. BABYLON.serializeAsVector3()
  10292. ], SpotLight.prototype, "position", void 0);
  10293. __decorate([
  10294. BABYLON.serializeAsVector3()
  10295. ], SpotLight.prototype, "direction", void 0);
  10296. __decorate([
  10297. BABYLON.serialize()
  10298. ], SpotLight.prototype, "angle", void 0);
  10299. __decorate([
  10300. BABYLON.serialize()
  10301. ], SpotLight.prototype, "exponent", void 0);
  10302. return SpotLight;
  10303. })(BABYLON.Light);
  10304. BABYLON.SpotLight = SpotLight;
  10305. })(BABYLON || (BABYLON = {}));
  10306. var BABYLON;
  10307. (function (BABYLON) {
  10308. var HemisphericLight = (function (_super) {
  10309. __extends(HemisphericLight, _super);
  10310. function HemisphericLight(name, direction, scene) {
  10311. _super.call(this, name, scene);
  10312. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  10313. this.direction = direction;
  10314. }
  10315. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  10316. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  10317. return this.direction;
  10318. };
  10319. HemisphericLight.prototype.getShadowGenerator = function () {
  10320. return null;
  10321. };
  10322. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  10323. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10324. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  10325. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  10326. };
  10327. HemisphericLight.prototype._getWorldMatrix = function () {
  10328. if (!this._worldMatrix) {
  10329. this._worldMatrix = BABYLON.Matrix.Identity();
  10330. }
  10331. return this._worldMatrix;
  10332. };
  10333. HemisphericLight.prototype.getTypeID = function () {
  10334. return 3;
  10335. };
  10336. __decorate([
  10337. BABYLON.serializeAsColor3()
  10338. ], HemisphericLight.prototype, "groundColor", void 0);
  10339. __decorate([
  10340. BABYLON.serializeAsVector3()
  10341. ], HemisphericLight.prototype, "direction", void 0);
  10342. return HemisphericLight;
  10343. })(BABYLON.Light);
  10344. BABYLON.HemisphericLight = HemisphericLight;
  10345. })(BABYLON || (BABYLON = {}));
  10346. var BABYLON;
  10347. (function (BABYLON) {
  10348. var DirectionalLight = (function (_super) {
  10349. __extends(DirectionalLight, _super);
  10350. function DirectionalLight(name, direction, scene) {
  10351. _super.call(this, name, scene);
  10352. this.shadowOrthoScale = 0.5;
  10353. this.autoUpdateExtends = true;
  10354. // Cache
  10355. this._orthoLeft = Number.MAX_VALUE;
  10356. this._orthoRight = Number.MIN_VALUE;
  10357. this._orthoTop = Number.MIN_VALUE;
  10358. this._orthoBottom = Number.MAX_VALUE;
  10359. this.position = direction.scale(-1);
  10360. this.direction = direction;
  10361. }
  10362. DirectionalLight.prototype.getAbsolutePosition = function () {
  10363. return this.transformedPosition ? this.transformedPosition : this.position;
  10364. };
  10365. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  10366. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10367. return this.direction;
  10368. };
  10369. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10370. var activeCamera = this.getScene().activeCamera;
  10371. // Check extends
  10372. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  10373. var tempVector3 = BABYLON.Vector3.Zero();
  10374. this._orthoLeft = Number.MAX_VALUE;
  10375. this._orthoRight = Number.MIN_VALUE;
  10376. this._orthoTop = Number.MIN_VALUE;
  10377. this._orthoBottom = Number.MAX_VALUE;
  10378. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  10379. var mesh = renderList[meshIndex];
  10380. if (!mesh) {
  10381. continue;
  10382. }
  10383. var boundingInfo = mesh.getBoundingInfo();
  10384. if (!boundingInfo) {
  10385. continue;
  10386. }
  10387. var boundingBox = boundingInfo.boundingBox;
  10388. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  10389. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  10390. if (tempVector3.x < this._orthoLeft)
  10391. this._orthoLeft = tempVector3.x;
  10392. if (tempVector3.y < this._orthoBottom)
  10393. this._orthoBottom = tempVector3.y;
  10394. if (tempVector3.x > this._orthoRight)
  10395. this._orthoRight = tempVector3.x;
  10396. if (tempVector3.y > this._orthoTop)
  10397. this._orthoTop = tempVector3.y;
  10398. }
  10399. }
  10400. }
  10401. var xOffset = this._orthoRight - this._orthoLeft;
  10402. var yOffset = this._orthoTop - this._orthoBottom;
  10403. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  10404. };
  10405. DirectionalLight.prototype.supportsVSM = function () {
  10406. return true;
  10407. };
  10408. DirectionalLight.prototype.needRefreshPerFrame = function () {
  10409. return true;
  10410. };
  10411. DirectionalLight.prototype.needCube = function () {
  10412. return false;
  10413. };
  10414. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  10415. return this.direction;
  10416. };
  10417. DirectionalLight.prototype.computeTransformedPosition = function () {
  10418. if (this.parent && this.parent.getWorldMatrix) {
  10419. if (!this.transformedPosition) {
  10420. this.transformedPosition = BABYLON.Vector3.Zero();
  10421. }
  10422. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10423. return true;
  10424. }
  10425. return false;
  10426. };
  10427. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  10428. if (this.parent && this.parent.getWorldMatrix) {
  10429. if (!this._transformedDirection) {
  10430. this._transformedDirection = BABYLON.Vector3.Zero();
  10431. }
  10432. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10433. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  10434. return;
  10435. }
  10436. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  10437. };
  10438. DirectionalLight.prototype._getWorldMatrix = function () {
  10439. if (!this._worldMatrix) {
  10440. this._worldMatrix = BABYLON.Matrix.Identity();
  10441. }
  10442. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10443. return this._worldMatrix;
  10444. };
  10445. DirectionalLight.prototype.getTypeID = function () {
  10446. return 1;
  10447. };
  10448. __decorate([
  10449. BABYLON.serializeAsVector3()
  10450. ], DirectionalLight.prototype, "position", void 0);
  10451. __decorate([
  10452. BABYLON.serializeAsVector3()
  10453. ], DirectionalLight.prototype, "direction", void 0);
  10454. __decorate([
  10455. BABYLON.serialize()
  10456. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  10457. __decorate([
  10458. BABYLON.serialize()
  10459. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  10460. return DirectionalLight;
  10461. })(BABYLON.Light);
  10462. BABYLON.DirectionalLight = DirectionalLight;
  10463. })(BABYLON || (BABYLON = {}));
  10464. var BABYLON;
  10465. (function (BABYLON) {
  10466. var ShadowGenerator = (function () {
  10467. function ShadowGenerator(mapSize, light) {
  10468. var _this = this;
  10469. // Members
  10470. this._filter = ShadowGenerator.FILTER_NONE;
  10471. this.blurScale = 2;
  10472. this._blurBoxOffset = 0;
  10473. this._bias = 0.00005;
  10474. this._lightDirection = BABYLON.Vector3.Zero();
  10475. this.forceBackFacesOnly = false;
  10476. this._darkness = 0;
  10477. this._transparencyShadow = false;
  10478. this._viewMatrix = BABYLON.Matrix.Zero();
  10479. this._projectionMatrix = BABYLON.Matrix.Zero();
  10480. this._transformMatrix = BABYLON.Matrix.Zero();
  10481. this._worldViewProjection = BABYLON.Matrix.Zero();
  10482. this._currentFaceIndex = 0;
  10483. this._currentFaceIndexCache = 0;
  10484. this._light = light;
  10485. this._scene = light.getScene();
  10486. this._mapSize = mapSize;
  10487. light._shadowGenerator = this;
  10488. // Render target
  10489. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  10490. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10491. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10492. this._shadowMap.anisotropicFilteringLevel = 1;
  10493. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10494. this._shadowMap.renderParticles = false;
  10495. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  10496. _this._currentFaceIndex = faceIndex;
  10497. });
  10498. this._shadowMap.onAfterUnbindObservable.add(function () {
  10499. if (!_this.useBlurVarianceShadowMap) {
  10500. return;
  10501. }
  10502. if (!_this._shadowMap2) {
  10503. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  10504. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10505. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10506. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  10507. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  10508. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  10509. effect.setTexture("textureSampler", _this._shadowMap);
  10510. });
  10511. _this.blurBoxOffset = 1;
  10512. }
  10513. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  10514. });
  10515. // Custom render function
  10516. var renderSubMesh = function (subMesh) {
  10517. var mesh = subMesh.getRenderingMesh();
  10518. var scene = _this._scene;
  10519. var engine = scene.getEngine();
  10520. // Culling
  10521. engine.setState(subMesh.getMaterial().backFaceCulling);
  10522. // Managing instances
  10523. var batch = mesh._getInstancesRenderList(subMesh._id);
  10524. if (batch.mustReturn) {
  10525. return;
  10526. }
  10527. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10528. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  10529. engine.enableEffect(_this._effect);
  10530. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  10531. var material = subMesh.getMaterial();
  10532. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  10533. _this._effect.setVector3("lightPosition", _this.getLight().position);
  10534. if (_this.getLight().needCube()) {
  10535. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  10536. }
  10537. // Alpha test
  10538. if (material && material.needAlphaTesting()) {
  10539. var alphaTexture = material.getAlphaTestTexture();
  10540. _this._effect.setTexture("diffuseSampler", alphaTexture);
  10541. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  10542. }
  10543. // Bones
  10544. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10545. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  10546. }
  10547. if (_this.forceBackFacesOnly) {
  10548. engine.setState(true, 0, false, true);
  10549. }
  10550. // Draw
  10551. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  10552. if (_this.forceBackFacesOnly) {
  10553. engine.setState(true, 0, false, false);
  10554. }
  10555. }
  10556. else {
  10557. // Need to reset refresh rate of the shadowMap
  10558. _this._shadowMap.resetRefreshCounter();
  10559. }
  10560. };
  10561. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  10562. var index;
  10563. for (index = 0; index < opaqueSubMeshes.length; index++) {
  10564. renderSubMesh(opaqueSubMeshes.data[index]);
  10565. }
  10566. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  10567. renderSubMesh(alphaTestSubMeshes.data[index]);
  10568. }
  10569. if (_this._transparencyShadow) {
  10570. for (index = 0; index < transparentSubMeshes.length; index++) {
  10571. renderSubMesh(transparentSubMeshes.data[index]);
  10572. }
  10573. }
  10574. };
  10575. this._shadowMap.onClearObservable.add(function (engine) {
  10576. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  10577. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  10578. }
  10579. else {
  10580. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  10581. }
  10582. });
  10583. }
  10584. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  10585. // Static
  10586. get: function () {
  10587. return ShadowGenerator._FILTER_NONE;
  10588. },
  10589. enumerable: true,
  10590. configurable: true
  10591. });
  10592. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  10593. get: function () {
  10594. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  10595. },
  10596. enumerable: true,
  10597. configurable: true
  10598. });
  10599. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  10600. get: function () {
  10601. return ShadowGenerator._FILTER_POISSONSAMPLING;
  10602. },
  10603. enumerable: true,
  10604. configurable: true
  10605. });
  10606. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  10607. get: function () {
  10608. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  10609. },
  10610. enumerable: true,
  10611. configurable: true
  10612. });
  10613. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  10614. get: function () {
  10615. return this._bias;
  10616. },
  10617. set: function (bias) {
  10618. this._bias = bias;
  10619. },
  10620. enumerable: true,
  10621. configurable: true
  10622. });
  10623. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  10624. get: function () {
  10625. return this._blurBoxOffset;
  10626. },
  10627. set: function (value) {
  10628. var _this = this;
  10629. if (this._blurBoxOffset === value) {
  10630. return;
  10631. }
  10632. this._blurBoxOffset = value;
  10633. if (this._boxBlurPostprocess) {
  10634. this._boxBlurPostprocess.dispose();
  10635. }
  10636. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  10637. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  10638. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  10639. });
  10640. },
  10641. enumerable: true,
  10642. configurable: true
  10643. });
  10644. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  10645. get: function () {
  10646. return this._filter;
  10647. },
  10648. set: function (value) {
  10649. if (this._filter === value) {
  10650. return;
  10651. }
  10652. this._filter = value;
  10653. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  10654. this._shadowMap.anisotropicFilteringLevel = 16;
  10655. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  10656. }
  10657. else {
  10658. this._shadowMap.anisotropicFilteringLevel = 1;
  10659. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10660. }
  10661. },
  10662. enumerable: true,
  10663. configurable: true
  10664. });
  10665. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  10666. get: function () {
  10667. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  10668. },
  10669. set: function (value) {
  10670. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10671. },
  10672. enumerable: true,
  10673. configurable: true
  10674. });
  10675. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  10676. get: function () {
  10677. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  10678. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  10679. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  10680. },
  10681. set: function (value) {
  10682. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  10683. },
  10684. enumerable: true,
  10685. configurable: true
  10686. });
  10687. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  10688. get: function () {
  10689. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  10690. },
  10691. set: function (value) {
  10692. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10693. },
  10694. enumerable: true,
  10695. configurable: true
  10696. });
  10697. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  10698. var defines = [];
  10699. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  10700. defines.push("#define VSM");
  10701. }
  10702. if (this.getLight().needCube()) {
  10703. defines.push("#define CUBEMAP");
  10704. }
  10705. var attribs = [BABYLON.VertexBuffer.PositionKind];
  10706. var mesh = subMesh.getMesh();
  10707. var material = subMesh.getMaterial();
  10708. // Alpha test
  10709. if (material && material.needAlphaTesting()) {
  10710. defines.push("#define ALPHATEST");
  10711. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10712. attribs.push(BABYLON.VertexBuffer.UVKind);
  10713. defines.push("#define UV1");
  10714. }
  10715. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10716. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10717. defines.push("#define UV2");
  10718. }
  10719. }
  10720. // Bones
  10721. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10722. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10723. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10724. if (mesh.numBoneInfluencers > 4) {
  10725. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  10726. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  10727. }
  10728. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  10729. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10730. }
  10731. else {
  10732. defines.push("#define NUM_BONE_INFLUENCERS 0");
  10733. }
  10734. // Instances
  10735. if (useInstances) {
  10736. defines.push("#define INSTANCES");
  10737. attribs.push("world0");
  10738. attribs.push("world1");
  10739. attribs.push("world2");
  10740. attribs.push("world3");
  10741. }
  10742. // Get correct effect
  10743. var join = defines.join("\n");
  10744. if (this._cachedDefines !== join) {
  10745. this._cachedDefines = join;
  10746. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  10747. }
  10748. return this._effect.isReady();
  10749. };
  10750. ShadowGenerator.prototype.getShadowMap = function () {
  10751. return this._shadowMap;
  10752. };
  10753. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  10754. if (this._shadowMap2) {
  10755. return this._shadowMap2;
  10756. }
  10757. return this._shadowMap;
  10758. };
  10759. ShadowGenerator.prototype.getLight = function () {
  10760. return this._light;
  10761. };
  10762. // Methods
  10763. ShadowGenerator.prototype.getTransformMatrix = function () {
  10764. var scene = this._scene;
  10765. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  10766. return this._transformMatrix;
  10767. }
  10768. this._currentRenderID = scene.getRenderId();
  10769. this._currentFaceIndexCache = this._currentFaceIndex;
  10770. var lightPosition = this._light.position;
  10771. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  10772. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  10773. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  10774. }
  10775. if (this._light.computeTransformedPosition()) {
  10776. lightPosition = this._light.transformedPosition;
  10777. }
  10778. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  10779. this._cachedPosition = lightPosition.clone();
  10780. this._cachedDirection = this._lightDirection.clone();
  10781. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  10782. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  10783. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  10784. }
  10785. return this._transformMatrix;
  10786. };
  10787. ShadowGenerator.prototype.getDarkness = function () {
  10788. return this._darkness;
  10789. };
  10790. ShadowGenerator.prototype.setDarkness = function (darkness) {
  10791. if (darkness >= 1.0)
  10792. this._darkness = 1.0;
  10793. else if (darkness <= 0.0)
  10794. this._darkness = 0.0;
  10795. else
  10796. this._darkness = darkness;
  10797. };
  10798. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  10799. this._transparencyShadow = hasShadow;
  10800. };
  10801. ShadowGenerator.prototype._packHalf = function (depth) {
  10802. var scale = depth * 255.0;
  10803. var fract = scale - Math.floor(scale);
  10804. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  10805. };
  10806. ShadowGenerator.prototype.dispose = function () {
  10807. this._shadowMap.dispose();
  10808. if (this._shadowMap2) {
  10809. this._shadowMap2.dispose();
  10810. }
  10811. if (this._downSamplePostprocess) {
  10812. this._downSamplePostprocess.dispose();
  10813. }
  10814. if (this._boxBlurPostprocess) {
  10815. this._boxBlurPostprocess.dispose();
  10816. }
  10817. };
  10818. ShadowGenerator.prototype.serialize = function () {
  10819. var serializationObject = {};
  10820. serializationObject.lightId = this._light.id;
  10821. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  10822. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  10823. serializationObject.usePoissonSampling = this.usePoissonSampling;
  10824. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  10825. serializationObject.renderList = [];
  10826. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  10827. var mesh = this.getShadowMap().renderList[meshIndex];
  10828. serializationObject.renderList.push(mesh.id);
  10829. }
  10830. return serializationObject;
  10831. };
  10832. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  10833. //casting to point light, as light is missing the position attr and typescript complains.
  10834. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  10835. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  10836. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  10837. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  10838. meshes.forEach(function (mesh) {
  10839. shadowGenerator.getShadowMap().renderList.push(mesh);
  10840. });
  10841. }
  10842. if (parsedShadowGenerator.usePoissonSampling) {
  10843. shadowGenerator.usePoissonSampling = true;
  10844. }
  10845. else if (parsedShadowGenerator.useVarianceShadowMap) {
  10846. shadowGenerator.useVarianceShadowMap = true;
  10847. }
  10848. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  10849. shadowGenerator.useBlurVarianceShadowMap = true;
  10850. if (parsedShadowGenerator.blurScale) {
  10851. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  10852. }
  10853. if (parsedShadowGenerator.blurBoxOffset) {
  10854. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  10855. }
  10856. }
  10857. if (parsedShadowGenerator.bias !== undefined) {
  10858. shadowGenerator.bias = parsedShadowGenerator.bias;
  10859. }
  10860. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  10861. return shadowGenerator;
  10862. };
  10863. ShadowGenerator._FILTER_NONE = 0;
  10864. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  10865. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  10866. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  10867. return ShadowGenerator;
  10868. })();
  10869. BABYLON.ShadowGenerator = ShadowGenerator;
  10870. })(BABYLON || (BABYLON = {}));
  10871. var BABYLON;
  10872. (function (BABYLON) {
  10873. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  10874. if (boxMin.x > sphereCenter.x + sphereRadius)
  10875. return false;
  10876. if (sphereCenter.x - sphereRadius > boxMax.x)
  10877. return false;
  10878. if (boxMin.y > sphereCenter.y + sphereRadius)
  10879. return false;
  10880. if (sphereCenter.y - sphereRadius > boxMax.y)
  10881. return false;
  10882. if (boxMin.z > sphereCenter.z + sphereRadius)
  10883. return false;
  10884. if (sphereCenter.z - sphereRadius > boxMax.z)
  10885. return false;
  10886. return true;
  10887. };
  10888. var getLowestRoot = function (a, b, c, maxR) {
  10889. var determinant = b * b - 4.0 * a * c;
  10890. var result = { root: 0, found: false };
  10891. if (determinant < 0)
  10892. return result;
  10893. var sqrtD = Math.sqrt(determinant);
  10894. var r1 = (-b - sqrtD) / (2.0 * a);
  10895. var r2 = (-b + sqrtD) / (2.0 * a);
  10896. if (r1 > r2) {
  10897. var temp = r2;
  10898. r2 = r1;
  10899. r1 = temp;
  10900. }
  10901. if (r1 > 0 && r1 < maxR) {
  10902. result.root = r1;
  10903. result.found = true;
  10904. return result;
  10905. }
  10906. if (r2 > 0 && r2 < maxR) {
  10907. result.root = r2;
  10908. result.found = true;
  10909. return result;
  10910. }
  10911. return result;
  10912. };
  10913. var Collider = (function () {
  10914. function Collider() {
  10915. this.radius = new BABYLON.Vector3(1, 1, 1);
  10916. this.retry = 0;
  10917. this.basePointWorld = BABYLON.Vector3.Zero();
  10918. this.velocityWorld = BABYLON.Vector3.Zero();
  10919. this.normalizedVelocity = BABYLON.Vector3.Zero();
  10920. this._collisionPoint = BABYLON.Vector3.Zero();
  10921. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  10922. this._tempVector = BABYLON.Vector3.Zero();
  10923. this._tempVector2 = BABYLON.Vector3.Zero();
  10924. this._tempVector3 = BABYLON.Vector3.Zero();
  10925. this._tempVector4 = BABYLON.Vector3.Zero();
  10926. this._edge = BABYLON.Vector3.Zero();
  10927. this._baseToVertex = BABYLON.Vector3.Zero();
  10928. this._destinationPoint = BABYLON.Vector3.Zero();
  10929. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  10930. this._displacementVector = BABYLON.Vector3.Zero();
  10931. }
  10932. // Methods
  10933. Collider.prototype._initialize = function (source, dir, e) {
  10934. this.velocity = dir;
  10935. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  10936. this.basePoint = source;
  10937. source.multiplyToRef(this.radius, this.basePointWorld);
  10938. dir.multiplyToRef(this.radius, this.velocityWorld);
  10939. this.velocityWorldLength = this.velocityWorld.length();
  10940. this.epsilon = e;
  10941. this.collisionFound = false;
  10942. };
  10943. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  10944. pa.subtractToRef(point, this._tempVector);
  10945. pb.subtractToRef(point, this._tempVector2);
  10946. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  10947. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10948. if (d < 0)
  10949. return false;
  10950. pc.subtractToRef(point, this._tempVector3);
  10951. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  10952. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10953. if (d < 0)
  10954. return false;
  10955. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10956. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10957. return d >= 0;
  10958. };
  10959. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10960. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10961. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10962. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10963. return false;
  10964. }
  10965. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10966. return false;
  10967. return true;
  10968. };
  10969. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10970. var t0;
  10971. var embeddedInPlane = false;
  10972. //defensive programming, actually not needed.
  10973. if (!trianglePlaneArray) {
  10974. trianglePlaneArray = [];
  10975. }
  10976. if (!trianglePlaneArray[faceIndex]) {
  10977. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10978. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10979. }
  10980. var trianglePlane = trianglePlaneArray[faceIndex];
  10981. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10982. return;
  10983. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10984. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10985. if (normalDotVelocity == 0) {
  10986. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10987. return;
  10988. embeddedInPlane = true;
  10989. t0 = 0;
  10990. }
  10991. else {
  10992. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10993. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10994. if (t0 > t1) {
  10995. var temp = t1;
  10996. t1 = t0;
  10997. t0 = temp;
  10998. }
  10999. if (t0 > 1.0 || t1 < 0.0)
  11000. return;
  11001. if (t0 < 0)
  11002. t0 = 0;
  11003. if (t0 > 1.0)
  11004. t0 = 1.0;
  11005. }
  11006. this._collisionPoint.copyFromFloats(0, 0, 0);
  11007. var found = false;
  11008. var t = 1.0;
  11009. if (!embeddedInPlane) {
  11010. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  11011. this.velocity.scaleToRef(t0, this._tempVector);
  11012. this._planeIntersectionPoint.addInPlace(this._tempVector);
  11013. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  11014. found = true;
  11015. t = t0;
  11016. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  11017. }
  11018. }
  11019. if (!found) {
  11020. var velocitySquaredLength = this.velocity.lengthSquared();
  11021. var a = velocitySquaredLength;
  11022. this.basePoint.subtractToRef(p1, this._tempVector);
  11023. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11024. var c = this._tempVector.lengthSquared() - 1.0;
  11025. var lowestRoot = getLowestRoot(a, b, c, t);
  11026. if (lowestRoot.found) {
  11027. t = lowestRoot.root;
  11028. found = true;
  11029. this._collisionPoint.copyFrom(p1);
  11030. }
  11031. this.basePoint.subtractToRef(p2, this._tempVector);
  11032. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11033. c = this._tempVector.lengthSquared() - 1.0;
  11034. lowestRoot = getLowestRoot(a, b, c, t);
  11035. if (lowestRoot.found) {
  11036. t = lowestRoot.root;
  11037. found = true;
  11038. this._collisionPoint.copyFrom(p2);
  11039. }
  11040. this.basePoint.subtractToRef(p3, this._tempVector);
  11041. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11042. c = this._tempVector.lengthSquared() - 1.0;
  11043. lowestRoot = getLowestRoot(a, b, c, t);
  11044. if (lowestRoot.found) {
  11045. t = lowestRoot.root;
  11046. found = true;
  11047. this._collisionPoint.copyFrom(p3);
  11048. }
  11049. p2.subtractToRef(p1, this._edge);
  11050. p1.subtractToRef(this.basePoint, this._baseToVertex);
  11051. var edgeSquaredLength = this._edge.lengthSquared();
  11052. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11053. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11054. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11055. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11056. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11057. lowestRoot = getLowestRoot(a, b, c, t);
  11058. if (lowestRoot.found) {
  11059. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11060. if (f >= 0.0 && f <= 1.0) {
  11061. t = lowestRoot.root;
  11062. found = true;
  11063. this._edge.scaleInPlace(f);
  11064. p1.addToRef(this._edge, this._collisionPoint);
  11065. }
  11066. }
  11067. p3.subtractToRef(p2, this._edge);
  11068. p2.subtractToRef(this.basePoint, this._baseToVertex);
  11069. edgeSquaredLength = this._edge.lengthSquared();
  11070. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11071. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11072. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11073. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11074. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11075. lowestRoot = getLowestRoot(a, b, c, t);
  11076. if (lowestRoot.found) {
  11077. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11078. if (f >= 0.0 && f <= 1.0) {
  11079. t = lowestRoot.root;
  11080. found = true;
  11081. this._edge.scaleInPlace(f);
  11082. p2.addToRef(this._edge, this._collisionPoint);
  11083. }
  11084. }
  11085. p1.subtractToRef(p3, this._edge);
  11086. p3.subtractToRef(this.basePoint, this._baseToVertex);
  11087. edgeSquaredLength = this._edge.lengthSquared();
  11088. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11089. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11090. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11091. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11092. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11093. lowestRoot = getLowestRoot(a, b, c, t);
  11094. if (lowestRoot.found) {
  11095. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11096. if (f >= 0.0 && f <= 1.0) {
  11097. t = lowestRoot.root;
  11098. found = true;
  11099. this._edge.scaleInPlace(f);
  11100. p3.addToRef(this._edge, this._collisionPoint);
  11101. }
  11102. }
  11103. }
  11104. if (found) {
  11105. var distToCollision = t * this.velocity.length();
  11106. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  11107. if (!this.intersectionPoint) {
  11108. this.intersectionPoint = this._collisionPoint.clone();
  11109. }
  11110. else {
  11111. this.intersectionPoint.copyFrom(this._collisionPoint);
  11112. }
  11113. this.nearestDistance = distToCollision;
  11114. this.collisionFound = true;
  11115. }
  11116. }
  11117. };
  11118. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  11119. for (var i = indexStart; i < indexEnd; i += 3) {
  11120. var p1 = pts[indices[i] - decal];
  11121. var p2 = pts[indices[i + 1] - decal];
  11122. var p3 = pts[indices[i + 2] - decal];
  11123. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  11124. }
  11125. };
  11126. Collider.prototype._getResponse = function (pos, vel) {
  11127. pos.addToRef(vel, this._destinationPoint);
  11128. vel.scaleInPlace((this.nearestDistance / vel.length()));
  11129. this.basePoint.addToRef(vel, pos);
  11130. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  11131. this._slidePlaneNormal.normalize();
  11132. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  11133. pos.addInPlace(this._displacementVector);
  11134. this.intersectionPoint.addInPlace(this._displacementVector);
  11135. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  11136. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  11137. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  11138. };
  11139. return Collider;
  11140. })();
  11141. BABYLON.Collider = Collider;
  11142. })(BABYLON || (BABYLON = {}));
  11143. var BABYLON;
  11144. (function (BABYLON) {
  11145. //WebWorker code will be inserted to this variable.
  11146. BABYLON.CollisionWorker = "";
  11147. (function (WorkerTaskType) {
  11148. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  11149. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  11150. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  11151. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  11152. var WorkerTaskType = BABYLON.WorkerTaskType;
  11153. (function (WorkerReplyType) {
  11154. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  11155. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  11156. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  11157. var WorkerReplyType = BABYLON.WorkerReplyType;
  11158. var CollisionCoordinatorWorker = (function () {
  11159. function CollisionCoordinatorWorker() {
  11160. var _this = this;
  11161. this._scaledPosition = BABYLON.Vector3.Zero();
  11162. this._scaledVelocity = BABYLON.Vector3.Zero();
  11163. this.onMeshUpdated = function (mesh) {
  11164. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  11165. };
  11166. this.onGeometryUpdated = function (geometry) {
  11167. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  11168. };
  11169. this._afterRender = function () {
  11170. if (!_this._init)
  11171. return;
  11172. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  11173. return;
  11174. }
  11175. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  11176. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  11177. if (_this._runningUpdated > 4) {
  11178. return;
  11179. }
  11180. ++_this._runningUpdated;
  11181. var payload = {
  11182. updatedMeshes: _this._addUpdateMeshesList,
  11183. updatedGeometries: _this._addUpdateGeometriesList,
  11184. removedGeometries: _this._toRemoveGeometryArray,
  11185. removedMeshes: _this._toRemoveMeshesArray
  11186. };
  11187. var message = {
  11188. payload: payload,
  11189. taskType: WorkerTaskType.UPDATE
  11190. };
  11191. var serializable = [];
  11192. for (var id in payload.updatedGeometries) {
  11193. if (payload.updatedGeometries.hasOwnProperty(id)) {
  11194. //prepare transferables
  11195. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  11196. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  11197. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  11198. }
  11199. }
  11200. _this._worker.postMessage(message, serializable);
  11201. _this._addUpdateMeshesList = {};
  11202. _this._addUpdateGeometriesList = {};
  11203. _this._toRemoveGeometryArray = [];
  11204. _this._toRemoveMeshesArray = [];
  11205. };
  11206. this._onMessageFromWorker = function (e) {
  11207. var returnData = e.data;
  11208. if (returnData.error != WorkerReplyType.SUCCESS) {
  11209. //TODO what errors can be returned from the worker?
  11210. BABYLON.Tools.Warn("error returned from worker!");
  11211. return;
  11212. }
  11213. switch (returnData.taskType) {
  11214. case WorkerTaskType.INIT:
  11215. _this._init = true;
  11216. //Update the worked with ALL of the scene's current state
  11217. _this._scene.meshes.forEach(function (mesh) {
  11218. _this.onMeshAdded(mesh);
  11219. });
  11220. _this._scene.getGeometries().forEach(function (geometry) {
  11221. _this.onGeometryAdded(geometry);
  11222. });
  11223. break;
  11224. case WorkerTaskType.UPDATE:
  11225. _this._runningUpdated--;
  11226. break;
  11227. case WorkerTaskType.COLLIDE:
  11228. _this._runningCollisionTask = false;
  11229. var returnPayload = returnData.payload;
  11230. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  11231. return;
  11232. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  11233. //cleanup
  11234. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  11235. break;
  11236. }
  11237. };
  11238. this._collisionsCallbackArray = [];
  11239. this._init = false;
  11240. this._runningUpdated = 0;
  11241. this._runningCollisionTask = false;
  11242. this._addUpdateMeshesList = {};
  11243. this._addUpdateGeometriesList = {};
  11244. this._toRemoveGeometryArray = [];
  11245. this._toRemoveMeshesArray = [];
  11246. }
  11247. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11248. if (!this._init)
  11249. return;
  11250. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  11251. return;
  11252. position.divideToRef(collider.radius, this._scaledPosition);
  11253. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11254. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  11255. var payload = {
  11256. collider: {
  11257. position: this._scaledPosition.asArray(),
  11258. velocity: this._scaledVelocity.asArray(),
  11259. radius: collider.radius.asArray()
  11260. },
  11261. collisionId: collisionIndex,
  11262. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  11263. maximumRetry: maximumRetry
  11264. };
  11265. var message = {
  11266. payload: payload,
  11267. taskType: WorkerTaskType.COLLIDE
  11268. };
  11269. this._worker.postMessage(message);
  11270. };
  11271. CollisionCoordinatorWorker.prototype.init = function (scene) {
  11272. this._scene = scene;
  11273. this._scene.registerAfterRender(this._afterRender);
  11274. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  11275. this._worker = new Worker(workerUrl);
  11276. this._worker.onmessage = this._onMessageFromWorker;
  11277. var message = {
  11278. payload: {},
  11279. taskType: WorkerTaskType.INIT
  11280. };
  11281. this._worker.postMessage(message);
  11282. };
  11283. CollisionCoordinatorWorker.prototype.destroy = function () {
  11284. this._scene.unregisterAfterRender(this._afterRender);
  11285. this._worker.terminate();
  11286. };
  11287. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  11288. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  11289. this.onMeshUpdated(mesh);
  11290. };
  11291. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  11292. this._toRemoveMeshesArray.push(mesh.uniqueId);
  11293. };
  11294. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  11295. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  11296. geometry.onGeometryUpdated = this.onGeometryUpdated;
  11297. this.onGeometryUpdated(geometry);
  11298. };
  11299. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  11300. this._toRemoveGeometryArray.push(geometry.id);
  11301. };
  11302. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  11303. var submeshes = [];
  11304. if (mesh.subMeshes) {
  11305. submeshes = mesh.subMeshes.map(function (sm, idx) {
  11306. return {
  11307. position: idx,
  11308. verticesStart: sm.verticesStart,
  11309. verticesCount: sm.verticesCount,
  11310. indexStart: sm.indexStart,
  11311. indexCount: sm.indexCount,
  11312. hasMaterial: !!sm.getMaterial(),
  11313. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11314. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  11315. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11316. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  11317. };
  11318. });
  11319. }
  11320. var geometryId = null;
  11321. if (mesh instanceof BABYLON.Mesh) {
  11322. geometryId = mesh.geometry ? mesh.geometry.id : null;
  11323. }
  11324. else if (mesh instanceof BABYLON.InstancedMesh) {
  11325. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  11326. }
  11327. return {
  11328. uniqueId: mesh.uniqueId,
  11329. id: mesh.id,
  11330. name: mesh.name,
  11331. geometryId: geometryId,
  11332. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11333. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  11334. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11335. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  11336. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  11337. subMeshes: submeshes,
  11338. checkCollisions: mesh.checkCollisions
  11339. };
  11340. };
  11341. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  11342. return {
  11343. id: geometry.id,
  11344. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  11345. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  11346. indices: new Int32Array(geometry.getIndices() || []),
  11347. };
  11348. };
  11349. return CollisionCoordinatorWorker;
  11350. })();
  11351. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  11352. var CollisionCoordinatorLegacy = (function () {
  11353. function CollisionCoordinatorLegacy() {
  11354. this._scaledPosition = BABYLON.Vector3.Zero();
  11355. this._scaledVelocity = BABYLON.Vector3.Zero();
  11356. this._finalPosition = BABYLON.Vector3.Zero();
  11357. }
  11358. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11359. position.divideToRef(collider.radius, this._scaledPosition);
  11360. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11361. collider.collidedMesh = null;
  11362. collider.retry = 0;
  11363. collider.initialVelocity = this._scaledVelocity;
  11364. collider.initialPosition = this._scaledPosition;
  11365. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  11366. this._finalPosition.multiplyInPlace(collider.radius);
  11367. //run the callback
  11368. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  11369. };
  11370. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  11371. this._scene = scene;
  11372. };
  11373. CollisionCoordinatorLegacy.prototype.destroy = function () {
  11374. //Legacy need no destruction method.
  11375. };
  11376. //No update in legacy mode
  11377. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  11378. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  11379. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  11380. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  11381. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  11382. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  11383. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  11384. if (excludedMesh === void 0) { excludedMesh = null; }
  11385. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  11386. if (collider.retry >= maximumRetry) {
  11387. finalPosition.copyFrom(position);
  11388. return;
  11389. }
  11390. collider._initialize(position, velocity, closeDistance);
  11391. // Check all meshes
  11392. for (var index = 0; index < this._scene.meshes.length; index++) {
  11393. var mesh = this._scene.meshes[index];
  11394. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  11395. mesh._checkCollision(collider);
  11396. }
  11397. }
  11398. if (!collider.collisionFound) {
  11399. position.addToRef(velocity, finalPosition);
  11400. return;
  11401. }
  11402. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  11403. collider._getResponse(position, velocity);
  11404. }
  11405. if (velocity.length() <= closeDistance) {
  11406. finalPosition.copyFrom(position);
  11407. return;
  11408. }
  11409. collider.retry++;
  11410. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  11411. };
  11412. return CollisionCoordinatorLegacy;
  11413. })();
  11414. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  11415. })(BABYLON || (BABYLON = {}));
  11416. var BABYLON;
  11417. (function (BABYLON) {
  11418. var Camera = (function (_super) {
  11419. __extends(Camera, _super);
  11420. function Camera(name, position, scene) {
  11421. _super.call(this, name, scene);
  11422. this.upVector = BABYLON.Vector3.Up();
  11423. this.orthoLeft = null;
  11424. this.orthoRight = null;
  11425. this.orthoBottom = null;
  11426. this.orthoTop = null;
  11427. this.fov = 0.8;
  11428. this.minZ = 1.0;
  11429. this.maxZ = 10000.0;
  11430. this.inertia = 0.9;
  11431. this.mode = Camera.PERSPECTIVE_CAMERA;
  11432. this.isIntermediate = false;
  11433. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  11434. this.layerMask = 0x0FFFFFFF;
  11435. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  11436. // Camera rig members
  11437. this.cameraRigMode = Camera.RIG_MODE_NONE;
  11438. this._rigCameras = new Array();
  11439. // Cache
  11440. this._computedViewMatrix = BABYLON.Matrix.Identity();
  11441. this._projectionMatrix = new BABYLON.Matrix();
  11442. this._postProcesses = new Array();
  11443. this._activeMeshes = new BABYLON.SmartArray(256);
  11444. this._globalPosition = BABYLON.Vector3.Zero();
  11445. scene.addCamera(this);
  11446. if (!scene.activeCamera) {
  11447. scene.activeCamera = this;
  11448. }
  11449. this.position = position;
  11450. }
  11451. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  11452. get: function () {
  11453. return Camera._PERSPECTIVE_CAMERA;
  11454. },
  11455. enumerable: true,
  11456. configurable: true
  11457. });
  11458. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  11459. get: function () {
  11460. return Camera._ORTHOGRAPHIC_CAMERA;
  11461. },
  11462. enumerable: true,
  11463. configurable: true
  11464. });
  11465. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  11466. get: function () {
  11467. return Camera._FOVMODE_VERTICAL_FIXED;
  11468. },
  11469. enumerable: true,
  11470. configurable: true
  11471. });
  11472. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  11473. get: function () {
  11474. return Camera._FOVMODE_HORIZONTAL_FIXED;
  11475. },
  11476. enumerable: true,
  11477. configurable: true
  11478. });
  11479. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  11480. get: function () {
  11481. return Camera._RIG_MODE_NONE;
  11482. },
  11483. enumerable: true,
  11484. configurable: true
  11485. });
  11486. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  11487. get: function () {
  11488. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  11489. },
  11490. enumerable: true,
  11491. configurable: true
  11492. });
  11493. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  11494. get: function () {
  11495. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  11496. },
  11497. enumerable: true,
  11498. configurable: true
  11499. });
  11500. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  11501. get: function () {
  11502. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  11503. },
  11504. enumerable: true,
  11505. configurable: true
  11506. });
  11507. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  11508. get: function () {
  11509. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  11510. },
  11511. enumerable: true,
  11512. configurable: true
  11513. });
  11514. Object.defineProperty(Camera, "RIG_MODE_VR", {
  11515. get: function () {
  11516. return Camera._RIG_MODE_VR;
  11517. },
  11518. enumerable: true,
  11519. configurable: true
  11520. });
  11521. /**
  11522. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11523. */
  11524. Camera.prototype.toString = function (fullDetails) {
  11525. var ret = "Name: " + this.name;
  11526. ret += ", type: " + this.getTypeName();
  11527. if (this.animations) {
  11528. for (var i = 0; i < this.animations.length; i++) {
  11529. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11530. }
  11531. }
  11532. if (fullDetails) {
  11533. }
  11534. return ret;
  11535. };
  11536. Object.defineProperty(Camera.prototype, "globalPosition", {
  11537. get: function () {
  11538. return this._globalPosition;
  11539. },
  11540. enumerable: true,
  11541. configurable: true
  11542. });
  11543. Camera.prototype.getActiveMeshes = function () {
  11544. return this._activeMeshes;
  11545. };
  11546. Camera.prototype.isActiveMesh = function (mesh) {
  11547. return (this._activeMeshes.indexOf(mesh) !== -1);
  11548. };
  11549. //Cache
  11550. Camera.prototype._initCache = function () {
  11551. _super.prototype._initCache.call(this);
  11552. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11553. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11554. this._cache.mode = undefined;
  11555. this._cache.minZ = undefined;
  11556. this._cache.maxZ = undefined;
  11557. this._cache.fov = undefined;
  11558. this._cache.aspectRatio = undefined;
  11559. this._cache.orthoLeft = undefined;
  11560. this._cache.orthoRight = undefined;
  11561. this._cache.orthoBottom = undefined;
  11562. this._cache.orthoTop = undefined;
  11563. this._cache.renderWidth = undefined;
  11564. this._cache.renderHeight = undefined;
  11565. };
  11566. Camera.prototype._updateCache = function (ignoreParentClass) {
  11567. if (!ignoreParentClass) {
  11568. _super.prototype._updateCache.call(this);
  11569. }
  11570. var engine = this.getEngine();
  11571. this._cache.position.copyFrom(this.position);
  11572. this._cache.upVector.copyFrom(this.upVector);
  11573. this._cache.mode = this.mode;
  11574. this._cache.minZ = this.minZ;
  11575. this._cache.maxZ = this.maxZ;
  11576. this._cache.fov = this.fov;
  11577. this._cache.aspectRatio = engine.getAspectRatio(this);
  11578. this._cache.orthoLeft = this.orthoLeft;
  11579. this._cache.orthoRight = this.orthoRight;
  11580. this._cache.orthoBottom = this.orthoBottom;
  11581. this._cache.orthoTop = this.orthoTop;
  11582. this._cache.renderWidth = engine.getRenderWidth();
  11583. this._cache.renderHeight = engine.getRenderHeight();
  11584. };
  11585. Camera.prototype._updateFromScene = function () {
  11586. this.updateCache();
  11587. this._update();
  11588. };
  11589. // Synchronized
  11590. Camera.prototype._isSynchronized = function () {
  11591. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  11592. };
  11593. Camera.prototype._isSynchronizedViewMatrix = function () {
  11594. if (!_super.prototype._isSynchronized.call(this))
  11595. return false;
  11596. return this._cache.position.equals(this.position)
  11597. && this._cache.upVector.equals(this.upVector)
  11598. && this.isSynchronizedWithParent();
  11599. };
  11600. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  11601. var check = this._cache.mode === this.mode
  11602. && this._cache.minZ === this.minZ
  11603. && this._cache.maxZ === this.maxZ;
  11604. if (!check) {
  11605. return false;
  11606. }
  11607. var engine = this.getEngine();
  11608. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11609. check = this._cache.fov === this.fov
  11610. && this._cache.aspectRatio === engine.getAspectRatio(this);
  11611. }
  11612. else {
  11613. check = this._cache.orthoLeft === this.orthoLeft
  11614. && this._cache.orthoRight === this.orthoRight
  11615. && this._cache.orthoBottom === this.orthoBottom
  11616. && this._cache.orthoTop === this.orthoTop
  11617. && this._cache.renderWidth === engine.getRenderWidth()
  11618. && this._cache.renderHeight === engine.getRenderHeight();
  11619. }
  11620. return check;
  11621. };
  11622. // Controls
  11623. Camera.prototype.attachControl = function (element, noPreventDefault) {
  11624. };
  11625. Camera.prototype.detachControl = function (element) {
  11626. };
  11627. Camera.prototype._update = function () {
  11628. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11629. this._updateRigCameras();
  11630. }
  11631. this._checkInputs();
  11632. };
  11633. Camera.prototype._checkInputs = function () {
  11634. };
  11635. Camera.prototype._cascadePostProcessesToRigCams = function () {
  11636. // invalidate framebuffer
  11637. if (this._postProcesses.length > 0) {
  11638. this._postProcesses[0].markTextureDirty();
  11639. }
  11640. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  11641. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  11642. var cam = this._rigCameras[i];
  11643. var rigPostProcess = cam._rigPostProcess;
  11644. // for VR rig, there does not have to be a post process
  11645. if (rigPostProcess) {
  11646. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  11647. if (isPass) {
  11648. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  11649. cam.isIntermediate = this._postProcesses.length === 0;
  11650. }
  11651. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  11652. rigPostProcess.markTextureDirty();
  11653. }
  11654. else {
  11655. cam._postProcesses = this._postProcesses.slice(0);
  11656. }
  11657. }
  11658. };
  11659. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  11660. if (insertAt === void 0) { insertAt = null; }
  11661. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  11662. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  11663. return 0;
  11664. }
  11665. if (insertAt == null || insertAt < 0) {
  11666. this._postProcesses.push(postProcess);
  11667. }
  11668. else {
  11669. this._postProcesses.splice(insertAt, 0, postProcess);
  11670. }
  11671. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  11672. return this._postProcesses.indexOf(postProcess);
  11673. };
  11674. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  11675. if (atIndices === void 0) { atIndices = null; }
  11676. var result = [];
  11677. var i;
  11678. var index;
  11679. if (!atIndices) {
  11680. var idx = this._postProcesses.indexOf(postProcess);
  11681. if (idx !== -1) {
  11682. this._postProcesses.splice(idx, 1);
  11683. }
  11684. }
  11685. else {
  11686. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  11687. // iterate descending, so can just splice as we go
  11688. for (i = atIndices.length - 1; i >= 0; i--) {
  11689. if (this._postProcesses[atIndices[i]] !== postProcess) {
  11690. result.push(i);
  11691. continue;
  11692. }
  11693. this._postProcesses.splice(index, 1);
  11694. }
  11695. }
  11696. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  11697. return result;
  11698. };
  11699. Camera.prototype.getWorldMatrix = function () {
  11700. if (!this._worldMatrix) {
  11701. this._worldMatrix = BABYLON.Matrix.Identity();
  11702. }
  11703. var viewMatrix = this.getViewMatrix();
  11704. viewMatrix.invertToRef(this._worldMatrix);
  11705. return this._worldMatrix;
  11706. };
  11707. Camera.prototype._getViewMatrix = function () {
  11708. return BABYLON.Matrix.Identity();
  11709. };
  11710. Camera.prototype.getViewMatrix = function (force) {
  11711. this._computedViewMatrix = this._computeViewMatrix(force);
  11712. if (!force && this._isSynchronizedViewMatrix()) {
  11713. return this._computedViewMatrix;
  11714. }
  11715. if (!this.parent || !this.parent.getWorldMatrix) {
  11716. this._globalPosition.copyFrom(this.position);
  11717. }
  11718. else {
  11719. if (!this._worldMatrix) {
  11720. this._worldMatrix = BABYLON.Matrix.Identity();
  11721. }
  11722. this._computedViewMatrix.invertToRef(this._worldMatrix);
  11723. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  11724. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  11725. this._computedViewMatrix.invert();
  11726. this._markSyncedWithParent();
  11727. }
  11728. this._currentRenderId = this.getScene().getRenderId();
  11729. return this._computedViewMatrix;
  11730. };
  11731. Camera.prototype._computeViewMatrix = function (force) {
  11732. if (!force && this._isSynchronizedViewMatrix()) {
  11733. return this._computedViewMatrix;
  11734. }
  11735. this._computedViewMatrix = this._getViewMatrix();
  11736. this._currentRenderId = this.getScene().getRenderId();
  11737. return this._computedViewMatrix;
  11738. };
  11739. Camera.prototype.getProjectionMatrix = function (force) {
  11740. if (!force && this._isSynchronizedProjectionMatrix()) {
  11741. return this._projectionMatrix;
  11742. }
  11743. var engine = this.getEngine();
  11744. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11745. if (this.minZ <= 0) {
  11746. this.minZ = 0.1;
  11747. }
  11748. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  11749. return this._projectionMatrix;
  11750. }
  11751. var halfWidth = engine.getRenderWidth() / 2.0;
  11752. var halfHeight = engine.getRenderHeight() / 2.0;
  11753. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  11754. return this._projectionMatrix;
  11755. };
  11756. Camera.prototype.dispose = function () {
  11757. // Animations
  11758. this.getScene().stopAnimation(this);
  11759. // Remove from scene
  11760. this.getScene().removeCamera(this);
  11761. while (this._rigCameras.length > 0) {
  11762. this._rigCameras.pop().dispose();
  11763. }
  11764. // Postprocesses
  11765. for (var i = 0; i < this._postProcesses.length; ++i) {
  11766. this._postProcesses[i].dispose(this);
  11767. }
  11768. _super.prototype.dispose.call(this);
  11769. };
  11770. // ---- Camera rigs section ----
  11771. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  11772. while (this._rigCameras.length > 0) {
  11773. this._rigCameras.pop().dispose();
  11774. }
  11775. this.cameraRigMode = mode;
  11776. this._cameraRigParams = {};
  11777. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  11778. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  11779. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11780. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11781. // create the rig cameras, unless none
  11782. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11783. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11784. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11785. }
  11786. switch (this.cameraRigMode) {
  11787. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11788. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  11789. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  11790. break;
  11791. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11792. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11793. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11794. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  11795. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  11796. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  11797. break;
  11798. case Camera.RIG_MODE_VR:
  11799. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  11800. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  11801. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  11802. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11803. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  11804. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  11805. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  11806. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  11807. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  11808. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11809. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  11810. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  11811. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  11812. if (metrics.compensateDistortion) {
  11813. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  11814. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  11815. }
  11816. break;
  11817. }
  11818. this._cascadePostProcessesToRigCams();
  11819. this._update();
  11820. };
  11821. Camera.prototype._getVRProjectionMatrix = function () {
  11822. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  11823. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  11824. return this._projectionMatrix;
  11825. };
  11826. Camera.prototype.setCameraRigParameter = function (name, value) {
  11827. if (!this._cameraRigParams) {
  11828. this._cameraRigParams = {};
  11829. }
  11830. this._cameraRigParams[name] = value;
  11831. //provisionnally:
  11832. if (name === "interaxialDistance") {
  11833. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  11834. }
  11835. };
  11836. /**
  11837. * needs to be overridden by children so sub has required properties to be copied
  11838. */
  11839. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  11840. return null;
  11841. };
  11842. /**
  11843. * May need to be overridden by children
  11844. */
  11845. Camera.prototype._updateRigCameras = function () {
  11846. for (var i = 0; i < this._rigCameras.length; i++) {
  11847. this._rigCameras[i].minZ = this.minZ;
  11848. this._rigCameras[i].maxZ = this.maxZ;
  11849. this._rigCameras[i].fov = this.fov;
  11850. }
  11851. // only update viewport when ANAGLYPH
  11852. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  11853. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  11854. }
  11855. };
  11856. Camera.prototype._setupInputs = function () {
  11857. };
  11858. Camera.prototype.serialize = function () {
  11859. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11860. // Type
  11861. serializationObject.type = this.getTypeName();
  11862. // Parent
  11863. if (this.parent) {
  11864. serializationObject.parentId = this.parent.id;
  11865. }
  11866. if (this.inputs) {
  11867. this.inputs.serialize(serializationObject);
  11868. }
  11869. // Animations
  11870. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11871. serializationObject.ranges = this.serializeAnimationRanges();
  11872. return serializationObject;
  11873. };
  11874. Camera.prototype.getTypeName = function () {
  11875. return "Camera";
  11876. };
  11877. Camera.prototype.clone = function (name) {
  11878. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  11879. };
  11880. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  11881. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  11882. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  11883. switch (type) {
  11884. case "ArcRotateCamera":
  11885. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  11886. case "DeviceOrientationCamera":
  11887. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  11888. case "FollowCamera":
  11889. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  11890. case "ArcFollowCamera":
  11891. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  11892. case "GamepadCamera":
  11893. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  11894. case "TouchCamera":
  11895. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  11896. case "VirtualJoysticksCamera":
  11897. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  11898. case "WebVRFreeCamera":
  11899. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11900. case "VRDeviceOrientationFreeCamera":
  11901. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11902. case "AnaglyphArcRotateCamera":
  11903. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11904. case "AnaglyphFreeCamera":
  11905. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11906. case "AnaglyphGamepadCamera":
  11907. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11908. case "AnaglyphUniversalCamera":
  11909. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11910. case "StereoscopicArcRotateCamera":
  11911. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11912. case "StereoscopicFreeCamera":
  11913. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11914. case "StereoscopicGamepadCamera":
  11915. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11916. case "StereoscopicUniversalCamera":
  11917. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11918. case "FreeCamera":
  11919. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11920. default:
  11921. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11922. }
  11923. };
  11924. Camera.Parse = function (parsedCamera, scene) {
  11925. var type = parsedCamera.type;
  11926. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  11927. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  11928. // Parent
  11929. if (parsedCamera.parentId) {
  11930. camera._waitingParentId = parsedCamera.parentId;
  11931. }
  11932. //If camera has an input manager, let it parse inputs settings
  11933. if (camera.inputs) {
  11934. camera.inputs.parse(parsedCamera);
  11935. camera._setupInputs();
  11936. }
  11937. // Target
  11938. if (parsedCamera.target) {
  11939. if (camera.setTarget) {
  11940. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11941. }
  11942. }
  11943. // Apply 3d rig, when found
  11944. if (parsedCamera.cameraRigMode) {
  11945. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11946. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11947. }
  11948. // Animations
  11949. if (parsedCamera.animations) {
  11950. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11951. var parsedAnimation = parsedCamera.animations[animationIndex];
  11952. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11953. }
  11954. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11955. }
  11956. if (parsedCamera.autoAnimate) {
  11957. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11958. }
  11959. return camera;
  11960. };
  11961. // Statics
  11962. Camera._PERSPECTIVE_CAMERA = 0;
  11963. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11964. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11965. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11966. Camera._RIG_MODE_NONE = 0;
  11967. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11968. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11969. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11970. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11971. Camera._RIG_MODE_VR = 20;
  11972. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11973. __decorate([
  11974. BABYLON.serializeAsVector3()
  11975. ], Camera.prototype, "position", void 0);
  11976. __decorate([
  11977. BABYLON.serializeAsVector3()
  11978. ], Camera.prototype, "upVector", void 0);
  11979. __decorate([
  11980. BABYLON.serialize()
  11981. ], Camera.prototype, "orthoLeft", void 0);
  11982. __decorate([
  11983. BABYLON.serialize()
  11984. ], Camera.prototype, "orthoRight", void 0);
  11985. __decorate([
  11986. BABYLON.serialize()
  11987. ], Camera.prototype, "orthoBottom", void 0);
  11988. __decorate([
  11989. BABYLON.serialize()
  11990. ], Camera.prototype, "orthoTop", void 0);
  11991. __decorate([
  11992. BABYLON.serialize()
  11993. ], Camera.prototype, "fov", void 0);
  11994. __decorate([
  11995. BABYLON.serialize()
  11996. ], Camera.prototype, "minZ", void 0);
  11997. __decorate([
  11998. BABYLON.serialize()
  11999. ], Camera.prototype, "maxZ", void 0);
  12000. __decorate([
  12001. BABYLON.serialize()
  12002. ], Camera.prototype, "inertia", void 0);
  12003. __decorate([
  12004. BABYLON.serialize()
  12005. ], Camera.prototype, "mode", void 0);
  12006. __decorate([
  12007. BABYLON.serialize()
  12008. ], Camera.prototype, "layerMask", void 0);
  12009. __decorate([
  12010. BABYLON.serialize()
  12011. ], Camera.prototype, "fovMode", void 0);
  12012. __decorate([
  12013. BABYLON.serialize()
  12014. ], Camera.prototype, "cameraRigMode", void 0);
  12015. __decorate([
  12016. BABYLON.serialize()
  12017. ], Camera.prototype, "interaxialDistance", void 0);
  12018. __decorate([
  12019. BABYLON.serialize()
  12020. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  12021. return Camera;
  12022. })(BABYLON.Node);
  12023. BABYLON.Camera = Camera;
  12024. })(BABYLON || (BABYLON = {}));
  12025. var BABYLON;
  12026. (function (BABYLON) {
  12027. BABYLON.CameraInputTypes = {};
  12028. var CameraInputsManager = (function () {
  12029. function CameraInputsManager(camera) {
  12030. this.attached = {};
  12031. this.camera = camera;
  12032. this.checkInputs = function () { };
  12033. }
  12034. CameraInputsManager.prototype.add = function (input) {
  12035. var type = input.getSimpleName();
  12036. if (this.attached[type]) {
  12037. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  12038. return;
  12039. }
  12040. this.attached[type] = input;
  12041. input.camera = this.camera;
  12042. //for checkInputs, we are dynamically creating a function
  12043. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  12044. if (input.checkInputs) {
  12045. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12046. }
  12047. if (this.attachedElement) {
  12048. input.attachControl(this.attachedElement);
  12049. }
  12050. };
  12051. CameraInputsManager.prototype.remove = function (inputToRemove) {
  12052. for (var cam in this.attached) {
  12053. var input = this.attached[cam];
  12054. if (input === inputToRemove) {
  12055. input.detachControl(this.attachedElement);
  12056. delete this.attached[cam];
  12057. this.rebuildInputCheck();
  12058. }
  12059. }
  12060. };
  12061. CameraInputsManager.prototype.removeByType = function (inputType) {
  12062. for (var cam in this.attached) {
  12063. var input = this.attached[cam];
  12064. if (input.getTypeName() === inputType) {
  12065. input.detachControl(this.attachedElement);
  12066. delete this.attached[cam];
  12067. this.rebuildInputCheck();
  12068. }
  12069. }
  12070. };
  12071. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  12072. var current = this.checkInputs;
  12073. return function () {
  12074. current();
  12075. fn();
  12076. };
  12077. };
  12078. CameraInputsManager.prototype.attachInput = function (input) {
  12079. input.attachControl(this.attachedElement, this.noPreventDefault);
  12080. };
  12081. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  12082. if (this.attachedElement) {
  12083. return;
  12084. }
  12085. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12086. this.attachedElement = element;
  12087. this.noPreventDefault = noPreventDefault;
  12088. for (var cam in this.attached) {
  12089. var input = this.attached[cam];
  12090. this.attached[cam].attachControl(element, noPreventDefault);
  12091. }
  12092. };
  12093. CameraInputsManager.prototype.detachElement = function (element) {
  12094. if (this.attachedElement !== element) {
  12095. return;
  12096. }
  12097. for (var cam in this.attached) {
  12098. var input = this.attached[cam];
  12099. this.attached[cam].detachControl(element);
  12100. }
  12101. this.attachedElement = null;
  12102. };
  12103. CameraInputsManager.prototype.rebuildInputCheck = function () {
  12104. this.checkInputs = function () { };
  12105. for (var cam in this.attached) {
  12106. var input = this.attached[cam];
  12107. if (input.checkInputs) {
  12108. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12109. }
  12110. }
  12111. };
  12112. CameraInputsManager.prototype.clear = function () {
  12113. if (this.attachedElement) {
  12114. this.detachElement(this.attachedElement);
  12115. }
  12116. this.attached = {};
  12117. this.attachedElement = null;
  12118. this.checkInputs = function () { };
  12119. };
  12120. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  12121. var inputs = {};
  12122. for (var cam in this.attached) {
  12123. var input = this.attached[cam];
  12124. var res = BABYLON.SerializationHelper.Serialize(input);
  12125. inputs[input.getTypeName()] = res;
  12126. }
  12127. serializedCamera.inputsmgr = inputs;
  12128. };
  12129. CameraInputsManager.prototype.parse = function (parsedCamera) {
  12130. var parsedInputs = parsedCamera.inputsmgr;
  12131. if (parsedInputs) {
  12132. this.clear();
  12133. for (var n in parsedInputs) {
  12134. var construct = BABYLON.CameraInputTypes[n];
  12135. if (construct) {
  12136. var parsedinput = parsedInputs[n];
  12137. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  12138. this.add(input);
  12139. }
  12140. }
  12141. }
  12142. else {
  12143. //2016-03-08 this part is for managing backward compatibility
  12144. for (var n in this.attached) {
  12145. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  12146. if (construct) {
  12147. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  12148. this.remove(this.attached[n]);
  12149. this.add(input);
  12150. }
  12151. }
  12152. }
  12153. };
  12154. return CameraInputsManager;
  12155. })();
  12156. BABYLON.CameraInputsManager = CameraInputsManager;
  12157. })(BABYLON || (BABYLON = {}));
  12158. var BABYLON;
  12159. (function (BABYLON) {
  12160. var FreeCameraMouseInput = (function () {
  12161. function FreeCameraMouseInput(touchEnabled) {
  12162. if (touchEnabled === void 0) { touchEnabled = true; }
  12163. this.touchEnabled = touchEnabled;
  12164. this.angularSensibility = 2000.0;
  12165. }
  12166. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  12167. var _this = this;
  12168. if (!this._pointerInput) {
  12169. var camera = this.camera;
  12170. var engine = this.camera.getEngine();
  12171. this._pointerInput = function (p, s) {
  12172. var evt = p.event;
  12173. if (!_this.touchEnabled && evt.pointerType === "touch") {
  12174. return;
  12175. }
  12176. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12177. try {
  12178. evt.srcElement.setPointerCapture(evt.pointerId);
  12179. }
  12180. catch (e) {
  12181. }
  12182. _this.previousPosition = {
  12183. x: evt.clientX,
  12184. y: evt.clientY
  12185. };
  12186. if (!noPreventDefault) {
  12187. evt.preventDefault();
  12188. }
  12189. }
  12190. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12191. try {
  12192. evt.srcElement.releasePointerCapture(evt.pointerId);
  12193. }
  12194. catch (e) {
  12195. }
  12196. _this.previousPosition = null;
  12197. if (!noPreventDefault) {
  12198. evt.preventDefault();
  12199. }
  12200. }
  12201. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12202. if (!_this.previousPosition && !engine.isPointerLock) {
  12203. return;
  12204. }
  12205. var offsetX;
  12206. var offsetY;
  12207. if (!engine.isPointerLock) {
  12208. offsetX = evt.clientX - _this.previousPosition.x;
  12209. offsetY = evt.clientY - _this.previousPosition.y;
  12210. }
  12211. else {
  12212. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12213. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12214. }
  12215. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  12216. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  12217. _this.previousPosition = {
  12218. x: evt.clientX,
  12219. y: evt.clientY
  12220. };
  12221. if (!noPreventDefault) {
  12222. evt.preventDefault();
  12223. }
  12224. }
  12225. };
  12226. }
  12227. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12228. };
  12229. FreeCameraMouseInput.prototype.detachControl = function (element) {
  12230. if (this._observer && element) {
  12231. this.camera.getScene().onPointerObservable.remove(this._observer);
  12232. this._observer = null;
  12233. this.previousPosition = null;
  12234. }
  12235. };
  12236. FreeCameraMouseInput.prototype.getTypeName = function () {
  12237. return "FreeCameraMouseInput";
  12238. };
  12239. FreeCameraMouseInput.prototype.getSimpleName = function () {
  12240. return "mouse";
  12241. };
  12242. __decorate([
  12243. BABYLON.serialize()
  12244. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  12245. return FreeCameraMouseInput;
  12246. })();
  12247. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  12248. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  12249. })(BABYLON || (BABYLON = {}));
  12250. var BABYLON;
  12251. (function (BABYLON) {
  12252. var FreeCameraKeyboardMoveInput = (function () {
  12253. function FreeCameraKeyboardMoveInput() {
  12254. this._keys = [];
  12255. this.keysUp = [38];
  12256. this.keysDown = [40];
  12257. this.keysLeft = [37];
  12258. this.keysRight = [39];
  12259. }
  12260. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12261. var _this = this;
  12262. if (!this._onKeyDown) {
  12263. this._onKeyDown = function (evt) {
  12264. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12265. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12266. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12267. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12268. var index = _this._keys.indexOf(evt.keyCode);
  12269. if (index === -1) {
  12270. _this._keys.push(evt.keyCode);
  12271. }
  12272. if (!noPreventDefault) {
  12273. evt.preventDefault();
  12274. }
  12275. }
  12276. };
  12277. this._onKeyUp = function (evt) {
  12278. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12279. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12280. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12281. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12282. var index = _this._keys.indexOf(evt.keyCode);
  12283. if (index >= 0) {
  12284. _this._keys.splice(index, 1);
  12285. }
  12286. if (!noPreventDefault) {
  12287. evt.preventDefault();
  12288. }
  12289. }
  12290. };
  12291. BABYLON.Tools.RegisterTopRootEvents([
  12292. { name: "keydown", handler: this._onKeyDown },
  12293. { name: "keyup", handler: this._onKeyUp },
  12294. { name: "blur", handler: this._onLostFocus }
  12295. ]);
  12296. }
  12297. };
  12298. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12299. if (this._onKeyDown) {
  12300. BABYLON.Tools.UnregisterTopRootEvents([
  12301. { name: "keydown", handler: this._onKeyDown },
  12302. { name: "keyup", handler: this._onKeyUp },
  12303. { name: "blur", handler: this._onLostFocus }
  12304. ]);
  12305. this._keys = [];
  12306. this._onKeyDown = null;
  12307. this._onKeyUp = null;
  12308. }
  12309. };
  12310. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12311. if (this._onKeyDown) {
  12312. var camera = this.camera;
  12313. // Keyboard
  12314. for (var index = 0; index < this._keys.length; index++) {
  12315. var keyCode = this._keys[index];
  12316. var speed = camera._computeLocalCameraSpeed();
  12317. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12318. camera._localDirection.copyFromFloats(-speed, 0, 0);
  12319. }
  12320. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12321. camera._localDirection.copyFromFloats(0, 0, speed);
  12322. }
  12323. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12324. camera._localDirection.copyFromFloats(speed, 0, 0);
  12325. }
  12326. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12327. camera._localDirection.copyFromFloats(0, 0, -speed);
  12328. }
  12329. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  12330. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  12331. camera.cameraDirection.addInPlace(camera._transformedDirection);
  12332. }
  12333. }
  12334. };
  12335. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12336. return "FreeCameraKeyboardMoveInput";
  12337. };
  12338. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  12339. this._keys = [];
  12340. };
  12341. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12342. return "keyboard";
  12343. };
  12344. __decorate([
  12345. BABYLON.serialize()
  12346. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12347. __decorate([
  12348. BABYLON.serialize()
  12349. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12350. __decorate([
  12351. BABYLON.serialize()
  12352. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12353. __decorate([
  12354. BABYLON.serialize()
  12355. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12356. return FreeCameraKeyboardMoveInput;
  12357. })();
  12358. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  12359. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  12360. })(BABYLON || (BABYLON = {}));
  12361. var BABYLON;
  12362. (function (BABYLON) {
  12363. var FreeCameraTouchInput = (function () {
  12364. function FreeCameraTouchInput() {
  12365. this._offsetX = null;
  12366. this._offsetY = null;
  12367. this._pointerCount = 0;
  12368. this._pointerPressed = [];
  12369. this.touchAngularSensibility = 200000.0;
  12370. this.touchMoveSensibility = 250.0;
  12371. }
  12372. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  12373. var _this = this;
  12374. var previousPosition;
  12375. if (this._pointerInput === undefined) {
  12376. this._onLostFocus = function (evt) {
  12377. _this._offsetX = null;
  12378. _this._offsetY = null;
  12379. };
  12380. this._pointerInput = function (p, s) {
  12381. var evt = p.event;
  12382. if (evt.pointerType === "mouse") {
  12383. return;
  12384. }
  12385. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12386. if (!noPreventDefault) {
  12387. evt.preventDefault();
  12388. }
  12389. _this._pointerPressed.push(evt.pointerId);
  12390. if (_this._pointerPressed.length !== 1) {
  12391. return;
  12392. }
  12393. previousPosition = {
  12394. x: evt.clientX,
  12395. y: evt.clientY
  12396. };
  12397. }
  12398. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12399. if (!noPreventDefault) {
  12400. evt.preventDefault();
  12401. }
  12402. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12403. if (index === -1) {
  12404. return;
  12405. }
  12406. _this._pointerPressed.splice(index, 1);
  12407. if (index != 0) {
  12408. return;
  12409. }
  12410. previousPosition = null;
  12411. _this._offsetX = null;
  12412. _this._offsetY = null;
  12413. }
  12414. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12415. if (!noPreventDefault) {
  12416. evt.preventDefault();
  12417. }
  12418. if (!previousPosition) {
  12419. return;
  12420. }
  12421. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12422. if (index != 0) {
  12423. return;
  12424. }
  12425. _this._offsetX = evt.clientX - previousPosition.x;
  12426. _this._offsetY = -(evt.clientY - previousPosition.y);
  12427. }
  12428. };
  12429. }
  12430. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12431. element.addEventListener("blur", this._onLostFocus);
  12432. };
  12433. FreeCameraTouchInput.prototype.detachControl = function (element) {
  12434. if (this._pointerInput && element) {
  12435. this.camera.getScene().onPointerObservable.remove(this._observer);
  12436. this._observer = null;
  12437. element.removeEventListener("blur", this._onLostFocus);
  12438. this._onLostFocus = null;
  12439. this._pointerPressed = [];
  12440. this._offsetX = null;
  12441. this._offsetY = null;
  12442. this._pointerCount = 0;
  12443. }
  12444. };
  12445. FreeCameraTouchInput.prototype.checkInputs = function () {
  12446. if (this._offsetX) {
  12447. var camera = this.camera;
  12448. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  12449. if (this._pointerPressed.length > 1) {
  12450. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  12451. }
  12452. else {
  12453. var speed = camera._computeLocalCameraSpeed();
  12454. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  12455. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  12456. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  12457. }
  12458. }
  12459. };
  12460. FreeCameraTouchInput.prototype.getTypeName = function () {
  12461. return "FreeCameraTouchInput";
  12462. };
  12463. FreeCameraTouchInput.prototype.getSimpleName = function () {
  12464. return "touch";
  12465. };
  12466. __decorate([
  12467. BABYLON.serialize()
  12468. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  12469. __decorate([
  12470. BABYLON.serialize()
  12471. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  12472. return FreeCameraTouchInput;
  12473. })();
  12474. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  12475. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  12476. })(BABYLON || (BABYLON = {}));
  12477. var BABYLON;
  12478. (function (BABYLON) {
  12479. var FreeCameraDeviceOrientationInput = (function () {
  12480. function FreeCameraDeviceOrientationInput() {
  12481. var _this = this;
  12482. this._screenOrientationAngle = 0;
  12483. this._screenQuaternion = new BABYLON.Quaternion();
  12484. this._alpha = 0;
  12485. this._beta = 0;
  12486. this._gamma = 0;
  12487. this._orientationChanged = function () {
  12488. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  12489. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  12490. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  12491. };
  12492. this._deviceOrientation = function (evt) {
  12493. _this._alpha = evt.alpha;
  12494. _this._beta = evt.beta;
  12495. _this._gamma = evt.gamma;
  12496. };
  12497. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  12498. this._orientationChanged();
  12499. }
  12500. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  12501. get: function () {
  12502. return this._camera;
  12503. },
  12504. set: function (camera) {
  12505. this._camera = camera;
  12506. if (!this._camera.rotationQuaternion)
  12507. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  12508. },
  12509. enumerable: true,
  12510. configurable: true
  12511. });
  12512. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12513. window.addEventListener("orientationchange", this._orientationChanged);
  12514. window.addEventListener("deviceorientation", this._deviceOrientation);
  12515. };
  12516. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  12517. window.removeEventListener("orientationchange", this._orientationChanged);
  12518. window.removeEventListener("deviceorientation", this._deviceOrientation);
  12519. };
  12520. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  12521. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  12522. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  12523. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  12524. //Mirror on XY Plane
  12525. this._camera.rotationQuaternion.z *= -1;
  12526. this._camera.rotationQuaternion.w *= -1;
  12527. };
  12528. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  12529. return "FreeCameraDeviceOrientationInput";
  12530. };
  12531. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  12532. return "deviceOrientation";
  12533. };
  12534. return FreeCameraDeviceOrientationInput;
  12535. })();
  12536. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  12537. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  12538. })(BABYLON || (BABYLON = {}));
  12539. var BABYLON;
  12540. (function (BABYLON) {
  12541. var FreeCameraVRDeviceOrientationInput = (function () {
  12542. function FreeCameraVRDeviceOrientationInput() {
  12543. this.alphaCorrection = 1;
  12544. this.betaCorrection = 1;
  12545. this.gammaCorrection = 1;
  12546. this._alpha = 0;
  12547. this._beta = 0;
  12548. this._gamma = 0;
  12549. this._dirty = false;
  12550. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12551. }
  12552. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12553. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12554. };
  12555. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12556. var camera = this.camera;
  12557. this._alpha = evt.alpha;
  12558. this._beta = evt.beta;
  12559. this._gamma = evt.gamma;
  12560. this._dirty = true;
  12561. };
  12562. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12563. if (this._dirty) {
  12564. this._dirty = false;
  12565. var rotationX = this._gamma;
  12566. if (rotationX < 0) {
  12567. rotationX = 90 + rotationX;
  12568. }
  12569. else {
  12570. // Incline it in the correct angle.
  12571. rotationX = 270 - rotationX;
  12572. }
  12573. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  12574. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  12575. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  12576. }
  12577. };
  12578. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12579. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12580. };
  12581. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12582. return "FreeCameraVRDeviceOrientationInput";
  12583. };
  12584. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12585. return "VRDeviceOrientation";
  12586. };
  12587. return FreeCameraVRDeviceOrientationInput;
  12588. })();
  12589. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  12590. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  12591. })(BABYLON || (BABYLON = {}));
  12592. var BABYLON;
  12593. (function (BABYLON) {
  12594. var FreeCameraGamepadInput = (function () {
  12595. function FreeCameraGamepadInput() {
  12596. this.gamepadAngularSensibility = 200;
  12597. this.gamepadMoveSensibility = 40;
  12598. }
  12599. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12600. var _this = this;
  12601. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12602. };
  12603. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  12604. if (this._gamepads) {
  12605. this._gamepads.dispose();
  12606. }
  12607. this.gamepad = null;
  12608. };
  12609. FreeCameraGamepadInput.prototype.checkInputs = function () {
  12610. if (this.gamepad) {
  12611. var camera = this.camera;
  12612. var LSValues = this.gamepad.leftStick;
  12613. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  12614. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12615. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12616. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12617. var RSValues = this.gamepad.rightStick;
  12618. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  12619. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  12620. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12621. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12622. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12623. var speed = camera._computeLocalCameraSpeed() * 50.0;
  12624. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12625. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12626. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12627. }
  12628. };
  12629. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12630. // Only the first gamepad can control the camera
  12631. if (gamepad.index === 0) {
  12632. this.gamepad = gamepad;
  12633. }
  12634. };
  12635. FreeCameraGamepadInput.prototype.getTypeName = function () {
  12636. return "FreeCameraGamepadInput";
  12637. };
  12638. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  12639. return "gamepad";
  12640. };
  12641. __decorate([
  12642. BABYLON.serialize()
  12643. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  12644. __decorate([
  12645. BABYLON.serialize()
  12646. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12647. return FreeCameraGamepadInput;
  12648. })();
  12649. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  12650. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  12651. })(BABYLON || (BABYLON = {}));
  12652. var BABYLON;
  12653. (function (BABYLON) {
  12654. var ArcRotateCameraKeyboardMoveInput = (function () {
  12655. function ArcRotateCameraKeyboardMoveInput() {
  12656. this._keys = [];
  12657. this.keysUp = [38];
  12658. this.keysDown = [40];
  12659. this.keysLeft = [37];
  12660. this.keysRight = [39];
  12661. }
  12662. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12663. var _this = this;
  12664. this._onKeyDown = function (evt) {
  12665. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12666. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12667. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12668. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12669. var index = _this._keys.indexOf(evt.keyCode);
  12670. if (index === -1) {
  12671. _this._keys.push(evt.keyCode);
  12672. }
  12673. if (evt.preventDefault) {
  12674. if (!noPreventDefault) {
  12675. evt.preventDefault();
  12676. }
  12677. }
  12678. }
  12679. };
  12680. this._onKeyUp = function (evt) {
  12681. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12682. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12683. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12684. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12685. var index = _this._keys.indexOf(evt.keyCode);
  12686. if (index >= 0) {
  12687. _this._keys.splice(index, 1);
  12688. }
  12689. if (evt.preventDefault) {
  12690. if (!noPreventDefault) {
  12691. evt.preventDefault();
  12692. }
  12693. }
  12694. }
  12695. };
  12696. this._onLostFocus = function () {
  12697. _this._keys = [];
  12698. };
  12699. BABYLON.Tools.RegisterTopRootEvents([
  12700. { name: "keydown", handler: this._onKeyDown },
  12701. { name: "keyup", handler: this._onKeyUp },
  12702. { name: "blur", handler: this._onLostFocus }
  12703. ]);
  12704. };
  12705. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12706. BABYLON.Tools.UnregisterTopRootEvents([
  12707. { name: "keydown", handler: this._onKeyDown },
  12708. { name: "keyup", handler: this._onKeyUp },
  12709. { name: "blur", handler: this._onLostFocus }
  12710. ]);
  12711. this._keys = [];
  12712. this._onKeyDown = null;
  12713. this._onKeyUp = null;
  12714. this._onLostFocus = null;
  12715. };
  12716. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12717. if (this._onKeyDown) {
  12718. var camera = this.camera;
  12719. for (var index = 0; index < this._keys.length; index++) {
  12720. var keyCode = this._keys[index];
  12721. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12722. camera.inertialAlphaOffset -= 0.01;
  12723. }
  12724. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12725. camera.inertialBetaOffset -= 0.01;
  12726. }
  12727. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12728. camera.inertialAlphaOffset += 0.01;
  12729. }
  12730. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12731. camera.inertialBetaOffset += 0.01;
  12732. }
  12733. }
  12734. }
  12735. };
  12736. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12737. return "ArcRotateCameraKeyboardMoveInput";
  12738. };
  12739. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12740. return "keyboard";
  12741. };
  12742. __decorate([
  12743. BABYLON.serialize()
  12744. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12745. __decorate([
  12746. BABYLON.serialize()
  12747. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12748. __decorate([
  12749. BABYLON.serialize()
  12750. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12751. __decorate([
  12752. BABYLON.serialize()
  12753. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12754. return ArcRotateCameraKeyboardMoveInput;
  12755. })();
  12756. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  12757. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  12758. })(BABYLON || (BABYLON = {}));
  12759. var BABYLON;
  12760. (function (BABYLON) {
  12761. var ArcRotateCameraMouseWheelInput = (function () {
  12762. function ArcRotateCameraMouseWheelInput() {
  12763. this.wheelPrecision = 3.0;
  12764. }
  12765. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  12766. var _this = this;
  12767. this._wheel = function (p, s) {
  12768. //sanity check - this should be a PointerWheel event.
  12769. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  12770. return;
  12771. var event = p.event;
  12772. var delta = 0;
  12773. if (event.wheelDelta) {
  12774. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  12775. }
  12776. else if (event.detail) {
  12777. delta = -event.detail / _this.wheelPrecision;
  12778. }
  12779. if (delta)
  12780. _this.camera.inertialRadiusOffset += delta;
  12781. if (event.preventDefault) {
  12782. if (!noPreventDefault) {
  12783. event.preventDefault();
  12784. }
  12785. }
  12786. };
  12787. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  12788. };
  12789. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  12790. if (this._observer && element) {
  12791. this.camera.getScene().onPointerObservable.remove(this._observer);
  12792. this._observer = null;
  12793. this._wheel = null;
  12794. }
  12795. };
  12796. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  12797. return "ArcRotateCameraMouseWheelInput";
  12798. };
  12799. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  12800. return "mousewheel";
  12801. };
  12802. __decorate([
  12803. BABYLON.serialize()
  12804. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  12805. return ArcRotateCameraMouseWheelInput;
  12806. })();
  12807. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  12808. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  12809. })(BABYLON || (BABYLON = {}));
  12810. var BABYLON;
  12811. (function (BABYLON) {
  12812. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12813. var ArcRotateCameraPointersInput = (function () {
  12814. function ArcRotateCameraPointersInput() {
  12815. this.angularSensibilityX = 1000.0;
  12816. this.angularSensibilityY = 1000.0;
  12817. this.pinchPrecision = 6.0;
  12818. this.panningSensibility = 50.0;
  12819. this._isRightClick = false;
  12820. this._isCtrlPushed = false;
  12821. this.pinchInwards = true;
  12822. }
  12823. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  12824. var _this = this;
  12825. var engine = this.camera.getEngine();
  12826. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  12827. var pointA, pointB;
  12828. var previousPinchDistance = 0;
  12829. this._pointerInput = function (p, s) {
  12830. var evt = p.event;
  12831. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12832. try {
  12833. evt.srcElement.setPointerCapture(evt.pointerId);
  12834. }
  12835. catch (e) {
  12836. }
  12837. // Manage panning with right click
  12838. _this._isRightClick = evt.button === 2;
  12839. // manage pointers
  12840. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  12841. if (pointA === undefined) {
  12842. pointA = cacheSoloPointer;
  12843. }
  12844. else if (pointB === undefined) {
  12845. pointB = cacheSoloPointer;
  12846. }
  12847. if (!noPreventDefault) {
  12848. evt.preventDefault();
  12849. }
  12850. }
  12851. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12852. try {
  12853. evt.srcElement.releasePointerCapture(evt.pointerId);
  12854. }
  12855. catch (e) {
  12856. }
  12857. cacheSoloPointer = null;
  12858. previousPinchDistance = 0;
  12859. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  12860. //but emptying completly pointers collection is required to fix a bug on iPhone :
  12861. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  12862. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  12863. pointA = pointB = undefined;
  12864. if (!noPreventDefault) {
  12865. evt.preventDefault();
  12866. }
  12867. }
  12868. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12869. if (!noPreventDefault) {
  12870. evt.preventDefault();
  12871. }
  12872. // One button down
  12873. if (pointA && pointB === undefined) {
  12874. if (_this.panningSensibility !== 0 &&
  12875. ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) ||
  12876. (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  12877. _this.camera
  12878. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  12879. _this.camera
  12880. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  12881. }
  12882. else {
  12883. var offsetX = evt.clientX - cacheSoloPointer.x;
  12884. var offsetY = evt.clientY - cacheSoloPointer.y;
  12885. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12886. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12887. }
  12888. cacheSoloPointer.x = evt.clientX;
  12889. cacheSoloPointer.y = evt.clientY;
  12890. }
  12891. else if (pointA && pointB) {
  12892. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  12893. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  12894. ed.x = evt.clientX;
  12895. ed.y = evt.clientY;
  12896. var direction = _this.pinchInwards ? 1 : -1;
  12897. var distX = pointA.x - pointB.x;
  12898. var distY = pointA.y - pointB.y;
  12899. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  12900. if (previousPinchDistance === 0) {
  12901. previousPinchDistance = pinchSquaredDistance;
  12902. return;
  12903. }
  12904. if (pinchSquaredDistance !== previousPinchDistance) {
  12905. _this.camera
  12906. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  12907. (_this.pinchPrecision *
  12908. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  12909. direction);
  12910. previousPinchDistance = pinchSquaredDistance;
  12911. }
  12912. }
  12913. }
  12914. };
  12915. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12916. this._onContextMenu = function (evt) {
  12917. evt.preventDefault();
  12918. };
  12919. if (!this.camera._useCtrlForPanning) {
  12920. element.addEventListener("contextmenu", this._onContextMenu, false);
  12921. }
  12922. this._onLostFocus = function () {
  12923. //this._keys = [];
  12924. pointA = pointB = undefined;
  12925. previousPinchDistance = 0;
  12926. cacheSoloPointer = null;
  12927. };
  12928. this._onKeyDown = function (evt) {
  12929. _this._isCtrlPushed = evt.ctrlKey;
  12930. };
  12931. this._onKeyUp = function (evt) {
  12932. _this._isCtrlPushed = evt.ctrlKey;
  12933. };
  12934. this._onMouseMove = function (evt) {
  12935. if (!engine.isPointerLock) {
  12936. return;
  12937. }
  12938. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12939. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12940. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12941. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12942. if (!noPreventDefault) {
  12943. evt.preventDefault();
  12944. }
  12945. };
  12946. this._onGestureStart = function (e) {
  12947. if (window.MSGesture === undefined) {
  12948. return;
  12949. }
  12950. if (!_this._MSGestureHandler) {
  12951. _this._MSGestureHandler = new MSGesture();
  12952. _this._MSGestureHandler.target = element;
  12953. }
  12954. _this._MSGestureHandler.addPointer(e.pointerId);
  12955. };
  12956. this._onGesture = function (e) {
  12957. _this.camera.radius *= e.scale;
  12958. if (e.preventDefault) {
  12959. if (!noPreventDefault) {
  12960. e.stopPropagation();
  12961. e.preventDefault();
  12962. }
  12963. }
  12964. };
  12965. element.addEventListener("mousemove", this._onMouseMove, false);
  12966. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12967. element.addEventListener("MSGestureChange", this._onGesture, false);
  12968. BABYLON.Tools.RegisterTopRootEvents([
  12969. { name: "keydown", handler: this._onKeyDown },
  12970. { name: "keyup", handler: this._onKeyUp },
  12971. { name: "blur", handler: this._onLostFocus }
  12972. ]);
  12973. };
  12974. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12975. if (element && this._observer) {
  12976. this.camera.getScene().onPointerObservable.remove(this._observer);
  12977. this._observer = null;
  12978. element.removeEventListener("contextmenu", this._onContextMenu);
  12979. element.removeEventListener("mousemove", this._onMouseMove);
  12980. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12981. element.removeEventListener("MSGestureChange", this._onGesture);
  12982. this._isRightClick = false;
  12983. this._isCtrlPushed = false;
  12984. this.pinchInwards = true;
  12985. this._onKeyDown = null;
  12986. this._onKeyUp = null;
  12987. this._onMouseMove = null;
  12988. this._onGestureStart = null;
  12989. this._onGesture = null;
  12990. this._MSGestureHandler = null;
  12991. this._onLostFocus = null;
  12992. this._onContextMenu = null;
  12993. }
  12994. BABYLON.Tools.UnregisterTopRootEvents([
  12995. { name: "keydown", handler: this._onKeyDown },
  12996. { name: "keyup", handler: this._onKeyUp },
  12997. { name: "blur", handler: this._onLostFocus }
  12998. ]);
  12999. };
  13000. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  13001. return "ArcRotateCameraPointersInput";
  13002. };
  13003. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  13004. return "pointers";
  13005. };
  13006. __decorate([
  13007. BABYLON.serialize()
  13008. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  13009. __decorate([
  13010. BABYLON.serialize()
  13011. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  13012. __decorate([
  13013. BABYLON.serialize()
  13014. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  13015. __decorate([
  13016. BABYLON.serialize()
  13017. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  13018. return ArcRotateCameraPointersInput;
  13019. })();
  13020. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  13021. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  13022. })(BABYLON || (BABYLON = {}));
  13023. var BABYLON;
  13024. (function (BABYLON) {
  13025. var ArcRotateCameraGamepadInput = (function () {
  13026. function ArcRotateCameraGamepadInput() {
  13027. this.gamepadRotationSensibility = 80;
  13028. this.gamepadMoveSensibility = 40;
  13029. }
  13030. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13031. var _this = this;
  13032. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13033. };
  13034. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  13035. if (this._gamepads) {
  13036. this._gamepads.dispose();
  13037. }
  13038. this.gamepad = null;
  13039. };
  13040. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  13041. if (this.gamepad) {
  13042. var camera = this.camera;
  13043. var RSValues = this.gamepad.rightStick;
  13044. if (RSValues.x != 0) {
  13045. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  13046. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  13047. camera.inertialAlphaOffset += normalizedRX;
  13048. }
  13049. }
  13050. if (RSValues.y != 0) {
  13051. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  13052. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  13053. camera.inertialBetaOffset += normalizedRY;
  13054. }
  13055. }
  13056. var LSValues = this.gamepad.leftStick;
  13057. if (LSValues.y != 0) {
  13058. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13059. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  13060. this.camera.inertialRadiusOffset -= normalizedLY;
  13061. }
  13062. }
  13063. }
  13064. };
  13065. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13066. // Only the first gamepad can control the camera
  13067. if (gamepad.index === 0) {
  13068. this.gamepad = gamepad;
  13069. }
  13070. };
  13071. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  13072. return "ArcRotateCameraGamepadInput";
  13073. };
  13074. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  13075. return "gamepad";
  13076. };
  13077. __decorate([
  13078. BABYLON.serialize()
  13079. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  13080. __decorate([
  13081. BABYLON.serialize()
  13082. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13083. return ArcRotateCameraGamepadInput;
  13084. })();
  13085. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  13086. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  13087. })(BABYLON || (BABYLON = {}));
  13088. var BABYLON;
  13089. (function (BABYLON) {
  13090. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  13091. function ArcRotateCameraVRDeviceOrientationInput() {
  13092. this.alphaCorrection = 1;
  13093. this.betaCorrection = 1;
  13094. this.gammaCorrection = 1;
  13095. this._alpha = 0;
  13096. this._beta = 0;
  13097. this._gamma = 0;
  13098. this._dirty = false;
  13099. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  13100. }
  13101. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13102. this.camera.attachControl(element, noPreventDefault);
  13103. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  13104. };
  13105. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  13106. var camera = this.camera;
  13107. this._alpha = +evt.alpha | 0;
  13108. this._beta = +evt.beta | 0;
  13109. this._gamma = +evt.gamma | 0;
  13110. this._dirty = true;
  13111. };
  13112. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  13113. if (this._dirty) {
  13114. this._dirty = false;
  13115. if (this._gamma < 0) {
  13116. this._gamma = 180 + this._gamma;
  13117. }
  13118. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  13119. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  13120. }
  13121. };
  13122. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  13123. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  13124. };
  13125. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  13126. return "ArcRotateCameraVRDeviceOrientationInput";
  13127. };
  13128. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  13129. return "VRDeviceOrientation";
  13130. };
  13131. return ArcRotateCameraVRDeviceOrientationInput;
  13132. })();
  13133. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  13134. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  13135. })(BABYLON || (BABYLON = {}));
  13136. var BABYLON;
  13137. (function (BABYLON) {
  13138. var TargetCamera = (function (_super) {
  13139. __extends(TargetCamera, _super);
  13140. function TargetCamera(name, position, scene) {
  13141. _super.call(this, name, position, scene);
  13142. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13143. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13144. this.rotation = new BABYLON.Vector3(0, 0, 0);
  13145. this.speed = 2.0;
  13146. this.noRotationConstraint = false;
  13147. this.lockedTarget = null;
  13148. this._currentTarget = BABYLON.Vector3.Zero();
  13149. this._viewMatrix = BABYLON.Matrix.Zero();
  13150. this._camMatrix = BABYLON.Matrix.Zero();
  13151. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  13152. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  13153. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  13154. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  13155. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  13156. this._lookAtTemp = BABYLON.Matrix.Zero();
  13157. this._tempMatrix = BABYLON.Matrix.Zero();
  13158. }
  13159. TargetCamera.prototype.getFrontPosition = function (distance) {
  13160. var direction = this.getTarget().subtract(this.position);
  13161. direction.normalize();
  13162. direction.scaleInPlace(distance);
  13163. return this.globalPosition.add(direction);
  13164. };
  13165. TargetCamera.prototype._getLockedTargetPosition = function () {
  13166. if (!this.lockedTarget) {
  13167. return null;
  13168. }
  13169. return this.lockedTarget.position || this.lockedTarget;
  13170. };
  13171. // Cache
  13172. TargetCamera.prototype._initCache = function () {
  13173. _super.prototype._initCache.call(this);
  13174. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13175. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13176. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13177. };
  13178. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  13179. if (!ignoreParentClass) {
  13180. _super.prototype._updateCache.call(this);
  13181. }
  13182. var lockedTargetPosition = this._getLockedTargetPosition();
  13183. if (!lockedTargetPosition) {
  13184. this._cache.lockedTarget = null;
  13185. }
  13186. else {
  13187. if (!this._cache.lockedTarget) {
  13188. this._cache.lockedTarget = lockedTargetPosition.clone();
  13189. }
  13190. else {
  13191. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  13192. }
  13193. }
  13194. this._cache.rotation.copyFrom(this.rotation);
  13195. if (this.rotationQuaternion)
  13196. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13197. };
  13198. // Synchronized
  13199. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  13200. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  13201. return false;
  13202. }
  13203. var lockedTargetPosition = this._getLockedTargetPosition();
  13204. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  13205. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  13206. };
  13207. // Methods
  13208. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  13209. var engine = this.getEngine();
  13210. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  13211. };
  13212. // Target
  13213. TargetCamera.prototype.setTarget = function (target) {
  13214. this.upVector.normalize();
  13215. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  13216. this._camMatrix.invert();
  13217. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  13218. var vDir = target.subtract(this.position);
  13219. if (vDir.x >= 0.0) {
  13220. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  13221. }
  13222. else {
  13223. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  13224. }
  13225. this.rotation.z = 0;
  13226. if (isNaN(this.rotation.x)) {
  13227. this.rotation.x = 0;
  13228. }
  13229. if (isNaN(this.rotation.y)) {
  13230. this.rotation.y = 0;
  13231. }
  13232. if (isNaN(this.rotation.z)) {
  13233. this.rotation.z = 0;
  13234. }
  13235. if (this.rotationQuaternion) {
  13236. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  13237. }
  13238. };
  13239. TargetCamera.prototype.getTarget = function () {
  13240. return this._currentTarget;
  13241. };
  13242. TargetCamera.prototype._decideIfNeedsToMove = function () {
  13243. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13244. };
  13245. TargetCamera.prototype._updatePosition = function () {
  13246. this.position.addInPlace(this.cameraDirection);
  13247. };
  13248. TargetCamera.prototype._checkInputs = function () {
  13249. var needToMove = this._decideIfNeedsToMove();
  13250. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  13251. // Move
  13252. if (needToMove) {
  13253. this._updatePosition();
  13254. }
  13255. // Rotate
  13256. if (needToRotate) {
  13257. this.rotation.x += this.cameraRotation.x;
  13258. this.rotation.y += this.cameraRotation.y;
  13259. if (!this.noRotationConstraint) {
  13260. var limit = (Math.PI / 2) * 0.95;
  13261. if (this.rotation.x > limit)
  13262. this.rotation.x = limit;
  13263. if (this.rotation.x < -limit)
  13264. this.rotation.x = -limit;
  13265. }
  13266. }
  13267. // Inertia
  13268. if (needToMove) {
  13269. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  13270. this.cameraDirection.x = 0;
  13271. }
  13272. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  13273. this.cameraDirection.y = 0;
  13274. }
  13275. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  13276. this.cameraDirection.z = 0;
  13277. }
  13278. this.cameraDirection.scaleInPlace(this.inertia);
  13279. }
  13280. if (needToRotate) {
  13281. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  13282. this.cameraRotation.x = 0;
  13283. }
  13284. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  13285. this.cameraRotation.y = 0;
  13286. }
  13287. this.cameraRotation.scaleInPlace(this.inertia);
  13288. }
  13289. _super.prototype._checkInputs.call(this);
  13290. };
  13291. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  13292. if (this.rotationQuaternion) {
  13293. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  13294. //update the up vector!
  13295. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  13296. }
  13297. else {
  13298. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  13299. }
  13300. };
  13301. TargetCamera.prototype._getViewMatrix = function () {
  13302. if (!this.lockedTarget) {
  13303. // Compute
  13304. this._updateCameraRotationMatrix();
  13305. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  13306. // Computing target and final matrix
  13307. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  13308. }
  13309. else {
  13310. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  13311. }
  13312. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  13313. return this._viewMatrix;
  13314. };
  13315. /**
  13316. * @override
  13317. * Override Camera.createRigCamera
  13318. */
  13319. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13320. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  13321. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  13322. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  13323. if (!this.rotationQuaternion) {
  13324. this.rotationQuaternion = new BABYLON.Quaternion();
  13325. }
  13326. rigCamera._cameraRigParams = {};
  13327. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  13328. }
  13329. return rigCamera;
  13330. }
  13331. return null;
  13332. };
  13333. /**
  13334. * @override
  13335. * Override Camera._updateRigCameras
  13336. */
  13337. TargetCamera.prototype._updateRigCameras = function () {
  13338. var camLeft = this._rigCameras[0];
  13339. var camRight = this._rigCameras[1];
  13340. switch (this.cameraRigMode) {
  13341. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13342. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13343. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13344. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13345. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  13346. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  13347. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  13348. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  13349. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  13350. camLeft.setTarget(this.getTarget());
  13351. camRight.setTarget(this.getTarget());
  13352. break;
  13353. case BABYLON.Camera.RIG_MODE_VR:
  13354. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13355. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13356. camLeft.position.copyFrom(this.position);
  13357. camRight.position.copyFrom(this.position);
  13358. break;
  13359. }
  13360. _super.prototype._updateRigCameras.call(this);
  13361. };
  13362. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  13363. if (!this._rigCamTransformMatrix) {
  13364. this._rigCamTransformMatrix = new BABYLON.Matrix();
  13365. }
  13366. var target = this.getTarget();
  13367. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  13368. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  13369. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  13370. };
  13371. TargetCamera.prototype.getTypeName = function () {
  13372. return "TargetCamera";
  13373. };
  13374. __decorate([
  13375. BABYLON.serializeAsVector3()
  13376. ], TargetCamera.prototype, "rotation", void 0);
  13377. __decorate([
  13378. BABYLON.serialize()
  13379. ], TargetCamera.prototype, "speed", void 0);
  13380. __decorate([
  13381. BABYLON.serializeAsMeshReference("lockedTargetId")
  13382. ], TargetCamera.prototype, "lockedTarget", void 0);
  13383. return TargetCamera;
  13384. })(BABYLON.Camera);
  13385. BABYLON.TargetCamera = TargetCamera;
  13386. })(BABYLON || (BABYLON = {}));
  13387. var BABYLON;
  13388. (function (BABYLON) {
  13389. var FreeCamera = (function (_super) {
  13390. __extends(FreeCamera, _super);
  13391. function FreeCamera(name, position, scene) {
  13392. var _this = this;
  13393. _super.call(this, name, position, scene);
  13394. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  13395. this.checkCollisions = false;
  13396. this.applyGravity = false;
  13397. this._collider = new BABYLON.Collider();
  13398. this._needMoveForGravity = false;
  13399. this._oldPosition = BABYLON.Vector3.Zero();
  13400. this._diffPosition = BABYLON.Vector3.Zero();
  13401. this._newPosition = BABYLON.Vector3.Zero();
  13402. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13403. if (collidedMesh === void 0) { collidedMesh = null; }
  13404. //TODO move this to the collision coordinator!
  13405. if (_this.getScene().workerCollisions)
  13406. newPosition.multiplyInPlace(_this._collider.radius);
  13407. var updatePosition = function (newPos) {
  13408. _this._newPosition.copyFrom(newPos);
  13409. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  13410. var oldPosition = _this.position.clone();
  13411. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  13412. _this.position.addInPlace(_this._diffPosition);
  13413. if (_this.onCollide && collidedMesh) {
  13414. _this.onCollide(collidedMesh);
  13415. }
  13416. }
  13417. };
  13418. updatePosition(newPosition);
  13419. };
  13420. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  13421. this.inputs.addKeyboard().addMouse();
  13422. }
  13423. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  13424. //-- begin properties for backward compatibility for inputs
  13425. get: function () {
  13426. var mouse = this.inputs.attached["mouse"];
  13427. if (mouse)
  13428. return mouse.angularSensibility;
  13429. },
  13430. set: function (value) {
  13431. var mouse = this.inputs.attached["mouse"];
  13432. if (mouse)
  13433. mouse.angularSensibility = value;
  13434. },
  13435. enumerable: true,
  13436. configurable: true
  13437. });
  13438. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  13439. get: function () {
  13440. var keyboard = this.inputs.attached["keyboard"];
  13441. if (keyboard)
  13442. return keyboard.keysUp;
  13443. },
  13444. set: function (value) {
  13445. var keyboard = this.inputs.attached["keyboard"];
  13446. if (keyboard)
  13447. keyboard.keysUp = value;
  13448. },
  13449. enumerable: true,
  13450. configurable: true
  13451. });
  13452. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  13453. get: function () {
  13454. var keyboard = this.inputs.attached["keyboard"];
  13455. if (keyboard)
  13456. return keyboard.keysDown;
  13457. },
  13458. set: function (value) {
  13459. var keyboard = this.inputs.attached["keyboard"];
  13460. if (keyboard)
  13461. keyboard.keysDown = value;
  13462. },
  13463. enumerable: true,
  13464. configurable: true
  13465. });
  13466. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  13467. get: function () {
  13468. var keyboard = this.inputs.attached["keyboard"];
  13469. if (keyboard)
  13470. return keyboard.keysLeft;
  13471. },
  13472. set: function (value) {
  13473. var keyboard = this.inputs.attached["keyboard"];
  13474. if (keyboard)
  13475. keyboard.keysLeft = value;
  13476. },
  13477. enumerable: true,
  13478. configurable: true
  13479. });
  13480. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  13481. get: function () {
  13482. var keyboard = this.inputs.attached["keyboard"];
  13483. if (keyboard)
  13484. return keyboard.keysRight;
  13485. },
  13486. set: function (value) {
  13487. var keyboard = this.inputs.attached["keyboard"];
  13488. if (keyboard)
  13489. keyboard.keysRight = value;
  13490. },
  13491. enumerable: true,
  13492. configurable: true
  13493. });
  13494. // Controls
  13495. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  13496. this.inputs.attachElement(element, noPreventDefault);
  13497. };
  13498. FreeCamera.prototype.detachControl = function (element) {
  13499. this.inputs.detachElement(element);
  13500. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13501. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13502. };
  13503. FreeCamera.prototype._collideWithWorld = function (velocity) {
  13504. var globalPosition;
  13505. if (this.parent) {
  13506. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  13507. }
  13508. else {
  13509. globalPosition = this.position;
  13510. }
  13511. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  13512. this._collider.radius = this.ellipsoid;
  13513. //no need for clone, as long as gravity is not on.
  13514. var actualVelocity = velocity;
  13515. //add gravity to the velocity to prevent the dual-collision checking
  13516. if (this.applyGravity) {
  13517. //this prevents mending with cameraDirection, a global variable of the free camera class.
  13518. actualVelocity = velocity.add(this.getScene().gravity);
  13519. }
  13520. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13521. };
  13522. FreeCamera.prototype._checkInputs = function () {
  13523. if (!this._localDirection) {
  13524. this._localDirection = BABYLON.Vector3.Zero();
  13525. this._transformedDirection = BABYLON.Vector3.Zero();
  13526. }
  13527. this.inputs.checkInputs();
  13528. _super.prototype._checkInputs.call(this);
  13529. };
  13530. FreeCamera.prototype._decideIfNeedsToMove = function () {
  13531. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13532. };
  13533. FreeCamera.prototype._updatePosition = function () {
  13534. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  13535. this._collideWithWorld(this.cameraDirection);
  13536. }
  13537. else {
  13538. this.position.addInPlace(this.cameraDirection);
  13539. }
  13540. };
  13541. FreeCamera.prototype.dispose = function () {
  13542. this.inputs.clear();
  13543. _super.prototype.dispose.call(this);
  13544. };
  13545. FreeCamera.prototype.getTypeName = function () {
  13546. return "FreeCamera";
  13547. };
  13548. __decorate([
  13549. BABYLON.serializeAsVector3()
  13550. ], FreeCamera.prototype, "ellipsoid", void 0);
  13551. __decorate([
  13552. BABYLON.serialize()
  13553. ], FreeCamera.prototype, "checkCollisions", void 0);
  13554. __decorate([
  13555. BABYLON.serialize()
  13556. ], FreeCamera.prototype, "applyGravity", void 0);
  13557. return FreeCamera;
  13558. })(BABYLON.TargetCamera);
  13559. BABYLON.FreeCamera = FreeCamera;
  13560. })(BABYLON || (BABYLON = {}));
  13561. var BABYLON;
  13562. (function (BABYLON) {
  13563. var FreeCameraInputsManager = (function (_super) {
  13564. __extends(FreeCameraInputsManager, _super);
  13565. function FreeCameraInputsManager(camera) {
  13566. _super.call(this, camera);
  13567. }
  13568. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13569. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13570. return this;
  13571. };
  13572. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  13573. if (touchEnabled === void 0) { touchEnabled = true; }
  13574. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  13575. return this;
  13576. };
  13577. FreeCameraInputsManager.prototype.addGamepad = function () {
  13578. this.add(new BABYLON.FreeCameraGamepadInput());
  13579. return this;
  13580. };
  13581. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  13582. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  13583. return this;
  13584. };
  13585. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13586. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  13587. return this;
  13588. };
  13589. FreeCameraInputsManager.prototype.addTouch = function () {
  13590. this.add(new BABYLON.FreeCameraTouchInput());
  13591. return this;
  13592. };
  13593. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  13594. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  13595. return this;
  13596. };
  13597. return FreeCameraInputsManager;
  13598. })(BABYLON.CameraInputsManager);
  13599. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  13600. })(BABYLON || (BABYLON = {}));
  13601. var BABYLON;
  13602. (function (BABYLON) {
  13603. var FollowCamera = (function (_super) {
  13604. __extends(FollowCamera, _super);
  13605. function FollowCamera(name, position, scene, target) {
  13606. _super.call(this, name, position, scene);
  13607. this.radius = 12;
  13608. this.rotationOffset = 0;
  13609. this.heightOffset = 4;
  13610. this.cameraAcceleration = 0.05;
  13611. this.maxCameraSpeed = 20;
  13612. this.target = target;
  13613. }
  13614. FollowCamera.prototype.getRadians = function (degrees) {
  13615. return degrees * Math.PI / 180;
  13616. };
  13617. FollowCamera.prototype.follow = function (cameraTarget) {
  13618. if (!cameraTarget)
  13619. return;
  13620. var yRotation;
  13621. if (cameraTarget.rotationQuaternion) {
  13622. var rotMatrix = new BABYLON.Matrix();
  13623. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  13624. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  13625. }
  13626. else {
  13627. yRotation = cameraTarget.rotation.y;
  13628. }
  13629. var radians = this.getRadians(this.rotationOffset) + yRotation;
  13630. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  13631. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  13632. var dx = targetX - this.position.x;
  13633. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  13634. var dz = (targetZ) - this.position.z;
  13635. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  13636. var vy = dy * this.cameraAcceleration;
  13637. var vz = dz * this.cameraAcceleration * 2;
  13638. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  13639. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13640. }
  13641. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  13642. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13643. }
  13644. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  13645. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13646. }
  13647. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  13648. this.setTarget(cameraTarget.position);
  13649. };
  13650. FollowCamera.prototype._checkInputs = function () {
  13651. _super.prototype._checkInputs.call(this);
  13652. this.follow(this.target);
  13653. };
  13654. FollowCamera.prototype.getTypeName = function () {
  13655. return "FollowCamera";
  13656. };
  13657. __decorate([
  13658. BABYLON.serialize()
  13659. ], FollowCamera.prototype, "radius", void 0);
  13660. __decorate([
  13661. BABYLON.serialize()
  13662. ], FollowCamera.prototype, "rotationOffset", void 0);
  13663. __decorate([
  13664. BABYLON.serialize()
  13665. ], FollowCamera.prototype, "heightOffset", void 0);
  13666. __decorate([
  13667. BABYLON.serialize()
  13668. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  13669. __decorate([
  13670. BABYLON.serialize()
  13671. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  13672. __decorate([
  13673. BABYLON.serializeAsMeshReference("lockedTargetId")
  13674. ], FollowCamera.prototype, "target", void 0);
  13675. return FollowCamera;
  13676. })(BABYLON.TargetCamera);
  13677. BABYLON.FollowCamera = FollowCamera;
  13678. var ArcFollowCamera = (function (_super) {
  13679. __extends(ArcFollowCamera, _super);
  13680. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  13681. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13682. this.alpha = alpha;
  13683. this.beta = beta;
  13684. this.radius = radius;
  13685. this.target = target;
  13686. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  13687. this.follow();
  13688. }
  13689. ArcFollowCamera.prototype.follow = function () {
  13690. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  13691. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  13692. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  13693. this.position = this.target.position.add(this._cartesianCoordinates);
  13694. this.setTarget(this.target.position);
  13695. };
  13696. ArcFollowCamera.prototype._checkInputs = function () {
  13697. _super.prototype._checkInputs.call(this);
  13698. this.follow();
  13699. };
  13700. ArcFollowCamera.prototype.getTypeName = function () {
  13701. return "ArcFollowCamera";
  13702. };
  13703. return ArcFollowCamera;
  13704. })(BABYLON.TargetCamera);
  13705. BABYLON.ArcFollowCamera = ArcFollowCamera;
  13706. })(BABYLON || (BABYLON = {}));
  13707. var BABYLON;
  13708. (function (BABYLON) {
  13709. // We're mainly based on the logic defined into the FreeCamera code
  13710. var TouchCamera = (function (_super) {
  13711. __extends(TouchCamera, _super);
  13712. //-- end properties for backward compatibility for inputs
  13713. function TouchCamera(name, position, scene) {
  13714. _super.call(this, name, position, scene);
  13715. this.inputs.addTouch();
  13716. this._setupInputs();
  13717. }
  13718. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  13719. //-- Begin properties for backward compatibility for inputs
  13720. get: function () {
  13721. var touch = this.inputs.attached["touch"];
  13722. if (touch)
  13723. return touch.touchAngularSensibility;
  13724. },
  13725. set: function (value) {
  13726. var touch = this.inputs.attached["touch"];
  13727. if (touch)
  13728. touch.touchAngularSensibility = value;
  13729. },
  13730. enumerable: true,
  13731. configurable: true
  13732. });
  13733. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  13734. get: function () {
  13735. var touch = this.inputs.attached["touch"];
  13736. if (touch)
  13737. return touch.touchMoveSensibility;
  13738. },
  13739. set: function (value) {
  13740. var touch = this.inputs.attached["touch"];
  13741. if (touch)
  13742. touch.touchMoveSensibility = value;
  13743. },
  13744. enumerable: true,
  13745. configurable: true
  13746. });
  13747. TouchCamera.prototype.getTypeName = function () {
  13748. return "TouchCamera";
  13749. };
  13750. TouchCamera.prototype._setupInputs = function () {
  13751. var mouse = this.inputs.attached["mouse"];
  13752. if (mouse) {
  13753. mouse.touchEnabled = false;
  13754. }
  13755. };
  13756. return TouchCamera;
  13757. })(BABYLON.FreeCamera);
  13758. BABYLON.TouchCamera = TouchCamera;
  13759. })(BABYLON || (BABYLON = {}));
  13760. var BABYLON;
  13761. (function (BABYLON) {
  13762. var ArcRotateCamera = (function (_super) {
  13763. __extends(ArcRotateCamera, _super);
  13764. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  13765. var _this = this;
  13766. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13767. this.inertialAlphaOffset = 0;
  13768. this.inertialBetaOffset = 0;
  13769. this.inertialRadiusOffset = 0;
  13770. this.lowerAlphaLimit = null;
  13771. this.upperAlphaLimit = null;
  13772. this.lowerBetaLimit = 0.01;
  13773. this.upperBetaLimit = Math.PI;
  13774. this.lowerRadiusLimit = null;
  13775. this.upperRadiusLimit = null;
  13776. this.inertialPanningX = 0;
  13777. this.inertialPanningY = 0;
  13778. //-- end properties for backward compatibility for inputs
  13779. this.zoomOnFactor = 1;
  13780. this.targetScreenOffset = BABYLON.Vector2.Zero();
  13781. this.allowUpsideDown = true;
  13782. this._viewMatrix = new BABYLON.Matrix();
  13783. // Panning
  13784. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  13785. this.checkCollisions = false;
  13786. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13787. this._collider = new BABYLON.Collider();
  13788. this._previousPosition = BABYLON.Vector3.Zero();
  13789. this._collisionVelocity = BABYLON.Vector3.Zero();
  13790. this._newPosition = BABYLON.Vector3.Zero();
  13791. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13792. if (collidedMesh === void 0) { collidedMesh = null; }
  13793. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  13794. newPosition.multiplyInPlace(_this._collider.radius);
  13795. }
  13796. if (!collidedMesh) {
  13797. _this._previousPosition.copyFrom(_this.position);
  13798. }
  13799. else {
  13800. _this.setPosition(newPosition);
  13801. if (_this.onCollide) {
  13802. _this.onCollide(collidedMesh);
  13803. }
  13804. }
  13805. // Recompute because of constraints
  13806. var cosa = Math.cos(_this.alpha);
  13807. var sina = Math.sin(_this.alpha);
  13808. var cosb = Math.cos(_this.beta);
  13809. var sinb = Math.sin(_this.beta);
  13810. if (sinb === 0) {
  13811. sinb = 0.0001;
  13812. }
  13813. var target = _this._getTargetPosition();
  13814. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  13815. _this.position.copyFrom(_this._newPosition);
  13816. var up = _this.upVector;
  13817. if (_this.allowUpsideDown && _this.beta < 0) {
  13818. up = up.clone();
  13819. up = up.negate();
  13820. }
  13821. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  13822. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  13823. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  13824. _this._collisionTriggered = false;
  13825. };
  13826. if (!target) {
  13827. this.target = BABYLON.Vector3.Zero();
  13828. }
  13829. else {
  13830. this.target = target;
  13831. }
  13832. this.alpha = alpha;
  13833. this.beta = beta;
  13834. this.radius = radius;
  13835. this.getViewMatrix();
  13836. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  13837. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  13838. }
  13839. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  13840. //-- begin properties for backward compatibility for inputs
  13841. get: function () {
  13842. var pointers = this.inputs.attached["pointers"];
  13843. if (pointers)
  13844. return pointers.angularSensibilityX;
  13845. },
  13846. set: function (value) {
  13847. var pointers = this.inputs.attached["pointers"];
  13848. if (pointers) {
  13849. pointers.angularSensibilityX = value;
  13850. }
  13851. },
  13852. enumerable: true,
  13853. configurable: true
  13854. });
  13855. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  13856. get: function () {
  13857. var pointers = this.inputs.attached["pointers"];
  13858. if (pointers)
  13859. return pointers.angularSensibilityY;
  13860. },
  13861. set: function (value) {
  13862. var pointers = this.inputs.attached["pointers"];
  13863. if (pointers) {
  13864. pointers.angularSensibilityY = value;
  13865. }
  13866. },
  13867. enumerable: true,
  13868. configurable: true
  13869. });
  13870. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  13871. get: function () {
  13872. var pointers = this.inputs.attached["pointers"];
  13873. if (pointers)
  13874. return pointers.pinchPrecision;
  13875. },
  13876. set: function (value) {
  13877. var pointers = this.inputs.attached["pointers"];
  13878. if (pointers) {
  13879. pointers.pinchPrecision = value;
  13880. }
  13881. },
  13882. enumerable: true,
  13883. configurable: true
  13884. });
  13885. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  13886. get: function () {
  13887. var pointers = this.inputs.attached["pointers"];
  13888. if (pointers)
  13889. return pointers.panningSensibility;
  13890. },
  13891. set: function (value) {
  13892. var pointers = this.inputs.attached["pointers"];
  13893. if (pointers) {
  13894. pointers.panningSensibility = value;
  13895. }
  13896. },
  13897. enumerable: true,
  13898. configurable: true
  13899. });
  13900. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  13901. get: function () {
  13902. var keyboard = this.inputs.attached["keyboard"];
  13903. if (keyboard)
  13904. return keyboard.keysUp;
  13905. },
  13906. set: function (value) {
  13907. var keyboard = this.inputs.attached["keyboard"];
  13908. if (keyboard)
  13909. keyboard.keysUp = value;
  13910. },
  13911. enumerable: true,
  13912. configurable: true
  13913. });
  13914. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  13915. get: function () {
  13916. var keyboard = this.inputs.attached["keyboard"];
  13917. if (keyboard)
  13918. return keyboard.keysDown;
  13919. },
  13920. set: function (value) {
  13921. var keyboard = this.inputs.attached["keyboard"];
  13922. if (keyboard)
  13923. keyboard.keysDown = value;
  13924. },
  13925. enumerable: true,
  13926. configurable: true
  13927. });
  13928. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  13929. get: function () {
  13930. var keyboard = this.inputs.attached["keyboard"];
  13931. if (keyboard)
  13932. return keyboard.keysLeft;
  13933. },
  13934. set: function (value) {
  13935. var keyboard = this.inputs.attached["keyboard"];
  13936. if (keyboard)
  13937. keyboard.keysLeft = value;
  13938. },
  13939. enumerable: true,
  13940. configurable: true
  13941. });
  13942. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  13943. get: function () {
  13944. var keyboard = this.inputs.attached["keyboard"];
  13945. if (keyboard)
  13946. return keyboard.keysRight;
  13947. },
  13948. set: function (value) {
  13949. var keyboard = this.inputs.attached["keyboard"];
  13950. if (keyboard)
  13951. keyboard.keysRight = value;
  13952. },
  13953. enumerable: true,
  13954. configurable: true
  13955. });
  13956. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  13957. get: function () {
  13958. var mousewheel = this.inputs.attached["mousewheel"];
  13959. if (mousewheel)
  13960. return mousewheel.wheelPrecision;
  13961. },
  13962. set: function (value) {
  13963. var mousewheel = this.inputs.attached["mousewheel"];
  13964. if (mousewheel)
  13965. mousewheel.wheelPrecision = value;
  13966. },
  13967. enumerable: true,
  13968. configurable: true
  13969. });
  13970. // Cache
  13971. ArcRotateCamera.prototype._initCache = function () {
  13972. _super.prototype._initCache.call(this);
  13973. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13974. this._cache.alpha = undefined;
  13975. this._cache.beta = undefined;
  13976. this._cache.radius = undefined;
  13977. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  13978. };
  13979. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  13980. if (!ignoreParentClass) {
  13981. _super.prototype._updateCache.call(this);
  13982. }
  13983. this._cache.target.copyFrom(this._getTargetPosition());
  13984. this._cache.alpha = this.alpha;
  13985. this._cache.beta = this.beta;
  13986. this._cache.radius = this.radius;
  13987. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  13988. };
  13989. ArcRotateCamera.prototype._getTargetPosition = function () {
  13990. if (this.target.getAbsolutePosition) {
  13991. return this.target.getAbsolutePosition();
  13992. }
  13993. return this.target;
  13994. };
  13995. // Synchronized
  13996. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13997. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13998. return false;
  13999. return this._cache.target.equals(this.target)
  14000. && this._cache.alpha === this.alpha
  14001. && this._cache.beta === this.beta
  14002. && this._cache.radius === this.radius
  14003. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  14004. };
  14005. // Methods
  14006. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  14007. var _this = this;
  14008. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  14009. this._useCtrlForPanning = useCtrlForPanning;
  14010. this.inputs.attachElement(element, noPreventDefault);
  14011. this._reset = function () {
  14012. _this.inertialAlphaOffset = 0;
  14013. _this.inertialBetaOffset = 0;
  14014. _this.inertialRadiusOffset = 0;
  14015. };
  14016. };
  14017. ArcRotateCamera.prototype.detachControl = function (element) {
  14018. this.inputs.detachElement(element);
  14019. if (this._reset) {
  14020. this._reset();
  14021. }
  14022. };
  14023. ArcRotateCamera.prototype._checkInputs = function () {
  14024. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  14025. if (this._collisionTriggered) {
  14026. return;
  14027. }
  14028. this.inputs.checkInputs();
  14029. // Inertia
  14030. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  14031. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  14032. this.beta += this.inertialBetaOffset;
  14033. this.radius -= this.inertialRadiusOffset;
  14034. this.inertialAlphaOffset *= this.inertia;
  14035. this.inertialBetaOffset *= this.inertia;
  14036. this.inertialRadiusOffset *= this.inertia;
  14037. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  14038. this.inertialAlphaOffset = 0;
  14039. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  14040. this.inertialBetaOffset = 0;
  14041. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  14042. this.inertialRadiusOffset = 0;
  14043. }
  14044. // Panning inertia
  14045. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  14046. if (!this._localDirection) {
  14047. this._localDirection = BABYLON.Vector3.Zero();
  14048. this._transformedDirection = BABYLON.Vector3.Zero();
  14049. }
  14050. this.inertialPanningX *= this.inertia;
  14051. this.inertialPanningY *= this.inertia;
  14052. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  14053. this.inertialPanningX = 0;
  14054. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  14055. this.inertialPanningY = 0;
  14056. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  14057. this._localDirection.multiplyInPlace(this.panningAxis);
  14058. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  14059. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  14060. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  14061. if (!this.panningAxis.y) {
  14062. this._transformedDirection.y = 0;
  14063. }
  14064. if (!this.target.getAbsolutePosition) {
  14065. this.target.addInPlace(this._transformedDirection);
  14066. }
  14067. }
  14068. // Limits
  14069. this._checkLimits();
  14070. _super.prototype._checkInputs.call(this);
  14071. };
  14072. ArcRotateCamera.prototype._checkLimits = function () {
  14073. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  14074. if (this.allowUpsideDown && this.beta > Math.PI) {
  14075. this.beta = this.beta - (2 * Math.PI);
  14076. }
  14077. }
  14078. else {
  14079. if (this.beta < this.lowerBetaLimit) {
  14080. this.beta = this.lowerBetaLimit;
  14081. }
  14082. }
  14083. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  14084. if (this.allowUpsideDown && this.beta < -Math.PI) {
  14085. this.beta = this.beta + (2 * Math.PI);
  14086. }
  14087. }
  14088. else {
  14089. if (this.beta > this.upperBetaLimit) {
  14090. this.beta = this.upperBetaLimit;
  14091. }
  14092. }
  14093. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  14094. this.alpha = this.lowerAlphaLimit;
  14095. }
  14096. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  14097. this.alpha = this.upperAlphaLimit;
  14098. }
  14099. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  14100. this.radius = this.lowerRadiusLimit;
  14101. }
  14102. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  14103. this.radius = this.upperRadiusLimit;
  14104. }
  14105. };
  14106. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  14107. var radiusv3 = this.position.subtract(this._getTargetPosition());
  14108. this.radius = radiusv3.length();
  14109. // Alpha
  14110. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  14111. if (radiusv3.z < 0) {
  14112. this.alpha = 2 * Math.PI - this.alpha;
  14113. }
  14114. // Beta
  14115. this.beta = Math.acos(radiusv3.y / this.radius);
  14116. this._checkLimits();
  14117. };
  14118. ArcRotateCamera.prototype.setPosition = function (position) {
  14119. if (this.position.equals(position)) {
  14120. return;
  14121. }
  14122. this.position = position;
  14123. this.rebuildAnglesAndRadius();
  14124. };
  14125. ArcRotateCamera.prototype.setTarget = function (target) {
  14126. if (this._getTargetPosition().equals(target)) {
  14127. return;
  14128. }
  14129. this.target = target;
  14130. this.rebuildAnglesAndRadius();
  14131. };
  14132. ArcRotateCamera.prototype._getViewMatrix = function () {
  14133. // Compute
  14134. var cosa = Math.cos(this.alpha);
  14135. var sina = Math.sin(this.alpha);
  14136. var cosb = Math.cos(this.beta);
  14137. var sinb = Math.sin(this.beta);
  14138. if (sinb === 0) {
  14139. sinb = 0.0001;
  14140. }
  14141. var target = this._getTargetPosition();
  14142. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  14143. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  14144. this._collider.radius = this.collisionRadius;
  14145. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  14146. this._collisionTriggered = true;
  14147. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14148. }
  14149. else {
  14150. this.position.copyFrom(this._newPosition);
  14151. var up = this.upVector;
  14152. if (this.allowUpsideDown && this.beta < 0) {
  14153. up = up.clone();
  14154. up = up.negate();
  14155. }
  14156. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  14157. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  14158. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  14159. }
  14160. return this._viewMatrix;
  14161. };
  14162. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  14163. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14164. meshes = meshes || this.getScene().meshes;
  14165. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  14166. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  14167. this.radius = distance * this.zoomOnFactor;
  14168. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  14169. };
  14170. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  14171. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14172. var meshesOrMinMaxVector;
  14173. var distance;
  14174. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  14175. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  14176. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  14177. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  14178. }
  14179. else {
  14180. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  14181. distance = meshesOrMinMaxVectorAndDistance.distance;
  14182. }
  14183. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  14184. if (!doNotUpdateMaxZ) {
  14185. this.maxZ = distance * 2;
  14186. }
  14187. };
  14188. /**
  14189. * @override
  14190. * Override Camera.createRigCamera
  14191. */
  14192. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14193. var alphaShift;
  14194. switch (this.cameraRigMode) {
  14195. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14196. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14197. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14198. case BABYLON.Camera.RIG_MODE_VR:
  14199. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  14200. break;
  14201. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14202. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  14203. break;
  14204. }
  14205. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  14206. rigCam._cameraRigParams = {};
  14207. return rigCam;
  14208. };
  14209. /**
  14210. * @override
  14211. * Override Camera._updateRigCameras
  14212. */
  14213. ArcRotateCamera.prototype._updateRigCameras = function () {
  14214. var camLeft = this._rigCameras[0];
  14215. var camRight = this._rigCameras[1];
  14216. camLeft.beta = camRight.beta = this.beta;
  14217. camLeft.radius = camRight.radius = this.radius;
  14218. switch (this.cameraRigMode) {
  14219. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14220. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14221. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14222. case BABYLON.Camera.RIG_MODE_VR:
  14223. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14224. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14225. break;
  14226. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14227. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14228. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14229. break;
  14230. }
  14231. _super.prototype._updateRigCameras.call(this);
  14232. };
  14233. ArcRotateCamera.prototype.dispose = function () {
  14234. this.inputs.clear();
  14235. _super.prototype.dispose.call(this);
  14236. };
  14237. ArcRotateCamera.prototype.getTypeName = function () {
  14238. return "ArcRotateCamera";
  14239. };
  14240. __decorate([
  14241. BABYLON.serialize()
  14242. ], ArcRotateCamera.prototype, "alpha", void 0);
  14243. __decorate([
  14244. BABYLON.serialize()
  14245. ], ArcRotateCamera.prototype, "beta", void 0);
  14246. __decorate([
  14247. BABYLON.serialize()
  14248. ], ArcRotateCamera.prototype, "radius", void 0);
  14249. __decorate([
  14250. BABYLON.serializeAsVector3()
  14251. ], ArcRotateCamera.prototype, "target", void 0);
  14252. __decorate([
  14253. BABYLON.serialize()
  14254. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  14255. __decorate([
  14256. BABYLON.serialize()
  14257. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  14258. __decorate([
  14259. BABYLON.serialize()
  14260. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  14261. __decorate([
  14262. BABYLON.serialize()
  14263. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  14264. __decorate([
  14265. BABYLON.serialize()
  14266. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  14267. __decorate([
  14268. BABYLON.serialize()
  14269. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  14270. __decorate([
  14271. BABYLON.serialize()
  14272. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  14273. __decorate([
  14274. BABYLON.serialize()
  14275. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  14276. __decorate([
  14277. BABYLON.serialize()
  14278. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  14279. __decorate([
  14280. BABYLON.serialize()
  14281. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  14282. __decorate([
  14283. BABYLON.serialize()
  14284. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  14285. __decorate([
  14286. BABYLON.serialize()
  14287. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  14288. __decorate([
  14289. BABYLON.serialize()
  14290. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  14291. return ArcRotateCamera;
  14292. })(BABYLON.TargetCamera);
  14293. BABYLON.ArcRotateCamera = ArcRotateCamera;
  14294. })(BABYLON || (BABYLON = {}));
  14295. var BABYLON;
  14296. (function (BABYLON) {
  14297. var ArcRotateCameraInputsManager = (function (_super) {
  14298. __extends(ArcRotateCameraInputsManager, _super);
  14299. function ArcRotateCameraInputsManager(camera) {
  14300. _super.call(this, camera);
  14301. }
  14302. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  14303. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  14304. return this;
  14305. };
  14306. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  14307. this.add(new BABYLON.ArcRotateCameraPointersInput());
  14308. return this;
  14309. };
  14310. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  14311. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  14312. return this;
  14313. };
  14314. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  14315. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  14316. return this;
  14317. };
  14318. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  14319. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  14320. return this;
  14321. };
  14322. return ArcRotateCameraInputsManager;
  14323. })(BABYLON.CameraInputsManager);
  14324. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  14325. })(BABYLON || (BABYLON = {}));
  14326. var BABYLON;
  14327. (function (BABYLON) {
  14328. var RenderingManager = (function () {
  14329. function RenderingManager(scene) {
  14330. this._renderingGroups = new Array();
  14331. this._scene = scene;
  14332. }
  14333. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  14334. if (this._scene._activeParticleSystems.length === 0) {
  14335. return;
  14336. }
  14337. // Particles
  14338. var activeCamera = this._scene.activeCamera;
  14339. var beforeParticlesDate = BABYLON.Tools.Now;
  14340. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14341. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14342. if (particleSystem.renderingGroupId !== index) {
  14343. continue;
  14344. }
  14345. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14346. continue;
  14347. }
  14348. this._clearDepthBuffer();
  14349. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14350. this._scene._activeParticles += particleSystem.render();
  14351. }
  14352. }
  14353. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  14354. };
  14355. RenderingManager.prototype._renderSprites = function (index) {
  14356. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  14357. return;
  14358. }
  14359. // Sprites
  14360. var activeCamera = this._scene.activeCamera;
  14361. var beforeSpritessDate = BABYLON.Tools.Now;
  14362. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  14363. var spriteManager = this._scene.spriteManagers[id];
  14364. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14365. this._clearDepthBuffer();
  14366. spriteManager.render();
  14367. }
  14368. }
  14369. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  14370. };
  14371. RenderingManager.prototype._clearDepthBuffer = function () {
  14372. if (this._depthBufferAlreadyCleaned) {
  14373. return;
  14374. }
  14375. this._scene.getEngine().clear(0, false, true);
  14376. this._depthBufferAlreadyCleaned = true;
  14377. };
  14378. RenderingManager.prototype._renderSpritesAndParticles = function () {
  14379. if (this._currentRenderSprites) {
  14380. this._renderSprites(this._currentIndex);
  14381. }
  14382. if (this._currentRenderParticles) {
  14383. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  14384. }
  14385. };
  14386. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14387. this._currentActiveMeshes = activeMeshes;
  14388. this._currentRenderParticles = renderParticles;
  14389. this._currentRenderSprites = renderSprites;
  14390. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14391. this._depthBufferAlreadyCleaned = index == 0;
  14392. var renderingGroup = this._renderingGroups[index];
  14393. var needToStepBack = false;
  14394. this._currentIndex = index;
  14395. if (renderingGroup) {
  14396. this._clearDepthBuffer();
  14397. if (!renderingGroup.onBeforeTransparentRendering) {
  14398. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  14399. }
  14400. if (!renderingGroup.render(customRenderFunction)) {
  14401. this._renderingGroups.splice(index, 1);
  14402. needToStepBack = true;
  14403. this._renderSpritesAndParticles();
  14404. }
  14405. }
  14406. else {
  14407. this._renderSpritesAndParticles();
  14408. }
  14409. if (needToStepBack) {
  14410. index--;
  14411. }
  14412. }
  14413. };
  14414. RenderingManager.prototype.reset = function () {
  14415. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  14416. if (renderingGroup) {
  14417. renderingGroup.prepare();
  14418. }
  14419. });
  14420. };
  14421. RenderingManager.prototype.dispatch = function (subMesh) {
  14422. var mesh = subMesh.getMesh();
  14423. var renderingGroupId = mesh.renderingGroupId || 0;
  14424. if (!this._renderingGroups[renderingGroupId]) {
  14425. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  14426. }
  14427. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14428. };
  14429. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14430. return RenderingManager;
  14431. })();
  14432. BABYLON.RenderingManager = RenderingManager;
  14433. })(BABYLON || (BABYLON = {}));
  14434. var BABYLON;
  14435. (function (BABYLON) {
  14436. var RenderingGroup = (function () {
  14437. function RenderingGroup(index, scene) {
  14438. this.index = index;
  14439. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14440. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14441. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14442. this._scene = scene;
  14443. }
  14444. RenderingGroup.prototype.render = function (customRenderFunction) {
  14445. if (customRenderFunction) {
  14446. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14447. return true;
  14448. }
  14449. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  14450. if (this.onBeforeTransparentRendering) {
  14451. this.onBeforeTransparentRendering();
  14452. }
  14453. return false;
  14454. }
  14455. var engine = this._scene.getEngine();
  14456. // Opaque
  14457. var subIndex;
  14458. var submesh;
  14459. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  14460. submesh = this._opaqueSubMeshes.data[subIndex];
  14461. submesh.render(false);
  14462. }
  14463. // Alpha test
  14464. engine.setAlphaTesting(true);
  14465. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  14466. submesh = this._alphaTestSubMeshes.data[subIndex];
  14467. submesh.render(false);
  14468. }
  14469. engine.setAlphaTesting(false);
  14470. if (this.onBeforeTransparentRendering) {
  14471. this.onBeforeTransparentRendering();
  14472. }
  14473. // Transparent
  14474. if (this._transparentSubMeshes.length) {
  14475. // Sorting
  14476. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  14477. submesh = this._transparentSubMeshes.data[subIndex];
  14478. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  14479. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  14480. }
  14481. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  14482. sortedArray.sort(function (a, b) {
  14483. // Alpha index first
  14484. if (a._alphaIndex > b._alphaIndex) {
  14485. return 1;
  14486. }
  14487. if (a._alphaIndex < b._alphaIndex) {
  14488. return -1;
  14489. }
  14490. // Then distance to camera
  14491. if (a._distanceToCamera < b._distanceToCamera) {
  14492. return 1;
  14493. }
  14494. if (a._distanceToCamera > b._distanceToCamera) {
  14495. return -1;
  14496. }
  14497. return 0;
  14498. });
  14499. // Rendering
  14500. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14501. submesh = sortedArray[subIndex];
  14502. submesh.render(true);
  14503. }
  14504. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14505. }
  14506. return true;
  14507. };
  14508. RenderingGroup.prototype.prepare = function () {
  14509. this._opaqueSubMeshes.reset();
  14510. this._transparentSubMeshes.reset();
  14511. this._alphaTestSubMeshes.reset();
  14512. };
  14513. RenderingGroup.prototype.dispatch = function (subMesh) {
  14514. var material = subMesh.getMaterial();
  14515. var mesh = subMesh.getMesh();
  14516. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14517. this._transparentSubMeshes.push(subMesh);
  14518. }
  14519. else if (material.needAlphaTesting()) {
  14520. this._alphaTestSubMeshes.push(subMesh);
  14521. }
  14522. else {
  14523. this._opaqueSubMeshes.push(subMesh); // Opaque
  14524. }
  14525. };
  14526. return RenderingGroup;
  14527. })();
  14528. BABYLON.RenderingGroup = RenderingGroup;
  14529. })(BABYLON || (BABYLON = {}));
  14530. var BABYLON;
  14531. (function (BABYLON) {
  14532. var PointerEventTypes = (function () {
  14533. function PointerEventTypes() {
  14534. }
  14535. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14536. get: function () {
  14537. return PointerEventTypes._POINTERDOWN;
  14538. },
  14539. enumerable: true,
  14540. configurable: true
  14541. });
  14542. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14543. get: function () {
  14544. return PointerEventTypes._POINTERUP;
  14545. },
  14546. enumerable: true,
  14547. configurable: true
  14548. });
  14549. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14550. get: function () {
  14551. return PointerEventTypes._POINTERMOVE;
  14552. },
  14553. enumerable: true,
  14554. configurable: true
  14555. });
  14556. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14557. get: function () {
  14558. return PointerEventTypes._POINTERWHEEL;
  14559. },
  14560. enumerable: true,
  14561. configurable: true
  14562. });
  14563. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14564. get: function () {
  14565. return PointerEventTypes._POINTERPICK;
  14566. },
  14567. enumerable: true,
  14568. configurable: true
  14569. });
  14570. PointerEventTypes._POINTERDOWN = 0x01;
  14571. PointerEventTypes._POINTERUP = 0x02;
  14572. PointerEventTypes._POINTERMOVE = 0x04;
  14573. PointerEventTypes._POINTERWHEEL = 0x08;
  14574. PointerEventTypes._POINTERPICK = 0x10;
  14575. return PointerEventTypes;
  14576. })();
  14577. BABYLON.PointerEventTypes = PointerEventTypes;
  14578. var PointerInfoBase = (function () {
  14579. function PointerInfoBase(type, event) {
  14580. this.type = type;
  14581. this.event = event;
  14582. }
  14583. return PointerInfoBase;
  14584. })();
  14585. BABYLON.PointerInfoBase = PointerInfoBase;
  14586. /**
  14587. * This class is used to store pointer related info for the onPrePointerObservable event.
  14588. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  14589. */
  14590. var PointerInfoPre = (function (_super) {
  14591. __extends(PointerInfoPre, _super);
  14592. function PointerInfoPre(type, event, localX, localY) {
  14593. _super.call(this, type, event);
  14594. this.skipOnPointerObservable = false;
  14595. this.localPosition = new BABYLON.Vector2(localX, localY);
  14596. }
  14597. return PointerInfoPre;
  14598. })(PointerInfoBase);
  14599. BABYLON.PointerInfoPre = PointerInfoPre;
  14600. /**
  14601. * This type contains all the data related to a pointer event in Babylon.js.
  14602. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  14603. */
  14604. var PointerInfo = (function (_super) {
  14605. __extends(PointerInfo, _super);
  14606. function PointerInfo(type, event, pickInfo) {
  14607. _super.call(this, type, event);
  14608. this.pickInfo = pickInfo;
  14609. }
  14610. return PointerInfo;
  14611. })(PointerInfoBase);
  14612. BABYLON.PointerInfo = PointerInfo;
  14613. /**
  14614. * Represents a scene to be rendered by the engine.
  14615. * @see http://doc.babylonjs.com/page.php?p=21911
  14616. */
  14617. var Scene = (function () {
  14618. /**
  14619. * @constructor
  14620. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14621. */
  14622. function Scene(engine) {
  14623. // Members
  14624. this.autoClear = true;
  14625. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14626. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14627. this.forceWireframe = false;
  14628. this.forcePointsCloud = false;
  14629. this.forceShowBoundingBoxes = false;
  14630. this.animationsEnabled = true;
  14631. this.constantlyUpdateMeshUnderPointer = false;
  14632. // Events
  14633. /**
  14634. * An event triggered when the scene is disposed.
  14635. * @type {BABYLON.Observable}
  14636. */
  14637. this.onDisposeObservable = new BABYLON.Observable();
  14638. /**
  14639. * An event triggered before rendering the scene
  14640. * @type {BABYLON.Observable}
  14641. */
  14642. this.onBeforeRenderObservable = new BABYLON.Observable();
  14643. /**
  14644. * An event triggered after rendering the scene
  14645. * @type {BABYLON.Observable}
  14646. */
  14647. this.onAfterRenderObservable = new BABYLON.Observable();
  14648. /**
  14649. * An event triggered when the scene is ready
  14650. * @type {BABYLON.Observable}
  14651. */
  14652. this.onReadyObservable = new BABYLON.Observable();
  14653. /**
  14654. * An event triggered before rendering a camera
  14655. * @type {BABYLON.Observable}
  14656. */
  14657. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14658. /**
  14659. * An event triggered after rendering a camera
  14660. * @type {BABYLON.Observable}
  14661. */
  14662. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14663. /**
  14664. * An event triggered when a camera is created
  14665. * @type {BABYLON.Observable}
  14666. */
  14667. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14668. /**
  14669. * An event triggered when a camera is removed
  14670. * @type {BABYLON.Observable}
  14671. */
  14672. this.onCameraRemovedObservable = new BABYLON.Observable();
  14673. /**
  14674. * An event triggered when a light is created
  14675. * @type {BABYLON.Observable}
  14676. */
  14677. this.onNewLightAddedObservable = new BABYLON.Observable();
  14678. /**
  14679. * An event triggered when a light is removed
  14680. * @type {BABYLON.Observable}
  14681. */
  14682. this.onLightRemovedObservable = new BABYLON.Observable();
  14683. /**
  14684. * An event triggered when a geometry is created
  14685. * @type {BABYLON.Observable}
  14686. */
  14687. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14688. /**
  14689. * An event triggered when a geometry is removed
  14690. * @type {BABYLON.Observable}
  14691. */
  14692. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14693. /**
  14694. * An event triggered when a mesh is created
  14695. * @type {BABYLON.Observable}
  14696. */
  14697. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14698. /**
  14699. * An event triggered when a mesh is removed
  14700. * @type {BABYLON.Observable}
  14701. */
  14702. this.onMeshRemovedObservable = new BABYLON.Observable();
  14703. // Animations
  14704. this.animations = [];
  14705. /**
  14706. * This observable event is triggered when any mouse event registered during Scene.attach() is called BEFORE the 3D engine to process anything (mesh/sprite picking for instance).
  14707. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  14708. */
  14709. this.onPrePointerObservable = new BABYLON.Observable();
  14710. /**
  14711. * Observable event triggered each time an input event is received from the rendering canvas
  14712. */
  14713. this.onPointerObservable = new BABYLON.Observable();
  14714. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  14715. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14716. this._startingPointerTime = 0;
  14717. // Fog
  14718. /**
  14719. * is fog enabled on this scene.
  14720. * @type {boolean}
  14721. */
  14722. this.fogEnabled = true;
  14723. this.fogMode = Scene.FOGMODE_NONE;
  14724. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14725. this.fogDensity = 0.1;
  14726. this.fogStart = 0;
  14727. this.fogEnd = 1000.0;
  14728. // Lights
  14729. /**
  14730. * is shadow enabled on this scene.
  14731. * @type {boolean}
  14732. */
  14733. this.shadowsEnabled = true;
  14734. /**
  14735. * is light enabled on this scene.
  14736. * @type {boolean}
  14737. */
  14738. this.lightsEnabled = true;
  14739. /**
  14740. * All of the lights added to this scene.
  14741. * @see BABYLON.Light
  14742. * @type {BABYLON.Light[]}
  14743. */
  14744. this.lights = new Array();
  14745. // Cameras
  14746. /**
  14747. * All of the cameras added to this scene.
  14748. * @see BABYLON.Camera
  14749. * @type {BABYLON.Camera[]}
  14750. */
  14751. this.cameras = new Array();
  14752. this.activeCameras = new Array();
  14753. // Meshes
  14754. /**
  14755. * All of the (abstract) meshes added to this scene.
  14756. * @see BABYLON.AbstractMesh
  14757. * @type {BABYLON.AbstractMesh[]}
  14758. */
  14759. this.meshes = new Array();
  14760. // Geometries
  14761. this._geometries = new Array();
  14762. this.materials = new Array();
  14763. this.multiMaterials = new Array();
  14764. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14765. // Textures
  14766. this.texturesEnabled = true;
  14767. this.textures = new Array();
  14768. // Particles
  14769. this.particlesEnabled = true;
  14770. this.particleSystems = new Array();
  14771. // Sprites
  14772. this.spritesEnabled = true;
  14773. this.spriteManagers = new Array();
  14774. // Layers
  14775. this.layers = new Array();
  14776. // Skeletons
  14777. this.skeletonsEnabled = true;
  14778. this.skeletons = new Array();
  14779. // Lens flares
  14780. this.lensFlaresEnabled = true;
  14781. this.lensFlareSystems = new Array();
  14782. // Collisions
  14783. this.collisionsEnabled = true;
  14784. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14785. // Postprocesses
  14786. this.postProcessesEnabled = true;
  14787. // Customs render targets
  14788. this.renderTargetsEnabled = true;
  14789. this.dumpNextRenderTargets = false;
  14790. this.customRenderTargets = new Array();
  14791. // Imported meshes
  14792. this.importedMeshesFiles = new Array();
  14793. // Probes
  14794. this.probesEnabled = true;
  14795. this.reflectionProbes = new Array();
  14796. this._actionManagers = new Array();
  14797. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14798. // Procedural textures
  14799. this.proceduralTexturesEnabled = true;
  14800. this._proceduralTextures = new Array();
  14801. this.soundTracks = new Array();
  14802. this._audioEnabled = true;
  14803. this._headphone = false;
  14804. this._totalVertices = 0;
  14805. this._activeIndices = 0;
  14806. this._activeParticles = 0;
  14807. this._lastFrameDuration = 0;
  14808. this._evaluateActiveMeshesDuration = 0;
  14809. this._renderTargetsDuration = 0;
  14810. this._particlesDuration = 0;
  14811. this._renderDuration = 0;
  14812. this._spritesDuration = 0;
  14813. this._animationRatio = 0;
  14814. this._renderId = 0;
  14815. this._executeWhenReadyTimeoutId = -1;
  14816. this._intermediateRendering = false;
  14817. this._toBeDisposed = new BABYLON.SmartArray(256);
  14818. this._pendingData = []; //ANY
  14819. this._activeMeshes = new BABYLON.SmartArray(256);
  14820. this._processedMaterials = new BABYLON.SmartArray(256);
  14821. this._renderTargets = new BABYLON.SmartArray(256);
  14822. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14823. this._activeSkeletons = new BABYLON.SmartArray(32);
  14824. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14825. this._activeBones = 0;
  14826. this._activeAnimatables = new Array();
  14827. this._transformMatrix = BABYLON.Matrix.Zero();
  14828. this._edgesRenderers = new BABYLON.SmartArray(16);
  14829. this._uniqueIdCounter = 0;
  14830. this._engine = engine;
  14831. engine.scenes.push(this);
  14832. this._renderingManager = new BABYLON.RenderingManager(this);
  14833. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14834. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14835. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  14836. if (BABYLON.OutlineRenderer) {
  14837. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14838. }
  14839. this.attachControl();
  14840. if (BABYLON.SoundTrack) {
  14841. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14842. }
  14843. //simplification queue
  14844. if (BABYLON.SimplificationQueue) {
  14845. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14846. }
  14847. //collision coordinator initialization. For now legacy per default.
  14848. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14849. }
  14850. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14851. get: function () {
  14852. return Scene._FOGMODE_NONE;
  14853. },
  14854. enumerable: true,
  14855. configurable: true
  14856. });
  14857. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14858. get: function () {
  14859. return Scene._FOGMODE_EXP;
  14860. },
  14861. enumerable: true,
  14862. configurable: true
  14863. });
  14864. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14865. get: function () {
  14866. return Scene._FOGMODE_EXP2;
  14867. },
  14868. enumerable: true,
  14869. configurable: true
  14870. });
  14871. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14872. get: function () {
  14873. return Scene._FOGMODE_LINEAR;
  14874. },
  14875. enumerable: true,
  14876. configurable: true
  14877. });
  14878. Object.defineProperty(Scene.prototype, "onDispose", {
  14879. set: function (callback) {
  14880. if (this._onDisposeObserver) {
  14881. this.onDisposeObservable.remove(this._onDisposeObserver);
  14882. }
  14883. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14884. },
  14885. enumerable: true,
  14886. configurable: true
  14887. });
  14888. Object.defineProperty(Scene.prototype, "beforeRender", {
  14889. set: function (callback) {
  14890. if (this._onBeforeRenderObserver) {
  14891. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14892. }
  14893. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14894. },
  14895. enumerable: true,
  14896. configurable: true
  14897. });
  14898. Object.defineProperty(Scene.prototype, "afterRender", {
  14899. set: function (callback) {
  14900. if (this._onAfterRenderObserver) {
  14901. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14902. }
  14903. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14904. },
  14905. enumerable: true,
  14906. configurable: true
  14907. });
  14908. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14909. set: function (callback) {
  14910. if (this._onBeforeCameraRenderObserver) {
  14911. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14912. }
  14913. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14914. },
  14915. enumerable: true,
  14916. configurable: true
  14917. });
  14918. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14919. set: function (callback) {
  14920. if (this._onAfterCameraRenderObserver) {
  14921. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14922. }
  14923. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14924. },
  14925. enumerable: true,
  14926. configurable: true
  14927. });
  14928. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  14929. get: function () {
  14930. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  14931. },
  14932. enumerable: true,
  14933. configurable: true
  14934. });
  14935. Object.defineProperty(Scene.prototype, "debugLayer", {
  14936. // Properties
  14937. get: function () {
  14938. if (!this._debugLayer) {
  14939. this._debugLayer = new BABYLON.DebugLayer(this);
  14940. }
  14941. return this._debugLayer;
  14942. },
  14943. enumerable: true,
  14944. configurable: true
  14945. });
  14946. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14947. get: function () {
  14948. return this._workerCollisions;
  14949. },
  14950. set: function (enabled) {
  14951. enabled = (enabled && !!Worker);
  14952. this._workerCollisions = enabled;
  14953. if (this.collisionCoordinator) {
  14954. this.collisionCoordinator.destroy();
  14955. }
  14956. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14957. this.collisionCoordinator.init(this);
  14958. },
  14959. enumerable: true,
  14960. configurable: true
  14961. });
  14962. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  14963. get: function () {
  14964. return this._selectionOctree;
  14965. },
  14966. enumerable: true,
  14967. configurable: true
  14968. });
  14969. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14970. /**
  14971. * The mesh that is currently under the pointer.
  14972. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14973. */
  14974. get: function () {
  14975. return this._pointerOverMesh;
  14976. },
  14977. enumerable: true,
  14978. configurable: true
  14979. });
  14980. Object.defineProperty(Scene.prototype, "pointerX", {
  14981. /**
  14982. * Current on-screen X position of the pointer
  14983. * @return {number} X position of the pointer
  14984. */
  14985. get: function () {
  14986. return this._pointerX;
  14987. },
  14988. enumerable: true,
  14989. configurable: true
  14990. });
  14991. Object.defineProperty(Scene.prototype, "pointerY", {
  14992. /**
  14993. * Current on-screen Y position of the pointer
  14994. * @return {number} Y position of the pointer
  14995. */
  14996. get: function () {
  14997. return this._pointerY;
  14998. },
  14999. enumerable: true,
  15000. configurable: true
  15001. });
  15002. Scene.prototype.getCachedMaterial = function () {
  15003. return this._cachedMaterial;
  15004. };
  15005. Scene.prototype.getBoundingBoxRenderer = function () {
  15006. return this._boundingBoxRenderer;
  15007. };
  15008. Scene.prototype.getOutlineRenderer = function () {
  15009. return this._outlineRenderer;
  15010. };
  15011. Scene.prototype.getEngine = function () {
  15012. return this._engine;
  15013. };
  15014. Scene.prototype.getTotalVertices = function () {
  15015. return this._totalVertices;
  15016. };
  15017. Scene.prototype.getActiveIndices = function () {
  15018. return this._activeIndices;
  15019. };
  15020. Scene.prototype.getActiveParticles = function () {
  15021. return this._activeParticles;
  15022. };
  15023. Scene.prototype.getActiveBones = function () {
  15024. return this._activeBones;
  15025. };
  15026. // Stats
  15027. Scene.prototype.getLastFrameDuration = function () {
  15028. return this._lastFrameDuration;
  15029. };
  15030. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15031. return this._evaluateActiveMeshesDuration;
  15032. };
  15033. Scene.prototype.getActiveMeshes = function () {
  15034. return this._activeMeshes;
  15035. };
  15036. Scene.prototype.getRenderTargetsDuration = function () {
  15037. return this._renderTargetsDuration;
  15038. };
  15039. Scene.prototype.getRenderDuration = function () {
  15040. return this._renderDuration;
  15041. };
  15042. Scene.prototype.getParticlesDuration = function () {
  15043. return this._particlesDuration;
  15044. };
  15045. Scene.prototype.getSpritesDuration = function () {
  15046. return this._spritesDuration;
  15047. };
  15048. Scene.prototype.getAnimationRatio = function () {
  15049. return this._animationRatio;
  15050. };
  15051. Scene.prototype.getRenderId = function () {
  15052. return this._renderId;
  15053. };
  15054. Scene.prototype.incrementRenderId = function () {
  15055. this._renderId++;
  15056. };
  15057. Scene.prototype._updatePointerPosition = function (evt) {
  15058. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15059. this._pointerX = evt.clientX - canvasRect.left;
  15060. this._pointerY = evt.clientY - canvasRect.top;
  15061. this._unTranslatedPointerX = this._pointerX;
  15062. this._unTranslatedPointerY = this._pointerY;
  15063. if (this.cameraToUseForPointers) {
  15064. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15065. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15066. }
  15067. };
  15068. // Pointers handling
  15069. /**
  15070. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15071. * @param attachUp defines if you want to attach events to pointerup
  15072. * @param attachDown defines if you want to attach events to pointerdown
  15073. * @param attachMove defines if you want to attach events to pointermove
  15074. */
  15075. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15076. var _this = this;
  15077. if (attachUp === void 0) { attachUp = true; }
  15078. if (attachDown === void 0) { attachDown = true; }
  15079. if (attachMove === void 0) { attachMove = true; }
  15080. var spritePredicate = function (sprite) {
  15081. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  15082. };
  15083. this._onPointerMove = function (evt) {
  15084. _this._updatePointerPosition(evt);
  15085. // PreObservable support
  15086. if (_this.onPrePointerObservable.hasObservers()) {
  15087. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15088. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15089. _this.onPrePointerObservable.notifyObservers(pi, type);
  15090. if (pi.skipOnPointerObservable) {
  15091. return;
  15092. }
  15093. }
  15094. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15095. return;
  15096. }
  15097. var canvas = _this._engine.getRenderingCanvas();
  15098. if (!_this.pointerMovePredicate) {
  15099. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  15100. }
  15101. // Meshes
  15102. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  15103. if (pickResult.hit && pickResult.pickedMesh) {
  15104. _this.setPointerOverSprite(null);
  15105. _this.setPointerOverMesh(pickResult.pickedMesh);
  15106. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  15107. canvas.style.cursor = "pointer";
  15108. }
  15109. else {
  15110. canvas.style.cursor = "";
  15111. }
  15112. }
  15113. else {
  15114. _this.setPointerOverMesh(null);
  15115. // Sprites
  15116. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15117. if (pickResult.hit && pickResult.pickedSprite) {
  15118. canvas.style.cursor = "pointer";
  15119. _this.setPointerOverSprite(pickResult.pickedSprite);
  15120. }
  15121. else {
  15122. _this.setPointerOverSprite(null);
  15123. // Restore pointer
  15124. canvas.style.cursor = "";
  15125. }
  15126. }
  15127. if (_this.onPointerMove) {
  15128. _this.onPointerMove(evt, pickResult);
  15129. }
  15130. if (_this.onPointerObservable.hasObservers()) {
  15131. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15132. var pi = new PointerInfo(type, evt, pickResult);
  15133. _this.onPointerObservable.notifyObservers(pi, type);
  15134. }
  15135. };
  15136. this._onPointerDown = function (evt) {
  15137. _this._updatePointerPosition(evt);
  15138. // PreObservable support
  15139. if (_this.onPrePointerObservable.hasObservers()) {
  15140. var type = PointerEventTypes.POINTERDOWN;
  15141. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15142. _this.onPrePointerObservable.notifyObservers(pi, type);
  15143. if (pi.skipOnPointerObservable) {
  15144. return;
  15145. }
  15146. }
  15147. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15148. return;
  15149. }
  15150. _this._startingPointerPosition.x = _this._pointerX;
  15151. _this._startingPointerPosition.y = _this._pointerY;
  15152. _this._startingPointerTime = new Date().getTime();
  15153. if (!_this.pointerDownPredicate) {
  15154. _this.pointerDownPredicate = function (mesh) {
  15155. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  15156. };
  15157. }
  15158. // Meshes
  15159. _this._pickedDownMesh = null;
  15160. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15161. if (pickResult.hit && pickResult.pickedMesh) {
  15162. if (pickResult.pickedMesh.actionManager) {
  15163. _this._pickedDownMesh = pickResult.pickedMesh;
  15164. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  15165. switch (evt.button) {
  15166. case 0:
  15167. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15168. break;
  15169. case 1:
  15170. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15171. break;
  15172. case 2:
  15173. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15174. break;
  15175. }
  15176. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15177. }
  15178. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15179. var that = _this;
  15180. window.setTimeout(function () {
  15181. var pickResult = that.pick(that._unTranslatedPointerX, that._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  15182. if (pickResult.hit && pickResult.pickedMesh) {
  15183. if (pickResult.pickedMesh.actionManager) {
  15184. if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
  15185. that._startingPointerTime = 0;
  15186. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15187. }
  15188. }
  15189. }
  15190. }, BABYLON.ActionManager.LongPressDelay);
  15191. }
  15192. }
  15193. }
  15194. if (_this.onPointerDown) {
  15195. _this.onPointerDown(evt, pickResult);
  15196. }
  15197. if (_this.onPointerObservable.hasObservers()) {
  15198. var type = PointerEventTypes.POINTERDOWN;
  15199. var pi = new PointerInfo(type, evt, pickResult);
  15200. _this.onPointerObservable.notifyObservers(pi, type);
  15201. }
  15202. // Sprites
  15203. _this._pickedDownSprite = null;
  15204. if (_this.spriteManagers.length > 0) {
  15205. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15206. if (pickResult.hit && pickResult.pickedSprite) {
  15207. if (pickResult.pickedSprite.actionManager) {
  15208. _this._pickedDownSprite = pickResult.pickedSprite;
  15209. switch (evt.button) {
  15210. case 0:
  15211. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15212. break;
  15213. case 1:
  15214. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15215. break;
  15216. case 2:
  15217. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15218. break;
  15219. }
  15220. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15221. }
  15222. }
  15223. }
  15224. };
  15225. this._onPointerUp = function (evt) {
  15226. _this._updatePointerPosition(evt);
  15227. // PreObservable support
  15228. if (_this.onPrePointerObservable.hasObservers()) {
  15229. var type = PointerEventTypes.POINTERUP;
  15230. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15231. _this.onPrePointerObservable.notifyObservers(pi, type);
  15232. if (pi.skipOnPointerObservable) {
  15233. return;
  15234. }
  15235. }
  15236. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15237. return;
  15238. }
  15239. if (!_this.pointerUpPredicate) {
  15240. _this.pointerUpPredicate = function (mesh) {
  15241. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  15242. };
  15243. }
  15244. // Meshes
  15245. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  15246. if (pickResult.hit && pickResult.pickedMesh) {
  15247. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  15248. if (_this.onPointerPick) {
  15249. _this.onPointerPick(evt, pickResult);
  15250. }
  15251. if (_this.onPointerObservable.hasObservers()) {
  15252. var type = PointerEventTypes.POINTERPICK;
  15253. var pi = new PointerInfo(type, evt, pickResult);
  15254. _this.onPointerObservable.notifyObservers(pi, type);
  15255. }
  15256. }
  15257. if (pickResult.pickedMesh.actionManager) {
  15258. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15259. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15260. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15261. }
  15262. }
  15263. }
  15264. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  15265. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  15266. }
  15267. if (_this.onPointerUp) {
  15268. _this.onPointerUp(evt, pickResult);
  15269. }
  15270. if (_this.onPointerObservable.hasObservers()) {
  15271. var type = PointerEventTypes.POINTERUP;
  15272. var pi = new PointerInfo(type, evt, pickResult);
  15273. _this.onPointerObservable.notifyObservers(pi, type);
  15274. }
  15275. _this._startingPointerTime = 0;
  15276. // Sprites
  15277. if (_this.spriteManagers.length > 0) {
  15278. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15279. if (pickResult.hit && pickResult.pickedSprite) {
  15280. if (pickResult.pickedSprite.actionManager) {
  15281. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15282. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15283. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15284. }
  15285. }
  15286. }
  15287. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  15288. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  15289. }
  15290. }
  15291. };
  15292. this._onKeyDown = function (evt) {
  15293. if (_this.actionManager) {
  15294. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15295. }
  15296. };
  15297. this._onKeyUp = function (evt) {
  15298. if (_this.actionManager) {
  15299. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15300. }
  15301. };
  15302. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15303. if (attachMove) {
  15304. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  15305. // Wheel
  15306. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  15307. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  15308. }
  15309. if (attachDown) {
  15310. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  15311. }
  15312. if (attachUp) {
  15313. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  15314. }
  15315. BABYLON.Tools.RegisterTopRootEvents([
  15316. { name: "keydown", handler: this._onKeyDown },
  15317. { name: "keyup", handler: this._onKeyUp }
  15318. ]);
  15319. };
  15320. Scene.prototype.detachControl = function () {
  15321. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15322. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  15323. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  15324. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  15325. // Wheel
  15326. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  15327. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  15328. BABYLON.Tools.UnregisterTopRootEvents([
  15329. { name: "keydown", handler: this._onKeyDown },
  15330. { name: "keyup", handler: this._onKeyUp }
  15331. ]);
  15332. };
  15333. // Ready
  15334. Scene.prototype.isReady = function () {
  15335. if (this._pendingData.length > 0) {
  15336. return false;
  15337. }
  15338. var index;
  15339. for (index = 0; index < this._geometries.length; index++) {
  15340. var geometry = this._geometries[index];
  15341. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15342. return false;
  15343. }
  15344. }
  15345. for (index = 0; index < this.meshes.length; index++) {
  15346. var mesh = this.meshes[index];
  15347. if (!mesh.isReady()) {
  15348. return false;
  15349. }
  15350. var mat = mesh.material;
  15351. if (mat) {
  15352. if (!mat.isReady(mesh)) {
  15353. return false;
  15354. }
  15355. }
  15356. }
  15357. return true;
  15358. };
  15359. Scene.prototype.resetCachedMaterial = function () {
  15360. this._cachedMaterial = null;
  15361. };
  15362. Scene.prototype.registerBeforeRender = function (func) {
  15363. this.onBeforeRenderObservable.add(func);
  15364. };
  15365. Scene.prototype.unregisterBeforeRender = function (func) {
  15366. this.onBeforeRenderObservable.removeCallback(func);
  15367. };
  15368. Scene.prototype.registerAfterRender = function (func) {
  15369. this.onAfterRenderObservable.add(func);
  15370. };
  15371. Scene.prototype.unregisterAfterRender = function (func) {
  15372. this.onAfterRenderObservable.removeCallback(func);
  15373. };
  15374. Scene.prototype._addPendingData = function (data) {
  15375. this._pendingData.push(data);
  15376. };
  15377. Scene.prototype._removePendingData = function (data) {
  15378. var index = this._pendingData.indexOf(data);
  15379. if (index !== -1) {
  15380. this._pendingData.splice(index, 1);
  15381. }
  15382. };
  15383. Scene.prototype.getWaitingItemsCount = function () {
  15384. return this._pendingData.length;
  15385. };
  15386. /**
  15387. * Registers a function to be executed when the scene is ready.
  15388. * @param {Function} func - the function to be executed.
  15389. */
  15390. Scene.prototype.executeWhenReady = function (func) {
  15391. var _this = this;
  15392. this.onReadyObservable.add(func);
  15393. if (this._executeWhenReadyTimeoutId !== -1) {
  15394. return;
  15395. }
  15396. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15397. _this._checkIsReady();
  15398. }, 150);
  15399. };
  15400. Scene.prototype._checkIsReady = function () {
  15401. var _this = this;
  15402. if (this.isReady()) {
  15403. this.onReadyObservable.notifyObservers(this);
  15404. this.onReadyObservable.clear();
  15405. this._executeWhenReadyTimeoutId = -1;
  15406. return;
  15407. }
  15408. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15409. _this._checkIsReady();
  15410. }, 150);
  15411. };
  15412. // Animations
  15413. /**
  15414. * Will start the animation sequence of a given target
  15415. * @param target - the target
  15416. * @param {number} from - from which frame should animation start
  15417. * @param {number} to - till which frame should animation run.
  15418. * @param {boolean} [loop] - should the animation loop
  15419. * @param {number} [speedRatio] - the speed in which to run the animation
  15420. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15421. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15422. * @return {BABYLON.Animatable} the animatable object created for this animation
  15423. * @see BABYLON.Animatable
  15424. * @see http://doc.babylonjs.com/page.php?p=22081
  15425. */
  15426. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15427. if (speedRatio === void 0) { speedRatio = 1.0; }
  15428. this.stopAnimation(target);
  15429. if (!animatable) {
  15430. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15431. }
  15432. // Local animations
  15433. if (target.animations) {
  15434. animatable.appendAnimations(target, target.animations);
  15435. }
  15436. // Children animations
  15437. if (target.getAnimatables) {
  15438. var animatables = target.getAnimatables();
  15439. for (var index = 0; index < animatables.length; index++) {
  15440. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15441. }
  15442. }
  15443. animatable.reset();
  15444. return animatable;
  15445. };
  15446. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15447. if (speedRatio === undefined) {
  15448. speedRatio = 1.0;
  15449. }
  15450. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15451. return animatable;
  15452. };
  15453. Scene.prototype.getAnimatableByTarget = function (target) {
  15454. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15455. if (this._activeAnimatables[index].target === target) {
  15456. return this._activeAnimatables[index];
  15457. }
  15458. }
  15459. return null;
  15460. };
  15461. Object.defineProperty(Scene.prototype, "Animatables", {
  15462. get: function () {
  15463. return this._activeAnimatables;
  15464. },
  15465. enumerable: true,
  15466. configurable: true
  15467. });
  15468. /**
  15469. * Will stop the animation of the given target
  15470. * @param target - the target
  15471. * @see beginAnimation
  15472. */
  15473. Scene.prototype.stopAnimation = function (target) {
  15474. var animatable = this.getAnimatableByTarget(target);
  15475. if (animatable) {
  15476. animatable.stop();
  15477. }
  15478. };
  15479. Scene.prototype._animate = function () {
  15480. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  15481. return;
  15482. }
  15483. if (!this._animationStartDate) {
  15484. if (this._pendingData.length > 0) {
  15485. return;
  15486. }
  15487. this._animationStartDate = BABYLON.Tools.Now;
  15488. }
  15489. // Getting time
  15490. var now = BABYLON.Tools.Now;
  15491. var delay = now - this._animationStartDate;
  15492. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15493. this._activeAnimatables[index]._animate(delay);
  15494. }
  15495. };
  15496. // Matrix
  15497. Scene.prototype.getViewMatrix = function () {
  15498. return this._viewMatrix;
  15499. };
  15500. Scene.prototype.getProjectionMatrix = function () {
  15501. return this._projectionMatrix;
  15502. };
  15503. Scene.prototype.getTransformMatrix = function () {
  15504. return this._transformMatrix;
  15505. };
  15506. Scene.prototype.setTransformMatrix = function (view, projection) {
  15507. this._viewMatrix = view;
  15508. this._projectionMatrix = projection;
  15509. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15510. };
  15511. // Methods
  15512. Scene.prototype.addMesh = function (newMesh) {
  15513. newMesh.uniqueId = this._uniqueIdCounter++;
  15514. var position = this.meshes.push(newMesh);
  15515. //notify the collision coordinator
  15516. this.collisionCoordinator.onMeshAdded(newMesh);
  15517. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  15518. };
  15519. Scene.prototype.removeMesh = function (toRemove) {
  15520. var index = this.meshes.indexOf(toRemove);
  15521. if (index !== -1) {
  15522. // Remove from the scene if mesh found
  15523. this.meshes.splice(index, 1);
  15524. }
  15525. //notify the collision coordinator
  15526. this.collisionCoordinator.onMeshRemoved(toRemove);
  15527. this.onMeshRemovedObservable.notifyObservers(toRemove);
  15528. return index;
  15529. };
  15530. Scene.prototype.removeSkeleton = function (toRemove) {
  15531. var index = this.skeletons.indexOf(toRemove);
  15532. if (index !== -1) {
  15533. // Remove from the scene if mesh found
  15534. this.skeletons.splice(index, 1);
  15535. }
  15536. return index;
  15537. };
  15538. Scene.prototype.removeLight = function (toRemove) {
  15539. var index = this.lights.indexOf(toRemove);
  15540. if (index !== -1) {
  15541. // Remove from the scene if mesh found
  15542. this.lights.splice(index, 1);
  15543. }
  15544. this.onLightRemovedObservable.notifyObservers(toRemove);
  15545. return index;
  15546. };
  15547. Scene.prototype.removeCamera = function (toRemove) {
  15548. var index = this.cameras.indexOf(toRemove);
  15549. if (index !== -1) {
  15550. // Remove from the scene if mesh found
  15551. this.cameras.splice(index, 1);
  15552. }
  15553. // Remove from activeCameras
  15554. var index2 = this.activeCameras.indexOf(toRemove);
  15555. if (index2 !== -1) {
  15556. // Remove from the scene if mesh found
  15557. this.activeCameras.splice(index2, 1);
  15558. }
  15559. // Reset the activeCamera
  15560. if (this.activeCamera === toRemove) {
  15561. if (this.cameras.length > 0) {
  15562. this.activeCamera = this.cameras[0];
  15563. }
  15564. else {
  15565. this.activeCamera = null;
  15566. }
  15567. }
  15568. this.onCameraRemovedObservable.notifyObservers(toRemove);
  15569. return index;
  15570. };
  15571. Scene.prototype.addLight = function (newLight) {
  15572. newLight.uniqueId = this._uniqueIdCounter++;
  15573. var position = this.lights.push(newLight);
  15574. this.onNewLightAddedObservable.notifyObservers(newLight);
  15575. };
  15576. Scene.prototype.addCamera = function (newCamera) {
  15577. newCamera.uniqueId = this._uniqueIdCounter++;
  15578. var position = this.cameras.push(newCamera);
  15579. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  15580. };
  15581. /**
  15582. * Switch active camera
  15583. * @param {Camera} newCamera - new active camera
  15584. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  15585. */
  15586. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  15587. if (attachControl === void 0) { attachControl = true; }
  15588. var canvas = this._engine.getRenderingCanvas();
  15589. this.activeCamera.detachControl(canvas);
  15590. this.activeCamera = newCamera;
  15591. if (attachControl) {
  15592. newCamera.attachControl(canvas);
  15593. }
  15594. };
  15595. /**
  15596. * sets the active camera of the scene using its ID
  15597. * @param {string} id - the camera's ID
  15598. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15599. * @see activeCamera
  15600. */
  15601. Scene.prototype.setActiveCameraByID = function (id) {
  15602. var camera = this.getCameraByID(id);
  15603. if (camera) {
  15604. this.activeCamera = camera;
  15605. return camera;
  15606. }
  15607. return null;
  15608. };
  15609. /**
  15610. * sets the active camera of the scene using its name
  15611. * @param {string} name - the camera's name
  15612. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15613. * @see activeCamera
  15614. */
  15615. Scene.prototype.setActiveCameraByName = function (name) {
  15616. var camera = this.getCameraByName(name);
  15617. if (camera) {
  15618. this.activeCamera = camera;
  15619. return camera;
  15620. }
  15621. return null;
  15622. };
  15623. /**
  15624. * get a material using its id
  15625. * @param {string} the material's ID
  15626. * @return {BABYLON.Material|null} the material or null if none found.
  15627. */
  15628. Scene.prototype.getMaterialByID = function (id) {
  15629. for (var index = 0; index < this.materials.length; index++) {
  15630. if (this.materials[index].id === id) {
  15631. return this.materials[index];
  15632. }
  15633. }
  15634. return null;
  15635. };
  15636. /**
  15637. * get a material using its name
  15638. * @param {string} the material's name
  15639. * @return {BABYLON.Material|null} the material or null if none found.
  15640. */
  15641. Scene.prototype.getMaterialByName = function (name) {
  15642. for (var index = 0; index < this.materials.length; index++) {
  15643. if (this.materials[index].name === name) {
  15644. return this.materials[index];
  15645. }
  15646. }
  15647. return null;
  15648. };
  15649. Scene.prototype.getLensFlareSystemByName = function (name) {
  15650. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15651. if (this.lensFlareSystems[index].name === name) {
  15652. return this.lensFlareSystems[index];
  15653. }
  15654. }
  15655. return null;
  15656. };
  15657. Scene.prototype.getLensFlareSystemByID = function (id) {
  15658. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15659. if (this.lensFlareSystems[index].id === id) {
  15660. return this.lensFlareSystems[index];
  15661. }
  15662. }
  15663. return null;
  15664. };
  15665. Scene.prototype.getCameraByID = function (id) {
  15666. for (var index = 0; index < this.cameras.length; index++) {
  15667. if (this.cameras[index].id === id) {
  15668. return this.cameras[index];
  15669. }
  15670. }
  15671. return null;
  15672. };
  15673. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  15674. for (var index = 0; index < this.cameras.length; index++) {
  15675. if (this.cameras[index].uniqueId === uniqueId) {
  15676. return this.cameras[index];
  15677. }
  15678. }
  15679. return null;
  15680. };
  15681. /**
  15682. * get a camera using its name
  15683. * @param {string} the camera's name
  15684. * @return {BABYLON.Camera|null} the camera or null if none found.
  15685. */
  15686. Scene.prototype.getCameraByName = function (name) {
  15687. for (var index = 0; index < this.cameras.length; index++) {
  15688. if (this.cameras[index].name === name) {
  15689. return this.cameras[index];
  15690. }
  15691. }
  15692. return null;
  15693. };
  15694. /**
  15695. * get a bone using its id
  15696. * @param {string} the bone's id
  15697. * @return {BABYLON.Bone|null} the bone or null if not found
  15698. */
  15699. Scene.prototype.getBoneByID = function (id) {
  15700. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15701. var skeleton = this.skeletons[skeletonIndex];
  15702. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15703. if (skeleton.bones[boneIndex].id === id) {
  15704. return skeleton.bones[boneIndex];
  15705. }
  15706. }
  15707. }
  15708. return null;
  15709. };
  15710. /**
  15711. * get a bone using its id
  15712. * @param {string} the bone's name
  15713. * @return {BABYLON.Bone|null} the bone or null if not found
  15714. */
  15715. Scene.prototype.getBoneByName = function (name) {
  15716. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15717. var skeleton = this.skeletons[skeletonIndex];
  15718. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15719. if (skeleton.bones[boneIndex].name === name) {
  15720. return skeleton.bones[boneIndex];
  15721. }
  15722. }
  15723. }
  15724. return null;
  15725. };
  15726. /**
  15727. * get a light node using its name
  15728. * @param {string} the light's name
  15729. * @return {BABYLON.Light|null} the light or null if none found.
  15730. */
  15731. Scene.prototype.getLightByName = function (name) {
  15732. for (var index = 0; index < this.lights.length; index++) {
  15733. if (this.lights[index].name === name) {
  15734. return this.lights[index];
  15735. }
  15736. }
  15737. return null;
  15738. };
  15739. /**
  15740. * get a light node using its ID
  15741. * @param {string} the light's id
  15742. * @return {BABYLON.Light|null} the light or null if none found.
  15743. */
  15744. Scene.prototype.getLightByID = function (id) {
  15745. for (var index = 0; index < this.lights.length; index++) {
  15746. if (this.lights[index].id === id) {
  15747. return this.lights[index];
  15748. }
  15749. }
  15750. return null;
  15751. };
  15752. /**
  15753. * get a light node using its scene-generated unique ID
  15754. * @param {number} the light's unique id
  15755. * @return {BABYLON.Light|null} the light or null if none found.
  15756. */
  15757. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  15758. for (var index = 0; index < this.lights.length; index++) {
  15759. if (this.lights[index].uniqueId === uniqueId) {
  15760. return this.lights[index];
  15761. }
  15762. }
  15763. return null;
  15764. };
  15765. /**
  15766. * get a particle system by id
  15767. * @param id {number} the particle system id
  15768. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  15769. */
  15770. Scene.prototype.getParticleSystemByID = function (id) {
  15771. for (var index = 0; index < this.particleSystems.length; index++) {
  15772. if (this.particleSystems[index].id === id) {
  15773. return this.particleSystems[index];
  15774. }
  15775. }
  15776. return null;
  15777. };
  15778. /**
  15779. * get a geometry using its ID
  15780. * @param {string} the geometry's id
  15781. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  15782. */
  15783. Scene.prototype.getGeometryByID = function (id) {
  15784. for (var index = 0; index < this._geometries.length; index++) {
  15785. if (this._geometries[index].id === id) {
  15786. return this._geometries[index];
  15787. }
  15788. }
  15789. return null;
  15790. };
  15791. /**
  15792. * add a new geometry to this scene.
  15793. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  15794. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  15795. * @return {boolean} was the geometry added or not
  15796. */
  15797. Scene.prototype.pushGeometry = function (geometry, force) {
  15798. if (!force && this.getGeometryByID(geometry.id)) {
  15799. return false;
  15800. }
  15801. this._geometries.push(geometry);
  15802. //notify the collision coordinator
  15803. this.collisionCoordinator.onGeometryAdded(geometry);
  15804. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  15805. return true;
  15806. };
  15807. /**
  15808. * Removes an existing geometry
  15809. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  15810. * @return {boolean} was the geometry removed or not
  15811. */
  15812. Scene.prototype.removeGeometry = function (geometry) {
  15813. var index = this._geometries.indexOf(geometry);
  15814. if (index > -1) {
  15815. this._geometries.splice(index, 1);
  15816. //notify the collision coordinator
  15817. this.collisionCoordinator.onGeometryDeleted(geometry);
  15818. this.onGeometryRemovedObservable.notifyObservers(geometry);
  15819. return true;
  15820. }
  15821. return false;
  15822. };
  15823. Scene.prototype.getGeometries = function () {
  15824. return this._geometries;
  15825. };
  15826. /**
  15827. * Get the first added mesh found of a given ID
  15828. * @param {string} id - the id to search for
  15829. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15830. */
  15831. Scene.prototype.getMeshByID = function (id) {
  15832. for (var index = 0; index < this.meshes.length; index++) {
  15833. if (this.meshes[index].id === id) {
  15834. return this.meshes[index];
  15835. }
  15836. }
  15837. return null;
  15838. };
  15839. Scene.prototype.getMeshesByID = function (id) {
  15840. return this.meshes.filter(function (m) {
  15841. return m.id === id;
  15842. });
  15843. };
  15844. /**
  15845. * Get a mesh with its auto-generated unique id
  15846. * @param {number} uniqueId - the unique id to search for
  15847. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15848. */
  15849. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  15850. for (var index = 0; index < this.meshes.length; index++) {
  15851. if (this.meshes[index].uniqueId === uniqueId) {
  15852. return this.meshes[index];
  15853. }
  15854. }
  15855. return null;
  15856. };
  15857. /**
  15858. * Get a the last added mesh found of a given ID
  15859. * @param {string} id - the id to search for
  15860. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15861. */
  15862. Scene.prototype.getLastMeshByID = function (id) {
  15863. for (var index = this.meshes.length - 1; index >= 0; index--) {
  15864. if (this.meshes[index].id === id) {
  15865. return this.meshes[index];
  15866. }
  15867. }
  15868. return null;
  15869. };
  15870. /**
  15871. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  15872. * @param {string} id - the id to search for
  15873. * @return {BABYLON.Node|null} the node found or null if not found at all.
  15874. */
  15875. Scene.prototype.getLastEntryByID = function (id) {
  15876. var index;
  15877. for (index = this.meshes.length - 1; index >= 0; index--) {
  15878. if (this.meshes[index].id === id) {
  15879. return this.meshes[index];
  15880. }
  15881. }
  15882. for (index = this.cameras.length - 1; index >= 0; index--) {
  15883. if (this.cameras[index].id === id) {
  15884. return this.cameras[index];
  15885. }
  15886. }
  15887. for (index = this.lights.length - 1; index >= 0; index--) {
  15888. if (this.lights[index].id === id) {
  15889. return this.lights[index];
  15890. }
  15891. }
  15892. return null;
  15893. };
  15894. Scene.prototype.getNodeByID = function (id) {
  15895. var mesh = this.getMeshByID(id);
  15896. if (mesh) {
  15897. return mesh;
  15898. }
  15899. var light = this.getLightByID(id);
  15900. if (light) {
  15901. return light;
  15902. }
  15903. var camera = this.getCameraByID(id);
  15904. if (camera) {
  15905. return camera;
  15906. }
  15907. var bone = this.getBoneByID(id);
  15908. return bone;
  15909. };
  15910. Scene.prototype.getNodeByName = function (name) {
  15911. var mesh = this.getMeshByName(name);
  15912. if (mesh) {
  15913. return mesh;
  15914. }
  15915. var light = this.getLightByName(name);
  15916. if (light) {
  15917. return light;
  15918. }
  15919. var camera = this.getCameraByName(name);
  15920. if (camera) {
  15921. return camera;
  15922. }
  15923. var bone = this.getBoneByName(name);
  15924. return bone;
  15925. };
  15926. Scene.prototype.getMeshByName = function (name) {
  15927. for (var index = 0; index < this.meshes.length; index++) {
  15928. if (this.meshes[index].name === name) {
  15929. return this.meshes[index];
  15930. }
  15931. }
  15932. return null;
  15933. };
  15934. Scene.prototype.getSoundByName = function (name) {
  15935. var index;
  15936. if (BABYLON.AudioEngine) {
  15937. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  15938. if (this.mainSoundTrack.soundCollection[index].name === name) {
  15939. return this.mainSoundTrack.soundCollection[index];
  15940. }
  15941. }
  15942. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  15943. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  15944. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  15945. return this.soundTracks[sdIndex].soundCollection[index];
  15946. }
  15947. }
  15948. }
  15949. }
  15950. return null;
  15951. };
  15952. Scene.prototype.getLastSkeletonByID = function (id) {
  15953. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  15954. if (this.skeletons[index].id === id) {
  15955. return this.skeletons[index];
  15956. }
  15957. }
  15958. return null;
  15959. };
  15960. Scene.prototype.getSkeletonById = function (id) {
  15961. for (var index = 0; index < this.skeletons.length; index++) {
  15962. if (this.skeletons[index].id === id) {
  15963. return this.skeletons[index];
  15964. }
  15965. }
  15966. return null;
  15967. };
  15968. Scene.prototype.getSkeletonByName = function (name) {
  15969. for (var index = 0; index < this.skeletons.length; index++) {
  15970. if (this.skeletons[index].name === name) {
  15971. return this.skeletons[index];
  15972. }
  15973. }
  15974. return null;
  15975. };
  15976. Scene.prototype.isActiveMesh = function (mesh) {
  15977. return (this._activeMeshes.indexOf(mesh) !== -1);
  15978. };
  15979. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  15980. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  15981. var material = subMesh.getMaterial();
  15982. if (mesh.showSubMeshesBoundingBox) {
  15983. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  15984. }
  15985. if (material) {
  15986. // Render targets
  15987. if (material.getRenderTargetTextures) {
  15988. if (this._processedMaterials.indexOf(material) === -1) {
  15989. this._processedMaterials.push(material);
  15990. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  15991. }
  15992. }
  15993. // Dispatch
  15994. this._activeIndices += subMesh.indexCount;
  15995. this._renderingManager.dispatch(subMesh);
  15996. }
  15997. }
  15998. };
  15999. Scene.prototype._isInIntermediateRendering = function () {
  16000. return this._intermediateRendering;
  16001. };
  16002. Scene.prototype._evaluateActiveMeshes = function () {
  16003. this.activeCamera._activeMeshes.reset();
  16004. this._activeMeshes.reset();
  16005. this._renderingManager.reset();
  16006. this._processedMaterials.reset();
  16007. this._activeParticleSystems.reset();
  16008. this._activeSkeletons.reset();
  16009. this._softwareSkinnedMeshes.reset();
  16010. this._boundingBoxRenderer.reset();
  16011. this._edgesRenderers.reset();
  16012. if (!this._frustumPlanes) {
  16013. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16014. }
  16015. else {
  16016. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16017. }
  16018. // Meshes
  16019. var meshes;
  16020. var len;
  16021. if (this._selectionOctree) {
  16022. var selection = this._selectionOctree.select(this._frustumPlanes);
  16023. meshes = selection.data;
  16024. len = selection.length;
  16025. }
  16026. else {
  16027. len = this.meshes.length;
  16028. meshes = this.meshes;
  16029. }
  16030. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16031. var mesh = meshes[meshIndex];
  16032. if (mesh.isBlocked) {
  16033. continue;
  16034. }
  16035. this._totalVertices += mesh.getTotalVertices();
  16036. if (!mesh.isReady() || !mesh.isEnabled()) {
  16037. continue;
  16038. }
  16039. mesh.computeWorldMatrix();
  16040. // Intersections
  16041. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  16042. this._meshesForIntersections.pushNoDuplicate(mesh);
  16043. }
  16044. // Switch to current LOD
  16045. var meshLOD = mesh.getLOD(this.activeCamera);
  16046. if (!meshLOD) {
  16047. continue;
  16048. }
  16049. mesh._preActivate();
  16050. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  16051. this._activeMeshes.push(mesh);
  16052. this.activeCamera._activeMeshes.push(mesh);
  16053. mesh._activate(this._renderId);
  16054. this._activeMesh(meshLOD);
  16055. }
  16056. }
  16057. // Particle systems
  16058. var beforeParticlesDate = BABYLON.Tools.Now;
  16059. if (this.particlesEnabled) {
  16060. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  16061. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  16062. var particleSystem = this.particleSystems[particleIndex];
  16063. if (!particleSystem.isStarted()) {
  16064. continue;
  16065. }
  16066. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  16067. this._activeParticleSystems.push(particleSystem);
  16068. particleSystem.animate();
  16069. }
  16070. }
  16071. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  16072. }
  16073. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  16074. };
  16075. Scene.prototype._activeMesh = function (mesh) {
  16076. if (mesh.skeleton && this.skeletonsEnabled) {
  16077. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  16078. mesh.skeleton.prepare();
  16079. }
  16080. if (!mesh.computeBonesUsingShaders) {
  16081. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  16082. }
  16083. }
  16084. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  16085. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  16086. }
  16087. if (mesh._edgesRenderer) {
  16088. this._edgesRenderers.push(mesh._edgesRenderer);
  16089. }
  16090. if (mesh && mesh.subMeshes) {
  16091. // Submeshes Octrees
  16092. var len;
  16093. var subMeshes;
  16094. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  16095. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  16096. len = intersections.length;
  16097. subMeshes = intersections.data;
  16098. }
  16099. else {
  16100. subMeshes = mesh.subMeshes;
  16101. len = subMeshes.length;
  16102. }
  16103. for (var subIndex = 0; subIndex < len; subIndex++) {
  16104. var subMesh = subMeshes[subIndex];
  16105. this._evaluateSubMesh(subMesh, mesh);
  16106. }
  16107. }
  16108. };
  16109. Scene.prototype.updateTransformMatrix = function (force) {
  16110. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  16111. };
  16112. Scene.prototype._renderForCamera = function (camera) {
  16113. var engine = this._engine;
  16114. this.activeCamera = camera;
  16115. if (!this.activeCamera)
  16116. throw new Error("Active camera not set");
  16117. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16118. // Viewport
  16119. engine.setViewport(this.activeCamera.viewport);
  16120. // Camera
  16121. this.resetCachedMaterial();
  16122. this._renderId++;
  16123. this.updateTransformMatrix();
  16124. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  16125. // Meshes
  16126. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  16127. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  16128. this._evaluateActiveMeshes();
  16129. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  16130. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  16131. // Software skinning
  16132. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  16133. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  16134. mesh.applySkeleton(mesh.skeleton);
  16135. }
  16136. // Render targets
  16137. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16138. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  16139. this._intermediateRendering = true;
  16140. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16141. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  16142. var renderTarget = this._renderTargets.data[renderIndex];
  16143. if (renderTarget._shouldRender()) {
  16144. this._renderId++;
  16145. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  16146. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  16147. }
  16148. }
  16149. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16150. this._intermediateRendering = false;
  16151. this._renderId++;
  16152. engine.restoreDefaultFramebuffer(); // Restore back buffer
  16153. }
  16154. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  16155. // Prepare Frame
  16156. this.postProcessManager._prepareFrame();
  16157. var beforeRenderDate = BABYLON.Tools.Now;
  16158. // Backgrounds
  16159. var layerIndex;
  16160. var layer;
  16161. if (this.layers.length) {
  16162. engine.setDepthBuffer(false);
  16163. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16164. layer = this.layers[layerIndex];
  16165. if (layer.isBackground) {
  16166. layer.render();
  16167. }
  16168. }
  16169. engine.setDepthBuffer(true);
  16170. }
  16171. // Render
  16172. BABYLON.Tools.StartPerformanceCounter("Main render");
  16173. this._renderingManager.render(null, null, true, true);
  16174. BABYLON.Tools.EndPerformanceCounter("Main render");
  16175. // Bounding boxes
  16176. this._boundingBoxRenderer.render();
  16177. // Edges
  16178. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16179. this._edgesRenderers.data[edgesRendererIndex].render();
  16180. }
  16181. // Lens flares
  16182. if (this.lensFlaresEnabled) {
  16183. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16184. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  16185. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  16186. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  16187. lensFlareSystem.render();
  16188. }
  16189. }
  16190. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16191. }
  16192. // Foregrounds
  16193. if (this.layers.length) {
  16194. engine.setDepthBuffer(false);
  16195. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16196. layer = this.layers[layerIndex];
  16197. if (!layer.isBackground) {
  16198. layer.render();
  16199. }
  16200. }
  16201. engine.setDepthBuffer(true);
  16202. }
  16203. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  16204. // Finalize frame
  16205. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  16206. // Update camera
  16207. this.activeCamera._updateFromScene();
  16208. // Reset some special arrays
  16209. this._renderTargets.reset();
  16210. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  16211. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16212. };
  16213. Scene.prototype._processSubCameras = function (camera) {
  16214. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  16215. this._renderForCamera(camera);
  16216. return;
  16217. }
  16218. // rig cameras
  16219. for (var index = 0; index < camera._rigCameras.length; index++) {
  16220. this._renderForCamera(camera._rigCameras[index]);
  16221. }
  16222. this.activeCamera = camera;
  16223. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  16224. // Update camera
  16225. this.activeCamera._updateFromScene();
  16226. };
  16227. Scene.prototype._checkIntersections = function () {
  16228. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  16229. var sourceMesh = this._meshesForIntersections.data[index];
  16230. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  16231. var action = sourceMesh.actionManager.actions[actionIndex];
  16232. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16233. var parameters = action.getTriggerParameter();
  16234. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  16235. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  16236. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  16237. if (areIntersecting && currentIntersectionInProgress === -1) {
  16238. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  16239. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16240. sourceMesh._intersectionsInProgress.push(otherMesh);
  16241. }
  16242. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16243. sourceMesh._intersectionsInProgress.push(otherMesh);
  16244. }
  16245. }
  16246. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  16247. //They intersected, and now they don't.
  16248. //is this trigger an exit trigger? execute an event.
  16249. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16250. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16251. }
  16252. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  16253. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16254. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  16255. }
  16256. }
  16257. }
  16258. }
  16259. }
  16260. };
  16261. Scene.prototype.render = function () {
  16262. var startDate = BABYLON.Tools.Now;
  16263. this._particlesDuration = 0;
  16264. this._spritesDuration = 0;
  16265. this._activeParticles = 0;
  16266. this._renderDuration = 0;
  16267. this._renderTargetsDuration = 0;
  16268. this._evaluateActiveMeshesDuration = 0;
  16269. this._totalVertices = 0;
  16270. this._activeIndices = 0;
  16271. this._activeBones = 0;
  16272. this.getEngine().resetDrawCalls();
  16273. this._meshesForIntersections.reset();
  16274. this.resetCachedMaterial();
  16275. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  16276. // Actions
  16277. if (this.actionManager) {
  16278. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  16279. }
  16280. //Simplification Queue
  16281. if (this.simplificationQueue && !this.simplificationQueue.running) {
  16282. this.simplificationQueue.executeNext();
  16283. }
  16284. // Animations
  16285. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  16286. this._animationRatio = deltaTime * (60.0 / 1000.0);
  16287. this._animate();
  16288. // Physics
  16289. if (this._physicsEngine) {
  16290. BABYLON.Tools.StartPerformanceCounter("Physics");
  16291. this._physicsEngine._step(deltaTime / 1000.0);
  16292. BABYLON.Tools.EndPerformanceCounter("Physics");
  16293. }
  16294. // Before render
  16295. this.onBeforeRenderObservable.notifyObservers(this);
  16296. // Customs render targets
  16297. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16298. var engine = this.getEngine();
  16299. var currentActiveCamera = this.activeCamera;
  16300. if (this.renderTargetsEnabled) {
  16301. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16302. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  16303. var renderTarget = this.customRenderTargets[customIndex];
  16304. if (renderTarget._shouldRender()) {
  16305. this._renderId++;
  16306. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  16307. if (!this.activeCamera)
  16308. throw new Error("Active camera not set");
  16309. // Viewport
  16310. engine.setViewport(this.activeCamera.viewport);
  16311. // Camera
  16312. this.updateTransformMatrix();
  16313. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  16314. }
  16315. }
  16316. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16317. this._renderId++;
  16318. }
  16319. if (this.customRenderTargets.length > 0) {
  16320. engine.restoreDefaultFramebuffer();
  16321. }
  16322. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  16323. this.activeCamera = currentActiveCamera;
  16324. // Procedural textures
  16325. if (this.proceduralTexturesEnabled) {
  16326. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16327. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  16328. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  16329. if (proceduralTexture._shouldRender()) {
  16330. proceduralTexture.render();
  16331. }
  16332. }
  16333. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16334. }
  16335. // Clear
  16336. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  16337. // Shadows
  16338. if (this.shadowsEnabled) {
  16339. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16340. var light = this.lights[lightIndex];
  16341. var shadowGenerator = light.getShadowGenerator();
  16342. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16343. this._renderTargets.push(shadowGenerator.getShadowMap());
  16344. }
  16345. }
  16346. }
  16347. // Depth renderer
  16348. if (this._depthRenderer) {
  16349. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16350. }
  16351. // RenderPipeline
  16352. this.postProcessRenderPipelineManager.update();
  16353. // Multi-cameras?
  16354. if (this.activeCameras.length > 0) {
  16355. var currentRenderId = this._renderId;
  16356. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16357. this._renderId = currentRenderId;
  16358. if (cameraIndex > 0) {
  16359. this._engine.clear(0, false, true);
  16360. }
  16361. this._processSubCameras(this.activeCameras[cameraIndex]);
  16362. }
  16363. }
  16364. else {
  16365. if (!this.activeCamera) {
  16366. throw new Error("No camera defined");
  16367. }
  16368. this._processSubCameras(this.activeCamera);
  16369. }
  16370. // Intersection checks
  16371. this._checkIntersections();
  16372. // Update the audio listener attached to the camera
  16373. if (BABYLON.AudioEngine) {
  16374. this._updateAudioParameters();
  16375. }
  16376. // After render
  16377. if (this.afterRender) {
  16378. this.afterRender();
  16379. }
  16380. this.onAfterRenderObservable.notifyObservers(this);
  16381. // Cleaning
  16382. for (var index = 0; index < this._toBeDisposed.length; index++) {
  16383. this._toBeDisposed.data[index].dispose();
  16384. this._toBeDisposed[index] = null;
  16385. }
  16386. this._toBeDisposed.reset();
  16387. if (this.dumpNextRenderTargets) {
  16388. this.dumpNextRenderTargets = false;
  16389. }
  16390. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  16391. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  16392. };
  16393. Scene.prototype._updateAudioParameters = function () {
  16394. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  16395. return;
  16396. }
  16397. var listeningCamera;
  16398. var audioEngine = BABYLON.Engine.audioEngine;
  16399. if (this.activeCameras.length > 0) {
  16400. listeningCamera = this.activeCameras[0];
  16401. }
  16402. else {
  16403. listeningCamera = this.activeCamera;
  16404. }
  16405. if (listeningCamera && audioEngine.canUseWebAudio) {
  16406. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  16407. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  16408. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  16409. cameraDirection.normalize();
  16410. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  16411. var i;
  16412. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16413. var sound = this.mainSoundTrack.soundCollection[i];
  16414. if (sound.useCustomAttenuation) {
  16415. sound.updateDistanceFromListener();
  16416. }
  16417. }
  16418. for (i = 0; i < this.soundTracks.length; i++) {
  16419. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16420. sound = this.soundTracks[i].soundCollection[j];
  16421. if (sound.useCustomAttenuation) {
  16422. sound.updateDistanceFromListener();
  16423. }
  16424. }
  16425. }
  16426. }
  16427. };
  16428. Object.defineProperty(Scene.prototype, "audioEnabled", {
  16429. // Audio
  16430. get: function () {
  16431. return this._audioEnabled;
  16432. },
  16433. set: function (value) {
  16434. this._audioEnabled = value;
  16435. if (BABYLON.AudioEngine) {
  16436. if (this._audioEnabled) {
  16437. this._enableAudio();
  16438. }
  16439. else {
  16440. this._disableAudio();
  16441. }
  16442. }
  16443. },
  16444. enumerable: true,
  16445. configurable: true
  16446. });
  16447. Scene.prototype._disableAudio = function () {
  16448. var i;
  16449. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16450. this.mainSoundTrack.soundCollection[i].pause();
  16451. }
  16452. for (i = 0; i < this.soundTracks.length; i++) {
  16453. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16454. this.soundTracks[i].soundCollection[j].pause();
  16455. }
  16456. }
  16457. };
  16458. Scene.prototype._enableAudio = function () {
  16459. var i;
  16460. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16461. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  16462. this.mainSoundTrack.soundCollection[i].play();
  16463. }
  16464. }
  16465. for (i = 0; i < this.soundTracks.length; i++) {
  16466. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16467. if (this.soundTracks[i].soundCollection[j].isPaused) {
  16468. this.soundTracks[i].soundCollection[j].play();
  16469. }
  16470. }
  16471. }
  16472. };
  16473. Object.defineProperty(Scene.prototype, "headphone", {
  16474. get: function () {
  16475. return this._headphone;
  16476. },
  16477. set: function (value) {
  16478. this._headphone = value;
  16479. if (BABYLON.AudioEngine) {
  16480. if (this._headphone) {
  16481. this._switchAudioModeForHeadphones();
  16482. }
  16483. else {
  16484. this._switchAudioModeForNormalSpeakers();
  16485. }
  16486. }
  16487. },
  16488. enumerable: true,
  16489. configurable: true
  16490. });
  16491. Scene.prototype._switchAudioModeForHeadphones = function () {
  16492. this.mainSoundTrack.switchPanningModelToHRTF();
  16493. for (var i = 0; i < this.soundTracks.length; i++) {
  16494. this.soundTracks[i].switchPanningModelToHRTF();
  16495. }
  16496. };
  16497. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  16498. this.mainSoundTrack.switchPanningModelToEqualPower();
  16499. for (var i = 0; i < this.soundTracks.length; i++) {
  16500. this.soundTracks[i].switchPanningModelToEqualPower();
  16501. }
  16502. };
  16503. Scene.prototype.enableDepthRenderer = function () {
  16504. if (this._depthRenderer) {
  16505. return this._depthRenderer;
  16506. }
  16507. this._depthRenderer = new BABYLON.DepthRenderer(this);
  16508. return this._depthRenderer;
  16509. };
  16510. Scene.prototype.disableDepthRenderer = function () {
  16511. if (!this._depthRenderer) {
  16512. return;
  16513. }
  16514. this._depthRenderer.dispose();
  16515. this._depthRenderer = null;
  16516. };
  16517. Scene.prototype.freezeMaterials = function () {
  16518. for (var i = 0; i < this.materials.length; i++) {
  16519. this.materials[i].freeze();
  16520. }
  16521. };
  16522. Scene.prototype.unfreezeMaterials = function () {
  16523. for (var i = 0; i < this.materials.length; i++) {
  16524. this.materials[i].unfreeze();
  16525. }
  16526. };
  16527. Scene.prototype.dispose = function () {
  16528. this.beforeRender = null;
  16529. this.afterRender = null;
  16530. this.skeletons = [];
  16531. this._boundingBoxRenderer.dispose();
  16532. if (this._depthRenderer) {
  16533. this._depthRenderer.dispose();
  16534. }
  16535. // Debug layer
  16536. if (this._debugLayer) {
  16537. this._debugLayer.hide();
  16538. }
  16539. // Events
  16540. this.onDisposeObservable.notifyObservers(this);
  16541. this.onDisposeObservable.clear();
  16542. this.onBeforeRenderObservable.clear();
  16543. this.onAfterRenderObservable.clear();
  16544. this.detachControl();
  16545. // Release sounds & sounds tracks
  16546. if (BABYLON.AudioEngine) {
  16547. this.disposeSounds();
  16548. }
  16549. // Detach cameras
  16550. var canvas = this._engine.getRenderingCanvas();
  16551. var index;
  16552. for (index = 0; index < this.cameras.length; index++) {
  16553. this.cameras[index].detachControl(canvas);
  16554. }
  16555. // Release lights
  16556. while (this.lights.length) {
  16557. this.lights[0].dispose();
  16558. }
  16559. // Release meshes
  16560. while (this.meshes.length) {
  16561. this.meshes[0].dispose(true);
  16562. }
  16563. // Release cameras
  16564. while (this.cameras.length) {
  16565. this.cameras[0].dispose();
  16566. }
  16567. // Release materials
  16568. while (this.materials.length) {
  16569. this.materials[0].dispose();
  16570. }
  16571. // Release particles
  16572. while (this.particleSystems.length) {
  16573. this.particleSystems[0].dispose();
  16574. }
  16575. // Release sprites
  16576. while (this.spriteManagers.length) {
  16577. this.spriteManagers[0].dispose();
  16578. }
  16579. // Release layers
  16580. while (this.layers.length) {
  16581. this.layers[0].dispose();
  16582. }
  16583. // Release textures
  16584. while (this.textures.length) {
  16585. this.textures[0].dispose();
  16586. }
  16587. // Post-processes
  16588. this.postProcessManager.dispose();
  16589. // Physics
  16590. if (this._physicsEngine) {
  16591. this.disablePhysicsEngine();
  16592. }
  16593. // Remove from engine
  16594. index = this._engine.scenes.indexOf(this);
  16595. if (index > -1) {
  16596. this._engine.scenes.splice(index, 1);
  16597. }
  16598. this._engine.wipeCaches();
  16599. };
  16600. // Release sounds & sounds tracks
  16601. Scene.prototype.disposeSounds = function () {
  16602. this.mainSoundTrack.dispose();
  16603. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  16604. this.soundTracks[scIndex].dispose();
  16605. }
  16606. };
  16607. // Octrees
  16608. Scene.prototype.getWorldExtends = function () {
  16609. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16610. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16611. for (var index = 0; index < this.meshes.length; index++) {
  16612. var mesh = this.meshes[index];
  16613. mesh.computeWorldMatrix(true);
  16614. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  16615. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  16616. BABYLON.Tools.CheckExtends(minBox, min, max);
  16617. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16618. }
  16619. return {
  16620. min: min,
  16621. max: max
  16622. };
  16623. };
  16624. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  16625. if (maxCapacity === void 0) { maxCapacity = 64; }
  16626. if (maxDepth === void 0) { maxDepth = 2; }
  16627. if (!this._selectionOctree) {
  16628. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  16629. }
  16630. var worldExtends = this.getWorldExtends();
  16631. // Update octree
  16632. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  16633. return this._selectionOctree;
  16634. };
  16635. // Picking
  16636. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  16637. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  16638. var engine = this._engine;
  16639. if (!camera) {
  16640. if (!this.activeCamera)
  16641. throw new Error("Active camera not set");
  16642. camera = this.activeCamera;
  16643. }
  16644. var cameraViewport = camera.viewport;
  16645. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16646. // Moving coordinates to local viewport world
  16647. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16648. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16649. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  16650. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  16651. };
  16652. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  16653. var engine = this._engine;
  16654. if (!camera) {
  16655. if (!this.activeCamera)
  16656. throw new Error("Active camera not set");
  16657. camera = this.activeCamera;
  16658. }
  16659. var cameraViewport = camera.viewport;
  16660. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16661. var identity = BABYLON.Matrix.Identity();
  16662. // Moving coordinates to local viewport world
  16663. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16664. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16665. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  16666. };
  16667. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  16668. var pickingInfo = null;
  16669. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  16670. var mesh = this.meshes[meshIndex];
  16671. if (predicate) {
  16672. if (!predicate(mesh)) {
  16673. continue;
  16674. }
  16675. }
  16676. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  16677. continue;
  16678. }
  16679. var world = mesh.getWorldMatrix();
  16680. var ray = rayFunction(world);
  16681. var result = mesh.intersects(ray, fastCheck);
  16682. if (!result || !result.hit)
  16683. continue;
  16684. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16685. continue;
  16686. pickingInfo = result;
  16687. if (fastCheck) {
  16688. break;
  16689. }
  16690. }
  16691. return pickingInfo || new BABYLON.PickingInfo();
  16692. };
  16693. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  16694. var pickingInfo = null;
  16695. camera = camera || this.activeCamera;
  16696. if (this.spriteManagers.length > 0) {
  16697. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  16698. var spriteManager = this.spriteManagers[spriteIndex];
  16699. if (!spriteManager.isPickable) {
  16700. continue;
  16701. }
  16702. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  16703. if (!result || !result.hit)
  16704. continue;
  16705. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16706. continue;
  16707. pickingInfo = result;
  16708. if (fastCheck) {
  16709. break;
  16710. }
  16711. }
  16712. }
  16713. return pickingInfo || new BABYLON.PickingInfo();
  16714. };
  16715. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  16716. var _this = this;
  16717. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16718. /// <param name="x">X position on screen</param>
  16719. /// <param name="y">Y position on screen</param>
  16720. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  16721. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16722. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  16723. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  16724. };
  16725. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  16726. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16727. /// <param name="x">X position on screen</param>
  16728. /// <param name="y">Y position on screen</param>
  16729. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  16730. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16731. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  16732. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  16733. };
  16734. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  16735. var _this = this;
  16736. return this._internalPick(function (world) {
  16737. if (!_this._pickWithRayInverseMatrix) {
  16738. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  16739. }
  16740. world.invertToRef(_this._pickWithRayInverseMatrix);
  16741. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  16742. }, predicate, fastCheck);
  16743. };
  16744. Scene.prototype.setPointerOverMesh = function (mesh) {
  16745. if (this._pointerOverMesh === mesh) {
  16746. return;
  16747. }
  16748. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16749. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16750. }
  16751. this._pointerOverMesh = mesh;
  16752. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16753. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16754. }
  16755. };
  16756. Scene.prototype.getPointerOverMesh = function () {
  16757. return this._pointerOverMesh;
  16758. };
  16759. Scene.prototype.setPointerOverSprite = function (sprite) {
  16760. if (this._pointerOverSprite === sprite) {
  16761. return;
  16762. }
  16763. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16764. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16765. }
  16766. this._pointerOverSprite = sprite;
  16767. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16768. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16769. }
  16770. };
  16771. Scene.prototype.getPointerOverSprite = function () {
  16772. return this._pointerOverSprite;
  16773. };
  16774. // Physics
  16775. Scene.prototype.getPhysicsEngine = function () {
  16776. return this._physicsEngine;
  16777. };
  16778. /**
  16779. * Enables physics to the current scene
  16780. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  16781. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  16782. * @return {boolean} was the physics engine initialized
  16783. */
  16784. Scene.prototype.enablePhysics = function (gravity, plugin) {
  16785. if (this._physicsEngine) {
  16786. return true;
  16787. }
  16788. try {
  16789. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  16790. return true;
  16791. }
  16792. catch (e) {
  16793. BABYLON.Tools.Error(e.message);
  16794. return false;
  16795. }
  16796. };
  16797. Scene.prototype.disablePhysicsEngine = function () {
  16798. if (!this._physicsEngine) {
  16799. return;
  16800. }
  16801. this._physicsEngine.dispose();
  16802. this._physicsEngine = undefined;
  16803. };
  16804. Scene.prototype.isPhysicsEnabled = function () {
  16805. return this._physicsEngine !== undefined;
  16806. };
  16807. /**
  16808. *
  16809. * Sets the gravity of the physics engine (and NOT of the scene)
  16810. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  16811. */
  16812. Scene.prototype.setGravity = function (gravity) {
  16813. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  16814. if (!this._physicsEngine) {
  16815. return;
  16816. }
  16817. this._physicsEngine.setGravity(gravity);
  16818. };
  16819. /**
  16820. * Legacy support, using the new API
  16821. * @Deprecated
  16822. */
  16823. Scene.prototype.createCompoundImpostor = function (parts, options) {
  16824. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  16825. if (parts.parts) {
  16826. options = parts;
  16827. parts = parts.parts;
  16828. }
  16829. var mainMesh = parts[0].mesh;
  16830. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  16831. for (var index = 1; index < parts.length; index++) {
  16832. var mesh = parts[index].mesh;
  16833. if (mesh.parent !== mainMesh) {
  16834. mesh.position = mesh.position.subtract(mainMesh.position);
  16835. mesh.parent = mainMesh;
  16836. }
  16837. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  16838. }
  16839. mainMesh.physicsImpostor.forceUpdate();
  16840. };
  16841. Scene.prototype.deleteCompoundImpostor = function (compound) {
  16842. var mesh = compound.parts[0].mesh;
  16843. mesh.physicsImpostor.dispose();
  16844. mesh.physicsImpostor = null;
  16845. };
  16846. // Misc.
  16847. Scene.prototype.createDefaultCameraOrLight = function () {
  16848. // Light
  16849. if (this.lights.length === 0) {
  16850. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  16851. }
  16852. // Camera
  16853. if (!this.activeCamera) {
  16854. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  16855. // Compute position
  16856. var worldExtends = this.getWorldExtends();
  16857. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  16858. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  16859. camera.setTarget(worldCenter);
  16860. this.activeCamera = camera;
  16861. }
  16862. };
  16863. // Tags
  16864. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  16865. if (tagsQuery === undefined) {
  16866. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  16867. return list;
  16868. }
  16869. var listByTags = [];
  16870. forEach = forEach || (function (item) { return; });
  16871. for (var i in list) {
  16872. var item = list[i];
  16873. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  16874. listByTags.push(item);
  16875. forEach(item);
  16876. }
  16877. }
  16878. return listByTags;
  16879. };
  16880. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  16881. return this._getByTags(this.meshes, tagsQuery, forEach);
  16882. };
  16883. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  16884. return this._getByTags(this.cameras, tagsQuery, forEach);
  16885. };
  16886. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  16887. return this._getByTags(this.lights, tagsQuery, forEach);
  16888. };
  16889. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  16890. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  16891. };
  16892. // Statics
  16893. Scene._FOGMODE_NONE = 0;
  16894. Scene._FOGMODE_EXP = 1;
  16895. Scene._FOGMODE_EXP2 = 2;
  16896. Scene._FOGMODE_LINEAR = 3;
  16897. Scene.MinDeltaTime = 1.0;
  16898. Scene.MaxDeltaTime = 1000.0;
  16899. return Scene;
  16900. })();
  16901. BABYLON.Scene = Scene;
  16902. })(BABYLON || (BABYLON = {}));
  16903. var BABYLON;
  16904. (function (BABYLON) {
  16905. var Buffer = (function () {
  16906. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  16907. if (engine instanceof BABYLON.Mesh) {
  16908. this._engine = engine.getScene().getEngine();
  16909. }
  16910. else {
  16911. this._engine = engine;
  16912. }
  16913. this._updatable = updatable;
  16914. this._data = data;
  16915. this._strideSize = stride;
  16916. if (!postponeInternalCreation) {
  16917. this.create();
  16918. }
  16919. this._instanced = instanced;
  16920. }
  16921. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  16922. // a lot of these parameters are ignored as they are overriden by the buffer
  16923. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  16924. };
  16925. // Properties
  16926. Buffer.prototype.isUpdatable = function () {
  16927. return this._updatable;
  16928. };
  16929. Buffer.prototype.getData = function () {
  16930. return this._data;
  16931. };
  16932. Buffer.prototype.getBuffer = function () {
  16933. return this._buffer;
  16934. };
  16935. Buffer.prototype.getStrideSize = function () {
  16936. return this._strideSize;
  16937. };
  16938. Buffer.prototype.getIsInstanced = function () {
  16939. return this._instanced;
  16940. };
  16941. // Methods
  16942. Buffer.prototype.create = function (data) {
  16943. if (!data && this._buffer) {
  16944. return; // nothing to do
  16945. }
  16946. data = data || this._data;
  16947. if (!this._buffer) {
  16948. if (this._updatable) {
  16949. this._buffer = this._engine.createDynamicVertexBuffer(data);
  16950. this._data = data;
  16951. }
  16952. else {
  16953. this._buffer = this._engine.createVertexBuffer(data);
  16954. }
  16955. }
  16956. else if (this._updatable) {
  16957. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  16958. this._data = data;
  16959. }
  16960. };
  16961. Buffer.prototype.update = function (data) {
  16962. this.create(data);
  16963. };
  16964. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  16965. if (!this._buffer) {
  16966. return;
  16967. }
  16968. if (this._updatable) {
  16969. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  16970. this._data = null;
  16971. }
  16972. };
  16973. Buffer.prototype.dispose = function () {
  16974. if (!this._buffer) {
  16975. return;
  16976. }
  16977. if (this._engine._releaseBuffer(this._buffer)) {
  16978. this._buffer = null;
  16979. }
  16980. };
  16981. return Buffer;
  16982. })();
  16983. BABYLON.Buffer = Buffer;
  16984. })(BABYLON || (BABYLON = {}));
  16985. var BABYLON;
  16986. (function (BABYLON) {
  16987. var VertexBuffer = (function () {
  16988. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  16989. if (!stride) {
  16990. // Deduce stride from kind
  16991. switch (kind) {
  16992. case VertexBuffer.PositionKind:
  16993. stride = 3;
  16994. break;
  16995. case VertexBuffer.NormalKind:
  16996. stride = 3;
  16997. break;
  16998. case VertexBuffer.UVKind:
  16999. case VertexBuffer.UV2Kind:
  17000. case VertexBuffer.UV3Kind:
  17001. case VertexBuffer.UV4Kind:
  17002. case VertexBuffer.UV5Kind:
  17003. case VertexBuffer.UV6Kind:
  17004. stride = 2;
  17005. break;
  17006. case VertexBuffer.ColorKind:
  17007. stride = 4;
  17008. break;
  17009. case VertexBuffer.MatricesIndicesKind:
  17010. case VertexBuffer.MatricesIndicesExtraKind:
  17011. stride = 4;
  17012. break;
  17013. case VertexBuffer.MatricesWeightsKind:
  17014. case VertexBuffer.MatricesWeightsExtraKind:
  17015. stride = 4;
  17016. break;
  17017. }
  17018. }
  17019. if (data instanceof BABYLON.Buffer) {
  17020. if (!stride) {
  17021. stride = data.getStrideSize();
  17022. }
  17023. this._buffer = data;
  17024. this._ownsBuffer = false;
  17025. }
  17026. else {
  17027. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  17028. this._ownsBuffer = true;
  17029. }
  17030. this._stride = stride;
  17031. this._offset = offset ? offset : 0;
  17032. this._size = size ? size : stride;
  17033. this._kind = kind;
  17034. }
  17035. VertexBuffer.prototype.getKind = function () {
  17036. return this._kind;
  17037. };
  17038. // Properties
  17039. VertexBuffer.prototype.isUpdatable = function () {
  17040. return this._buffer.isUpdatable();
  17041. };
  17042. VertexBuffer.prototype.getData = function () {
  17043. return this._buffer.getData();
  17044. };
  17045. VertexBuffer.prototype.getBuffer = function () {
  17046. return this._buffer.getBuffer();
  17047. };
  17048. VertexBuffer.prototype.getStrideSize = function () {
  17049. return this._stride;
  17050. };
  17051. VertexBuffer.prototype.getOffset = function () {
  17052. return this._offset;
  17053. };
  17054. VertexBuffer.prototype.getSize = function () {
  17055. return this._size;
  17056. };
  17057. VertexBuffer.prototype.getIsInstanced = function () {
  17058. return this._buffer.getIsInstanced();
  17059. };
  17060. // Methods
  17061. VertexBuffer.prototype.create = function (data) {
  17062. return this._buffer.create(data);
  17063. };
  17064. VertexBuffer.prototype.update = function (data) {
  17065. return this._buffer.update(data);
  17066. };
  17067. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  17068. return this._buffer.updateDirectly(data, offset);
  17069. };
  17070. VertexBuffer.prototype.dispose = function () {
  17071. if (this._ownsBuffer) {
  17072. this._buffer.dispose();
  17073. }
  17074. };
  17075. Object.defineProperty(VertexBuffer, "PositionKind", {
  17076. get: function () {
  17077. return VertexBuffer._PositionKind;
  17078. },
  17079. enumerable: true,
  17080. configurable: true
  17081. });
  17082. Object.defineProperty(VertexBuffer, "NormalKind", {
  17083. get: function () {
  17084. return VertexBuffer._NormalKind;
  17085. },
  17086. enumerable: true,
  17087. configurable: true
  17088. });
  17089. Object.defineProperty(VertexBuffer, "UVKind", {
  17090. get: function () {
  17091. return VertexBuffer._UVKind;
  17092. },
  17093. enumerable: true,
  17094. configurable: true
  17095. });
  17096. Object.defineProperty(VertexBuffer, "UV2Kind", {
  17097. get: function () {
  17098. return VertexBuffer._UV2Kind;
  17099. },
  17100. enumerable: true,
  17101. configurable: true
  17102. });
  17103. Object.defineProperty(VertexBuffer, "UV3Kind", {
  17104. get: function () {
  17105. return VertexBuffer._UV3Kind;
  17106. },
  17107. enumerable: true,
  17108. configurable: true
  17109. });
  17110. Object.defineProperty(VertexBuffer, "UV4Kind", {
  17111. get: function () {
  17112. return VertexBuffer._UV4Kind;
  17113. },
  17114. enumerable: true,
  17115. configurable: true
  17116. });
  17117. Object.defineProperty(VertexBuffer, "UV5Kind", {
  17118. get: function () {
  17119. return VertexBuffer._UV5Kind;
  17120. },
  17121. enumerable: true,
  17122. configurable: true
  17123. });
  17124. Object.defineProperty(VertexBuffer, "UV6Kind", {
  17125. get: function () {
  17126. return VertexBuffer._UV6Kind;
  17127. },
  17128. enumerable: true,
  17129. configurable: true
  17130. });
  17131. Object.defineProperty(VertexBuffer, "ColorKind", {
  17132. get: function () {
  17133. return VertexBuffer._ColorKind;
  17134. },
  17135. enumerable: true,
  17136. configurable: true
  17137. });
  17138. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  17139. get: function () {
  17140. return VertexBuffer._MatricesIndicesKind;
  17141. },
  17142. enumerable: true,
  17143. configurable: true
  17144. });
  17145. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  17146. get: function () {
  17147. return VertexBuffer._MatricesWeightsKind;
  17148. },
  17149. enumerable: true,
  17150. configurable: true
  17151. });
  17152. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  17153. get: function () {
  17154. return VertexBuffer._MatricesIndicesExtraKind;
  17155. },
  17156. enumerable: true,
  17157. configurable: true
  17158. });
  17159. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  17160. get: function () {
  17161. return VertexBuffer._MatricesWeightsExtraKind;
  17162. },
  17163. enumerable: true,
  17164. configurable: true
  17165. });
  17166. // Enums
  17167. VertexBuffer._PositionKind = "position";
  17168. VertexBuffer._NormalKind = "normal";
  17169. VertexBuffer._UVKind = "uv";
  17170. VertexBuffer._UV2Kind = "uv2";
  17171. VertexBuffer._UV3Kind = "uv3";
  17172. VertexBuffer._UV4Kind = "uv4";
  17173. VertexBuffer._UV5Kind = "uv5";
  17174. VertexBuffer._UV6Kind = "uv6";
  17175. VertexBuffer._ColorKind = "color";
  17176. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  17177. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  17178. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  17179. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  17180. return VertexBuffer;
  17181. })();
  17182. BABYLON.VertexBuffer = VertexBuffer;
  17183. })(BABYLON || (BABYLON = {}));
  17184. var BABYLON;
  17185. (function (BABYLON) {
  17186. /**
  17187. * Creates an instance based on a source mesh.
  17188. */
  17189. var InstancedMesh = (function (_super) {
  17190. __extends(InstancedMesh, _super);
  17191. function InstancedMesh(name, source) {
  17192. _super.call(this, name, source.getScene());
  17193. source.instances.push(this);
  17194. this._sourceMesh = source;
  17195. this.position.copyFrom(source.position);
  17196. this.rotation.copyFrom(source.rotation);
  17197. this.scaling.copyFrom(source.scaling);
  17198. if (source.rotationQuaternion) {
  17199. this.rotationQuaternion = source.rotationQuaternion.clone();
  17200. }
  17201. this.infiniteDistance = source.infiniteDistance;
  17202. this.setPivotMatrix(source.getPivotMatrix());
  17203. this.refreshBoundingInfo();
  17204. this._syncSubMeshes();
  17205. }
  17206. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  17207. // Methods
  17208. get: function () {
  17209. return this._sourceMesh.receiveShadows;
  17210. },
  17211. enumerable: true,
  17212. configurable: true
  17213. });
  17214. Object.defineProperty(InstancedMesh.prototype, "material", {
  17215. get: function () {
  17216. return this._sourceMesh.material;
  17217. },
  17218. enumerable: true,
  17219. configurable: true
  17220. });
  17221. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  17222. get: function () {
  17223. return this._sourceMesh.visibility;
  17224. },
  17225. enumerable: true,
  17226. configurable: true
  17227. });
  17228. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  17229. get: function () {
  17230. return this._sourceMesh.skeleton;
  17231. },
  17232. enumerable: true,
  17233. configurable: true
  17234. });
  17235. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  17236. get: function () {
  17237. return this._sourceMesh.renderingGroupId;
  17238. },
  17239. enumerable: true,
  17240. configurable: true
  17241. });
  17242. InstancedMesh.prototype.getTotalVertices = function () {
  17243. return this._sourceMesh.getTotalVertices();
  17244. };
  17245. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  17246. get: function () {
  17247. return this._sourceMesh;
  17248. },
  17249. enumerable: true,
  17250. configurable: true
  17251. });
  17252. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17253. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  17254. };
  17255. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  17256. return this._sourceMesh.isVerticesDataPresent(kind);
  17257. };
  17258. InstancedMesh.prototype.getIndices = function () {
  17259. return this._sourceMesh.getIndices();
  17260. };
  17261. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  17262. get: function () {
  17263. return this._sourceMesh._positions;
  17264. },
  17265. enumerable: true,
  17266. configurable: true
  17267. });
  17268. InstancedMesh.prototype.refreshBoundingInfo = function () {
  17269. var meshBB = this._sourceMesh.getBoundingInfo();
  17270. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  17271. this._updateBoundingInfo();
  17272. };
  17273. InstancedMesh.prototype._preActivate = function () {
  17274. if (this._currentLOD) {
  17275. this._currentLOD._preActivate();
  17276. }
  17277. };
  17278. InstancedMesh.prototype._activate = function (renderId) {
  17279. if (this._currentLOD) {
  17280. this._currentLOD._registerInstanceForRenderId(this, renderId);
  17281. }
  17282. };
  17283. InstancedMesh.prototype.getLOD = function (camera) {
  17284. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  17285. if (this._currentLOD === this.sourceMesh) {
  17286. return this;
  17287. }
  17288. return this._currentLOD;
  17289. };
  17290. InstancedMesh.prototype._syncSubMeshes = function () {
  17291. this.releaseSubMeshes();
  17292. if (this._sourceMesh.subMeshes) {
  17293. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  17294. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  17295. }
  17296. }
  17297. };
  17298. InstancedMesh.prototype._generatePointsArray = function () {
  17299. return this._sourceMesh._generatePointsArray();
  17300. };
  17301. // Clone
  17302. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17303. var result = this._sourceMesh.createInstance(name);
  17304. // Deep copy
  17305. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  17306. // Bounding info
  17307. this.refreshBoundingInfo();
  17308. // Parent
  17309. if (newParent) {
  17310. result.parent = newParent;
  17311. }
  17312. if (!doNotCloneChildren) {
  17313. // Children
  17314. for (var index = 0; index < this.getScene().meshes.length; index++) {
  17315. var mesh = this.getScene().meshes[index];
  17316. if (mesh.parent === this) {
  17317. mesh.clone(mesh.name, result);
  17318. }
  17319. }
  17320. }
  17321. result.computeWorldMatrix(true);
  17322. return result;
  17323. };
  17324. // Dispoe
  17325. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  17326. // Remove from mesh
  17327. var index = this._sourceMesh.instances.indexOf(this);
  17328. this._sourceMesh.instances.splice(index, 1);
  17329. _super.prototype.dispose.call(this, doNotRecurse);
  17330. };
  17331. return InstancedMesh;
  17332. })(BABYLON.AbstractMesh);
  17333. BABYLON.InstancedMesh = InstancedMesh;
  17334. })(BABYLON || (BABYLON = {}));
  17335. var BABYLON;
  17336. (function (BABYLON) {
  17337. var _InstancesBatch = (function () {
  17338. function _InstancesBatch() {
  17339. this.mustReturn = false;
  17340. this.visibleInstances = new Array();
  17341. this.renderSelf = new Array();
  17342. }
  17343. return _InstancesBatch;
  17344. })();
  17345. BABYLON._InstancesBatch = _InstancesBatch;
  17346. var Mesh = (function (_super) {
  17347. __extends(Mesh, _super);
  17348. /**
  17349. * @constructor
  17350. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  17351. * @param {Scene} scene The scene to add this mesh to.
  17352. * @param {Node} parent The parent of this mesh, if it has one
  17353. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  17354. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  17355. * When false, achieved by calling a clone(), also passing False.
  17356. * This will make creation of children, recursive.
  17357. */
  17358. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  17359. if (parent === void 0) { parent = null; }
  17360. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17361. _super.call(this, name, scene);
  17362. // Events
  17363. /**
  17364. * An event triggered before rendering the mesh
  17365. * @type {BABYLON.Observable}
  17366. */
  17367. this.onBeforeRenderObservable = new BABYLON.Observable();
  17368. /**
  17369. * An event triggered after rendering the mesh
  17370. * @type {BABYLON.Observable}
  17371. */
  17372. this.onAfterRenderObservable = new BABYLON.Observable();
  17373. /**
  17374. * An event triggered before drawing the mesh
  17375. * @type {BABYLON.Observable}
  17376. */
  17377. this.onBeforeDrawObservable = new BABYLON.Observable();
  17378. // Members
  17379. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17380. this.instances = new Array();
  17381. this._LODLevels = new Array();
  17382. this._visibleInstances = {};
  17383. this._renderIdForInstances = new Array();
  17384. this._batchCache = new _InstancesBatch();
  17385. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  17386. this._sideOrientation = Mesh._DEFAULTSIDE;
  17387. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  17388. if (source) {
  17389. // Geometry
  17390. if (source._geometry) {
  17391. source._geometry.applyToMesh(this);
  17392. }
  17393. // Deep copy
  17394. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  17395. // Pivot
  17396. this.setPivotMatrix(source.getPivotMatrix());
  17397. this.id = name + "." + source.id;
  17398. // Material
  17399. this.material = source.material;
  17400. var index;
  17401. if (!doNotCloneChildren) {
  17402. // Children
  17403. for (index = 0; index < scene.meshes.length; index++) {
  17404. var mesh = scene.meshes[index];
  17405. if (mesh.parent === source) {
  17406. // doNotCloneChildren is always going to be False
  17407. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  17408. }
  17409. }
  17410. }
  17411. // Physics clone
  17412. var physicsEngine = this.getScene().getPhysicsEngine();
  17413. if (clonePhysicsImpostor && physicsEngine) {
  17414. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  17415. if (impostor) {
  17416. this.physicsImpostor = impostor.clone(this);
  17417. }
  17418. }
  17419. // Particles
  17420. for (index = 0; index < scene.particleSystems.length; index++) {
  17421. var system = scene.particleSystems[index];
  17422. if (system.emitter === source) {
  17423. system.clone(system.name, this);
  17424. }
  17425. }
  17426. this.computeWorldMatrix(true);
  17427. }
  17428. // Parent
  17429. if (parent !== null) {
  17430. this.parent = parent;
  17431. }
  17432. }
  17433. Object.defineProperty(Mesh, "FRONTSIDE", {
  17434. /**
  17435. * Mesh side orientation : usually the external or front surface
  17436. */
  17437. get: function () {
  17438. return Mesh._FRONTSIDE;
  17439. },
  17440. enumerable: true,
  17441. configurable: true
  17442. });
  17443. Object.defineProperty(Mesh, "BACKSIDE", {
  17444. /**
  17445. * Mesh side orientation : usually the internal or back surface
  17446. */
  17447. get: function () {
  17448. return Mesh._BACKSIDE;
  17449. },
  17450. enumerable: true,
  17451. configurable: true
  17452. });
  17453. Object.defineProperty(Mesh, "DOUBLESIDE", {
  17454. /**
  17455. * Mesh side orientation : both internal and external or front and back surfaces
  17456. */
  17457. get: function () {
  17458. return Mesh._DOUBLESIDE;
  17459. },
  17460. enumerable: true,
  17461. configurable: true
  17462. });
  17463. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  17464. /**
  17465. * Mesh side orientation : by default, `FRONTSIDE`
  17466. */
  17467. get: function () {
  17468. return Mesh._DEFAULTSIDE;
  17469. },
  17470. enumerable: true,
  17471. configurable: true
  17472. });
  17473. Object.defineProperty(Mesh, "NO_CAP", {
  17474. /**
  17475. * Mesh cap setting : no cap
  17476. */
  17477. get: function () {
  17478. return Mesh._NO_CAP;
  17479. },
  17480. enumerable: true,
  17481. configurable: true
  17482. });
  17483. Object.defineProperty(Mesh, "CAP_START", {
  17484. /**
  17485. * Mesh cap setting : one cap at the beginning of the mesh
  17486. */
  17487. get: function () {
  17488. return Mesh._CAP_START;
  17489. },
  17490. enumerable: true,
  17491. configurable: true
  17492. });
  17493. Object.defineProperty(Mesh, "CAP_END", {
  17494. /**
  17495. * Mesh cap setting : one cap at the end of the mesh
  17496. */
  17497. get: function () {
  17498. return Mesh._CAP_END;
  17499. },
  17500. enumerable: true,
  17501. configurable: true
  17502. });
  17503. Object.defineProperty(Mesh, "CAP_ALL", {
  17504. /**
  17505. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  17506. */
  17507. get: function () {
  17508. return Mesh._CAP_ALL;
  17509. },
  17510. enumerable: true,
  17511. configurable: true
  17512. });
  17513. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  17514. set: function (callback) {
  17515. if (this._onBeforeDrawObserver) {
  17516. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  17517. }
  17518. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  17519. },
  17520. enumerable: true,
  17521. configurable: true
  17522. });
  17523. // Methods
  17524. /**
  17525. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17526. */
  17527. Mesh.prototype.toString = function (fullDetails) {
  17528. var ret = _super.prototype.toString.call(this, fullDetails);
  17529. ret += ", n vertices: " + this.getTotalVertices();
  17530. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  17531. if (this.animations) {
  17532. for (var i = 0; i < this.animations.length; i++) {
  17533. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17534. }
  17535. }
  17536. if (fullDetails) {
  17537. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  17538. }
  17539. return ret;
  17540. };
  17541. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  17542. get: function () {
  17543. return this._LODLevels.length > 0;
  17544. },
  17545. enumerable: true,
  17546. configurable: true
  17547. });
  17548. Mesh.prototype._sortLODLevels = function () {
  17549. this._LODLevels.sort(function (a, b) {
  17550. if (a.distance < b.distance) {
  17551. return 1;
  17552. }
  17553. if (a.distance > b.distance) {
  17554. return -1;
  17555. }
  17556. return 0;
  17557. });
  17558. };
  17559. /**
  17560. * Add a mesh as LOD level triggered at the given distance.
  17561. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17562. * @param {number} distance The distance from the center of the object to show this level
  17563. * @param {Mesh} mesh The mesh to be added as LOD level
  17564. * @return {Mesh} This mesh (for chaining)
  17565. */
  17566. Mesh.prototype.addLODLevel = function (distance, mesh) {
  17567. if (mesh && mesh._masterMesh) {
  17568. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  17569. return this;
  17570. }
  17571. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  17572. this._LODLevels.push(level);
  17573. if (mesh) {
  17574. mesh._masterMesh = this;
  17575. }
  17576. this._sortLODLevels();
  17577. return this;
  17578. };
  17579. /**
  17580. * Returns the LOD level mesh at the passed distance or null if not found.
  17581. * It is related to the method `addLODLevel(distance, mesh)`.
  17582. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17583. */
  17584. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  17585. for (var index = 0; index < this._LODLevels.length; index++) {
  17586. var level = this._LODLevels[index];
  17587. if (level.distance === distance) {
  17588. return level.mesh;
  17589. }
  17590. }
  17591. return null;
  17592. };
  17593. /**
  17594. * Remove a mesh from the LOD array
  17595. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17596. * @param {Mesh} mesh The mesh to be removed.
  17597. * @return {Mesh} This mesh (for chaining)
  17598. */
  17599. Mesh.prototype.removeLODLevel = function (mesh) {
  17600. for (var index = 0; index < this._LODLevels.length; index++) {
  17601. if (this._LODLevels[index].mesh === mesh) {
  17602. this._LODLevels.splice(index, 1);
  17603. if (mesh) {
  17604. mesh._masterMesh = null;
  17605. }
  17606. }
  17607. }
  17608. this._sortLODLevels();
  17609. return this;
  17610. };
  17611. /**
  17612. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  17613. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17614. */
  17615. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  17616. if (!this._LODLevels || this._LODLevels.length === 0) {
  17617. return this;
  17618. }
  17619. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  17620. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  17621. if (this.onLODLevelSelection) {
  17622. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  17623. }
  17624. return this;
  17625. }
  17626. for (var index = 0; index < this._LODLevels.length; index++) {
  17627. var level = this._LODLevels[index];
  17628. if (level.distance < distanceToCamera) {
  17629. if (level.mesh) {
  17630. level.mesh._preActivate();
  17631. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17632. }
  17633. if (this.onLODLevelSelection) {
  17634. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  17635. }
  17636. return level.mesh;
  17637. }
  17638. }
  17639. if (this.onLODLevelSelection) {
  17640. this.onLODLevelSelection(distanceToCamera, this, this);
  17641. }
  17642. return this;
  17643. };
  17644. Object.defineProperty(Mesh.prototype, "geometry", {
  17645. /**
  17646. * Returns the mesh internal Geometry object.
  17647. */
  17648. get: function () {
  17649. return this._geometry;
  17650. },
  17651. enumerable: true,
  17652. configurable: true
  17653. });
  17654. /**
  17655. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  17656. */
  17657. Mesh.prototype.getTotalVertices = function () {
  17658. if (!this._geometry) {
  17659. return 0;
  17660. }
  17661. return this._geometry.getTotalVertices();
  17662. };
  17663. /**
  17664. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  17665. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  17666. * Returns null if the mesh has no geometry or no vertex buffer.
  17667. * Possible `kind` values :
  17668. * - BABYLON.VertexBuffer.PositionKind
  17669. * - BABYLON.VertexBuffer.UVKind
  17670. * - BABYLON.VertexBuffer.UV2Kind
  17671. * - BABYLON.VertexBuffer.UV3Kind
  17672. * - BABYLON.VertexBuffer.UV4Kind
  17673. * - BABYLON.VertexBuffer.UV5Kind
  17674. * - BABYLON.VertexBuffer.UV6Kind
  17675. * - BABYLON.VertexBuffer.ColorKind
  17676. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17677. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17678. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17679. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17680. */
  17681. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17682. if (!this._geometry) {
  17683. return null;
  17684. }
  17685. return this._geometry.getVerticesData(kind, copyWhenShared);
  17686. };
  17687. /**
  17688. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  17689. * Returns `undefined` if the mesh has no geometry.
  17690. * Possible `kind` values :
  17691. * - BABYLON.VertexBuffer.PositionKind
  17692. * - BABYLON.VertexBuffer.UVKind
  17693. * - BABYLON.VertexBuffer.UV2Kind
  17694. * - BABYLON.VertexBuffer.UV3Kind
  17695. * - BABYLON.VertexBuffer.UV4Kind
  17696. * - BABYLON.VertexBuffer.UV5Kind
  17697. * - BABYLON.VertexBuffer.UV6Kind
  17698. * - BABYLON.VertexBuffer.ColorKind
  17699. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17700. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17701. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17702. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17703. */
  17704. Mesh.prototype.getVertexBuffer = function (kind) {
  17705. if (!this._geometry) {
  17706. return undefined;
  17707. }
  17708. return this._geometry.getVertexBuffer(kind);
  17709. };
  17710. /**
  17711. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  17712. * Possible `kind` values :
  17713. * - BABYLON.VertexBuffer.PositionKind
  17714. * - BABYLON.VertexBuffer.UVKind
  17715. * - BABYLON.VertexBuffer.UV2Kind
  17716. * - BABYLON.VertexBuffer.UV3Kind
  17717. * - BABYLON.VertexBuffer.UV4Kind
  17718. * - BABYLON.VertexBuffer.UV5Kind
  17719. * - BABYLON.VertexBuffer.UV6Kind
  17720. * - BABYLON.VertexBuffer.ColorKind
  17721. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17722. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17723. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17724. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17725. */
  17726. Mesh.prototype.isVerticesDataPresent = function (kind) {
  17727. if (!this._geometry) {
  17728. if (this._delayInfo) {
  17729. return this._delayInfo.indexOf(kind) !== -1;
  17730. }
  17731. return false;
  17732. }
  17733. return this._geometry.isVerticesDataPresent(kind);
  17734. };
  17735. /**
  17736. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  17737. * Possible `kind` values :
  17738. * - BABYLON.VertexBuffer.PositionKind
  17739. * - BABYLON.VertexBuffer.UVKind
  17740. * - BABYLON.VertexBuffer.UV2Kind
  17741. * - BABYLON.VertexBuffer.UV3Kind
  17742. * - BABYLON.VertexBuffer.UV4Kind
  17743. * - BABYLON.VertexBuffer.UV5Kind
  17744. * - BABYLON.VertexBuffer.UV6Kind
  17745. * - BABYLON.VertexBuffer.ColorKind
  17746. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17747. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17748. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17749. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17750. */
  17751. Mesh.prototype.getVerticesDataKinds = function () {
  17752. if (!this._geometry) {
  17753. var result = [];
  17754. if (this._delayInfo) {
  17755. for (var kind in this._delayInfo) {
  17756. result.push(kind);
  17757. }
  17758. }
  17759. return result;
  17760. }
  17761. return this._geometry.getVerticesDataKinds();
  17762. };
  17763. /**
  17764. * Returns a positive integer : the total number of indices in this mesh geometry.
  17765. * Returns zero if the mesh has no geometry.
  17766. */
  17767. Mesh.prototype.getTotalIndices = function () {
  17768. if (!this._geometry) {
  17769. return 0;
  17770. }
  17771. return this._geometry.getTotalIndices();
  17772. };
  17773. /**
  17774. * Returns an array of integers or a Int32Array populated with the mesh indices.
  17775. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  17776. * Returns an empty array if the mesh has no geometry.
  17777. */
  17778. Mesh.prototype.getIndices = function (copyWhenShared) {
  17779. if (!this._geometry) {
  17780. return [];
  17781. }
  17782. return this._geometry.getIndices(copyWhenShared);
  17783. };
  17784. Object.defineProperty(Mesh.prototype, "isBlocked", {
  17785. get: function () {
  17786. return this._masterMesh !== null && this._masterMesh !== undefined;
  17787. },
  17788. enumerable: true,
  17789. configurable: true
  17790. });
  17791. /**
  17792. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  17793. */
  17794. Mesh.prototype.isReady = function () {
  17795. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17796. return false;
  17797. }
  17798. return _super.prototype.isReady.call(this);
  17799. };
  17800. /**
  17801. * Boolean : true if the mesh has been disposed.
  17802. */
  17803. Mesh.prototype.isDisposed = function () {
  17804. return this._isDisposed;
  17805. };
  17806. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  17807. get: function () {
  17808. return this._sideOrientation;
  17809. },
  17810. /**
  17811. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  17812. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  17813. */
  17814. set: function (sideO) {
  17815. this._sideOrientation = sideO;
  17816. },
  17817. enumerable: true,
  17818. configurable: true
  17819. });
  17820. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  17821. /**
  17822. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  17823. * This property is pertinent only for updatable parametric shapes.
  17824. */
  17825. get: function () {
  17826. return this._areNormalsFrozen;
  17827. },
  17828. enumerable: true,
  17829. configurable: true
  17830. });
  17831. /**
  17832. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17833. * It has no effect at all on other shapes.
  17834. * It prevents the mesh normals from being recomputed on next `positions` array update.
  17835. */
  17836. Mesh.prototype.freezeNormals = function () {
  17837. this._areNormalsFrozen = true;
  17838. };
  17839. /**
  17840. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17841. * It has no effect at all on other shapes.
  17842. * It reactivates the mesh normals computation if it was previously frozen.
  17843. */
  17844. Mesh.prototype.unfreezeNormals = function () {
  17845. this._areNormalsFrozen = false;
  17846. };
  17847. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  17848. /**
  17849. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  17850. */
  17851. set: function (count) {
  17852. this._overridenInstanceCount = count;
  17853. },
  17854. enumerable: true,
  17855. configurable: true
  17856. });
  17857. // Methods
  17858. Mesh.prototype._preActivate = function () {
  17859. var sceneRenderId = this.getScene().getRenderId();
  17860. if (this._preActivateId === sceneRenderId) {
  17861. return;
  17862. }
  17863. this._preActivateId = sceneRenderId;
  17864. this._visibleInstances = null;
  17865. };
  17866. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17867. if (this._visibleInstances) {
  17868. this._visibleInstances.intermediateDefaultRenderId = renderId;
  17869. }
  17870. };
  17871. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  17872. if (!this._visibleInstances) {
  17873. this._visibleInstances = {};
  17874. this._visibleInstances.defaultRenderId = renderId;
  17875. this._visibleInstances.selfDefaultRenderId = this._renderId;
  17876. }
  17877. if (!this._visibleInstances[renderId]) {
  17878. this._visibleInstances[renderId] = new Array();
  17879. }
  17880. this._visibleInstances[renderId].push(instance);
  17881. };
  17882. /**
  17883. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  17884. * This means the mesh underlying bounding box and sphere are recomputed.
  17885. */
  17886. Mesh.prototype.refreshBoundingInfo = function () {
  17887. if (this._boundingInfo.isLocked) {
  17888. return;
  17889. }
  17890. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17891. if (data) {
  17892. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  17893. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17894. }
  17895. if (this.subMeshes) {
  17896. for (var index = 0; index < this.subMeshes.length; index++) {
  17897. this.subMeshes[index].refreshBoundingInfo();
  17898. }
  17899. }
  17900. this._updateBoundingInfo();
  17901. };
  17902. Mesh.prototype._createGlobalSubMesh = function () {
  17903. var totalVertices = this.getTotalVertices();
  17904. if (!totalVertices || !this.getIndices()) {
  17905. return null;
  17906. }
  17907. this.releaseSubMeshes();
  17908. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  17909. };
  17910. Mesh.prototype.subdivide = function (count) {
  17911. if (count < 1) {
  17912. return;
  17913. }
  17914. var totalIndices = this.getTotalIndices();
  17915. var subdivisionSize = (totalIndices / count) | 0;
  17916. var offset = 0;
  17917. // Ensure that subdivisionSize is a multiple of 3
  17918. while (subdivisionSize % 3 !== 0) {
  17919. subdivisionSize++;
  17920. }
  17921. this.releaseSubMeshes();
  17922. for (var index = 0; index < count; index++) {
  17923. if (offset >= totalIndices) {
  17924. break;
  17925. }
  17926. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  17927. offset += subdivisionSize;
  17928. }
  17929. this.synchronizeInstances();
  17930. };
  17931. /**
  17932. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17933. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17934. * The `data` are either a numeric array either a Float32Array.
  17935. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17936. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  17937. * Note that a new underlying VertexBuffer object is created each call.
  17938. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17939. *
  17940. * Possible `kind` values :
  17941. * - BABYLON.VertexBuffer.PositionKind
  17942. * - BABYLON.VertexBuffer.UVKind
  17943. * - BABYLON.VertexBuffer.UV2Kind
  17944. * - BABYLON.VertexBuffer.UV3Kind
  17945. * - BABYLON.VertexBuffer.UV4Kind
  17946. * - BABYLON.VertexBuffer.UV5Kind
  17947. * - BABYLON.VertexBuffer.UV6Kind
  17948. * - BABYLON.VertexBuffer.ColorKind
  17949. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17950. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17951. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17952. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17953. */
  17954. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17955. if (!this._geometry) {
  17956. var vertexData = new BABYLON.VertexData();
  17957. vertexData.set(data, kind);
  17958. var scene = this.getScene();
  17959. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  17960. }
  17961. else {
  17962. this._geometry.setVerticesData(kind, data, updatable, stride);
  17963. }
  17964. };
  17965. Mesh.prototype.setVerticesBuffer = function (buffer) {
  17966. if (!this._geometry) {
  17967. var scene = this.getScene();
  17968. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  17969. }
  17970. this._geometry.setVerticesBuffer(buffer);
  17971. };
  17972. /**
  17973. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17974. * If the mesh has no geometry, it is simply returned as it is.
  17975. * The `data` are either a numeric array either a Float32Array.
  17976. * No new underlying VertexBuffer object is created.
  17977. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17978. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17979. *
  17980. * Possible `kind` values :
  17981. * - BABYLON.VertexBuffer.PositionKind
  17982. * - BABYLON.VertexBuffer.UVKind
  17983. * - BABYLON.VertexBuffer.UV2Kind
  17984. * - BABYLON.VertexBuffer.UV3Kind
  17985. * - BABYLON.VertexBuffer.UV4Kind
  17986. * - BABYLON.VertexBuffer.UV5Kind
  17987. * - BABYLON.VertexBuffer.UV6Kind
  17988. * - BABYLON.VertexBuffer.ColorKind
  17989. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17990. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17991. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17992. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17993. */
  17994. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17995. if (!this._geometry) {
  17996. return;
  17997. }
  17998. if (!makeItUnique) {
  17999. this._geometry.updateVerticesData(kind, data, updateExtends);
  18000. }
  18001. else {
  18002. this.makeGeometryUnique();
  18003. this.updateVerticesData(kind, data, updateExtends, false);
  18004. }
  18005. };
  18006. /**
  18007. * Deprecated since BabylonJS v2.3
  18008. */
  18009. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  18010. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  18011. if (!this._geometry) {
  18012. return;
  18013. }
  18014. if (!makeItUnique) {
  18015. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  18016. }
  18017. else {
  18018. this.makeGeometryUnique();
  18019. this.updateVerticesDataDirectly(kind, data, offset, false);
  18020. }
  18021. };
  18022. /**
  18023. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  18024. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  18025. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  18026. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  18027. */
  18028. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  18029. if (computeNormals === void 0) { computeNormals = true; }
  18030. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18031. positionFunction(positions);
  18032. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  18033. if (computeNormals) {
  18034. var indices = this.getIndices();
  18035. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18036. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18037. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  18038. }
  18039. };
  18040. Mesh.prototype.makeGeometryUnique = function () {
  18041. if (!this._geometry) {
  18042. return;
  18043. }
  18044. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  18045. geometry.applyToMesh(this);
  18046. };
  18047. /**
  18048. * Sets the mesh indices.
  18049. * Expects an array populated with integers or a Int32Array.
  18050. * If the mesh has no geometry, a new `Geometry` object is created and set to the mesh.
  18051. * This method creates a new index buffer each call.
  18052. */
  18053. Mesh.prototype.setIndices = function (indices, totalVertices) {
  18054. if (!this._geometry) {
  18055. var vertexData = new BABYLON.VertexData();
  18056. vertexData.indices = indices;
  18057. var scene = this.getScene();
  18058. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  18059. }
  18060. else {
  18061. this._geometry.setIndices(indices, totalVertices);
  18062. }
  18063. };
  18064. /**
  18065. * Invert the geometry to move from a right handed system to a left handed one.
  18066. */
  18067. Mesh.prototype.toLeftHanded = function () {
  18068. if (!this._geometry) {
  18069. return;
  18070. }
  18071. this._geometry.toLeftHanded();
  18072. };
  18073. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  18074. var engine = this.getScene().getEngine();
  18075. // Wireframe
  18076. var indexToBind;
  18077. if (this._unIndexed) {
  18078. indexToBind = null;
  18079. }
  18080. else {
  18081. switch (fillMode) {
  18082. case BABYLON.Material.PointFillMode:
  18083. indexToBind = null;
  18084. break;
  18085. case BABYLON.Material.WireFrameFillMode:
  18086. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  18087. break;
  18088. default:
  18089. case BABYLON.Material.TriangleFillMode:
  18090. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  18091. break;
  18092. }
  18093. }
  18094. // VBOs
  18095. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  18096. };
  18097. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  18098. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  18099. return;
  18100. }
  18101. this.onBeforeDrawObservable.notifyObservers(this);
  18102. var engine = this.getScene().getEngine();
  18103. // Draw order
  18104. switch (fillMode) {
  18105. case BABYLON.Material.PointFillMode:
  18106. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18107. break;
  18108. case BABYLON.Material.WireFrameFillMode:
  18109. if (this._unIndexed) {
  18110. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18111. }
  18112. else {
  18113. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  18114. }
  18115. break;
  18116. default:
  18117. if (this._unIndexed) {
  18118. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18119. }
  18120. else {
  18121. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  18122. }
  18123. }
  18124. };
  18125. /**
  18126. * Registers for this mesh a javascript function called just before the rendering process.
  18127. * This function is passed the current mesh and doesn't return anything.
  18128. */
  18129. Mesh.prototype.registerBeforeRender = function (func) {
  18130. this.onBeforeRenderObservable.add(func);
  18131. };
  18132. /**
  18133. * Disposes a previously registered javascript function called before the rendering.
  18134. * This function is passed the current mesh and doesn't return anything.
  18135. */
  18136. Mesh.prototype.unregisterBeforeRender = function (func) {
  18137. this.onBeforeRenderObservable.removeCallback(func);
  18138. };
  18139. /**
  18140. * Registers for this mesh a javascript function called just after the rendering is complete.
  18141. * This function is passed the current mesh and doesn't return anything.
  18142. */
  18143. Mesh.prototype.registerAfterRender = function (func) {
  18144. this.onAfterRenderObservable.add(func);
  18145. };
  18146. /**
  18147. * Disposes a previously registered javascript function called after the rendering.
  18148. * This function is passed the current mesh and doesn't return anything.
  18149. */
  18150. Mesh.prototype.unregisterAfterRender = function (func) {
  18151. this.onAfterRenderObservable.removeCallback(func);
  18152. };
  18153. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  18154. var scene = this.getScene();
  18155. this._batchCache.mustReturn = false;
  18156. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  18157. this._batchCache.visibleInstances[subMeshId] = null;
  18158. if (this._visibleInstances) {
  18159. var currentRenderId = scene.getRenderId();
  18160. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  18161. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  18162. var selfRenderId = this._renderId;
  18163. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  18164. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  18165. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  18166. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  18167. }
  18168. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  18169. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  18170. this._batchCache.mustReturn = true;
  18171. return this._batchCache;
  18172. }
  18173. if (currentRenderId !== selfRenderId) {
  18174. this._batchCache.renderSelf[subMeshId] = false;
  18175. }
  18176. }
  18177. this._renderIdForInstances[subMeshId] = currentRenderId;
  18178. }
  18179. return this._batchCache;
  18180. };
  18181. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  18182. var visibleInstances = batch.visibleInstances[subMesh._id];
  18183. var matricesCount = visibleInstances.length + 1;
  18184. var bufferSize = matricesCount * 16 * 4;
  18185. var currentInstancesBufferSize = this._instancesBufferSize;
  18186. var instancesBuffer = this._instancesBuffer;
  18187. while (this._instancesBufferSize < bufferSize) {
  18188. this._instancesBufferSize *= 2;
  18189. }
  18190. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  18191. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  18192. }
  18193. var offset = 0;
  18194. var instancesCount = 0;
  18195. var world = this.getWorldMatrix();
  18196. if (batch.renderSelf[subMesh._id]) {
  18197. world.copyToArray(this._instancesData, offset);
  18198. offset += 16;
  18199. instancesCount++;
  18200. }
  18201. if (visibleInstances) {
  18202. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  18203. var instance = visibleInstances[instanceIndex];
  18204. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  18205. offset += 16;
  18206. instancesCount++;
  18207. }
  18208. }
  18209. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  18210. if (instancesBuffer) {
  18211. instancesBuffer.dispose();
  18212. }
  18213. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  18214. this._instancesBuffer = instancesBuffer;
  18215. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  18216. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  18217. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  18218. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  18219. }
  18220. else {
  18221. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  18222. }
  18223. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  18224. this._draw(subMesh, fillMode, instancesCount);
  18225. engine.unbindInstanceAttributes();
  18226. };
  18227. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  18228. var scene = this.getScene();
  18229. var engine = scene.getEngine();
  18230. if (hardwareInstancedRendering) {
  18231. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  18232. }
  18233. else {
  18234. if (batch.renderSelf[subMesh._id]) {
  18235. // Draw
  18236. if (onBeforeDraw) {
  18237. onBeforeDraw(false, this.getWorldMatrix());
  18238. }
  18239. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  18240. }
  18241. if (batch.visibleInstances[subMesh._id]) {
  18242. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  18243. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  18244. // World
  18245. var world = instance.getWorldMatrix();
  18246. if (onBeforeDraw) {
  18247. onBeforeDraw(true, world);
  18248. }
  18249. // Draw
  18250. this._draw(subMesh, fillMode);
  18251. }
  18252. }
  18253. }
  18254. };
  18255. /**
  18256. * Triggers the draw call for the mesh.
  18257. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  18258. */
  18259. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  18260. var scene = this.getScene();
  18261. // Managing instances
  18262. var batch = this._getInstancesRenderList(subMesh._id);
  18263. if (batch.mustReturn) {
  18264. return;
  18265. }
  18266. // Checking geometry state
  18267. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  18268. return;
  18269. }
  18270. var callbackIndex;
  18271. this.onBeforeRenderObservable.notifyObservers(this);
  18272. var engine = scene.getEngine();
  18273. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  18274. // Material
  18275. var effectiveMaterial = subMesh.getMaterial();
  18276. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  18277. return;
  18278. }
  18279. // Outline - step 1
  18280. var savedDepthWrite = engine.getDepthWrite();
  18281. if (this.renderOutline) {
  18282. engine.setDepthWrite(false);
  18283. scene.getOutlineRenderer().render(subMesh, batch);
  18284. engine.setDepthWrite(savedDepthWrite);
  18285. }
  18286. effectiveMaterial._preBind();
  18287. var effect = effectiveMaterial.getEffect();
  18288. // Bind
  18289. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  18290. this._bind(subMesh, effect, fillMode);
  18291. var world = this.getWorldMatrix();
  18292. effectiveMaterial.bind(world, this);
  18293. // Alpha mode
  18294. if (enableAlphaMode) {
  18295. engine.setAlphaMode(effectiveMaterial.alphaMode);
  18296. }
  18297. // Draw
  18298. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  18299. if (isInstance) {
  18300. effectiveMaterial.bindOnlyWorldMatrix(world);
  18301. }
  18302. });
  18303. // Unbind
  18304. effectiveMaterial.unbind();
  18305. // Outline - step 2
  18306. if (this.renderOutline && savedDepthWrite) {
  18307. engine.setDepthWrite(true);
  18308. engine.setColorWrite(false);
  18309. scene.getOutlineRenderer().render(subMesh, batch);
  18310. engine.setColorWrite(true);
  18311. }
  18312. // Overlay
  18313. if (this.renderOverlay) {
  18314. var currentMode = engine.getAlphaMode();
  18315. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  18316. scene.getOutlineRenderer().render(subMesh, batch, true);
  18317. engine.setAlphaMode(currentMode);
  18318. }
  18319. this.onAfterRenderObservable.notifyObservers(this);
  18320. };
  18321. /**
  18322. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  18323. */
  18324. Mesh.prototype.getEmittedParticleSystems = function () {
  18325. var results = new Array();
  18326. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18327. var particleSystem = this.getScene().particleSystems[index];
  18328. if (particleSystem.emitter === this) {
  18329. results.push(particleSystem);
  18330. }
  18331. }
  18332. return results;
  18333. };
  18334. /**
  18335. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  18336. */
  18337. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  18338. var results = new Array();
  18339. var descendants = this.getDescendants();
  18340. descendants.push(this);
  18341. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18342. var particleSystem = this.getScene().particleSystems[index];
  18343. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  18344. results.push(particleSystem);
  18345. }
  18346. }
  18347. return results;
  18348. };
  18349. Mesh.prototype._checkDelayState = function () {
  18350. var _this = this;
  18351. var that = this;
  18352. var scene = this.getScene();
  18353. if (this._geometry) {
  18354. this._geometry.load(scene);
  18355. }
  18356. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18357. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  18358. scene._addPendingData(that);
  18359. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  18360. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  18361. if (data instanceof ArrayBuffer) {
  18362. _this._delayLoadingFunction(data, _this);
  18363. }
  18364. else {
  18365. _this._delayLoadingFunction(JSON.parse(data), _this);
  18366. }
  18367. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18368. scene._removePendingData(_this);
  18369. }, function () { }, scene.database, getBinaryData);
  18370. }
  18371. };
  18372. /**
  18373. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  18374. */
  18375. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  18376. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18377. return false;
  18378. }
  18379. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  18380. return false;
  18381. }
  18382. this._checkDelayState();
  18383. return true;
  18384. };
  18385. /**
  18386. * Sets the mesh material by the material or multiMaterial `id` property.
  18387. * The material `id` is a string identifying the material or the multiMaterial.
  18388. * This method returns nothing.
  18389. */
  18390. Mesh.prototype.setMaterialByID = function (id) {
  18391. var materials = this.getScene().materials;
  18392. var index;
  18393. for (index = 0; index < materials.length; index++) {
  18394. if (materials[index].id === id) {
  18395. this.material = materials[index];
  18396. return;
  18397. }
  18398. }
  18399. // Multi
  18400. var multiMaterials = this.getScene().multiMaterials;
  18401. for (index = 0; index < multiMaterials.length; index++) {
  18402. if (multiMaterials[index].id === id) {
  18403. this.material = multiMaterials[index];
  18404. return;
  18405. }
  18406. }
  18407. };
  18408. /**
  18409. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  18410. */
  18411. Mesh.prototype.getAnimatables = function () {
  18412. var results = [];
  18413. if (this.material) {
  18414. results.push(this.material);
  18415. }
  18416. if (this.skeleton) {
  18417. results.push(this.skeleton);
  18418. }
  18419. return results;
  18420. };
  18421. /**
  18422. * Modifies the mesh geometry according to the passed transformation matrix.
  18423. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  18424. * The mesh normals are modified accordingly the same transformation.
  18425. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18426. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18427. */
  18428. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  18429. // Position
  18430. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18431. return;
  18432. }
  18433. var submeshes = this.subMeshes.splice(0);
  18434. this._resetPointsArrayCache();
  18435. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18436. var temp = [];
  18437. var index;
  18438. for (index = 0; index < data.length; index += 3) {
  18439. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  18440. }
  18441. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  18442. // Normals
  18443. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18444. return;
  18445. }
  18446. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18447. temp = [];
  18448. for (index = 0; index < data.length; index += 3) {
  18449. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  18450. }
  18451. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  18452. // flip faces?
  18453. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  18454. this.flipFaces();
  18455. }
  18456. // Restore submeshes
  18457. this.releaseSubMeshes();
  18458. this.subMeshes = submeshes;
  18459. };
  18460. /**
  18461. * Modifies the mesh geometry according to its own current World Matrix.
  18462. * The mesh World Matrix is then reset.
  18463. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  18464. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18465. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18466. */
  18467. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  18468. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  18469. this.scaling.copyFromFloats(1, 1, 1);
  18470. this.position.copyFromFloats(0, 0, 0);
  18471. this.rotation.copyFromFloats(0, 0, 0);
  18472. //only if quaternion is already set
  18473. if (this.rotationQuaternion) {
  18474. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  18475. }
  18476. this._worldMatrix = BABYLON.Matrix.Identity();
  18477. };
  18478. // Cache
  18479. Mesh.prototype._resetPointsArrayCache = function () {
  18480. this._positions = null;
  18481. };
  18482. Mesh.prototype._generatePointsArray = function () {
  18483. if (this._positions)
  18484. return true;
  18485. this._positions = [];
  18486. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18487. if (!data) {
  18488. return false;
  18489. }
  18490. for (var index = 0; index < data.length; index += 3) {
  18491. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  18492. }
  18493. return true;
  18494. };
  18495. /**
  18496. * Returns a new Mesh object generated from the current mesh properties.
  18497. * This method must not get confused with createInstance().
  18498. * The parameter `name` is a string, the name given to the new mesh.
  18499. * The optional parameter `newParent` can be any `Node` object (default `null`).
  18500. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  18501. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  18502. */
  18503. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  18504. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18505. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  18506. };
  18507. /**
  18508. * Disposes the mesh.
  18509. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  18510. */
  18511. Mesh.prototype.dispose = function (doNotRecurse) {
  18512. if (this._geometry) {
  18513. this._geometry.releaseForMesh(this, true);
  18514. }
  18515. // Instances
  18516. if (this._instancesBuffer) {
  18517. this._instancesBuffer.dispose();
  18518. this._instancesBuffer = null;
  18519. }
  18520. while (this.instances.length) {
  18521. this.instances[0].dispose();
  18522. }
  18523. _super.prototype.dispose.call(this, doNotRecurse);
  18524. };
  18525. /**
  18526. * Modifies the mesh geometry according to a displacement map.
  18527. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  18528. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  18529. * This method returns nothing.
  18530. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  18531. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  18532. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  18533. */
  18534. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  18535. var _this = this;
  18536. var scene = this.getScene();
  18537. var onload = function (img) {
  18538. // Getting height map data
  18539. var canvas = document.createElement("canvas");
  18540. var context = canvas.getContext("2d");
  18541. var heightMapWidth = img.width;
  18542. var heightMapHeight = img.height;
  18543. canvas.width = heightMapWidth;
  18544. canvas.height = heightMapHeight;
  18545. context.drawImage(img, 0, 0);
  18546. // Create VertexData from map data
  18547. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  18548. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  18549. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  18550. //execute success callback, if set
  18551. if (onSuccess) {
  18552. onSuccess(_this);
  18553. }
  18554. };
  18555. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  18556. };
  18557. /**
  18558. * Modifies the mesh geometry according to a displacementMap buffer.
  18559. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  18560. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  18561. * This method returns nothing.
  18562. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  18563. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  18564. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  18565. */
  18566. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  18567. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  18568. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  18569. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18570. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  18571. return;
  18572. }
  18573. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18574. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18575. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18576. var position = BABYLON.Vector3.Zero();
  18577. var normal = BABYLON.Vector3.Zero();
  18578. var uv = BABYLON.Vector2.Zero();
  18579. for (var index = 0; index < positions.length; index += 3) {
  18580. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  18581. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  18582. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  18583. // Compute height
  18584. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  18585. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  18586. var pos = (u + v * heightMapWidth) * 4;
  18587. var r = buffer[pos] / 255.0;
  18588. var g = buffer[pos + 1] / 255.0;
  18589. var b = buffer[pos + 2] / 255.0;
  18590. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  18591. normal.normalize();
  18592. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  18593. position = position.add(normal);
  18594. position.toArray(positions, index);
  18595. }
  18596. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  18597. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  18598. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18599. };
  18600. /**
  18601. * Modify the mesh to get a flat shading rendering.
  18602. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  18603. * This method returns nothing.
  18604. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  18605. */
  18606. Mesh.prototype.convertToFlatShadedMesh = function () {
  18607. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  18608. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  18609. var kinds = this.getVerticesDataKinds();
  18610. var vbs = [];
  18611. var data = [];
  18612. var newdata = [];
  18613. var updatableNormals = false;
  18614. var kindIndex;
  18615. var kind;
  18616. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18617. kind = kinds[kindIndex];
  18618. var vertexBuffer = this.getVertexBuffer(kind);
  18619. if (kind === BABYLON.VertexBuffer.NormalKind) {
  18620. updatableNormals = vertexBuffer.isUpdatable();
  18621. kinds.splice(kindIndex, 1);
  18622. kindIndex--;
  18623. continue;
  18624. }
  18625. vbs[kind] = vertexBuffer;
  18626. data[kind] = vbs[kind].getData();
  18627. newdata[kind] = [];
  18628. }
  18629. // Save previous submeshes
  18630. var previousSubmeshes = this.subMeshes.slice(0);
  18631. var indices = this.getIndices();
  18632. var totalIndices = this.getTotalIndices();
  18633. // Generating unique vertices per face
  18634. var index;
  18635. for (index = 0; index < totalIndices; index++) {
  18636. var vertexIndex = indices[index];
  18637. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18638. kind = kinds[kindIndex];
  18639. var stride = vbs[kind].getStrideSize();
  18640. for (var offset = 0; offset < stride; offset++) {
  18641. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  18642. }
  18643. }
  18644. }
  18645. // Updating faces & normal
  18646. var normals = [];
  18647. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  18648. for (index = 0; index < totalIndices; index += 3) {
  18649. indices[index] = index;
  18650. indices[index + 1] = index + 1;
  18651. indices[index + 2] = index + 2;
  18652. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  18653. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  18654. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  18655. var p1p2 = p1.subtract(p2);
  18656. var p3p2 = p3.subtract(p2);
  18657. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  18658. // Store same normals for every vertex
  18659. for (var localIndex = 0; localIndex < 3; localIndex++) {
  18660. normals.push(normal.x);
  18661. normals.push(normal.y);
  18662. normals.push(normal.z);
  18663. }
  18664. }
  18665. this.setIndices(indices);
  18666. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  18667. // Updating vertex buffers
  18668. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18669. kind = kinds[kindIndex];
  18670. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  18671. }
  18672. // Updating submeshes
  18673. this.releaseSubMeshes();
  18674. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  18675. var previousOne = previousSubmeshes[submeshIndex];
  18676. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  18677. }
  18678. this.synchronizeInstances();
  18679. };
  18680. /**
  18681. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  18682. * In other words, more vertices, no more indices and a single bigger VBO.
  18683. * This method returns nothing.
  18684. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  18685. *
  18686. */
  18687. Mesh.prototype.convertToUnIndexedMesh = function () {
  18688. /// <summary>Remove indices by unfolding faces into buffers</summary>
  18689. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  18690. var kinds = this.getVerticesDataKinds();
  18691. var vbs = [];
  18692. var data = [];
  18693. var newdata = [];
  18694. var updatableNormals = false;
  18695. var kindIndex;
  18696. var kind;
  18697. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18698. kind = kinds[kindIndex];
  18699. var vertexBuffer = this.getVertexBuffer(kind);
  18700. vbs[kind] = vertexBuffer;
  18701. data[kind] = vbs[kind].getData();
  18702. newdata[kind] = [];
  18703. }
  18704. // Save previous submeshes
  18705. var previousSubmeshes = this.subMeshes.slice(0);
  18706. var indices = this.getIndices();
  18707. var totalIndices = this.getTotalIndices();
  18708. // Generating unique vertices per face
  18709. var index;
  18710. for (index = 0; index < totalIndices; index++) {
  18711. var vertexIndex = indices[index];
  18712. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18713. kind = kinds[kindIndex];
  18714. var stride = vbs[kind].getStrideSize();
  18715. for (var offset = 0; offset < stride; offset++) {
  18716. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  18717. }
  18718. }
  18719. }
  18720. // Updating indices
  18721. for (index = 0; index < totalIndices; index += 3) {
  18722. indices[index] = index;
  18723. indices[index + 1] = index + 1;
  18724. indices[index + 2] = index + 2;
  18725. }
  18726. this.setIndices(indices);
  18727. // Updating vertex buffers
  18728. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18729. kind = kinds[kindIndex];
  18730. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  18731. }
  18732. // Updating submeshes
  18733. this.releaseSubMeshes();
  18734. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  18735. var previousOne = previousSubmeshes[submeshIndex];
  18736. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  18737. }
  18738. this._unIndexed = true;
  18739. this.synchronizeInstances();
  18740. };
  18741. /**
  18742. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  18743. * This method returns nothing.
  18744. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  18745. */
  18746. Mesh.prototype.flipFaces = function (flipNormals) {
  18747. if (flipNormals === void 0) { flipNormals = false; }
  18748. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  18749. var i;
  18750. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18751. for (i = 0; i < vertex_data.normals.length; i++) {
  18752. vertex_data.normals[i] *= -1;
  18753. }
  18754. }
  18755. var temp;
  18756. for (i = 0; i < vertex_data.indices.length; i += 3) {
  18757. // reassign indices
  18758. temp = vertex_data.indices[i + 1];
  18759. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  18760. vertex_data.indices[i + 2] = temp;
  18761. }
  18762. vertex_data.applyToMesh(this);
  18763. };
  18764. // Instances
  18765. /**
  18766. * Creates a new InstancedMesh object from the mesh model.
  18767. * An instance shares the same properties and the same material than its model.
  18768. * Only these properties of each instance can then be set individually :
  18769. * - position
  18770. * - rotation
  18771. * - rotationQuaternion
  18772. * - setPivotMatrix
  18773. * - scaling
  18774. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  18775. * Warning : this method is not supported for Line mesh and LineSystem
  18776. */
  18777. Mesh.prototype.createInstance = function (name) {
  18778. return new BABYLON.InstancedMesh(name, this);
  18779. };
  18780. /**
  18781. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  18782. * After this call, all the mesh instances have the same submeshes than the current mesh.
  18783. * This method returns nothing.
  18784. */
  18785. Mesh.prototype.synchronizeInstances = function () {
  18786. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  18787. var instance = this.instances[instanceIndex];
  18788. instance._syncSubMeshes();
  18789. }
  18790. };
  18791. /**
  18792. * Simplify the mesh according to the given array of settings.
  18793. * Function will return immediately and will simplify async. It returns nothing.
  18794. * @param settings a collection of simplification settings.
  18795. * @param parallelProcessing should all levels calculate parallel or one after the other.
  18796. * @param type the type of simplification to run.
  18797. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  18798. */
  18799. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  18800. if (parallelProcessing === void 0) { parallelProcessing = true; }
  18801. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  18802. this.getScene().simplificationQueue.addTask({
  18803. settings: settings,
  18804. parallelProcessing: parallelProcessing,
  18805. mesh: this,
  18806. simplificationType: simplificationType,
  18807. successCallback: successCallback
  18808. });
  18809. };
  18810. /**
  18811. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  18812. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  18813. * This should be used together with the simplification to avoid disappearing triangles.
  18814. * @param successCallback an optional success callback to be called after the optimization finished.
  18815. */
  18816. Mesh.prototype.optimizeIndices = function (successCallback) {
  18817. var _this = this;
  18818. var indices = this.getIndices();
  18819. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18820. var vectorPositions = [];
  18821. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  18822. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  18823. }
  18824. var dupes = [];
  18825. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  18826. var realPos = vectorPositions.length - 1 - iteration;
  18827. var testedPosition = vectorPositions[realPos];
  18828. for (var j = 0; j < realPos; ++j) {
  18829. var againstPosition = vectorPositions[j];
  18830. if (testedPosition.equals(againstPosition)) {
  18831. dupes[realPos] = j;
  18832. break;
  18833. }
  18834. }
  18835. }, function () {
  18836. for (var i = 0; i < indices.length; ++i) {
  18837. indices[i] = dupes[indices[i]] || indices[i];
  18838. }
  18839. //indices are now reordered
  18840. var originalSubMeshes = _this.subMeshes.slice(0);
  18841. _this.setIndices(indices);
  18842. _this.subMeshes = originalSubMeshes;
  18843. if (successCallback) {
  18844. successCallback(_this);
  18845. }
  18846. });
  18847. };
  18848. // Statics
  18849. /**
  18850. * Returns a new Mesh object what is a deep copy of the passed mesh.
  18851. * The parameter `parsedMesh` is the mesh to be copied.
  18852. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18853. */
  18854. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  18855. var mesh = new Mesh(parsedMesh.name, scene);
  18856. mesh.id = parsedMesh.id;
  18857. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18858. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18859. if (parsedMesh.rotationQuaternion) {
  18860. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18861. }
  18862. else if (parsedMesh.rotation) {
  18863. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18864. }
  18865. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18866. if (parsedMesh.localMatrix) {
  18867. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18868. }
  18869. else if (parsedMesh.pivotMatrix) {
  18870. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18871. }
  18872. mesh.setEnabled(parsedMesh.isEnabled);
  18873. mesh.isVisible = parsedMesh.isVisible;
  18874. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18875. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18876. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18877. if (parsedMesh.applyFog !== undefined) {
  18878. mesh.applyFog = parsedMesh.applyFog;
  18879. }
  18880. if (parsedMesh.pickable !== undefined) {
  18881. mesh.isPickable = parsedMesh.pickable;
  18882. }
  18883. if (parsedMesh.alphaIndex !== undefined) {
  18884. mesh.alphaIndex = parsedMesh.alphaIndex;
  18885. }
  18886. mesh.receiveShadows = parsedMesh.receiveShadows;
  18887. mesh.billboardMode = parsedMesh.billboardMode;
  18888. if (parsedMesh.visibility !== undefined) {
  18889. mesh.visibility = parsedMesh.visibility;
  18890. }
  18891. mesh.checkCollisions = parsedMesh.checkCollisions;
  18892. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18893. // freezeWorldMatrix
  18894. if (parsedMesh.freezeWorldMatrix) {
  18895. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  18896. }
  18897. // Parent
  18898. if (parsedMesh.parentId) {
  18899. mesh._waitingParentId = parsedMesh.parentId;
  18900. }
  18901. // Actions
  18902. if (parsedMesh.actions !== undefined) {
  18903. mesh._waitingActions = parsedMesh.actions;
  18904. }
  18905. // Geometry
  18906. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18907. if (parsedMesh.delayLoadingFile) {
  18908. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18909. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18910. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18911. if (parsedMesh._binaryInfo) {
  18912. mesh._binaryInfo = parsedMesh._binaryInfo;
  18913. }
  18914. mesh._delayInfo = [];
  18915. if (parsedMesh.hasUVs) {
  18916. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18917. }
  18918. if (parsedMesh.hasUVs2) {
  18919. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18920. }
  18921. if (parsedMesh.hasUVs3) {
  18922. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  18923. }
  18924. if (parsedMesh.hasUVs4) {
  18925. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  18926. }
  18927. if (parsedMesh.hasUVs5) {
  18928. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  18929. }
  18930. if (parsedMesh.hasUVs6) {
  18931. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  18932. }
  18933. if (parsedMesh.hasColors) {
  18934. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18935. }
  18936. if (parsedMesh.hasMatricesIndices) {
  18937. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18938. }
  18939. if (parsedMesh.hasMatricesWeights) {
  18940. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18941. }
  18942. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  18943. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18944. mesh._checkDelayState();
  18945. }
  18946. }
  18947. else {
  18948. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  18949. }
  18950. // Material
  18951. if (parsedMesh.materialId) {
  18952. mesh.setMaterialByID(parsedMesh.materialId);
  18953. }
  18954. else {
  18955. mesh.material = null;
  18956. }
  18957. // Skeleton
  18958. if (parsedMesh.skeletonId > -1) {
  18959. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18960. if (parsedMesh.numBoneInfluencers) {
  18961. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  18962. }
  18963. }
  18964. // Animations
  18965. if (parsedMesh.animations) {
  18966. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18967. var parsedAnimation = parsedMesh.animations[animationIndex];
  18968. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18969. }
  18970. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  18971. }
  18972. if (parsedMesh.autoAnimate) {
  18973. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  18974. }
  18975. // Layer Mask
  18976. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18977. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18978. }
  18979. else {
  18980. mesh.layerMask = 0x0FFFFFFF;
  18981. }
  18982. //(Deprecated) physics
  18983. if (parsedMesh.physicsImpostor) {
  18984. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  18985. mass: parsedMesh.physicsMass,
  18986. friction: parsedMesh.physicsFriction,
  18987. restitution: parsedMesh.physicsRestitution
  18988. }, scene);
  18989. }
  18990. // Instances
  18991. if (parsedMesh.instances) {
  18992. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18993. var parsedInstance = parsedMesh.instances[index];
  18994. var instance = mesh.createInstance(parsedInstance.name);
  18995. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18996. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18997. if (parsedInstance.rotationQuaternion) {
  18998. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18999. }
  19000. else if (parsedInstance.rotation) {
  19001. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19002. }
  19003. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19004. instance.checkCollisions = mesh.checkCollisions;
  19005. if (parsedMesh.animations) {
  19006. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19007. parsedAnimation = parsedMesh.animations[animationIndex];
  19008. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19009. }
  19010. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  19011. }
  19012. }
  19013. }
  19014. return mesh;
  19015. };
  19016. /**
  19017. * Creates a ribbon mesh.
  19018. * Please consider using the same method from the MeshBuilder class instead.
  19019. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19020. *
  19021. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19022. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19023. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19024. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19025. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  19026. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  19027. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  19028. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19029. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19030. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19031. */
  19032. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  19033. return BABYLON.MeshBuilder.CreateRibbon(name, {
  19034. pathArray: pathArray,
  19035. closeArray: closeArray,
  19036. closePath: closePath,
  19037. offset: offset,
  19038. updatable: updatable,
  19039. sideOrientation: sideOrientation,
  19040. instance: instance
  19041. }, scene);
  19042. };
  19043. /**
  19044. * Creates a plane polygonal mesh. By default, this is a disc.
  19045. * Please consider using the same method from the MeshBuilder class instead.
  19046. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19047. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  19048. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19049. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19050. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19051. */
  19052. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  19053. var options = {
  19054. radius: radius,
  19055. tessellation: tessellation,
  19056. sideOrientation: sideOrientation,
  19057. updatable: updatable
  19058. };
  19059. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  19060. };
  19061. /**
  19062. * Creates a box mesh.
  19063. * Please consider using the same method from the MeshBuilder class instead.
  19064. * The parameter `size` sets the size (float) of each box side (default 1).
  19065. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19066. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19067. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19068. */
  19069. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  19070. var options = {
  19071. size: size,
  19072. sideOrientation: sideOrientation,
  19073. updatable: updatable
  19074. };
  19075. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  19076. };
  19077. /**
  19078. * Creates a sphere mesh.
  19079. * Please consider using the same method from the MeshBuilder class instead.
  19080. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19081. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19082. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19083. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19084. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19085. */
  19086. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  19087. var options = {
  19088. segments: segments,
  19089. diameterX: diameter,
  19090. diameterY: diameter,
  19091. diameterZ: diameter,
  19092. sideOrientation: sideOrientation,
  19093. updatable: updatable
  19094. };
  19095. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  19096. };
  19097. /**
  19098. * Creates a cylinder or a cone mesh.
  19099. * Please consider using the same method from the MeshBuilder class instead.
  19100. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19101. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19102. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  19103. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19104. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19105. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19106. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19107. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19108. */
  19109. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  19110. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  19111. if (scene !== undefined) {
  19112. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  19113. updatable = scene;
  19114. }
  19115. scene = subdivisions;
  19116. subdivisions = 1;
  19117. }
  19118. var options = {
  19119. height: height,
  19120. diameterTop: diameterTop,
  19121. diameterBottom: diameterBottom,
  19122. tessellation: tessellation,
  19123. subdivisions: subdivisions,
  19124. sideOrientation: sideOrientation,
  19125. updatable: updatable
  19126. };
  19127. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  19128. };
  19129. // Torus (Code from SharpDX.org)
  19130. /**
  19131. * Creates a torus mesh.
  19132. * Please consider using the same method from the MeshBuilder class instead.
  19133. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19134. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19135. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19136. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19137. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19138. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19139. */
  19140. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  19141. var options = {
  19142. diameter: diameter,
  19143. thickness: thickness,
  19144. tessellation: tessellation,
  19145. sideOrientation: sideOrientation,
  19146. updatable: updatable
  19147. };
  19148. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  19149. };
  19150. /**
  19151. * Creates a torus knot mesh.
  19152. * Please consider using the same method from the MeshBuilder class instead.
  19153. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19154. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19155. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19156. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19157. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19158. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19159. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19160. */
  19161. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  19162. var options = {
  19163. radius: radius,
  19164. tube: tube,
  19165. radialSegments: radialSegments,
  19166. tubularSegments: tubularSegments,
  19167. p: p,
  19168. q: q,
  19169. sideOrientation: sideOrientation,
  19170. updatable: updatable
  19171. };
  19172. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  19173. };
  19174. /**
  19175. * Creates a line mesh.
  19176. * Please consider using the same method from the MeshBuilder class instead.
  19177. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  19178. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19179. * The parameter `points` is an array successive Vector3.
  19180. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  19181. * When updating an instance, remember that only point positions can change, not the number of points.
  19182. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19183. */
  19184. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  19185. var options = {
  19186. points: points,
  19187. updatable: updatable,
  19188. instance: instance
  19189. };
  19190. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  19191. };
  19192. /**
  19193. * Creates a dashed line mesh.
  19194. * Please consider using the same method from the MeshBuilder class instead.
  19195. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  19196. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19197. * The parameter `points` is an array successive Vector3.
  19198. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19199. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19200. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19201. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  19202. * When updating an instance, remember that only point positions can change, not the number of points.
  19203. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19204. */
  19205. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  19206. var options = {
  19207. points: points,
  19208. dashSize: dashSize,
  19209. gapSize: gapSize,
  19210. dashNb: dashNb,
  19211. updatable: updatable
  19212. };
  19213. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  19214. };
  19215. /**
  19216. * Creates an extruded shape mesh.
  19217. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19218. * Please consider using the same method from the MeshBuilder class instead.
  19219. *
  19220. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19221. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  19222. * extruded along the Z axis.
  19223. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19224. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  19225. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19226. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19227. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  19228. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19229. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19230. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19231. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19232. */
  19233. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  19234. var options = {
  19235. shape: shape,
  19236. path: path,
  19237. scale: scale,
  19238. rotation: rotation,
  19239. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19240. sideOrientation: sideOrientation,
  19241. instance: instance,
  19242. updatable: updatable
  19243. };
  19244. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  19245. };
  19246. /**
  19247. * Creates an custom extruded shape mesh.
  19248. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19249. * Please consider using the same method from the MeshBuilder class instead.
  19250. *
  19251. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19252. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  19253. * extruded along the Z axis.
  19254. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19255. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  19256. * and the distance of this point from the begining of the path :
  19257. * ```javascript
  19258. * var rotationFunction = function(i, distance) {
  19259. * // do things
  19260. * return rotationValue; }
  19261. * ```
  19262. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19263. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  19264. * and the distance of this point from the begining of the path :
  19265. * ```javascript
  19266. * var scaleFunction = function(i, distance) {
  19267. * // do things
  19268. * return scaleValue;}
  19269. * ```
  19270. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19271. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19272. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19273. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19274. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  19275. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19276. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19277. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19278. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19279. */
  19280. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  19281. var options = {
  19282. shape: shape,
  19283. path: path,
  19284. scaleFunction: scaleFunction,
  19285. rotationFunction: rotationFunction,
  19286. ribbonCloseArray: ribbonCloseArray,
  19287. ribbonClosePath: ribbonClosePath,
  19288. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19289. sideOrientation: sideOrientation,
  19290. instance: instance,
  19291. updatable: updatable
  19292. };
  19293. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  19294. };
  19295. /**
  19296. * Creates lathe mesh.
  19297. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19298. * Please consider using the same method from the MeshBuilder class instead.
  19299. *
  19300. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  19301. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19302. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19303. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19304. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19305. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19306. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19307. */
  19308. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  19309. var options = {
  19310. shape: shape,
  19311. radius: radius,
  19312. tessellation: tessellation,
  19313. sideOrientation: sideOrientation,
  19314. updatable: updatable
  19315. };
  19316. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  19317. };
  19318. /**
  19319. * Creates a plane mesh.
  19320. * Please consider using the same method from the MeshBuilder class instead.
  19321. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19322. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19323. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19324. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19325. */
  19326. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  19327. var options = {
  19328. size: size,
  19329. width: size,
  19330. height: size,
  19331. sideOrientation: sideOrientation,
  19332. updatable: updatable
  19333. };
  19334. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  19335. };
  19336. /**
  19337. * Creates a ground mesh.
  19338. * Please consider using the same method from the MeshBuilder class instead.
  19339. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19340. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19341. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19342. */
  19343. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  19344. var options = {
  19345. width: width,
  19346. height: height,
  19347. subdivisions: subdivisions,
  19348. updatable: updatable
  19349. };
  19350. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  19351. };
  19352. /**
  19353. * Creates a tiled ground mesh.
  19354. * Please consider using the same method from the MeshBuilder class instead.
  19355. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19356. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19357. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19358. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19359. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19360. * numbers of subdivisions on the ground width and height of each tile.
  19361. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19362. */
  19363. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  19364. var options = {
  19365. xmin: xmin,
  19366. zmin: zmin,
  19367. xmax: xmax,
  19368. zmax: zmax,
  19369. subdivisions: subdivisions,
  19370. precision: precision,
  19371. updatable: updatable
  19372. };
  19373. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  19374. };
  19375. /**
  19376. * Creates a ground mesh from a height map.
  19377. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19378. * Please consider using the same method from the MeshBuilder class instead.
  19379. * The parameter `url` sets the URL of the height map image resource.
  19380. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19381. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19382. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19383. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19384. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  19385. * This function is passed the newly built mesh :
  19386. * ```javascript
  19387. * function(mesh) { // do things
  19388. * return; }
  19389. * ```
  19390. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19391. */
  19392. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  19393. var options = {
  19394. width: width,
  19395. height: height,
  19396. subdivisions: subdivisions,
  19397. minHeight: minHeight,
  19398. maxHeight: maxHeight,
  19399. updatable: updatable,
  19400. onReady: onReady
  19401. };
  19402. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  19403. };
  19404. /**
  19405. * Creates a tube mesh.
  19406. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19407. *
  19408. * Please consider using the same method from the MeshBuilder class instead.
  19409. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  19410. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19411. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19412. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19413. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  19414. * It must return a radius value (positive float) :
  19415. * ```javascript
  19416. * var radiusFunction = function(i, distance) {
  19417. * // do things
  19418. * return radius; }
  19419. * ```
  19420. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19421. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  19422. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19423. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19424. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19425. */
  19426. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  19427. var options = {
  19428. path: path,
  19429. radius: radius,
  19430. tessellation: tessellation,
  19431. radiusFunction: radiusFunction,
  19432. arc: 1,
  19433. cap: cap,
  19434. updatable: updatable,
  19435. sideOrientation: sideOrientation,
  19436. instance: instance
  19437. };
  19438. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  19439. };
  19440. /**
  19441. * Creates a polyhedron mesh.
  19442. *
  19443. * Please consider using the same method from the MeshBuilder class instead.
  19444. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  19445. * to choose the wanted type.
  19446. * The parameter `size` (positive float, default 1) sets the polygon size.
  19447. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19448. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  19449. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  19450. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  19451. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19452. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  19453. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19454. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19455. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19456. */
  19457. Mesh.CreatePolyhedron = function (name, options, scene) {
  19458. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  19459. };
  19460. /**
  19461. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19462. * Please consider using the same method from the MeshBuilder class instead.
  19463. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19464. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  19465. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19466. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  19467. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19468. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19469. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19470. */
  19471. Mesh.CreateIcoSphere = function (name, options, scene) {
  19472. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  19473. };
  19474. /**
  19475. * Creates a decal mesh.
  19476. * Please consider using the same method from the MeshBuilder class instead.
  19477. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  19478. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19479. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19480. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  19481. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  19482. */
  19483. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  19484. var options = {
  19485. position: position,
  19486. normal: normal,
  19487. size: size,
  19488. angle: angle
  19489. };
  19490. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  19491. };
  19492. // Skeletons
  19493. /**
  19494. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19495. */
  19496. Mesh.prototype.setPositionsForCPUSkinning = function () {
  19497. var source;
  19498. if (!this._sourcePositions) {
  19499. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19500. this._sourcePositions = new Float32Array(source);
  19501. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  19502. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  19503. }
  19504. }
  19505. return this._sourcePositions;
  19506. };
  19507. /**
  19508. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19509. */
  19510. Mesh.prototype.setNormalsForCPUSkinning = function () {
  19511. var source;
  19512. if (!this._sourceNormals) {
  19513. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19514. this._sourceNormals = new Float32Array(source);
  19515. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  19516. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  19517. }
  19518. }
  19519. return this._sourceNormals;
  19520. };
  19521. /**
  19522. * Update the vertex buffers by applying transformation from the bones
  19523. * @param {skeleton} skeleton to apply
  19524. */
  19525. Mesh.prototype.applySkeleton = function (skeleton) {
  19526. if (!this.geometry) {
  19527. return;
  19528. }
  19529. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  19530. return;
  19531. }
  19532. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  19533. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19534. return this;
  19535. }
  19536. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19537. return this;
  19538. }
  19539. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19540. return this;
  19541. }
  19542. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19543. return this;
  19544. }
  19545. if (!this._sourcePositions) {
  19546. this.setPositionsForCPUSkinning();
  19547. }
  19548. if (!this._sourceNormals) {
  19549. this.setNormalsForCPUSkinning();
  19550. }
  19551. // positionsData checks for not being Float32Array will only pass at most once
  19552. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19553. if (!(positionsData instanceof Float32Array)) {
  19554. positionsData = new Float32Array(positionsData);
  19555. }
  19556. // normalsData checks for not being Float32Array will only pass at most once
  19557. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19558. if (!(normalsData instanceof Float32Array)) {
  19559. normalsData = new Float32Array(normalsData);
  19560. }
  19561. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19562. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19563. var needExtras = this.numBoneInfluencers > 4;
  19564. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  19565. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  19566. var skeletonMatrices = skeleton.getTransformMatrices(this);
  19567. var tempVector3 = BABYLON.Vector3.Zero();
  19568. var finalMatrix = new BABYLON.Matrix();
  19569. var tempMatrix = new BABYLON.Matrix();
  19570. var matWeightIdx = 0;
  19571. var inf;
  19572. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  19573. var weight;
  19574. for (inf = 0; inf < 4; inf++) {
  19575. weight = matricesWeightsData[matWeightIdx + inf];
  19576. if (weight > 0) {
  19577. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  19578. finalMatrix.addToSelf(tempMatrix);
  19579. }
  19580. else
  19581. break;
  19582. }
  19583. if (needExtras) {
  19584. for (inf = 0; inf < 4; inf++) {
  19585. weight = matricesWeightsExtraData[matWeightIdx + inf];
  19586. if (weight > 0) {
  19587. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  19588. finalMatrix.addToSelf(tempMatrix);
  19589. }
  19590. else
  19591. break;
  19592. }
  19593. }
  19594. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  19595. tempVector3.toArray(positionsData, index);
  19596. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  19597. tempVector3.toArray(normalsData, index);
  19598. finalMatrix.reset();
  19599. }
  19600. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  19601. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  19602. return this;
  19603. };
  19604. // Tools
  19605. /**
  19606. * Returns an object `{min: Vector3, max: Vector3}`
  19607. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  19608. */
  19609. Mesh.MinMax = function (meshes) {
  19610. var minVector = null;
  19611. var maxVector = null;
  19612. for (var i in meshes) {
  19613. var mesh = meshes[i];
  19614. var boundingBox = mesh.getBoundingInfo().boundingBox;
  19615. if (!minVector) {
  19616. minVector = boundingBox.minimumWorld;
  19617. maxVector = boundingBox.maximumWorld;
  19618. continue;
  19619. }
  19620. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  19621. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  19622. }
  19623. return {
  19624. min: minVector,
  19625. max: maxVector
  19626. };
  19627. };
  19628. /**
  19629. * Returns a `Vector3`, the center of the `{min: Vector3, max: Vector3}` or the center of MinMax vector3 computed from a mesh array.
  19630. */
  19631. Mesh.Center = function (meshesOrMinMaxVector) {
  19632. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  19633. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  19634. };
  19635. /**
  19636. * Merge the array of meshes into a single mesh for performance reasons.
  19637. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  19638. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  19639. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  19640. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  19641. */
  19642. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  19643. if (disposeSource === void 0) { disposeSource = true; }
  19644. var index;
  19645. if (!allow32BitsIndices) {
  19646. var totalVertices = 0;
  19647. // Counting vertices
  19648. for (index = 0; index < meshes.length; index++) {
  19649. if (meshes[index]) {
  19650. totalVertices += meshes[index].getTotalVertices();
  19651. if (totalVertices > 65536) {
  19652. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  19653. return null;
  19654. }
  19655. }
  19656. }
  19657. }
  19658. // Merge
  19659. var vertexData;
  19660. var otherVertexData;
  19661. var source;
  19662. for (index = 0; index < meshes.length; index++) {
  19663. if (meshes[index]) {
  19664. meshes[index].computeWorldMatrix(true);
  19665. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  19666. otherVertexData.transform(meshes[index].getWorldMatrix());
  19667. if (vertexData) {
  19668. vertexData.merge(otherVertexData);
  19669. }
  19670. else {
  19671. vertexData = otherVertexData;
  19672. source = meshes[index];
  19673. }
  19674. }
  19675. }
  19676. if (!meshSubclass) {
  19677. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  19678. }
  19679. vertexData.applyToMesh(meshSubclass);
  19680. // Setting properties
  19681. meshSubclass.material = source.material;
  19682. meshSubclass.checkCollisions = source.checkCollisions;
  19683. // Cleaning
  19684. if (disposeSource) {
  19685. for (index = 0; index < meshes.length; index++) {
  19686. if (meshes[index]) {
  19687. meshes[index].dispose();
  19688. }
  19689. }
  19690. }
  19691. return meshSubclass;
  19692. };
  19693. // Consts
  19694. Mesh._FRONTSIDE = 0;
  19695. Mesh._BACKSIDE = 1;
  19696. Mesh._DOUBLESIDE = 2;
  19697. Mesh._DEFAULTSIDE = 0;
  19698. Mesh._NO_CAP = 0;
  19699. Mesh._CAP_START = 1;
  19700. Mesh._CAP_END = 2;
  19701. Mesh._CAP_ALL = 3;
  19702. return Mesh;
  19703. })(BABYLON.AbstractMesh);
  19704. BABYLON.Mesh = Mesh;
  19705. })(BABYLON || (BABYLON = {}));
  19706. var BABYLON;
  19707. (function (BABYLON) {
  19708. var SubMesh = (function () {
  19709. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  19710. if (createBoundingBox === void 0) { createBoundingBox = true; }
  19711. this.materialIndex = materialIndex;
  19712. this.verticesStart = verticesStart;
  19713. this.verticesCount = verticesCount;
  19714. this.indexStart = indexStart;
  19715. this.indexCount = indexCount;
  19716. this._renderId = 0;
  19717. this._mesh = mesh;
  19718. this._renderingMesh = renderingMesh || mesh;
  19719. mesh.subMeshes.push(this);
  19720. this._trianglePlanes = [];
  19721. this._id = mesh.subMeshes.length - 1;
  19722. if (createBoundingBox) {
  19723. this.refreshBoundingInfo();
  19724. mesh.computeWorldMatrix(true);
  19725. }
  19726. }
  19727. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  19728. get: function () {
  19729. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  19730. },
  19731. enumerable: true,
  19732. configurable: true
  19733. });
  19734. SubMesh.prototype.getBoundingInfo = function () {
  19735. if (this.IsGlobal) {
  19736. return this._mesh.getBoundingInfo();
  19737. }
  19738. return this._boundingInfo;
  19739. };
  19740. SubMesh.prototype.getMesh = function () {
  19741. return this._mesh;
  19742. };
  19743. SubMesh.prototype.getRenderingMesh = function () {
  19744. return this._renderingMesh;
  19745. };
  19746. SubMesh.prototype.getMaterial = function () {
  19747. var rootMaterial = this._renderingMesh.material;
  19748. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  19749. var multiMaterial = rootMaterial;
  19750. return multiMaterial.getSubMaterial(this.materialIndex);
  19751. }
  19752. if (!rootMaterial) {
  19753. return this._mesh.getScene().defaultMaterial;
  19754. }
  19755. return rootMaterial;
  19756. };
  19757. // Methods
  19758. SubMesh.prototype.refreshBoundingInfo = function () {
  19759. this._lastColliderWorldVertices = null;
  19760. if (this.IsGlobal) {
  19761. return;
  19762. }
  19763. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19764. if (!data) {
  19765. this._boundingInfo = this._mesh._boundingInfo;
  19766. return;
  19767. }
  19768. var indices = this._renderingMesh.getIndices();
  19769. var extend;
  19770. //is this the only submesh?
  19771. if (this.indexStart === 0 && this.indexCount === indices.length) {
  19772. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  19773. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  19774. }
  19775. else {
  19776. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  19777. }
  19778. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19779. };
  19780. SubMesh.prototype._checkCollision = function (collider) {
  19781. return this.getBoundingInfo()._checkCollision(collider);
  19782. };
  19783. SubMesh.prototype.updateBoundingInfo = function (world) {
  19784. if (!this.getBoundingInfo()) {
  19785. this.refreshBoundingInfo();
  19786. }
  19787. this.getBoundingInfo().update(world);
  19788. };
  19789. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  19790. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  19791. };
  19792. SubMesh.prototype.render = function (enableAlphaMode) {
  19793. this._renderingMesh.render(this, enableAlphaMode);
  19794. };
  19795. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  19796. if (!this._linesIndexBuffer) {
  19797. var linesIndices = [];
  19798. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19799. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  19800. }
  19801. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  19802. this.linesIndexCount = linesIndices.length;
  19803. }
  19804. return this._linesIndexBuffer;
  19805. };
  19806. SubMesh.prototype.canIntersects = function (ray) {
  19807. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  19808. };
  19809. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  19810. var intersectInfo = null;
  19811. // LineMesh first as it's also a Mesh...
  19812. if (this._mesh instanceof BABYLON.LinesMesh) {
  19813. var lineMesh = this._mesh;
  19814. // Line test
  19815. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  19816. var p0 = positions[indices[index]];
  19817. var p1 = positions[indices[index + 1]];
  19818. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  19819. if (length < 0) {
  19820. continue;
  19821. }
  19822. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  19823. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  19824. if (fastCheck) {
  19825. break;
  19826. }
  19827. }
  19828. }
  19829. }
  19830. else {
  19831. // Triangles test
  19832. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19833. var p0 = positions[indices[index]];
  19834. var p1 = positions[indices[index + 1]];
  19835. var p2 = positions[indices[index + 2]];
  19836. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  19837. if (currentIntersectInfo) {
  19838. if (currentIntersectInfo.distance < 0) {
  19839. continue;
  19840. }
  19841. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  19842. intersectInfo = currentIntersectInfo;
  19843. intersectInfo.faceId = index / 3;
  19844. if (fastCheck) {
  19845. break;
  19846. }
  19847. }
  19848. }
  19849. }
  19850. }
  19851. return intersectInfo;
  19852. };
  19853. // Clone
  19854. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  19855. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  19856. if (!this.IsGlobal) {
  19857. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  19858. }
  19859. return result;
  19860. };
  19861. // Dispose
  19862. SubMesh.prototype.dispose = function () {
  19863. if (this._linesIndexBuffer) {
  19864. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  19865. this._linesIndexBuffer = null;
  19866. }
  19867. // Remove from mesh
  19868. var index = this._mesh.subMeshes.indexOf(this);
  19869. this._mesh.subMeshes.splice(index, 1);
  19870. };
  19871. // Statics
  19872. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  19873. var minVertexIndex = Number.MAX_VALUE;
  19874. var maxVertexIndex = -Number.MAX_VALUE;
  19875. renderingMesh = renderingMesh || mesh;
  19876. var indices = renderingMesh.getIndices();
  19877. for (var index = startIndex; index < startIndex + indexCount; index++) {
  19878. var vertexIndex = indices[index];
  19879. if (vertexIndex < minVertexIndex)
  19880. minVertexIndex = vertexIndex;
  19881. if (vertexIndex > maxVertexIndex)
  19882. maxVertexIndex = vertexIndex;
  19883. }
  19884. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  19885. };
  19886. return SubMesh;
  19887. })();
  19888. BABYLON.SubMesh = SubMesh;
  19889. })(BABYLON || (BABYLON = {}));
  19890. var BABYLON;
  19891. (function (BABYLON) {
  19892. var MeshBuilder = (function () {
  19893. function MeshBuilder() {
  19894. }
  19895. /**
  19896. * Creates a box mesh.
  19897. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  19898. * The parameter `size` sets the size (float) of each box side (default 1).
  19899. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  19900. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements).
  19901. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19902. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19903. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19904. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19905. */
  19906. MeshBuilder.CreateBox = function (name, options, scene) {
  19907. var box = new BABYLON.Mesh(name, scene);
  19908. var vertexData = BABYLON.VertexData.CreateBox(options);
  19909. vertexData.applyToMesh(box, options.updatable);
  19910. return box;
  19911. };
  19912. /**
  19913. * Creates a sphere mesh.
  19914. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  19915. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19916. * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`).
  19917. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19918. * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
  19919. * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude).
  19920. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19921. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19922. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19923. */
  19924. MeshBuilder.CreateSphere = function (name, options, scene) {
  19925. var sphere = new BABYLON.Mesh(name, scene);
  19926. var vertexData = BABYLON.VertexData.CreateSphere(options);
  19927. vertexData.applyToMesh(sphere, options.updatable);
  19928. return sphere;
  19929. };
  19930. /**
  19931. * Creates a plane polygonal mesh. By default, this is a disc.
  19932. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  19933. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19934. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  19935. * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
  19936. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19937. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19938. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19939. */
  19940. MeshBuilder.CreateDisc = function (name, options, scene) {
  19941. var disc = new BABYLON.Mesh(name, scene);
  19942. var vertexData = BABYLON.VertexData.CreateDisc(options);
  19943. vertexData.applyToMesh(disc, options.updatable);
  19944. return disc;
  19945. };
  19946. /**
  19947. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19948. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  19949. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19950. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  19951. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19952. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  19953. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19954. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19955. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19956. */
  19957. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  19958. var sphere = new BABYLON.Mesh(name, scene);
  19959. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  19960. vertexData.applyToMesh(sphere, options.updatable);
  19961. return sphere;
  19962. };
  19963. ;
  19964. /**
  19965. * Creates a ribbon mesh.
  19966. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19967. *
  19968. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19969. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19970. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19971. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19972. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  19973. * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  19974. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  19975. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19976. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19977. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19978. */
  19979. MeshBuilder.CreateRibbon = function (name, options, scene) {
  19980. var pathArray = options.pathArray;
  19981. var closeArray = options.closeArray;
  19982. var closePath = options.closePath;
  19983. var offset = options.offset;
  19984. var sideOrientation = options.sideOrientation;
  19985. var instance = options.instance;
  19986. var updatable = options.updatable;
  19987. if (instance) {
  19988. // positionFunction : ribbon case
  19989. // only pathArray and sideOrientation parameters are taken into account for positions update
  19990. var positionFunction = function (positions) {
  19991. var minlg = pathArray[0].length;
  19992. var i = 0;
  19993. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  19994. for (var si = 1; si <= ns; si++) {
  19995. for (var p = 0; p < pathArray.length; p++) {
  19996. var path = pathArray[p];
  19997. var l = path.length;
  19998. minlg = (minlg < l) ? minlg : l;
  19999. var j = 0;
  20000. while (j < minlg) {
  20001. positions[i] = path[j].x;
  20002. positions[i + 1] = path[j].y;
  20003. positions[i + 2] = path[j].z;
  20004. j++;
  20005. i += 3;
  20006. }
  20007. if (instance._closePath) {
  20008. positions[i] = path[0].x;
  20009. positions[i + 1] = path[0].y;
  20010. positions[i + 2] = path[0].z;
  20011. i += 3;
  20012. }
  20013. }
  20014. }
  20015. };
  20016. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20017. positionFunction(positions);
  20018. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20019. if (!(instance.areNormalsFrozen)) {
  20020. var indices = instance.getIndices();
  20021. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20022. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20023. if (instance._closePath) {
  20024. var indexFirst = 0;
  20025. var indexLast = 0;
  20026. for (var p = 0; p < pathArray.length; p++) {
  20027. indexFirst = instance._idx[p] * 3;
  20028. if (p + 1 < pathArray.length) {
  20029. indexLast = (instance._idx[p + 1] - 1) * 3;
  20030. }
  20031. else {
  20032. indexLast = normals.length - 3;
  20033. }
  20034. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  20035. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  20036. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  20037. normals[indexLast] = normals[indexFirst];
  20038. normals[indexLast + 1] = normals[indexFirst + 1];
  20039. normals[indexLast + 2] = normals[indexFirst + 2];
  20040. }
  20041. }
  20042. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20043. }
  20044. return instance;
  20045. }
  20046. else {
  20047. var ribbon = new BABYLON.Mesh(name, scene);
  20048. ribbon.sideOrientation = sideOrientation;
  20049. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  20050. if (closePath) {
  20051. ribbon._idx = vertexData._idx;
  20052. }
  20053. ribbon._closePath = closePath;
  20054. ribbon._closeArray = closeArray;
  20055. vertexData.applyToMesh(ribbon, updatable);
  20056. return ribbon;
  20057. }
  20058. };
  20059. /**
  20060. * Creates a cylinder or a cone mesh.
  20061. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  20062. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20063. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20064. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  20065. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20066. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20067. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  20068. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  20069. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  20070. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements).
  20071. * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
  20072. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  20073. * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
  20074. * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
  20075. * If `enclose` is false, a ring surface is one element.
  20076. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  20077. * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  20078. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20079. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20080. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20081. */
  20082. MeshBuilder.CreateCylinder = function (name, options, scene) {
  20083. var cylinder = new BABYLON.Mesh(name, scene);
  20084. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  20085. vertexData.applyToMesh(cylinder, options.updatable);
  20086. return cylinder;
  20087. };
  20088. /**
  20089. * Creates a torus mesh.
  20090. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  20091. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20092. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20093. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20094. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20095. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20096. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20097. */
  20098. MeshBuilder.CreateTorus = function (name, options, scene) {
  20099. var torus = new BABYLON.Mesh(name, scene);
  20100. var vertexData = BABYLON.VertexData.CreateTorus(options);
  20101. vertexData.applyToMesh(torus, options.updatable);
  20102. return torus;
  20103. };
  20104. /**
  20105. * Creates a torus knot mesh.
  20106. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  20107. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20108. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20109. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20110. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20111. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20112. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20113. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20114. */
  20115. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  20116. var torusKnot = new BABYLON.Mesh(name, scene);
  20117. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  20118. vertexData.applyToMesh(torusKnot, options.updatable);
  20119. return torusKnot;
  20120. };
  20121. /**
  20122. * Creates a line system mesh.
  20123. * A line system is a pool of many lines gathered in a single mesh.
  20124. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  20125. * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter.
  20126. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  20127. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  20128. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  20129. * updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  20130. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  20131. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20132. */
  20133. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  20134. var instance = options.instance;
  20135. var lines = options.lines;
  20136. if (instance) {
  20137. var positionFunction = function (positions) {
  20138. var i = 0;
  20139. for (var l = 0; l < lines.length; l++) {
  20140. var points = lines[l];
  20141. for (var p = 0; p < points.length; p++) {
  20142. positions[i] = points[p].x;
  20143. positions[i + 1] = points[p].y;
  20144. positions[i + 2] = points[p].z;
  20145. i += 3;
  20146. }
  20147. }
  20148. };
  20149. instance.updateMeshPositions(positionFunction, false);
  20150. return instance;
  20151. }
  20152. // line system creation
  20153. var lineSystem = new BABYLON.LinesMesh(name, scene);
  20154. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  20155. vertexData.applyToMesh(lineSystem, options.updatable);
  20156. return lineSystem;
  20157. };
  20158. /**
  20159. * Creates a line mesh.
  20160. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  20161. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  20162. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20163. * The parameter `points` is an array successive Vector3.
  20164. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  20165. * When updating an instance, remember that only point positions can change, not the number of points.
  20166. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20167. */
  20168. MeshBuilder.CreateLines = function (name, options, scene) {
  20169. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  20170. return lines;
  20171. };
  20172. /**
  20173. * Creates a dashed line mesh.
  20174. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  20175. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  20176. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20177. * The parameter `points` is an array successive Vector3.
  20178. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20179. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20180. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20181. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  20182. * When updating an instance, remember that only point positions can change, not the number of points.
  20183. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20184. */
  20185. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  20186. var points = options.points;
  20187. var instance = options.instance;
  20188. var gapSize = options.gapSize;
  20189. var dashNb = options.dashNb;
  20190. var dashSize = options.dashSize;
  20191. if (instance) {
  20192. var positionFunction = function (positions) {
  20193. var curvect = BABYLON.Vector3.Zero();
  20194. var nbSeg = positions.length / 6;
  20195. var lg = 0;
  20196. var nb = 0;
  20197. var shft = 0;
  20198. var dashshft = 0;
  20199. var curshft = 0;
  20200. var p = 0;
  20201. var i = 0;
  20202. var j = 0;
  20203. for (i = 0; i < points.length - 1; i++) {
  20204. points[i + 1].subtractToRef(points[i], curvect);
  20205. lg += curvect.length();
  20206. }
  20207. shft = lg / nbSeg;
  20208. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  20209. for (i = 0; i < points.length - 1; i++) {
  20210. points[i + 1].subtractToRef(points[i], curvect);
  20211. nb = Math.floor(curvect.length() / shft);
  20212. curvect.normalize();
  20213. j = 0;
  20214. while (j < nb && p < positions.length) {
  20215. curshft = shft * j;
  20216. positions[p] = points[i].x + curshft * curvect.x;
  20217. positions[p + 1] = points[i].y + curshft * curvect.y;
  20218. positions[p + 2] = points[i].z + curshft * curvect.z;
  20219. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  20220. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  20221. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  20222. p += 6;
  20223. j++;
  20224. }
  20225. }
  20226. while (p < positions.length) {
  20227. positions[p] = points[i].x;
  20228. positions[p + 1] = points[i].y;
  20229. positions[p + 2] = points[i].z;
  20230. p += 3;
  20231. }
  20232. };
  20233. instance.updateMeshPositions(positionFunction, false);
  20234. return instance;
  20235. }
  20236. // dashed lines creation
  20237. var dashedLines = new BABYLON.LinesMesh(name, scene);
  20238. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  20239. vertexData.applyToMesh(dashedLines, options.updatable);
  20240. dashedLines.dashSize = dashSize;
  20241. dashedLines.gapSize = gapSize;
  20242. return dashedLines;
  20243. };
  20244. /**
  20245. * Creates an extruded shape mesh.
  20246. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  20247. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  20248. *
  20249. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20250. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  20251. * extruded along the Z axis.
  20252. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20253. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  20254. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20255. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  20256. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  20257. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20258. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20259. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20260. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20261. */
  20262. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  20263. var path = options.path;
  20264. var shape = options.shape;
  20265. var scale = options.scale || 1;
  20266. var rotation = options.rotation || 0;
  20267. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20268. var updatable = options.updatable;
  20269. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20270. var instance = options.instance;
  20271. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  20272. };
  20273. /**
  20274. * Creates an custom extruded shape mesh.
  20275. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  20276. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  20277. *
  20278. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20279. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  20280. * extruded along the Z axis.
  20281. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20282. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  20283. * and the distance of this point from the begining of the path :
  20284. * ```javascript
  20285. * var rotationFunction = function(i, distance) {
  20286. * // do things
  20287. * return rotationValue; }
  20288. * ```
  20289. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20290. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  20291. * and the distance of this point from the begining of the path :
  20292. * ```javascript
  20293. * var scaleFunction = function(i, distance) {
  20294. * // do things
  20295. * return scaleValue;}
  20296. * ```
  20297. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20298. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20299. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20300. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  20301. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  20302. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20303. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20304. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20305. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20306. */
  20307. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  20308. var path = options.path;
  20309. var shape = options.shape;
  20310. var scaleFunction = options.scaleFunction || (function () { return 1; });
  20311. var rotationFunction = options.rotationFunction || (function () { return 0; });
  20312. var ribbonCloseArray = options.ribbonCloseArray || false;
  20313. var ribbonClosePath = options.ribbonClosePath || false;
  20314. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20315. var updatable = options.updatable;
  20316. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20317. var instance = options.instance;
  20318. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  20319. };
  20320. /**
  20321. * Creates lathe mesh.
  20322. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20323. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  20324. *
  20325. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  20326. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20327. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20328. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20329. * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape.
  20330. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  20331. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  20332. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20333. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20334. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20335. */
  20336. MeshBuilder.CreateLathe = function (name, options, scene) {
  20337. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  20338. var closed = (options.closed === undefined) ? true : options.closed;
  20339. var shape = options.shape;
  20340. var radius = options.radius || 1;
  20341. var tessellation = options.tessellation || 64;
  20342. var updatable = options.updatable;
  20343. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20344. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  20345. var pi2 = Math.PI * 2;
  20346. var paths = new Array();
  20347. var i = 0;
  20348. var p = 0;
  20349. var step = pi2 / tessellation * arc;
  20350. var rotated;
  20351. var path = new Array();
  20352. ;
  20353. for (i = 0; i <= tessellation; i++) {
  20354. var path = [];
  20355. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  20356. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  20357. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  20358. }
  20359. for (p = 0; p < shape.length; p++) {
  20360. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  20361. path.push(rotated);
  20362. }
  20363. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  20364. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  20365. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  20366. }
  20367. paths.push(path);
  20368. }
  20369. // lathe ribbon
  20370. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  20371. return lathe;
  20372. };
  20373. /**
  20374. * Creates a plane mesh.
  20375. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20376. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20377. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  20378. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  20379. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20380. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20381. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20382. */
  20383. MeshBuilder.CreatePlane = function (name, options, scene) {
  20384. var plane = new BABYLON.Mesh(name, scene);
  20385. var vertexData = BABYLON.VertexData.CreatePlane(options);
  20386. vertexData.applyToMesh(plane, options.updatable);
  20387. if (options.sourcePlane) {
  20388. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  20389. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  20390. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  20391. plane.rotate(vectorProduct, product);
  20392. }
  20393. return plane;
  20394. };
  20395. /**
  20396. * Creates a ground mesh.
  20397. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20398. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20399. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20400. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20401. */
  20402. MeshBuilder.CreateGround = function (name, options, scene) {
  20403. var ground = new BABYLON.GroundMesh(name, scene);
  20404. ground._setReady(false);
  20405. ground._subdivisions = options.subdivisions || 1;
  20406. ground._width = options.width || 1;
  20407. ground._height = options.height || 1;
  20408. ground._maxX = ground._width / 2;
  20409. ground._maxZ = ground._height / 2;
  20410. ground._minX = -ground._maxX;
  20411. ground._minZ = -ground._maxZ;
  20412. var vertexData = BABYLON.VertexData.CreateGround(options);
  20413. vertexData.applyToMesh(ground, options.updatable);
  20414. ground._setReady(true);
  20415. return ground;
  20416. };
  20417. /**
  20418. * Creates a tiled ground mesh.
  20419. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  20420. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20421. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20422. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20423. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20424. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20425. * numbers of subdivisions on the ground width and height of each tile.
  20426. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20427. */
  20428. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  20429. var tiledGround = new BABYLON.Mesh(name, scene);
  20430. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  20431. vertexData.applyToMesh(tiledGround, options.updatable);
  20432. return tiledGround;
  20433. };
  20434. /**
  20435. * Creates a ground mesh from a height map.
  20436. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20437. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  20438. * The parameter `url` sets the URL of the height map image resource.
  20439. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20440. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20441. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20442. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20443. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  20444. * This function is passed the newly built mesh :
  20445. * ```javascript
  20446. * function(mesh) { // do things
  20447. * return; }
  20448. * ```
  20449. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20450. */
  20451. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  20452. var width = options.width || 10;
  20453. var height = options.height || 10;
  20454. var subdivisions = options.subdivisions || 1;
  20455. var minHeight = options.minHeight;
  20456. var maxHeight = options.maxHeight || 10;
  20457. var updatable = options.updatable;
  20458. var onReady = options.onReady;
  20459. var ground = new BABYLON.GroundMesh(name, scene);
  20460. ground._subdivisions = subdivisions;
  20461. ground._width = width;
  20462. ground._height = height;
  20463. ground._maxX = ground._width / 2;
  20464. ground._maxZ = ground._height / 2;
  20465. ground._minX = -ground._maxX;
  20466. ground._minZ = -ground._maxZ;
  20467. ground._setReady(false);
  20468. var onload = function (img) {
  20469. // Getting height map data
  20470. var canvas = document.createElement("canvas");
  20471. var context = canvas.getContext("2d");
  20472. var bufferWidth = img.width;
  20473. var bufferHeight = img.height;
  20474. canvas.width = bufferWidth;
  20475. canvas.height = bufferHeight;
  20476. context.drawImage(img, 0, 0);
  20477. // Create VertexData from map data
  20478. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20479. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  20480. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  20481. width: width, height: height,
  20482. subdivisions: subdivisions,
  20483. minHeight: minHeight, maxHeight: maxHeight,
  20484. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  20485. });
  20486. vertexData.applyToMesh(ground, updatable);
  20487. ground._setReady(true);
  20488. //execute ready callback, if set
  20489. if (onReady) {
  20490. onReady(ground);
  20491. }
  20492. };
  20493. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20494. return ground;
  20495. };
  20496. /**
  20497. * Creates a tube mesh.
  20498. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  20499. *
  20500. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  20501. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20502. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20503. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20504. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20505. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  20506. * It must return a radius value (positive float) :
  20507. * ```javascript
  20508. * var radiusFunction = function(i, distance) {
  20509. * // do things
  20510. * return radius; }
  20511. * ```
  20512. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  20513. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  20514. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  20515. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20516. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20517. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20518. */
  20519. MeshBuilder.CreateTube = function (name, options, scene) {
  20520. var path = options.path;
  20521. var radius = options.radius || 1;
  20522. var tessellation = options.tessellation || 64;
  20523. var radiusFunction = options.radiusFunction;
  20524. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  20525. var updatable = options.updatable;
  20526. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20527. var instance = options.instance;
  20528. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  20529. // tube geometry
  20530. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  20531. var tangents = path3D.getTangents();
  20532. var normals = path3D.getNormals();
  20533. var distances = path3D.getDistances();
  20534. var pi2 = Math.PI * 2;
  20535. var step = pi2 / tessellation * arc;
  20536. var returnRadius = function () { return radius; };
  20537. var radiusFunctionFinal = radiusFunction || returnRadius;
  20538. var circlePath;
  20539. var rad;
  20540. var normal;
  20541. var rotated;
  20542. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20543. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20544. for (var i = 0; i < path.length; i++) {
  20545. rad = radiusFunctionFinal(i, distances[i]); // current radius
  20546. circlePath = Array(); // current circle array
  20547. normal = normals[i]; // current normal
  20548. for (var t = 0; t < tessellation; t++) {
  20549. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  20550. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  20551. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  20552. rotated.scaleInPlace(rad).addInPlace(path[i]);
  20553. circlePath[t] = rotated;
  20554. }
  20555. circlePaths[index] = circlePath;
  20556. index++;
  20557. }
  20558. // cap
  20559. var capPath = function (nbPoints, pathIndex) {
  20560. var pointCap = Array();
  20561. for (var i = 0; i < nbPoints; i++) {
  20562. pointCap.push(path[pathIndex]);
  20563. }
  20564. return pointCap;
  20565. };
  20566. switch (cap) {
  20567. case BABYLON.Mesh.NO_CAP:
  20568. break;
  20569. case BABYLON.Mesh.CAP_START:
  20570. circlePaths[0] = capPath(tessellation, 0);
  20571. circlePaths[1] = circlePaths[2].slice(0);
  20572. break;
  20573. case BABYLON.Mesh.CAP_END:
  20574. circlePaths[index] = circlePaths[index - 1].slice(0);
  20575. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  20576. break;
  20577. case BABYLON.Mesh.CAP_ALL:
  20578. circlePaths[0] = capPath(tessellation, 0);
  20579. circlePaths[1] = circlePaths[2].slice(0);
  20580. circlePaths[index] = circlePaths[index - 1].slice(0);
  20581. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  20582. break;
  20583. default:
  20584. break;
  20585. }
  20586. return circlePaths;
  20587. };
  20588. var path3D;
  20589. var pathArray;
  20590. if (instance) {
  20591. var arc = options.arc || instance.arc;
  20592. path3D = (instance.path3D).update(path);
  20593. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  20594. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  20595. instance.path3D = path3D;
  20596. instance.pathArray = pathArray;
  20597. instance.arc = arc;
  20598. return instance;
  20599. }
  20600. // tube creation
  20601. path3D = new BABYLON.Path3D(path);
  20602. var newPathArray = new Array();
  20603. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20604. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  20605. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  20606. tube.pathArray = pathArray;
  20607. tube.path3D = path3D;
  20608. tube.tessellation = tessellation;
  20609. tube.cap = cap;
  20610. tube.arc = options.arc;
  20611. return tube;
  20612. };
  20613. /**
  20614. * Creates a polyhedron mesh.
  20615. *
  20616. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  20617. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  20618. * to choose the wanted type.
  20619. * The parameter `size` (positive float, default 1) sets the polygon size.
  20620. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20621. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  20622. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  20623. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  20624. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  20625. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  20626. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20627. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20628. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20629. */
  20630. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  20631. var polyhedron = new BABYLON.Mesh(name, scene);
  20632. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  20633. vertexData.applyToMesh(polyhedron, options.updatable);
  20634. return polyhedron;
  20635. };
  20636. /**
  20637. * Creates a decal mesh.
  20638. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  20639. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  20640. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20641. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20642. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  20643. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20644. */
  20645. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  20646. var indices = sourceMesh.getIndices();
  20647. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20648. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20649. var position = options.position || BABYLON.Vector3.Zero();
  20650. var normal = options.normal || BABYLON.Vector3.Up();
  20651. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  20652. var angle = options.angle || 0;
  20653. // Getting correct rotation
  20654. if (!normal) {
  20655. var target = new BABYLON.Vector3(0, 0, 1);
  20656. var camera = sourceMesh.getScene().activeCamera;
  20657. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  20658. normal = camera.globalPosition.subtract(cameraWorldTarget);
  20659. }
  20660. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  20661. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  20662. var pitch = Math.atan2(normal.y, len);
  20663. // Matrix
  20664. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  20665. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  20666. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  20667. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  20668. var vertexData = new BABYLON.VertexData();
  20669. vertexData.indices = [];
  20670. vertexData.positions = [];
  20671. vertexData.normals = [];
  20672. vertexData.uvs = [];
  20673. var currentVertexDataIndex = 0;
  20674. var extractDecalVector3 = function (indexId) {
  20675. var vertexId = indices[indexId];
  20676. var result = new BABYLON.PositionNormalVertex();
  20677. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  20678. // Send vector to decal local world
  20679. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  20680. // Get normal
  20681. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  20682. return result;
  20683. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  20684. var clip = function (vertices, axis) {
  20685. if (vertices.length === 0) {
  20686. return vertices;
  20687. }
  20688. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  20689. var clipVertices = function (v0, v1) {
  20690. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  20691. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  20692. };
  20693. var result = new Array();
  20694. for (var index = 0; index < vertices.length; index += 3) {
  20695. var v1Out;
  20696. var v2Out;
  20697. var v3Out;
  20698. var total = 0;
  20699. var nV1, nV2, nV3, nV4;
  20700. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  20701. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  20702. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  20703. v1Out = d1 > 0;
  20704. v2Out = d2 > 0;
  20705. v3Out = d3 > 0;
  20706. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  20707. switch (total) {
  20708. case 0:
  20709. result.push(vertices[index]);
  20710. result.push(vertices[index + 1]);
  20711. result.push(vertices[index + 2]);
  20712. break;
  20713. case 1:
  20714. if (v1Out) {
  20715. nV1 = vertices[index + 1];
  20716. nV2 = vertices[index + 2];
  20717. nV3 = clipVertices(vertices[index], nV1);
  20718. nV4 = clipVertices(vertices[index], nV2);
  20719. }
  20720. if (v2Out) {
  20721. nV1 = vertices[index];
  20722. nV2 = vertices[index + 2];
  20723. nV3 = clipVertices(vertices[index + 1], nV1);
  20724. nV4 = clipVertices(vertices[index + 1], nV2);
  20725. result.push(nV3);
  20726. result.push(nV2.clone());
  20727. result.push(nV1.clone());
  20728. result.push(nV2.clone());
  20729. result.push(nV3.clone());
  20730. result.push(nV4);
  20731. break;
  20732. }
  20733. if (v3Out) {
  20734. nV1 = vertices[index];
  20735. nV2 = vertices[index + 1];
  20736. nV3 = clipVertices(vertices[index + 2], nV1);
  20737. nV4 = clipVertices(vertices[index + 2], nV2);
  20738. }
  20739. result.push(nV1.clone());
  20740. result.push(nV2.clone());
  20741. result.push(nV3);
  20742. result.push(nV4);
  20743. result.push(nV3.clone());
  20744. result.push(nV2.clone());
  20745. break;
  20746. case 2:
  20747. if (!v1Out) {
  20748. nV1 = vertices[index].clone();
  20749. nV2 = clipVertices(nV1, vertices[index + 1]);
  20750. nV3 = clipVertices(nV1, vertices[index + 2]);
  20751. result.push(nV1);
  20752. result.push(nV2);
  20753. result.push(nV3);
  20754. }
  20755. if (!v2Out) {
  20756. nV1 = vertices[index + 1].clone();
  20757. nV2 = clipVertices(nV1, vertices[index + 2]);
  20758. nV3 = clipVertices(nV1, vertices[index]);
  20759. result.push(nV1);
  20760. result.push(nV2);
  20761. result.push(nV3);
  20762. }
  20763. if (!v3Out) {
  20764. nV1 = vertices[index + 2].clone();
  20765. nV2 = clipVertices(nV1, vertices[index]);
  20766. nV3 = clipVertices(nV1, vertices[index + 1]);
  20767. result.push(nV1);
  20768. result.push(nV2);
  20769. result.push(nV3);
  20770. }
  20771. break;
  20772. case 3:
  20773. break;
  20774. }
  20775. }
  20776. return result;
  20777. };
  20778. for (var index = 0; index < indices.length; index += 3) {
  20779. var faceVertices = new Array();
  20780. faceVertices.push(extractDecalVector3(index));
  20781. faceVertices.push(extractDecalVector3(index + 1));
  20782. faceVertices.push(extractDecalVector3(index + 2));
  20783. // Clip
  20784. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  20785. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  20786. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  20787. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  20788. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  20789. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  20790. if (faceVertices.length === 0) {
  20791. continue;
  20792. }
  20793. // Add UVs and get back to world
  20794. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  20795. var vertex = faceVertices[vIndex];
  20796. //TODO check for Int32Array
  20797. vertexData.indices.push(currentVertexDataIndex);
  20798. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  20799. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  20800. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  20801. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  20802. currentVertexDataIndex++;
  20803. }
  20804. }
  20805. // Return mesh
  20806. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  20807. vertexData.applyToMesh(decal);
  20808. decal.position = position.clone();
  20809. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  20810. return decal;
  20811. };
  20812. // Privates
  20813. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  20814. // extrusion geometry
  20815. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  20816. var tangents = path3D.getTangents();
  20817. var normals = path3D.getNormals();
  20818. var binormals = path3D.getBinormals();
  20819. var distances = path3D.getDistances();
  20820. var angle = 0;
  20821. var returnScale = function () { return scale; };
  20822. var returnRotation = function () { return rotation; };
  20823. var rotate = custom ? rotateFunction : returnRotation;
  20824. var scl = custom ? scaleFunction : returnScale;
  20825. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20826. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20827. for (var i = 0; i < curve.length; i++) {
  20828. var shapePath = new Array();
  20829. var angleStep = rotate(i, distances[i]);
  20830. var scaleRatio = scl(i, distances[i]);
  20831. for (var p = 0; p < shape.length; p++) {
  20832. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  20833. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  20834. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  20835. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  20836. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  20837. shapePath[p] = rotated;
  20838. }
  20839. shapePaths[index] = shapePath;
  20840. angle += angleStep;
  20841. index++;
  20842. }
  20843. // cap
  20844. var capPath = function (shapePath) {
  20845. var pointCap = Array();
  20846. var barycenter = BABYLON.Vector3.Zero();
  20847. var i;
  20848. for (i = 0; i < shapePath.length; i++) {
  20849. barycenter.addInPlace(shapePath[i]);
  20850. }
  20851. barycenter.scaleInPlace(1 / shapePath.length);
  20852. for (i = 0; i < shapePath.length; i++) {
  20853. pointCap.push(barycenter);
  20854. }
  20855. return pointCap;
  20856. };
  20857. switch (cap) {
  20858. case BABYLON.Mesh.NO_CAP:
  20859. break;
  20860. case BABYLON.Mesh.CAP_START:
  20861. shapePaths[0] = capPath(shapePaths[2]);
  20862. shapePaths[1] = shapePaths[2].slice(0);
  20863. break;
  20864. case BABYLON.Mesh.CAP_END:
  20865. shapePaths[index] = shapePaths[index - 1];
  20866. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20867. break;
  20868. case BABYLON.Mesh.CAP_ALL:
  20869. shapePaths[0] = capPath(shapePaths[2]);
  20870. shapePaths[1] = shapePaths[2].slice(0);
  20871. shapePaths[index] = shapePaths[index - 1];
  20872. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20873. break;
  20874. default:
  20875. break;
  20876. }
  20877. return shapePaths;
  20878. };
  20879. var path3D;
  20880. var pathArray;
  20881. if (instance) {
  20882. path3D = (instance.path3D).update(curve);
  20883. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  20884. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  20885. return instance;
  20886. }
  20887. // extruded shape creation
  20888. path3D = new BABYLON.Path3D(curve);
  20889. var newShapePaths = new Array();
  20890. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20891. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  20892. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  20893. extrudedGeneric.pathArray = pathArray;
  20894. extrudedGeneric.path3D = path3D;
  20895. extrudedGeneric.cap = cap;
  20896. return extrudedGeneric;
  20897. };
  20898. return MeshBuilder;
  20899. })();
  20900. BABYLON.MeshBuilder = MeshBuilder;
  20901. })(BABYLON || (BABYLON = {}));
  20902. var BABYLON;
  20903. (function (BABYLON) {
  20904. var BaseTexture = (function () {
  20905. function BaseTexture(scene) {
  20906. this.hasAlpha = false;
  20907. this.getAlphaFromRGB = false;
  20908. this.level = 1;
  20909. this.coordinatesIndex = 0;
  20910. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20911. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20912. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20913. this.anisotropicFilteringLevel = 4;
  20914. this.isCube = false;
  20915. this.isRenderTarget = false;
  20916. this.animations = new Array();
  20917. /**
  20918. * An event triggered when the texture is disposed.
  20919. * @type {BABYLON.Observable}
  20920. */
  20921. this.onDisposeObservable = new BABYLON.Observable();
  20922. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20923. this._scene = scene;
  20924. this._scene.textures.push(this);
  20925. }
  20926. BaseTexture.prototype.toString = function () {
  20927. return this.name;
  20928. };
  20929. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20930. set: function (callback) {
  20931. if (this._onDisposeObserver) {
  20932. this.onDisposeObservable.remove(this._onDisposeObserver);
  20933. }
  20934. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20935. },
  20936. enumerable: true,
  20937. configurable: true
  20938. });
  20939. BaseTexture.prototype.getScene = function () {
  20940. return this._scene;
  20941. };
  20942. BaseTexture.prototype.getTextureMatrix = function () {
  20943. return null;
  20944. };
  20945. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20946. return null;
  20947. };
  20948. BaseTexture.prototype.getInternalTexture = function () {
  20949. return this._texture;
  20950. };
  20951. BaseTexture.prototype.isReady = function () {
  20952. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20953. return true;
  20954. }
  20955. if (this._texture) {
  20956. return this._texture.isReady;
  20957. }
  20958. return false;
  20959. };
  20960. BaseTexture.prototype.getSize = function () {
  20961. if (this._texture._width) {
  20962. return { width: this._texture._width, height: this._texture._height };
  20963. }
  20964. if (this._texture._size) {
  20965. return { width: this._texture._size, height: this._texture._size };
  20966. }
  20967. return { width: 0, height: 0 };
  20968. };
  20969. BaseTexture.prototype.getBaseSize = function () {
  20970. if (!this.isReady() || !this._texture)
  20971. return { width: 0, height: 0 };
  20972. if (this._texture._size) {
  20973. return { width: this._texture._size, height: this._texture._size };
  20974. }
  20975. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  20976. };
  20977. BaseTexture.prototype.scale = function (ratio) {
  20978. };
  20979. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20980. get: function () {
  20981. return false;
  20982. },
  20983. enumerable: true,
  20984. configurable: true
  20985. });
  20986. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  20987. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20988. for (var index = 0; index < texturesCache.length; index++) {
  20989. var texturesCacheEntry = texturesCache[index];
  20990. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20991. texturesCache.splice(index, 1);
  20992. return;
  20993. }
  20994. }
  20995. };
  20996. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20997. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20998. for (var index = 0; index < texturesCache.length; index++) {
  20999. var texturesCacheEntry = texturesCache[index];
  21000. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  21001. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21002. texturesCacheEntry.references++;
  21003. return texturesCacheEntry;
  21004. }
  21005. }
  21006. }
  21007. return null;
  21008. };
  21009. BaseTexture.prototype.delayLoad = function () {
  21010. };
  21011. BaseTexture.prototype.clone = function () {
  21012. return null;
  21013. };
  21014. BaseTexture.prototype.releaseInternalTexture = function () {
  21015. if (this._texture) {
  21016. this._scene.getEngine().releaseInternalTexture(this._texture);
  21017. delete this._texture;
  21018. }
  21019. };
  21020. BaseTexture.prototype.dispose = function () {
  21021. // Animations
  21022. this.getScene().stopAnimation(this);
  21023. // Remove from scene
  21024. var index = this._scene.textures.indexOf(this);
  21025. if (index >= 0) {
  21026. this._scene.textures.splice(index, 1);
  21027. }
  21028. if (this._texture === undefined) {
  21029. return;
  21030. }
  21031. // Release
  21032. this.releaseInternalTexture();
  21033. // Callback
  21034. this.onDisposeObservable.notifyObservers(this);
  21035. this.onDisposeObservable.clear();
  21036. };
  21037. BaseTexture.prototype.serialize = function () {
  21038. if (!this.name) {
  21039. return null;
  21040. }
  21041. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21042. // Animations
  21043. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21044. return serializationObject;
  21045. };
  21046. __decorate([
  21047. BABYLON.serialize()
  21048. ], BaseTexture.prototype, "name", void 0);
  21049. __decorate([
  21050. BABYLON.serialize()
  21051. ], BaseTexture.prototype, "hasAlpha", void 0);
  21052. __decorate([
  21053. BABYLON.serialize()
  21054. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21055. __decorate([
  21056. BABYLON.serialize()
  21057. ], BaseTexture.prototype, "level", void 0);
  21058. __decorate([
  21059. BABYLON.serialize()
  21060. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21061. __decorate([
  21062. BABYLON.serialize()
  21063. ], BaseTexture.prototype, "coordinatesMode", void 0);
  21064. __decorate([
  21065. BABYLON.serialize()
  21066. ], BaseTexture.prototype, "wrapU", void 0);
  21067. __decorate([
  21068. BABYLON.serialize()
  21069. ], BaseTexture.prototype, "wrapV", void 0);
  21070. __decorate([
  21071. BABYLON.serialize()
  21072. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21073. __decorate([
  21074. BABYLON.serialize()
  21075. ], BaseTexture.prototype, "isCube", void 0);
  21076. __decorate([
  21077. BABYLON.serialize()
  21078. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21079. return BaseTexture;
  21080. })();
  21081. BABYLON.BaseTexture = BaseTexture;
  21082. })(BABYLON || (BABYLON = {}));
  21083. var BABYLON;
  21084. (function (BABYLON) {
  21085. var Texture = (function (_super) {
  21086. __extends(Texture, _super);
  21087. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  21088. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21089. if (onLoad === void 0) { onLoad = null; }
  21090. if (onError === void 0) { onError = null; }
  21091. if (buffer === void 0) { buffer = null; }
  21092. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21093. _super.call(this, scene);
  21094. this.uOffset = 0;
  21095. this.vOffset = 0;
  21096. this.uScale = 1.0;
  21097. this.vScale = 1.0;
  21098. this.uAng = 0;
  21099. this.vAng = 0;
  21100. this.wAng = 0;
  21101. this.name = url;
  21102. this.url = url;
  21103. this._noMipmap = noMipmap;
  21104. this._invertY = invertY;
  21105. this._samplingMode = samplingMode;
  21106. this._buffer = buffer;
  21107. this._deleteBuffer = deleteBuffer;
  21108. if (!url) {
  21109. return;
  21110. }
  21111. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  21112. if (!this._texture) {
  21113. if (!scene.useDelayedTextureLoading) {
  21114. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  21115. if (deleteBuffer) {
  21116. delete this._buffer;
  21117. }
  21118. }
  21119. else {
  21120. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21121. this._delayedOnLoad = onLoad;
  21122. this._delayedOnError = onError;
  21123. }
  21124. }
  21125. else {
  21126. BABYLON.Tools.SetImmediate(function () {
  21127. if (onLoad) {
  21128. onLoad();
  21129. }
  21130. });
  21131. }
  21132. }
  21133. Object.defineProperty(Texture.prototype, "noMipmap", {
  21134. get: function () {
  21135. return this._noMipmap;
  21136. },
  21137. enumerable: true,
  21138. configurable: true
  21139. });
  21140. Texture.prototype.delayLoad = function () {
  21141. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21142. return;
  21143. }
  21144. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21145. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21146. if (!this._texture) {
  21147. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  21148. if (this._deleteBuffer) {
  21149. delete this._buffer;
  21150. }
  21151. }
  21152. };
  21153. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21154. if (!this._texture) {
  21155. return;
  21156. }
  21157. this._samplingMode = samplingMode;
  21158. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21159. };
  21160. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21161. x *= this.uScale;
  21162. y *= this.vScale;
  21163. x -= 0.5 * this.uScale;
  21164. y -= 0.5 * this.vScale;
  21165. z -= 0.5;
  21166. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21167. t.x += 0.5 * this.uScale + this.uOffset;
  21168. t.y += 0.5 * this.vScale + this.vOffset;
  21169. t.z += 0.5;
  21170. };
  21171. Texture.prototype.getTextureMatrix = function () {
  21172. if (this.uOffset === this._cachedUOffset &&
  21173. this.vOffset === this._cachedVOffset &&
  21174. this.uScale === this._cachedUScale &&
  21175. this.vScale === this._cachedVScale &&
  21176. this.uAng === this._cachedUAng &&
  21177. this.vAng === this._cachedVAng &&
  21178. this.wAng === this._cachedWAng) {
  21179. return this._cachedTextureMatrix;
  21180. }
  21181. this._cachedUOffset = this.uOffset;
  21182. this._cachedVOffset = this.vOffset;
  21183. this._cachedUScale = this.uScale;
  21184. this._cachedVScale = this.vScale;
  21185. this._cachedUAng = this.uAng;
  21186. this._cachedVAng = this.vAng;
  21187. this._cachedWAng = this.wAng;
  21188. if (!this._cachedTextureMatrix) {
  21189. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21190. this._rowGenerationMatrix = new BABYLON.Matrix();
  21191. this._t0 = BABYLON.Vector3.Zero();
  21192. this._t1 = BABYLON.Vector3.Zero();
  21193. this._t2 = BABYLON.Vector3.Zero();
  21194. }
  21195. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21196. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21197. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21198. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21199. this._t1.subtractInPlace(this._t0);
  21200. this._t2.subtractInPlace(this._t0);
  21201. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21202. this._cachedTextureMatrix.m[0] = this._t1.x;
  21203. this._cachedTextureMatrix.m[1] = this._t1.y;
  21204. this._cachedTextureMatrix.m[2] = this._t1.z;
  21205. this._cachedTextureMatrix.m[4] = this._t2.x;
  21206. this._cachedTextureMatrix.m[5] = this._t2.y;
  21207. this._cachedTextureMatrix.m[6] = this._t2.z;
  21208. this._cachedTextureMatrix.m[8] = this._t0.x;
  21209. this._cachedTextureMatrix.m[9] = this._t0.y;
  21210. this._cachedTextureMatrix.m[10] = this._t0.z;
  21211. return this._cachedTextureMatrix;
  21212. };
  21213. Texture.prototype.getReflectionTextureMatrix = function () {
  21214. if (this.uOffset === this._cachedUOffset &&
  21215. this.vOffset === this._cachedVOffset &&
  21216. this.uScale === this._cachedUScale &&
  21217. this.vScale === this._cachedVScale &&
  21218. this.coordinatesMode === this._cachedCoordinatesMode) {
  21219. return this._cachedTextureMatrix;
  21220. }
  21221. if (!this._cachedTextureMatrix) {
  21222. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21223. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21224. }
  21225. this._cachedCoordinatesMode = this.coordinatesMode;
  21226. switch (this.coordinatesMode) {
  21227. case Texture.PLANAR_MODE:
  21228. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21229. this._cachedTextureMatrix[0] = this.uScale;
  21230. this._cachedTextureMatrix[5] = this.vScale;
  21231. this._cachedTextureMatrix[12] = this.uOffset;
  21232. this._cachedTextureMatrix[13] = this.vOffset;
  21233. break;
  21234. case Texture.PROJECTION_MODE:
  21235. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21236. this._projectionModeMatrix.m[0] = 0.5;
  21237. this._projectionModeMatrix.m[5] = -0.5;
  21238. this._projectionModeMatrix.m[10] = 0.0;
  21239. this._projectionModeMatrix.m[12] = 0.5;
  21240. this._projectionModeMatrix.m[13] = 0.5;
  21241. this._projectionModeMatrix.m[14] = 1.0;
  21242. this._projectionModeMatrix.m[15] = 1.0;
  21243. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21244. break;
  21245. default:
  21246. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21247. break;
  21248. }
  21249. return this._cachedTextureMatrix;
  21250. };
  21251. Texture.prototype.clone = function () {
  21252. var _this = this;
  21253. return BABYLON.SerializationHelper.Clone(function () {
  21254. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21255. }, this);
  21256. };
  21257. // Statics
  21258. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  21259. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21260. if (onLoad === void 0) { onLoad = null; }
  21261. if (onError === void 0) { onError = null; }
  21262. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  21263. };
  21264. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21265. if (parsedTexture.isCube) {
  21266. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21267. }
  21268. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21269. return null;
  21270. }
  21271. var texture = BABYLON.SerializationHelper.Parse(function () {
  21272. if (parsedTexture.mirrorPlane) {
  21273. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21274. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21275. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21276. return mirrorTexture;
  21277. }
  21278. else if (parsedTexture.isRenderTarget) {
  21279. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21280. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21281. return renderTargetTexture;
  21282. }
  21283. else {
  21284. var texture;
  21285. if (parsedTexture.base64String) {
  21286. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21287. }
  21288. else {
  21289. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21290. }
  21291. return texture;
  21292. }
  21293. }, parsedTexture, scene);
  21294. // Animations
  21295. if (parsedTexture.animations) {
  21296. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21297. var parsedAnimation = parsedTexture.animations[animationIndex];
  21298. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21299. }
  21300. }
  21301. return texture;
  21302. };
  21303. // Constants
  21304. Texture.NEAREST_SAMPLINGMODE = 1;
  21305. Texture.BILINEAR_SAMPLINGMODE = 2;
  21306. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21307. Texture.EXPLICIT_MODE = 0;
  21308. Texture.SPHERICAL_MODE = 1;
  21309. Texture.PLANAR_MODE = 2;
  21310. Texture.CUBIC_MODE = 3;
  21311. Texture.PROJECTION_MODE = 4;
  21312. Texture.SKYBOX_MODE = 5;
  21313. Texture.INVCUBIC_MODE = 6;
  21314. Texture.EQUIRECTANGULAR_MODE = 7;
  21315. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21316. Texture.CLAMP_ADDRESSMODE = 0;
  21317. Texture.WRAP_ADDRESSMODE = 1;
  21318. Texture.MIRROR_ADDRESSMODE = 2;
  21319. __decorate([
  21320. BABYLON.serialize()
  21321. ], Texture.prototype, "url", void 0);
  21322. __decorate([
  21323. BABYLON.serialize()
  21324. ], Texture.prototype, "uOffset", void 0);
  21325. __decorate([
  21326. BABYLON.serialize()
  21327. ], Texture.prototype, "vOffset", void 0);
  21328. __decorate([
  21329. BABYLON.serialize()
  21330. ], Texture.prototype, "uScale", void 0);
  21331. __decorate([
  21332. BABYLON.serialize()
  21333. ], Texture.prototype, "vScale", void 0);
  21334. __decorate([
  21335. BABYLON.serialize()
  21336. ], Texture.prototype, "uAng", void 0);
  21337. __decorate([
  21338. BABYLON.serialize()
  21339. ], Texture.prototype, "vAng", void 0);
  21340. __decorate([
  21341. BABYLON.serialize()
  21342. ], Texture.prototype, "wAng", void 0);
  21343. return Texture;
  21344. })(BABYLON.BaseTexture);
  21345. BABYLON.Texture = Texture;
  21346. })(BABYLON || (BABYLON = {}));
  21347. var BABYLON;
  21348. (function (BABYLON) {
  21349. var CubeTexture = (function (_super) {
  21350. __extends(CubeTexture, _super);
  21351. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  21352. _super.call(this, scene);
  21353. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  21354. this.name = rootUrl;
  21355. this.url = rootUrl;
  21356. this._noMipmap = noMipmap;
  21357. this.hasAlpha = false;
  21358. if (!rootUrl && !files) {
  21359. return;
  21360. }
  21361. this._texture = this._getFromCache(rootUrl, noMipmap);
  21362. if (!files) {
  21363. if (!extensions) {
  21364. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  21365. }
  21366. files = [];
  21367. for (var index = 0; index < extensions.length; index++) {
  21368. files.push(rootUrl + extensions[index]);
  21369. }
  21370. this._extensions = extensions;
  21371. }
  21372. this._files = files;
  21373. if (!this._texture) {
  21374. if (!scene.useDelayedTextureLoading) {
  21375. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  21376. }
  21377. else {
  21378. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21379. }
  21380. }
  21381. this.isCube = true;
  21382. this._textureMatrix = BABYLON.Matrix.Identity();
  21383. }
  21384. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  21385. return new CubeTexture("", scene, null, noMipmap, files);
  21386. };
  21387. // Methods
  21388. CubeTexture.prototype.delayLoad = function () {
  21389. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21390. return;
  21391. }
  21392. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21393. this._texture = this._getFromCache(this.url, this._noMipmap);
  21394. if (!this._texture) {
  21395. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  21396. }
  21397. };
  21398. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  21399. return this._textureMatrix;
  21400. };
  21401. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  21402. var texture = BABYLON.SerializationHelper.Parse(function () {
  21403. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  21404. }, parsedTexture, scene);
  21405. // Animations
  21406. if (parsedTexture.animations) {
  21407. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21408. var parsedAnimation = parsedTexture.animations[animationIndex];
  21409. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21410. }
  21411. }
  21412. return texture;
  21413. };
  21414. CubeTexture.prototype.clone = function () {
  21415. var _this = this;
  21416. return BABYLON.SerializationHelper.Clone(function () {
  21417. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  21418. }, this);
  21419. };
  21420. return CubeTexture;
  21421. })(BABYLON.BaseTexture);
  21422. BABYLON.CubeTexture = CubeTexture;
  21423. })(BABYLON || (BABYLON = {}));
  21424. var BABYLON;
  21425. (function (BABYLON) {
  21426. var RenderTargetTexture = (function (_super) {
  21427. __extends(RenderTargetTexture, _super);
  21428. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode) {
  21429. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  21430. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  21431. if (isCube === void 0) { isCube = false; }
  21432. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21433. _super.call(this, null, scene, !generateMipMaps);
  21434. this.isCube = isCube;
  21435. /**
  21436. * Use this list to define the list of mesh you want to render.
  21437. */
  21438. this.renderList = new Array();
  21439. this.renderParticles = true;
  21440. this.renderSprites = false;
  21441. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  21442. // Events
  21443. /**
  21444. * An event triggered when the texture is unbind.
  21445. * @type {BABYLON.Observable}
  21446. */
  21447. this.onAfterUnbindObservable = new BABYLON.Observable();
  21448. /**
  21449. * An event triggered before rendering the texture
  21450. * @type {BABYLON.Observable}
  21451. */
  21452. this.onBeforeRenderObservable = new BABYLON.Observable();
  21453. /**
  21454. * An event triggered after rendering the texture
  21455. * @type {BABYLON.Observable}
  21456. */
  21457. this.onAfterRenderObservable = new BABYLON.Observable();
  21458. /**
  21459. * An event triggered after the texture clear
  21460. * @type {BABYLON.Observable}
  21461. */
  21462. this.onClearObservable = new BABYLON.Observable();
  21463. this._currentRefreshId = -1;
  21464. this._refreshRate = 1;
  21465. this.name = name;
  21466. this.isRenderTarget = true;
  21467. this._size = size;
  21468. this._generateMipMaps = generateMipMaps;
  21469. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  21470. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  21471. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21472. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21473. }
  21474. if (isCube) {
  21475. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, samplingMode: samplingMode });
  21476. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  21477. this._textureMatrix = BABYLON.Matrix.Identity();
  21478. }
  21479. else {
  21480. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type, samplingMode: samplingMode });
  21481. }
  21482. // Rendering groups
  21483. this._renderingManager = new BABYLON.RenderingManager(scene);
  21484. }
  21485. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  21486. get: function () {
  21487. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  21488. },
  21489. enumerable: true,
  21490. configurable: true
  21491. });
  21492. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  21493. get: function () {
  21494. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  21495. },
  21496. enumerable: true,
  21497. configurable: true
  21498. });
  21499. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  21500. get: function () {
  21501. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  21502. },
  21503. enumerable: true,
  21504. configurable: true
  21505. });
  21506. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  21507. set: function (callback) {
  21508. if (this._onAfterUnbindObserver) {
  21509. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  21510. }
  21511. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  21512. },
  21513. enumerable: true,
  21514. configurable: true
  21515. });
  21516. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  21517. set: function (callback) {
  21518. if (this._onBeforeRenderObserver) {
  21519. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21520. }
  21521. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21522. },
  21523. enumerable: true,
  21524. configurable: true
  21525. });
  21526. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  21527. set: function (callback) {
  21528. if (this._onAfterRenderObserver) {
  21529. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21530. }
  21531. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21532. },
  21533. enumerable: true,
  21534. configurable: true
  21535. });
  21536. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  21537. set: function (callback) {
  21538. if (this._onClearObserver) {
  21539. this.onClearObservable.remove(this._onClearObserver);
  21540. }
  21541. this._onClearObserver = this.onClearObservable.add(callback);
  21542. },
  21543. enumerable: true,
  21544. configurable: true
  21545. });
  21546. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  21547. this._currentRefreshId = -1;
  21548. };
  21549. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  21550. get: function () {
  21551. return this._refreshRate;
  21552. },
  21553. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  21554. set: function (value) {
  21555. this._refreshRate = value;
  21556. this.resetRefreshCounter();
  21557. },
  21558. enumerable: true,
  21559. configurable: true
  21560. });
  21561. RenderTargetTexture.prototype._shouldRender = function () {
  21562. if (this._currentRefreshId === -1) {
  21563. this._currentRefreshId = 1;
  21564. return true;
  21565. }
  21566. if (this.refreshRate === this._currentRefreshId) {
  21567. this._currentRefreshId = 1;
  21568. return true;
  21569. }
  21570. this._currentRefreshId++;
  21571. return false;
  21572. };
  21573. RenderTargetTexture.prototype.isReady = function () {
  21574. if (!this.getScene().renderTargetsEnabled) {
  21575. return false;
  21576. }
  21577. return _super.prototype.isReady.call(this);
  21578. };
  21579. RenderTargetTexture.prototype.getRenderSize = function () {
  21580. return this._size;
  21581. };
  21582. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  21583. get: function () {
  21584. return true;
  21585. },
  21586. enumerable: true,
  21587. configurable: true
  21588. });
  21589. RenderTargetTexture.prototype.scale = function (ratio) {
  21590. var newSize = this._size * ratio;
  21591. this.resize(newSize, this._generateMipMaps);
  21592. };
  21593. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  21594. if (this.isCube) {
  21595. return this._textureMatrix;
  21596. }
  21597. return _super.prototype.getReflectionTextureMatrix.call(this);
  21598. };
  21599. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  21600. this.releaseInternalTexture();
  21601. if (this.isCube) {
  21602. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  21603. }
  21604. else {
  21605. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  21606. }
  21607. };
  21608. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  21609. var scene = this.getScene();
  21610. if (this.useCameraPostProcesses !== undefined) {
  21611. useCameraPostProcess = this.useCameraPostProcesses;
  21612. }
  21613. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  21614. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  21615. }
  21616. if (this._waitingRenderList) {
  21617. this.renderList = [];
  21618. for (var index = 0; index < this._waitingRenderList.length; index++) {
  21619. var id = this._waitingRenderList[index];
  21620. this.renderList.push(scene.getMeshByID(id));
  21621. }
  21622. delete this._waitingRenderList;
  21623. }
  21624. // Is predicate defined?
  21625. if (this.renderListPredicate) {
  21626. this.renderList.splice(0); // Clear previous renderList
  21627. var sceneMeshes = this.getScene().meshes;
  21628. for (var index = 0; index < sceneMeshes.length; index++) {
  21629. var mesh = sceneMeshes[index];
  21630. if (this.renderListPredicate(mesh)) {
  21631. this.renderList.push(mesh);
  21632. }
  21633. }
  21634. }
  21635. if (this.renderList && this.renderList.length === 0) {
  21636. return;
  21637. }
  21638. // Prepare renderingManager
  21639. this._renderingManager.reset();
  21640. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  21641. var sceneRenderId = scene.getRenderId();
  21642. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  21643. var mesh = currentRenderList[meshIndex];
  21644. if (mesh) {
  21645. if (!mesh.isReady()) {
  21646. // Reset _currentRefreshId
  21647. this.resetRefreshCounter();
  21648. continue;
  21649. }
  21650. mesh._preActivateForIntermediateRendering(sceneRenderId);
  21651. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  21652. mesh._activate(sceneRenderId);
  21653. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  21654. var subMesh = mesh.subMeshes[subIndex];
  21655. scene._activeIndices += subMesh.indexCount;
  21656. this._renderingManager.dispatch(subMesh);
  21657. }
  21658. }
  21659. }
  21660. }
  21661. if (this.isCube) {
  21662. for (var face = 0; face < 6; face++) {
  21663. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  21664. scene.incrementRenderId();
  21665. scene.resetCachedMaterial();
  21666. }
  21667. }
  21668. else {
  21669. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  21670. }
  21671. this.onAfterUnbindObservable.notifyObservers(this);
  21672. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  21673. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  21674. }
  21675. scene.resetCachedMaterial();
  21676. };
  21677. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  21678. var scene = this.getScene();
  21679. var engine = scene.getEngine();
  21680. // Bind
  21681. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  21682. if (this.isCube) {
  21683. engine.bindFramebuffer(this._texture, faceIndex);
  21684. }
  21685. else {
  21686. engine.bindFramebuffer(this._texture);
  21687. }
  21688. }
  21689. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  21690. // Clear
  21691. if (this.onClearObservable.hasObservers()) {
  21692. this.onClearObservable.notifyObservers(engine);
  21693. }
  21694. else {
  21695. engine.clear(scene.clearColor, true, true);
  21696. }
  21697. if (!this._doNotChangeAspectRatio) {
  21698. scene.updateTransformMatrix(true);
  21699. }
  21700. // Render
  21701. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  21702. if (useCameraPostProcess) {
  21703. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  21704. }
  21705. if (!this._doNotChangeAspectRatio) {
  21706. scene.updateTransformMatrix(true);
  21707. }
  21708. this.onAfterRenderObservable.notifyObservers(faceIndex);
  21709. // Dump ?
  21710. if (dumpForDebug) {
  21711. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  21712. }
  21713. // Unbind
  21714. if (!this.isCube || faceIndex === 5) {
  21715. if (this.isCube) {
  21716. if (faceIndex === 5) {
  21717. engine.generateMipMapsForCubemap(this._texture);
  21718. }
  21719. }
  21720. engine.unBindFramebuffer(this._texture, this.isCube);
  21721. }
  21722. };
  21723. RenderTargetTexture.prototype.clone = function () {
  21724. var textureSize = this.getSize();
  21725. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21726. // Base texture
  21727. newTexture.hasAlpha = this.hasAlpha;
  21728. newTexture.level = this.level;
  21729. // RenderTarget Texture
  21730. newTexture.coordinatesMode = this.coordinatesMode;
  21731. newTexture.renderList = this.renderList.slice(0);
  21732. return newTexture;
  21733. };
  21734. RenderTargetTexture.prototype.serialize = function () {
  21735. if (!this.name) {
  21736. return null;
  21737. }
  21738. var serializationObject = _super.prototype.serialize.call(this);
  21739. serializationObject.renderTargetSize = this.getRenderSize();
  21740. serializationObject.renderList = [];
  21741. for (var index = 0; index < this.renderList.length; index++) {
  21742. serializationObject.renderList.push(this.renderList[index].id);
  21743. }
  21744. return serializationObject;
  21745. };
  21746. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  21747. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  21748. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  21749. return RenderTargetTexture;
  21750. })(BABYLON.Texture);
  21751. BABYLON.RenderTargetTexture = RenderTargetTexture;
  21752. })(BABYLON || (BABYLON = {}));
  21753. var BABYLON;
  21754. (function (BABYLON) {
  21755. var ProceduralTexture = (function (_super) {
  21756. __extends(ProceduralTexture, _super);
  21757. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  21758. if (generateMipMaps === void 0) { generateMipMaps = true; }
  21759. if (isCube === void 0) { isCube = false; }
  21760. _super.call(this, null, scene, !generateMipMaps);
  21761. this.isCube = isCube;
  21762. this.isEnabled = true;
  21763. this._currentRefreshId = -1;
  21764. this._refreshRate = 1;
  21765. this._vertexBuffers = {};
  21766. this._uniforms = new Array();
  21767. this._samplers = new Array();
  21768. this._textures = new Array();
  21769. this._floats = new Array();
  21770. this._floatsArrays = {};
  21771. this._colors3 = new Array();
  21772. this._colors4 = new Array();
  21773. this._vectors2 = new Array();
  21774. this._vectors3 = new Array();
  21775. this._matrices = new Array();
  21776. this._fallbackTextureUsed = false;
  21777. scene._proceduralTextures.push(this);
  21778. this.name = name;
  21779. this.isRenderTarget = true;
  21780. this._size = size;
  21781. this._generateMipMaps = generateMipMaps;
  21782. this.setFragment(fragment);
  21783. this._fallbackTexture = fallbackTexture;
  21784. var engine = scene.getEngine();
  21785. if (isCube) {
  21786. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  21787. this.setFloat("face", 0);
  21788. }
  21789. else {
  21790. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  21791. }
  21792. // VBO
  21793. var vertices = [];
  21794. vertices.push(1, 1);
  21795. vertices.push(-1, 1);
  21796. vertices.push(-1, -1);
  21797. vertices.push(1, -1);
  21798. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  21799. // Indices
  21800. var indices = [];
  21801. indices.push(0);
  21802. indices.push(1);
  21803. indices.push(2);
  21804. indices.push(0);
  21805. indices.push(2);
  21806. indices.push(3);
  21807. this._indexBuffer = engine.createIndexBuffer(indices);
  21808. }
  21809. ProceduralTexture.prototype.reset = function () {
  21810. if (this._effect === undefined) {
  21811. return;
  21812. }
  21813. var engine = this.getScene().getEngine();
  21814. engine._releaseEffect(this._effect);
  21815. };
  21816. ProceduralTexture.prototype.isReady = function () {
  21817. var _this = this;
  21818. var engine = this.getScene().getEngine();
  21819. var shaders;
  21820. if (!this._fragment) {
  21821. return false;
  21822. }
  21823. if (this._fallbackTextureUsed) {
  21824. return true;
  21825. }
  21826. if (this._fragment.fragmentElement !== undefined) {
  21827. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  21828. }
  21829. else {
  21830. shaders = { vertex: "procedural", fragment: this._fragment };
  21831. }
  21832. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  21833. _this.releaseInternalTexture();
  21834. if (_this._fallbackTexture) {
  21835. _this._texture = _this._fallbackTexture._texture;
  21836. _this._texture.references++;
  21837. }
  21838. _this._fallbackTextureUsed = true;
  21839. });
  21840. return this._effect.isReady();
  21841. };
  21842. ProceduralTexture.prototype.resetRefreshCounter = function () {
  21843. this._currentRefreshId = -1;
  21844. };
  21845. ProceduralTexture.prototype.setFragment = function (fragment) {
  21846. this._fragment = fragment;
  21847. };
  21848. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  21849. get: function () {
  21850. return this._refreshRate;
  21851. },
  21852. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  21853. set: function (value) {
  21854. this._refreshRate = value;
  21855. this.resetRefreshCounter();
  21856. },
  21857. enumerable: true,
  21858. configurable: true
  21859. });
  21860. ProceduralTexture.prototype._shouldRender = function () {
  21861. if (!this.isEnabled || !this.isReady() || !this._texture) {
  21862. return false;
  21863. }
  21864. if (this._fallbackTextureUsed) {
  21865. return false;
  21866. }
  21867. if (this._currentRefreshId === -1) {
  21868. this._currentRefreshId = 1;
  21869. return true;
  21870. }
  21871. if (this.refreshRate === this._currentRefreshId) {
  21872. this._currentRefreshId = 1;
  21873. return true;
  21874. }
  21875. this._currentRefreshId++;
  21876. return false;
  21877. };
  21878. ProceduralTexture.prototype.getRenderSize = function () {
  21879. return this._size;
  21880. };
  21881. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  21882. if (this._fallbackTextureUsed) {
  21883. return;
  21884. }
  21885. this.releaseInternalTexture();
  21886. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  21887. };
  21888. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  21889. if (this._uniforms.indexOf(uniformName) === -1) {
  21890. this._uniforms.push(uniformName);
  21891. }
  21892. };
  21893. ProceduralTexture.prototype.setTexture = function (name, texture) {
  21894. if (this._samplers.indexOf(name) === -1) {
  21895. this._samplers.push(name);
  21896. }
  21897. this._textures[name] = texture;
  21898. return this;
  21899. };
  21900. ProceduralTexture.prototype.setFloat = function (name, value) {
  21901. this._checkUniform(name);
  21902. this._floats[name] = value;
  21903. return this;
  21904. };
  21905. ProceduralTexture.prototype.setFloats = function (name, value) {
  21906. this._checkUniform(name);
  21907. this._floatsArrays[name] = value;
  21908. return this;
  21909. };
  21910. ProceduralTexture.prototype.setColor3 = function (name, value) {
  21911. this._checkUniform(name);
  21912. this._colors3[name] = value;
  21913. return this;
  21914. };
  21915. ProceduralTexture.prototype.setColor4 = function (name, value) {
  21916. this._checkUniform(name);
  21917. this._colors4[name] = value;
  21918. return this;
  21919. };
  21920. ProceduralTexture.prototype.setVector2 = function (name, value) {
  21921. this._checkUniform(name);
  21922. this._vectors2[name] = value;
  21923. return this;
  21924. };
  21925. ProceduralTexture.prototype.setVector3 = function (name, value) {
  21926. this._checkUniform(name);
  21927. this._vectors3[name] = value;
  21928. return this;
  21929. };
  21930. ProceduralTexture.prototype.setMatrix = function (name, value) {
  21931. this._checkUniform(name);
  21932. this._matrices[name] = value;
  21933. return this;
  21934. };
  21935. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21936. var scene = this.getScene();
  21937. var engine = scene.getEngine();
  21938. // Render
  21939. engine.enableEffect(this._effect);
  21940. engine.setState(false);
  21941. // Texture
  21942. for (var name in this._textures) {
  21943. this._effect.setTexture(name, this._textures[name]);
  21944. }
  21945. // Float
  21946. for (name in this._floats) {
  21947. this._effect.setFloat(name, this._floats[name]);
  21948. }
  21949. // Floats
  21950. for (name in this._floatsArrays) {
  21951. this._effect.setArray(name, this._floatsArrays[name]);
  21952. }
  21953. // Color3
  21954. for (name in this._colors3) {
  21955. this._effect.setColor3(name, this._colors3[name]);
  21956. }
  21957. // Color4
  21958. for (name in this._colors4) {
  21959. var color = this._colors4[name];
  21960. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21961. }
  21962. // Vector2
  21963. for (name in this._vectors2) {
  21964. this._effect.setVector2(name, this._vectors2[name]);
  21965. }
  21966. // Vector3
  21967. for (name in this._vectors3) {
  21968. this._effect.setVector3(name, this._vectors3[name]);
  21969. }
  21970. // Matrix
  21971. for (name in this._matrices) {
  21972. this._effect.setMatrix(name, this._matrices[name]);
  21973. }
  21974. // VBOs
  21975. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  21976. if (this.isCube) {
  21977. for (var face = 0; face < 6; face++) {
  21978. engine.bindFramebuffer(this._texture, face);
  21979. this._effect.setFloat("face", face);
  21980. // Clear
  21981. engine.clear(scene.clearColor, true, true);
  21982. // Draw order
  21983. engine.draw(true, 0, 6);
  21984. // Mipmaps
  21985. if (face === 5) {
  21986. engine.generateMipMapsForCubemap(this._texture);
  21987. }
  21988. }
  21989. }
  21990. else {
  21991. engine.bindFramebuffer(this._texture);
  21992. // Clear
  21993. engine.clear(scene.clearColor, true, true);
  21994. // Draw order
  21995. engine.draw(true, 0, 6);
  21996. }
  21997. // Unbind
  21998. engine.unBindFramebuffer(this._texture, this.isCube);
  21999. if (this.onGenerated) {
  22000. this.onGenerated();
  22001. }
  22002. };
  22003. ProceduralTexture.prototype.clone = function () {
  22004. var textureSize = this.getSize();
  22005. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  22006. // Base texture
  22007. newTexture.hasAlpha = this.hasAlpha;
  22008. newTexture.level = this.level;
  22009. // RenderTarget Texture
  22010. newTexture.coordinatesMode = this.coordinatesMode;
  22011. return newTexture;
  22012. };
  22013. ProceduralTexture.prototype.dispose = function () {
  22014. var index = this.getScene()._proceduralTextures.indexOf(this);
  22015. if (index >= 0) {
  22016. this.getScene()._proceduralTextures.splice(index, 1);
  22017. }
  22018. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  22019. if (vertexBuffer) {
  22020. vertexBuffer.dispose();
  22021. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  22022. }
  22023. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  22024. this._indexBuffer = null;
  22025. }
  22026. _super.prototype.dispose.call(this);
  22027. };
  22028. return ProceduralTexture;
  22029. })(BABYLON.Texture);
  22030. BABYLON.ProceduralTexture = ProceduralTexture;
  22031. })(BABYLON || (BABYLON = {}));
  22032. var BABYLON;
  22033. (function (BABYLON) {
  22034. var MirrorTexture = (function (_super) {
  22035. __extends(MirrorTexture, _super);
  22036. function MirrorTexture(name, size, scene, generateMipMaps) {
  22037. var _this = this;
  22038. _super.call(this, name, size, scene, generateMipMaps, true);
  22039. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  22040. this._transformMatrix = BABYLON.Matrix.Zero();
  22041. this._mirrorMatrix = BABYLON.Matrix.Zero();
  22042. this.onBeforeRenderObservable.add(function () {
  22043. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  22044. _this._savedViewMatrix = scene.getViewMatrix();
  22045. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  22046. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  22047. scene.clipPlane = _this.mirrorPlane;
  22048. scene.getEngine().cullBackFaces = false;
  22049. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  22050. });
  22051. this.onAfterRenderObservable.add(function () {
  22052. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  22053. scene.getEngine().cullBackFaces = true;
  22054. scene._mirroredCameraPosition = null;
  22055. delete scene.clipPlane;
  22056. });
  22057. }
  22058. MirrorTexture.prototype.clone = function () {
  22059. var textureSize = this.getSize();
  22060. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22061. // Base texture
  22062. newTexture.hasAlpha = this.hasAlpha;
  22063. newTexture.level = this.level;
  22064. // Mirror Texture
  22065. newTexture.mirrorPlane = this.mirrorPlane.clone();
  22066. newTexture.renderList = this.renderList.slice(0);
  22067. return newTexture;
  22068. };
  22069. MirrorTexture.prototype.serialize = function () {
  22070. if (!this.name) {
  22071. return null;
  22072. }
  22073. var serializationObject = _super.prototype.serialize.call(this);
  22074. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  22075. return serializationObject;
  22076. };
  22077. return MirrorTexture;
  22078. })(BABYLON.RenderTargetTexture);
  22079. BABYLON.MirrorTexture = MirrorTexture;
  22080. })(BABYLON || (BABYLON = {}));
  22081. var BABYLON;
  22082. (function (BABYLON) {
  22083. /**
  22084. * Creates a refraction texture used by refraction channel of the standard material.
  22085. * @param name the texture name
  22086. * @param size size of the underlying texture
  22087. * @param scene root scene
  22088. */
  22089. var RefractionTexture = (function (_super) {
  22090. __extends(RefractionTexture, _super);
  22091. function RefractionTexture(name, size, scene, generateMipMaps) {
  22092. var _this = this;
  22093. _super.call(this, name, size, scene, generateMipMaps, true);
  22094. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  22095. this.depth = 2.0;
  22096. this.onBeforeRenderObservable.add(function () {
  22097. scene.clipPlane = _this.refractionPlane;
  22098. });
  22099. this.onAfterRenderObservable.add(function () {
  22100. delete scene.clipPlane;
  22101. });
  22102. }
  22103. RefractionTexture.prototype.clone = function () {
  22104. var textureSize = this.getSize();
  22105. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22106. // Base texture
  22107. newTexture.hasAlpha = this.hasAlpha;
  22108. newTexture.level = this.level;
  22109. // Refraction Texture
  22110. newTexture.refractionPlane = this.refractionPlane.clone();
  22111. newTexture.renderList = this.renderList.slice(0);
  22112. newTexture.depth = this.depth;
  22113. return newTexture;
  22114. };
  22115. RefractionTexture.prototype.serialize = function () {
  22116. if (!this.name) {
  22117. return null;
  22118. }
  22119. var serializationObject = _super.prototype.serialize.call(this);
  22120. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  22121. serializationObject.depth = this.depth;
  22122. return serializationObject;
  22123. };
  22124. return RefractionTexture;
  22125. })(BABYLON.RenderTargetTexture);
  22126. BABYLON.RefractionTexture = RefractionTexture;
  22127. })(BABYLON || (BABYLON = {}));
  22128. var BABYLON;
  22129. (function (BABYLON) {
  22130. var DynamicTexture = (function (_super) {
  22131. __extends(DynamicTexture, _super);
  22132. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  22133. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22134. _super.call(this, null, scene, !generateMipMaps);
  22135. this.name = name;
  22136. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22137. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22138. this._generateMipMaps = generateMipMaps;
  22139. if (options.getContext) {
  22140. this._canvas = options;
  22141. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  22142. }
  22143. else {
  22144. this._canvas = document.createElement("canvas");
  22145. if (options.width) {
  22146. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  22147. }
  22148. else {
  22149. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  22150. }
  22151. }
  22152. var textureSize = this.getSize();
  22153. this._canvas.width = textureSize.width;
  22154. this._canvas.height = textureSize.height;
  22155. this._context = this._canvas.getContext("2d");
  22156. }
  22157. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  22158. get: function () {
  22159. return true;
  22160. },
  22161. enumerable: true,
  22162. configurable: true
  22163. });
  22164. DynamicTexture.prototype.scale = function (ratio) {
  22165. var textureSize = this.getSize();
  22166. textureSize.width *= ratio;
  22167. textureSize.height *= ratio;
  22168. this._canvas.width = textureSize.width;
  22169. this._canvas.height = textureSize.height;
  22170. this.releaseInternalTexture();
  22171. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  22172. };
  22173. DynamicTexture.prototype.getContext = function () {
  22174. return this._context;
  22175. };
  22176. DynamicTexture.prototype.clear = function () {
  22177. var size = this.getSize();
  22178. this._context.fillRect(0, 0, size.width, size.height);
  22179. };
  22180. DynamicTexture.prototype.update = function (invertY) {
  22181. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  22182. };
  22183. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  22184. if (update === void 0) { update = true; }
  22185. var size = this.getSize();
  22186. if (clearColor) {
  22187. this._context.fillStyle = clearColor;
  22188. this._context.fillRect(0, 0, size.width, size.height);
  22189. }
  22190. this._context.font = font;
  22191. if (x === null) {
  22192. var textSize = this._context.measureText(text);
  22193. x = (size.width - textSize.width) / 2;
  22194. }
  22195. this._context.fillStyle = color;
  22196. this._context.fillText(text, x, y);
  22197. if (update) {
  22198. this.update(invertY);
  22199. }
  22200. };
  22201. DynamicTexture.prototype.clone = function () {
  22202. var textureSize = this.getSize();
  22203. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  22204. // Base texture
  22205. newTexture.hasAlpha = this.hasAlpha;
  22206. newTexture.level = this.level;
  22207. // Dynamic Texture
  22208. newTexture.wrapU = this.wrapU;
  22209. newTexture.wrapV = this.wrapV;
  22210. return newTexture;
  22211. };
  22212. return DynamicTexture;
  22213. })(BABYLON.Texture);
  22214. BABYLON.DynamicTexture = DynamicTexture;
  22215. })(BABYLON || (BABYLON = {}));
  22216. var BABYLON;
  22217. (function (BABYLON) {
  22218. var VideoTexture = (function (_super) {
  22219. __extends(VideoTexture, _super);
  22220. /**
  22221. * Creates a video texture.
  22222. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  22223. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  22224. * @param {BABYLON.Scene} scene is obviously the current scene.
  22225. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  22226. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  22227. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  22228. */
  22229. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  22230. var _this = this;
  22231. if (generateMipMaps === void 0) { generateMipMaps = false; }
  22232. if (invertY === void 0) { invertY = false; }
  22233. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22234. _super.call(this, null, scene, !generateMipMaps, invertY);
  22235. this._autoLaunch = true;
  22236. var urls;
  22237. this.name = name;
  22238. if (urlsOrVideo instanceof HTMLVideoElement) {
  22239. this.video = urlsOrVideo;
  22240. }
  22241. else {
  22242. urls = urlsOrVideo;
  22243. this.video = document.createElement("video");
  22244. this.video.autoplay = false;
  22245. this.video.loop = true;
  22246. }
  22247. this._generateMipMaps = generateMipMaps;
  22248. this._samplingMode = samplingMode;
  22249. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  22250. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22251. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22252. }
  22253. else {
  22254. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22255. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22256. this._generateMipMaps = false;
  22257. }
  22258. if (urls) {
  22259. this.video.addEventListener("canplaythrough", function () {
  22260. _this._createTexture();
  22261. });
  22262. urls.forEach(function (url) {
  22263. var source = document.createElement("source");
  22264. source.src = url;
  22265. _this.video.appendChild(source);
  22266. });
  22267. }
  22268. else {
  22269. this._createTexture();
  22270. }
  22271. this._lastUpdate = BABYLON.Tools.Now;
  22272. }
  22273. VideoTexture.prototype._createTexture = function () {
  22274. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  22275. this._texture.isReady = true;
  22276. };
  22277. VideoTexture.prototype.update = function () {
  22278. if (this._autoLaunch) {
  22279. this._autoLaunch = false;
  22280. this.video.play();
  22281. }
  22282. var now = BABYLON.Tools.Now;
  22283. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  22284. return false;
  22285. }
  22286. this._lastUpdate = now;
  22287. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  22288. return true;
  22289. };
  22290. return VideoTexture;
  22291. })(BABYLON.Texture);
  22292. BABYLON.VideoTexture = VideoTexture;
  22293. })(BABYLON || (BABYLON = {}));
  22294. var BABYLON;
  22295. (function (BABYLON) {
  22296. var CustomProceduralTexture = (function (_super) {
  22297. __extends(CustomProceduralTexture, _super);
  22298. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  22299. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  22300. this._animate = true;
  22301. this._time = 0;
  22302. this._texturePath = texturePath;
  22303. //Try to load json
  22304. this.loadJson(texturePath);
  22305. this.refreshRate = 1;
  22306. }
  22307. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  22308. var _this = this;
  22309. var that = this;
  22310. function noConfigFile() {
  22311. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  22312. try {
  22313. that.setFragment(that._texturePath);
  22314. }
  22315. catch (ex) {
  22316. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  22317. }
  22318. }
  22319. var configFileUrl = jsonUrl + "/config.json";
  22320. var xhr = new XMLHttpRequest();
  22321. xhr.open("GET", configFileUrl, true);
  22322. xhr.addEventListener("load", function () {
  22323. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  22324. try {
  22325. _this._config = JSON.parse(xhr.response);
  22326. _this.updateShaderUniforms();
  22327. _this.updateTextures();
  22328. _this.setFragment(_this._texturePath + "/custom");
  22329. _this._animate = _this._config.animate;
  22330. _this.refreshRate = _this._config.refreshrate;
  22331. }
  22332. catch (ex) {
  22333. noConfigFile();
  22334. }
  22335. }
  22336. else {
  22337. noConfigFile();
  22338. }
  22339. }, false);
  22340. xhr.addEventListener("error", function () {
  22341. noConfigFile();
  22342. }, false);
  22343. try {
  22344. xhr.send();
  22345. }
  22346. catch (ex) {
  22347. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  22348. }
  22349. };
  22350. CustomProceduralTexture.prototype.isReady = function () {
  22351. if (!_super.prototype.isReady.call(this)) {
  22352. return false;
  22353. }
  22354. for (var name in this._textures) {
  22355. var texture = this._textures[name];
  22356. if (!texture.isReady()) {
  22357. return false;
  22358. }
  22359. }
  22360. return true;
  22361. };
  22362. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  22363. if (this._animate) {
  22364. this._time += this.getScene().getAnimationRatio() * 0.03;
  22365. this.updateShaderUniforms();
  22366. }
  22367. _super.prototype.render.call(this, useCameraPostProcess);
  22368. };
  22369. CustomProceduralTexture.prototype.updateTextures = function () {
  22370. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  22371. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  22372. }
  22373. };
  22374. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  22375. if (this._config) {
  22376. for (var j = 0; j < this._config.uniforms.length; j++) {
  22377. var uniform = this._config.uniforms[j];
  22378. switch (uniform.type) {
  22379. case "float":
  22380. this.setFloat(uniform.name, uniform.value);
  22381. break;
  22382. case "color3":
  22383. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  22384. break;
  22385. case "color4":
  22386. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  22387. break;
  22388. case "vector2":
  22389. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  22390. break;
  22391. case "vector3":
  22392. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  22393. break;
  22394. }
  22395. }
  22396. }
  22397. this.setFloat("time", this._time);
  22398. };
  22399. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  22400. get: function () {
  22401. return this._animate;
  22402. },
  22403. set: function (value) {
  22404. this._animate = value;
  22405. },
  22406. enumerable: true,
  22407. configurable: true
  22408. });
  22409. return CustomProceduralTexture;
  22410. })(BABYLON.ProceduralTexture);
  22411. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  22412. })(BABYLON || (BABYLON = {}));
  22413. var BABYLON;
  22414. (function (BABYLON) {
  22415. var EffectFallbacks = (function () {
  22416. function EffectFallbacks() {
  22417. this._defines = {};
  22418. this._currentRank = 32;
  22419. this._maxRank = -1;
  22420. }
  22421. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22422. if (!this._defines[rank]) {
  22423. if (rank < this._currentRank) {
  22424. this._currentRank = rank;
  22425. }
  22426. if (rank > this._maxRank) {
  22427. this._maxRank = rank;
  22428. }
  22429. this._defines[rank] = new Array();
  22430. }
  22431. this._defines[rank].push(define);
  22432. };
  22433. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22434. this._meshRank = rank;
  22435. this._mesh = mesh;
  22436. if (rank > this._maxRank) {
  22437. this._maxRank = rank;
  22438. }
  22439. };
  22440. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22441. get: function () {
  22442. return this._currentRank <= this._maxRank;
  22443. },
  22444. enumerable: true,
  22445. configurable: true
  22446. });
  22447. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22448. var currentFallbacks = this._defines[this._currentRank];
  22449. for (var index = 0; index < currentFallbacks.length; index++) {
  22450. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22451. }
  22452. if (this._mesh && this._currentRank === this._meshRank) {
  22453. this._mesh.computeBonesUsingShaders = false;
  22454. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22455. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22456. }
  22457. this._currentRank++;
  22458. return currentDefines;
  22459. };
  22460. return EffectFallbacks;
  22461. })();
  22462. BABYLON.EffectFallbacks = EffectFallbacks;
  22463. var Effect = (function () {
  22464. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22465. var _this = this;
  22466. this._isReady = false;
  22467. this._compilationError = "";
  22468. this._valueCache = [];
  22469. this._engine = engine;
  22470. this.name = baseName;
  22471. this.defines = defines;
  22472. this._uniformsNames = uniformsNames.concat(samplers);
  22473. this._samplers = samplers;
  22474. this._attributesNames = attributesNames;
  22475. this.onError = onError;
  22476. this.onCompiled = onCompiled;
  22477. this._indexParameters = indexParameters;
  22478. var vertexSource;
  22479. var fragmentSource;
  22480. if (baseName.vertexElement) {
  22481. vertexSource = document.getElementById(baseName.vertexElement);
  22482. if (!vertexSource) {
  22483. vertexSource = baseName.vertexElement;
  22484. }
  22485. }
  22486. else {
  22487. vertexSource = baseName.vertex || baseName;
  22488. }
  22489. if (baseName.fragmentElement) {
  22490. fragmentSource = document.getElementById(baseName.fragmentElement);
  22491. if (!fragmentSource) {
  22492. fragmentSource = baseName.fragmentElement;
  22493. }
  22494. }
  22495. else {
  22496. fragmentSource = baseName.fragment || baseName;
  22497. }
  22498. this._loadVertexShader(vertexSource, function (vertexCode) {
  22499. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22500. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22501. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22502. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  22503. });
  22504. });
  22505. });
  22506. });
  22507. }
  22508. // Properties
  22509. Effect.prototype.isReady = function () {
  22510. return this._isReady;
  22511. };
  22512. Effect.prototype.getProgram = function () {
  22513. return this._program;
  22514. };
  22515. Effect.prototype.getAttributesNames = function () {
  22516. return this._attributesNames;
  22517. };
  22518. Effect.prototype.getAttributeLocation = function (index) {
  22519. return this._attributes[index];
  22520. };
  22521. Effect.prototype.getAttributeLocationByName = function (name) {
  22522. var index = this._attributesNames.indexOf(name);
  22523. return this._attributes[index];
  22524. };
  22525. Effect.prototype.getAttributesCount = function () {
  22526. return this._attributes.length;
  22527. };
  22528. Effect.prototype.getUniformIndex = function (uniformName) {
  22529. return this._uniformsNames.indexOf(uniformName);
  22530. };
  22531. Effect.prototype.getUniform = function (uniformName) {
  22532. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22533. };
  22534. Effect.prototype.getSamplers = function () {
  22535. return this._samplers;
  22536. };
  22537. Effect.prototype.getCompilationError = function () {
  22538. return this._compilationError;
  22539. };
  22540. // Methods
  22541. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22542. // DOM element ?
  22543. if (vertex instanceof HTMLElement) {
  22544. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22545. callback(vertexCode);
  22546. return;
  22547. }
  22548. // Is in local store ?
  22549. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22550. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22551. return;
  22552. }
  22553. var vertexShaderUrl;
  22554. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22555. vertexShaderUrl = vertex;
  22556. }
  22557. else {
  22558. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22559. }
  22560. // Vertex shader
  22561. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22562. };
  22563. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22564. // DOM element ?
  22565. if (fragment instanceof HTMLElement) {
  22566. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22567. callback(fragmentCode);
  22568. return;
  22569. }
  22570. // Is in local store ?
  22571. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22572. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22573. return;
  22574. }
  22575. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22576. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22577. return;
  22578. }
  22579. var fragmentShaderUrl;
  22580. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22581. fragmentShaderUrl = fragment;
  22582. }
  22583. else {
  22584. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22585. }
  22586. // Fragment shader
  22587. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22588. };
  22589. Effect.prototype._dumpShadersName = function () {
  22590. if (this.name.vertexElement) {
  22591. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  22592. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  22593. }
  22594. else if (this.name.vertex) {
  22595. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  22596. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  22597. }
  22598. else {
  22599. BABYLON.Tools.Error("Vertex shader:" + this.name);
  22600. BABYLON.Tools.Error("Fragment shader:" + this.name);
  22601. }
  22602. };
  22603. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22604. var _this = this;
  22605. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22606. var match = regex.exec(sourceCode);
  22607. var returnValue = new String(sourceCode);
  22608. while (match != null) {
  22609. var includeFile = match[1];
  22610. if (Effect.IncludesShadersStore[includeFile]) {
  22611. // Substitution
  22612. var includeContent = Effect.IncludesShadersStore[includeFile];
  22613. if (match[2]) {
  22614. var splits = match[3].split(",");
  22615. for (var index = 0; index < splits.length; index += 2) {
  22616. var source = new RegExp(splits[index], "g");
  22617. var dest = splits[index + 1];
  22618. includeContent = includeContent.replace(source, dest);
  22619. }
  22620. }
  22621. if (match[4]) {
  22622. var indexString = match[5];
  22623. if (indexString.indexOf("..") !== -1) {
  22624. var indexSplits = indexString.split("..");
  22625. var minIndex = parseInt(indexSplits[0]);
  22626. var maxIndex = parseInt(indexSplits[1]);
  22627. var sourceIncludeContent = includeContent.slice(0);
  22628. includeContent = "";
  22629. if (isNaN(maxIndex)) {
  22630. maxIndex = this._indexParameters[indexSplits[1]];
  22631. }
  22632. for (var i = minIndex; i <= maxIndex; i++) {
  22633. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22634. }
  22635. }
  22636. else {
  22637. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22638. }
  22639. }
  22640. // Replace
  22641. returnValue = returnValue.replace(match[0], includeContent);
  22642. }
  22643. else {
  22644. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22645. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22646. Effect.IncludesShadersStore[includeFile] = fileContent;
  22647. _this._processIncludes(returnValue, callback);
  22648. });
  22649. return;
  22650. }
  22651. match = regex.exec(sourceCode);
  22652. }
  22653. callback(returnValue);
  22654. };
  22655. Effect.prototype._processPrecision = function (source) {
  22656. if (source.indexOf("precision highp float") === -1) {
  22657. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22658. source = "precision mediump float;\n" + source;
  22659. }
  22660. else {
  22661. source = "precision highp float;\n" + source;
  22662. }
  22663. }
  22664. else {
  22665. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22666. source = source.replace("precision highp float", "precision mediump float");
  22667. }
  22668. }
  22669. return source;
  22670. };
  22671. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22672. try {
  22673. var engine = this._engine;
  22674. // Precision
  22675. vertexSourceCode = this._processPrecision(vertexSourceCode);
  22676. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  22677. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22678. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22679. this._attributes = engine.getAttributes(this._program, attributesNames);
  22680. for (var index = 0; index < this._samplers.length; index++) {
  22681. var sampler = this.getUniform(this._samplers[index]);
  22682. if (sampler == null) {
  22683. this._samplers.splice(index, 1);
  22684. index--;
  22685. }
  22686. }
  22687. engine.bindSamplers(this);
  22688. this._isReady = true;
  22689. if (this.onCompiled) {
  22690. this.onCompiled(this);
  22691. }
  22692. }
  22693. catch (e) {
  22694. // Is it a problem with precision?
  22695. if (e.message.indexOf("highp") !== -1) {
  22696. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  22697. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  22698. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22699. return;
  22700. }
  22701. // Let's go through fallbacks then
  22702. if (fallbacks && fallbacks.isMoreFallbacks) {
  22703. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  22704. this._dumpShadersName();
  22705. defines = fallbacks.reduce(defines);
  22706. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22707. }
  22708. else {
  22709. BABYLON.Tools.Error("Unable to compile effect: ");
  22710. this._dumpShadersName();
  22711. BABYLON.Tools.Error("Defines: " + defines);
  22712. BABYLON.Tools.Error("Error: " + e.message);
  22713. this._compilationError = e.message;
  22714. if (this.onError) {
  22715. this.onError(this, this._compilationError);
  22716. }
  22717. }
  22718. }
  22719. };
  22720. Object.defineProperty(Effect.prototype, "isSupported", {
  22721. get: function () {
  22722. return this._compilationError === "";
  22723. },
  22724. enumerable: true,
  22725. configurable: true
  22726. });
  22727. Effect.prototype._bindTexture = function (channel, texture) {
  22728. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  22729. };
  22730. Effect.prototype.setTexture = function (channel, texture) {
  22731. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  22732. };
  22733. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  22734. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  22735. };
  22736. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  22737. if (!this._valueCache[uniformName]) {
  22738. this._valueCache[uniformName] = new BABYLON.Matrix();
  22739. }
  22740. for (var index = 0; index < 16; index++) {
  22741. this._valueCache[uniformName].m[index] = matrix.m[index];
  22742. }
  22743. };
  22744. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22745. if (!this._valueCache[uniformName]) {
  22746. this._valueCache[uniformName] = [x, y];
  22747. return;
  22748. }
  22749. this._valueCache[uniformName][0] = x;
  22750. this._valueCache[uniformName][1] = y;
  22751. };
  22752. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22753. if (!this._valueCache[uniformName]) {
  22754. this._valueCache[uniformName] = [x, y, z];
  22755. return;
  22756. }
  22757. this._valueCache[uniformName][0] = x;
  22758. this._valueCache[uniformName][1] = y;
  22759. this._valueCache[uniformName][2] = z;
  22760. };
  22761. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22762. if (!this._valueCache[uniformName]) {
  22763. this._valueCache[uniformName] = [x, y, z, w];
  22764. return;
  22765. }
  22766. this._valueCache[uniformName][0] = x;
  22767. this._valueCache[uniformName][1] = y;
  22768. this._valueCache[uniformName][2] = z;
  22769. this._valueCache[uniformName][3] = w;
  22770. };
  22771. Effect.prototype.setArray = function (uniformName, array) {
  22772. this._engine.setArray(this.getUniform(uniformName), array);
  22773. return this;
  22774. };
  22775. Effect.prototype.setArray2 = function (uniformName, array) {
  22776. this._engine.setArray2(this.getUniform(uniformName), array);
  22777. return this;
  22778. };
  22779. Effect.prototype.setArray3 = function (uniformName, array) {
  22780. this._engine.setArray3(this.getUniform(uniformName), array);
  22781. return this;
  22782. };
  22783. Effect.prototype.setArray4 = function (uniformName, array) {
  22784. this._engine.setArray4(this.getUniform(uniformName), array);
  22785. return this;
  22786. };
  22787. Effect.prototype.setMatrices = function (uniformName, matrices) {
  22788. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  22789. return this;
  22790. };
  22791. Effect.prototype.setMatrix = function (uniformName, matrix) {
  22792. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  22793. // return this;
  22794. // this._cacheMatrix(uniformName, matrix);
  22795. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  22796. return this;
  22797. };
  22798. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  22799. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  22800. return this;
  22801. };
  22802. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  22803. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  22804. return this;
  22805. };
  22806. Effect.prototype.setFloat = function (uniformName, value) {
  22807. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  22808. return this;
  22809. this._valueCache[uniformName] = value;
  22810. this._engine.setFloat(this.getUniform(uniformName), value);
  22811. return this;
  22812. };
  22813. Effect.prototype.setBool = function (uniformName, bool) {
  22814. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  22815. return this;
  22816. this._valueCache[uniformName] = bool;
  22817. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  22818. return this;
  22819. };
  22820. Effect.prototype.setVector2 = function (uniformName, vector2) {
  22821. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  22822. return this;
  22823. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  22824. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  22825. return this;
  22826. };
  22827. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  22828. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  22829. return this;
  22830. this._cacheFloat2(uniformName, x, y);
  22831. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  22832. return this;
  22833. };
  22834. Effect.prototype.setVector3 = function (uniformName, vector3) {
  22835. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  22836. return this;
  22837. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  22838. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  22839. return this;
  22840. };
  22841. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  22842. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  22843. return this;
  22844. this._cacheFloat3(uniformName, x, y, z);
  22845. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  22846. return this;
  22847. };
  22848. Effect.prototype.setVector4 = function (uniformName, vector4) {
  22849. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector4.x && this._valueCache[uniformName][1] === vector4.y && this._valueCache[uniformName][2] === vector4.z && this._valueCache[uniformName][3] === vector4.w)
  22850. return this;
  22851. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  22852. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  22853. return this;
  22854. };
  22855. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  22856. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  22857. return this;
  22858. this._cacheFloat4(uniformName, x, y, z, w);
  22859. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  22860. return this;
  22861. };
  22862. Effect.prototype.setColor3 = function (uniformName, color3) {
  22863. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  22864. return this;
  22865. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  22866. this._engine.setColor3(this.getUniform(uniformName), color3);
  22867. return this;
  22868. };
  22869. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  22870. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b && this._valueCache[uniformName][3] === alpha)
  22871. return this;
  22872. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  22873. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  22874. return this;
  22875. };
  22876. // Statics
  22877. Effect.ShadersStore = {};
  22878. Effect.IncludesShadersStore = {};
  22879. return Effect;
  22880. })();
  22881. BABYLON.Effect = Effect;
  22882. })(BABYLON || (BABYLON = {}));
  22883. var BABYLON;
  22884. (function (BABYLON) {
  22885. var MaterialHelper = (function () {
  22886. function MaterialHelper() {
  22887. }
  22888. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  22889. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22890. var lightIndex = 0;
  22891. var needNormals = false;
  22892. var needRebuild = false;
  22893. for (var index = 0; index < scene.lights.length; index++) {
  22894. var light = scene.lights[index];
  22895. if (!light.isEnabled()) {
  22896. continue;
  22897. }
  22898. // Excluded check
  22899. if (light._excludedMeshesIds.length > 0) {
  22900. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  22901. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  22902. if (excludedMesh) {
  22903. light.excludedMeshes.push(excludedMesh);
  22904. }
  22905. }
  22906. light._excludedMeshesIds = [];
  22907. }
  22908. // Included check
  22909. if (light._includedOnlyMeshesIds.length > 0) {
  22910. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  22911. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  22912. if (includedOnlyMesh) {
  22913. light.includedOnlyMeshes.push(includedOnlyMesh);
  22914. }
  22915. }
  22916. light._includedOnlyMeshesIds = [];
  22917. }
  22918. if (!light.canAffectMesh(mesh)) {
  22919. continue;
  22920. }
  22921. needNormals = true;
  22922. if (defines["LIGHT" + lightIndex] === undefined) {
  22923. needRebuild = true;
  22924. }
  22925. defines["LIGHT" + lightIndex] = true;
  22926. var type;
  22927. if (light instanceof BABYLON.SpotLight) {
  22928. type = "SPOTLIGHT" + lightIndex;
  22929. }
  22930. else if (light instanceof BABYLON.HemisphericLight) {
  22931. type = "HEMILIGHT" + lightIndex;
  22932. }
  22933. else if (light instanceof BABYLON.PointLight) {
  22934. type = "POINTLIGHT" + lightIndex;
  22935. }
  22936. else {
  22937. type = "DIRLIGHT" + lightIndex;
  22938. }
  22939. if (defines[type] === undefined) {
  22940. needRebuild = true;
  22941. }
  22942. defines[type] = true;
  22943. // Specular
  22944. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  22945. defines["SPECULARTERM"] = true;
  22946. }
  22947. // Shadows
  22948. if (scene.shadowsEnabled) {
  22949. var shadowGenerator = light.getShadowGenerator();
  22950. if (mesh && mesh.receiveShadows && shadowGenerator) {
  22951. if (defines["SHADOW" + lightIndex] === undefined) {
  22952. needRebuild = true;
  22953. }
  22954. defines["SHADOW" + lightIndex] = true;
  22955. defines["SHADOWS"] = true;
  22956. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  22957. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  22958. needRebuild = true;
  22959. }
  22960. defines["SHADOWVSM" + lightIndex] = true;
  22961. }
  22962. if (shadowGenerator.usePoissonSampling) {
  22963. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  22964. needRebuild = true;
  22965. }
  22966. defines["SHADOWPCF" + lightIndex] = true;
  22967. }
  22968. }
  22969. }
  22970. lightIndex++;
  22971. if (lightIndex === maxSimultaneousLights)
  22972. break;
  22973. }
  22974. if (needRebuild) {
  22975. defines.rebuild();
  22976. }
  22977. return needNormals;
  22978. };
  22979. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  22980. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22981. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22982. if (!defines["LIGHT" + lightIndex]) {
  22983. break;
  22984. }
  22985. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  22986. samplersList.push("shadowSampler" + lightIndex);
  22987. }
  22988. };
  22989. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  22990. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22991. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22992. if (!defines["LIGHT" + lightIndex]) {
  22993. break;
  22994. }
  22995. if (lightIndex > 0) {
  22996. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22997. }
  22998. if (defines["SHADOW" + lightIndex]) {
  22999. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23000. }
  23001. if (defines["SHADOWPCF" + lightIndex]) {
  23002. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23003. }
  23004. if (defines["SHADOWVSM" + lightIndex]) {
  23005. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  23006. }
  23007. }
  23008. };
  23009. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23010. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23011. fallbacks.addCPUSkinningFallback(0, mesh);
  23012. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23013. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23014. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23015. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23016. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23017. }
  23018. }
  23019. };
  23020. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23021. if (defines["INSTANCES"]) {
  23022. attribs.push("world0");
  23023. attribs.push("world1");
  23024. attribs.push("world2");
  23025. attribs.push("world3");
  23026. }
  23027. };
  23028. // Bindings
  23029. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  23030. var shadowGenerator = light.getShadowGenerator();
  23031. if (mesh.receiveShadows && shadowGenerator) {
  23032. if (!light.needCube()) {
  23033. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  23034. }
  23035. else {
  23036. if (!depthValuesAlreadySet) {
  23037. depthValuesAlreadySet = true;
  23038. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  23039. }
  23040. }
  23041. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  23042. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  23043. }
  23044. return depthValuesAlreadySet;
  23045. };
  23046. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23047. if (light instanceof BABYLON.PointLight) {
  23048. // Point Light
  23049. light.transferToEffect(effect, "vLightData" + lightIndex);
  23050. }
  23051. else if (light instanceof BABYLON.DirectionalLight) {
  23052. // Directional Light
  23053. light.transferToEffect(effect, "vLightData" + lightIndex);
  23054. }
  23055. else if (light instanceof BABYLON.SpotLight) {
  23056. // Spot Light
  23057. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  23058. }
  23059. else if (light instanceof BABYLON.HemisphericLight) {
  23060. // Hemispheric Light
  23061. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  23062. }
  23063. };
  23064. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23065. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23066. var lightIndex = 0;
  23067. var depthValuesAlreadySet = false;
  23068. for (var index = 0; index < scene.lights.length; index++) {
  23069. var light = scene.lights[index];
  23070. if (!light.isEnabled()) {
  23071. continue;
  23072. }
  23073. if (!light.canAffectMesh(mesh)) {
  23074. continue;
  23075. }
  23076. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23077. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23078. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  23079. if (defines["SPECULARTERM"]) {
  23080. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23081. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  23082. }
  23083. // Shadows
  23084. if (scene.shadowsEnabled) {
  23085. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  23086. }
  23087. lightIndex++;
  23088. if (lightIndex === maxSimultaneousLights)
  23089. break;
  23090. }
  23091. };
  23092. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23093. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23094. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23095. effect.setColor3("vFogColor", scene.fogColor);
  23096. }
  23097. };
  23098. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23099. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23100. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  23101. }
  23102. };
  23103. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23104. if (defines["LOGARITHMICDEPTH"]) {
  23105. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23106. }
  23107. };
  23108. MaterialHelper.BindClipPlane = function (effect, scene) {
  23109. if (scene.clipPlane) {
  23110. var clipPlane = scene.clipPlane;
  23111. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23112. }
  23113. };
  23114. return MaterialHelper;
  23115. })();
  23116. BABYLON.MaterialHelper = MaterialHelper;
  23117. })(BABYLON || (BABYLON = {}));
  23118. var BABYLON;
  23119. (function (BABYLON) {
  23120. var FresnelParameters = (function () {
  23121. function FresnelParameters() {
  23122. this.isEnabled = true;
  23123. this.leftColor = BABYLON.Color3.White();
  23124. this.rightColor = BABYLON.Color3.Black();
  23125. this.bias = 0;
  23126. this.power = 1;
  23127. }
  23128. FresnelParameters.prototype.clone = function () {
  23129. var newFresnelParameters = new FresnelParameters();
  23130. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  23131. return new FresnelParameters;
  23132. };
  23133. FresnelParameters.prototype.serialize = function () {
  23134. var serializationObject = {};
  23135. serializationObject.isEnabled = this.isEnabled;
  23136. serializationObject.leftColor = this.leftColor;
  23137. serializationObject.rightColor = this.rightColor;
  23138. serializationObject.bias = this.bias;
  23139. serializationObject.power = this.power;
  23140. return serializationObject;
  23141. };
  23142. FresnelParameters.Parse = function (parsedFresnelParameters) {
  23143. var fresnelParameters = new FresnelParameters();
  23144. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  23145. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  23146. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  23147. fresnelParameters.bias = parsedFresnelParameters.bias;
  23148. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  23149. return fresnelParameters;
  23150. };
  23151. return FresnelParameters;
  23152. })();
  23153. BABYLON.FresnelParameters = FresnelParameters;
  23154. })(BABYLON || (BABYLON = {}));
  23155. var BABYLON;
  23156. (function (BABYLON) {
  23157. var MaterialDefines = (function () {
  23158. function MaterialDefines() {
  23159. }
  23160. MaterialDefines.prototype.rebuild = function () {
  23161. if (this._keys) {
  23162. delete this._keys;
  23163. }
  23164. this._keys = Object.keys(this);
  23165. };
  23166. MaterialDefines.prototype.isEqual = function (other) {
  23167. if (this._keys.length !== other._keys.length) {
  23168. return false;
  23169. }
  23170. for (var index = 0; index < this._keys.length; index++) {
  23171. var prop = this._keys[index];
  23172. if (this[prop] !== other[prop]) {
  23173. return false;
  23174. }
  23175. }
  23176. return true;
  23177. };
  23178. MaterialDefines.prototype.cloneTo = function (other) {
  23179. if (this._keys.length !== other._keys.length) {
  23180. other._keys = this._keys.slice(0);
  23181. }
  23182. for (var index = 0; index < this._keys.length; index++) {
  23183. var prop = this._keys[index];
  23184. other[prop] = this[prop];
  23185. }
  23186. };
  23187. MaterialDefines.prototype.reset = function () {
  23188. for (var index = 0; index < this._keys.length; index++) {
  23189. var prop = this._keys[index];
  23190. if (typeof (this[prop]) === "number") {
  23191. this[prop] = 0;
  23192. }
  23193. else {
  23194. this[prop] = false;
  23195. }
  23196. }
  23197. };
  23198. MaterialDefines.prototype.toString = function () {
  23199. var result = "";
  23200. for (var index = 0; index < this._keys.length; index++) {
  23201. var prop = this._keys[index];
  23202. if (typeof (this[prop]) === "number") {
  23203. result += "#define " + prop + " " + this[prop] + "\n";
  23204. }
  23205. else if (this[prop]) {
  23206. result += "#define " + prop + "\n";
  23207. }
  23208. }
  23209. return result;
  23210. };
  23211. return MaterialDefines;
  23212. })();
  23213. BABYLON.MaterialDefines = MaterialDefines;
  23214. var Material = (function () {
  23215. function Material(name, scene, doNotAdd) {
  23216. this.name = name;
  23217. this.checkReadyOnEveryCall = false;
  23218. this.checkReadyOnlyOnce = false;
  23219. this.state = "";
  23220. this.alpha = 1.0;
  23221. this.backFaceCulling = true;
  23222. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23223. /**
  23224. * An event triggered when the material is disposed.
  23225. * @type {BABYLON.Observable}
  23226. */
  23227. this.onDisposeObservable = new BABYLON.Observable();
  23228. /**
  23229. * An event triggered when the material is compiled.
  23230. * @type {BABYLON.Observable}
  23231. */
  23232. this.onBindObservable = new BABYLON.Observable();
  23233. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23234. this.disableDepthWrite = false;
  23235. this.fogEnabled = true;
  23236. this.pointSize = 1.0;
  23237. this.zOffset = 0;
  23238. this._wasPreviouslyReady = false;
  23239. this._fillMode = Material.TriangleFillMode;
  23240. this.id = name;
  23241. this._scene = scene;
  23242. if (!doNotAdd) {
  23243. scene.materials.push(this);
  23244. }
  23245. }
  23246. Object.defineProperty(Material, "TriangleFillMode", {
  23247. get: function () {
  23248. return Material._TriangleFillMode;
  23249. },
  23250. enumerable: true,
  23251. configurable: true
  23252. });
  23253. Object.defineProperty(Material, "WireFrameFillMode", {
  23254. get: function () {
  23255. return Material._WireFrameFillMode;
  23256. },
  23257. enumerable: true,
  23258. configurable: true
  23259. });
  23260. Object.defineProperty(Material, "PointFillMode", {
  23261. get: function () {
  23262. return Material._PointFillMode;
  23263. },
  23264. enumerable: true,
  23265. configurable: true
  23266. });
  23267. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23268. get: function () {
  23269. return Material._ClockWiseSideOrientation;
  23270. },
  23271. enumerable: true,
  23272. configurable: true
  23273. });
  23274. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23275. get: function () {
  23276. return Material._CounterClockWiseSideOrientation;
  23277. },
  23278. enumerable: true,
  23279. configurable: true
  23280. });
  23281. Object.defineProperty(Material.prototype, "onDispose", {
  23282. set: function (callback) {
  23283. if (this._onDisposeObserver) {
  23284. this.onDisposeObservable.remove(this._onDisposeObserver);
  23285. }
  23286. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23287. },
  23288. enumerable: true,
  23289. configurable: true
  23290. });
  23291. Object.defineProperty(Material.prototype, "onBind", {
  23292. set: function (callback) {
  23293. if (this._onBindObserver) {
  23294. this.onBindObservable.remove(this._onBindObserver);
  23295. }
  23296. this._onBindObserver = this.onBindObservable.add(callback);
  23297. },
  23298. enumerable: true,
  23299. configurable: true
  23300. });
  23301. Object.defineProperty(Material.prototype, "wireframe", {
  23302. get: function () {
  23303. return this._fillMode === Material.WireFrameFillMode;
  23304. },
  23305. set: function (value) {
  23306. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23307. },
  23308. enumerable: true,
  23309. configurable: true
  23310. });
  23311. Object.defineProperty(Material.prototype, "pointsCloud", {
  23312. get: function () {
  23313. return this._fillMode === Material.PointFillMode;
  23314. },
  23315. set: function (value) {
  23316. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23317. },
  23318. enumerable: true,
  23319. configurable: true
  23320. });
  23321. Object.defineProperty(Material.prototype, "fillMode", {
  23322. get: function () {
  23323. return this._fillMode;
  23324. },
  23325. set: function (value) {
  23326. this._fillMode = value;
  23327. },
  23328. enumerable: true,
  23329. configurable: true
  23330. });
  23331. /**
  23332. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23333. * subclasses should override adding information pertainent to themselves
  23334. */
  23335. Material.prototype.toString = function (fullDetails) {
  23336. var ret = "Name: " + this.name;
  23337. if (fullDetails) {
  23338. }
  23339. return ret;
  23340. };
  23341. Object.defineProperty(Material.prototype, "isFrozen", {
  23342. get: function () {
  23343. return this.checkReadyOnlyOnce;
  23344. },
  23345. enumerable: true,
  23346. configurable: true
  23347. });
  23348. Material.prototype.freeze = function () {
  23349. this.checkReadyOnlyOnce = true;
  23350. };
  23351. Material.prototype.unfreeze = function () {
  23352. this.checkReadyOnlyOnce = false;
  23353. };
  23354. Material.prototype.isReady = function (mesh, useInstances) {
  23355. return true;
  23356. };
  23357. Material.prototype.getEffect = function () {
  23358. return this._effect;
  23359. };
  23360. Material.prototype.getScene = function () {
  23361. return this._scene;
  23362. };
  23363. Material.prototype.needAlphaBlending = function () {
  23364. return (this.alpha < 1.0);
  23365. };
  23366. Material.prototype.needAlphaTesting = function () {
  23367. return false;
  23368. };
  23369. Material.prototype.getAlphaTestTexture = function () {
  23370. return null;
  23371. };
  23372. Material.prototype.markDirty = function () {
  23373. this._wasPreviouslyReady = false;
  23374. };
  23375. Material.prototype._preBind = function () {
  23376. var engine = this._scene.getEngine();
  23377. engine.enableEffect(this._effect);
  23378. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  23379. };
  23380. Material.prototype.bind = function (world, mesh) {
  23381. this._scene._cachedMaterial = this;
  23382. this.onBindObservable.notifyObservers(mesh);
  23383. if (this.disableDepthWrite) {
  23384. var engine = this._scene.getEngine();
  23385. this._cachedDepthWriteState = engine.getDepthWrite();
  23386. engine.setDepthWrite(false);
  23387. }
  23388. };
  23389. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23390. };
  23391. Material.prototype.unbind = function () {
  23392. if (this.disableDepthWrite) {
  23393. var engine = this._scene.getEngine();
  23394. engine.setDepthWrite(this._cachedDepthWriteState);
  23395. }
  23396. };
  23397. Material.prototype.clone = function (name) {
  23398. return null;
  23399. };
  23400. Material.prototype.getBindedMeshes = function () {
  23401. var result = new Array();
  23402. for (var index = 0; index < this._scene.meshes.length; index++) {
  23403. var mesh = this._scene.meshes[index];
  23404. if (mesh.material === this) {
  23405. result.push(mesh);
  23406. }
  23407. }
  23408. return result;
  23409. };
  23410. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23411. // Animations
  23412. this.getScene().stopAnimation(this);
  23413. // Remove from scene
  23414. var index = this._scene.materials.indexOf(this);
  23415. if (index >= 0) {
  23416. this._scene.materials.splice(index, 1);
  23417. }
  23418. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  23419. if (forceDisposeEffect && this._effect) {
  23420. this._scene.getEngine()._releaseEffect(this._effect);
  23421. this._effect = null;
  23422. }
  23423. // Remove from meshes
  23424. for (index = 0; index < this._scene.meshes.length; index++) {
  23425. var mesh = this._scene.meshes[index];
  23426. if (mesh.material === this) {
  23427. mesh.material = null;
  23428. }
  23429. }
  23430. // Callback
  23431. this.onDisposeObservable.notifyObservers(this);
  23432. this.onDisposeObservable.clear();
  23433. this.onBindObservable.clear();
  23434. };
  23435. Material.prototype.serialize = function () {
  23436. return BABYLON.SerializationHelper.Serialize(this);
  23437. };
  23438. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  23439. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  23440. multiMaterial.id = parsedMultiMaterial.id;
  23441. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  23442. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  23443. var subMatId = parsedMultiMaterial.materials[matIndex];
  23444. if (subMatId) {
  23445. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  23446. }
  23447. else {
  23448. multiMaterial.subMaterials.push(null);
  23449. }
  23450. }
  23451. return multiMaterial;
  23452. };
  23453. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  23454. if (!parsedMaterial.customType) {
  23455. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  23456. }
  23457. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  23458. return materialType.Parse(parsedMaterial, scene, rootUrl);
  23459. ;
  23460. };
  23461. Material._TriangleFillMode = 0;
  23462. Material._WireFrameFillMode = 1;
  23463. Material._PointFillMode = 2;
  23464. Material._ClockWiseSideOrientation = 0;
  23465. Material._CounterClockWiseSideOrientation = 1;
  23466. __decorate([
  23467. BABYLON.serialize()
  23468. ], Material.prototype, "id", void 0);
  23469. __decorate([
  23470. BABYLON.serialize()
  23471. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  23472. __decorate([
  23473. BABYLON.serialize()
  23474. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  23475. __decorate([
  23476. BABYLON.serialize()
  23477. ], Material.prototype, "state", void 0);
  23478. __decorate([
  23479. BABYLON.serialize()
  23480. ], Material.prototype, "alpha", void 0);
  23481. __decorate([
  23482. BABYLON.serialize()
  23483. ], Material.prototype, "backFaceCulling", void 0);
  23484. __decorate([
  23485. BABYLON.serialize()
  23486. ], Material.prototype, "sideOrientation", void 0);
  23487. __decorate([
  23488. BABYLON.serialize()
  23489. ], Material.prototype, "alphaMode", void 0);
  23490. __decorate([
  23491. BABYLON.serialize()
  23492. ], Material.prototype, "disableDepthWrite", void 0);
  23493. __decorate([
  23494. BABYLON.serialize()
  23495. ], Material.prototype, "fogEnabled", void 0);
  23496. __decorate([
  23497. BABYLON.serialize()
  23498. ], Material.prototype, "pointSize", void 0);
  23499. __decorate([
  23500. BABYLON.serialize()
  23501. ], Material.prototype, "zOffset", void 0);
  23502. __decorate([
  23503. BABYLON.serialize()
  23504. ], Material.prototype, "wireframe", null);
  23505. __decorate([
  23506. BABYLON.serialize()
  23507. ], Material.prototype, "pointsCloud", null);
  23508. __decorate([
  23509. BABYLON.serialize()
  23510. ], Material.prototype, "fillMode", null);
  23511. return Material;
  23512. })();
  23513. BABYLON.Material = Material;
  23514. })(BABYLON || (BABYLON = {}));
  23515. var BABYLON;
  23516. (function (BABYLON) {
  23517. var StandardMaterialDefines = (function (_super) {
  23518. __extends(StandardMaterialDefines, _super);
  23519. function StandardMaterialDefines() {
  23520. _super.call(this);
  23521. this.DIFFUSE = false;
  23522. this.AMBIENT = false;
  23523. this.OPACITY = false;
  23524. this.OPACITYRGB = false;
  23525. this.REFLECTION = false;
  23526. this.EMISSIVE = false;
  23527. this.SPECULAR = false;
  23528. this.BUMP = false;
  23529. this.PARALLAX = false;
  23530. this.PARALLAXOCCLUSION = false;
  23531. this.SPECULAROVERALPHA = false;
  23532. this.CLIPPLANE = false;
  23533. this.ALPHATEST = false;
  23534. this.ALPHAFROMDIFFUSE = false;
  23535. this.POINTSIZE = false;
  23536. this.FOG = false;
  23537. this.SPECULARTERM = false;
  23538. this.DIFFUSEFRESNEL = false;
  23539. this.OPACITYFRESNEL = false;
  23540. this.REFLECTIONFRESNEL = false;
  23541. this.REFRACTIONFRESNEL = false;
  23542. this.EMISSIVEFRESNEL = false;
  23543. this.FRESNEL = false;
  23544. this.NORMAL = false;
  23545. this.UV1 = false;
  23546. this.UV2 = false;
  23547. this.VERTEXCOLOR = false;
  23548. this.VERTEXALPHA = false;
  23549. this.NUM_BONE_INFLUENCERS = 0;
  23550. this.BonesPerMesh = 0;
  23551. this.INSTANCES = false;
  23552. this.GLOSSINESS = false;
  23553. this.ROUGHNESS = false;
  23554. this.EMISSIVEASILLUMINATION = false;
  23555. this.LINKEMISSIVEWITHDIFFUSE = false;
  23556. this.REFLECTIONFRESNELFROMSPECULAR = false;
  23557. this.LIGHTMAP = false;
  23558. this.USELIGHTMAPASSHADOWMAP = false;
  23559. this.REFLECTIONMAP_3D = false;
  23560. this.REFLECTIONMAP_SPHERICAL = false;
  23561. this.REFLECTIONMAP_PLANAR = false;
  23562. this.REFLECTIONMAP_CUBIC = false;
  23563. this.REFLECTIONMAP_PROJECTION = false;
  23564. this.REFLECTIONMAP_SKYBOX = false;
  23565. this.REFLECTIONMAP_EXPLICIT = false;
  23566. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  23567. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  23568. this.INVERTCUBICMAP = false;
  23569. this.LOGARITHMICDEPTH = false;
  23570. this.REFRACTION = false;
  23571. this.REFRACTIONMAP_3D = false;
  23572. this.REFLECTIONOVERALPHA = false;
  23573. this.INVERTNORMALMAPX = false;
  23574. this.INVERTNORMALMAPY = false;
  23575. this.rebuild();
  23576. }
  23577. return StandardMaterialDefines;
  23578. })(BABYLON.MaterialDefines);
  23579. var StandardMaterial = (function (_super) {
  23580. __extends(StandardMaterial, _super);
  23581. function StandardMaterial(name, scene) {
  23582. var _this = this;
  23583. _super.call(this, name, scene);
  23584. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23585. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  23586. this.specularColor = new BABYLON.Color3(1, 1, 1);
  23587. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  23588. this.specularPower = 64;
  23589. this.useAlphaFromDiffuseTexture = false;
  23590. this.useEmissiveAsIllumination = false;
  23591. this.linkEmissiveWithDiffuse = false;
  23592. this.useReflectionFresnelFromSpecular = false;
  23593. this.useSpecularOverAlpha = false;
  23594. this.useReflectionOverAlpha = false;
  23595. this.disableLighting = false;
  23596. this.useParallax = false;
  23597. this.useParallaxOcclusion = false;
  23598. this.parallaxScaleBias = 0.05;
  23599. this.roughness = 0;
  23600. this.indexOfRefraction = 0.98;
  23601. this.invertRefractionY = true;
  23602. this.useLightmapAsShadowmap = false;
  23603. this.useGlossinessFromSpecularMapAlpha = false;
  23604. this.maxSimultaneousLights = 4;
  23605. /**
  23606. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  23607. */
  23608. this.invertNormalMapX = false;
  23609. /**
  23610. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  23611. */
  23612. this.invertNormalMapY = false;
  23613. this._renderTargets = new BABYLON.SmartArray(16);
  23614. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  23615. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  23616. this._defines = new StandardMaterialDefines();
  23617. this._cachedDefines = new StandardMaterialDefines();
  23618. this._cachedDefines.BonesPerMesh = -1;
  23619. this.getRenderTargetTextures = function () {
  23620. _this._renderTargets.reset();
  23621. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  23622. _this._renderTargets.push(_this.reflectionTexture);
  23623. }
  23624. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  23625. _this._renderTargets.push(_this.refractionTexture);
  23626. }
  23627. return _this._renderTargets;
  23628. };
  23629. }
  23630. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  23631. get: function () {
  23632. return this._useLogarithmicDepth;
  23633. },
  23634. set: function (value) {
  23635. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  23636. },
  23637. enumerable: true,
  23638. configurable: true
  23639. });
  23640. StandardMaterial.prototype.needAlphaBlending = function () {
  23641. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  23642. };
  23643. StandardMaterial.prototype.needAlphaTesting = function () {
  23644. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  23645. };
  23646. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  23647. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  23648. };
  23649. StandardMaterial.prototype.getAlphaTestTexture = function () {
  23650. return this.diffuseTexture;
  23651. };
  23652. // Methods
  23653. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  23654. if (!mesh) {
  23655. return true;
  23656. }
  23657. if (this._defines.INSTANCES !== useInstances) {
  23658. return false;
  23659. }
  23660. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  23661. return true;
  23662. }
  23663. return false;
  23664. };
  23665. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  23666. if (this.isFrozen) {
  23667. if (this._wasPreviouslyReady) {
  23668. return true;
  23669. }
  23670. }
  23671. var scene = this.getScene();
  23672. if (!this.checkReadyOnEveryCall) {
  23673. if (this._renderId === scene.getRenderId()) {
  23674. if (this._checkCache(scene, mesh, useInstances)) {
  23675. return true;
  23676. }
  23677. }
  23678. }
  23679. var engine = scene.getEngine();
  23680. var needNormals = false;
  23681. var needUVs = false;
  23682. this._defines.reset();
  23683. // Textures
  23684. if (scene.texturesEnabled) {
  23685. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  23686. if (!this.diffuseTexture.isReady()) {
  23687. return false;
  23688. }
  23689. else {
  23690. needUVs = true;
  23691. this._defines.DIFFUSE = true;
  23692. }
  23693. }
  23694. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  23695. if (!this.ambientTexture.isReady()) {
  23696. return false;
  23697. }
  23698. else {
  23699. needUVs = true;
  23700. this._defines.AMBIENT = true;
  23701. }
  23702. }
  23703. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  23704. if (!this.opacityTexture.isReady()) {
  23705. return false;
  23706. }
  23707. else {
  23708. needUVs = true;
  23709. this._defines.OPACITY = true;
  23710. if (this.opacityTexture.getAlphaFromRGB) {
  23711. this._defines.OPACITYRGB = true;
  23712. }
  23713. }
  23714. }
  23715. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  23716. if (!this.reflectionTexture.isReady()) {
  23717. return false;
  23718. }
  23719. else {
  23720. needNormals = true;
  23721. this._defines.REFLECTION = true;
  23722. if (this.roughness > 0) {
  23723. this._defines.ROUGHNESS = true;
  23724. }
  23725. if (this.useReflectionOverAlpha) {
  23726. this._defines.REFLECTIONOVERALPHA = true;
  23727. }
  23728. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  23729. this._defines.INVERTCUBICMAP = true;
  23730. }
  23731. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  23732. switch (this.reflectionTexture.coordinatesMode) {
  23733. case BABYLON.Texture.CUBIC_MODE:
  23734. case BABYLON.Texture.INVCUBIC_MODE:
  23735. this._defines.REFLECTIONMAP_CUBIC = true;
  23736. break;
  23737. case BABYLON.Texture.EXPLICIT_MODE:
  23738. this._defines.REFLECTIONMAP_EXPLICIT = true;
  23739. break;
  23740. case BABYLON.Texture.PLANAR_MODE:
  23741. this._defines.REFLECTIONMAP_PLANAR = true;
  23742. break;
  23743. case BABYLON.Texture.PROJECTION_MODE:
  23744. this._defines.REFLECTIONMAP_PROJECTION = true;
  23745. break;
  23746. case BABYLON.Texture.SKYBOX_MODE:
  23747. this._defines.REFLECTIONMAP_SKYBOX = true;
  23748. break;
  23749. case BABYLON.Texture.SPHERICAL_MODE:
  23750. this._defines.REFLECTIONMAP_SPHERICAL = true;
  23751. break;
  23752. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  23753. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  23754. break;
  23755. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  23756. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  23757. break;
  23758. }
  23759. }
  23760. }
  23761. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23762. if (!this.emissiveTexture.isReady()) {
  23763. return false;
  23764. }
  23765. else {
  23766. needUVs = true;
  23767. this._defines.EMISSIVE = true;
  23768. }
  23769. }
  23770. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23771. if (!this.lightmapTexture.isReady()) {
  23772. return false;
  23773. }
  23774. else {
  23775. needUVs = true;
  23776. this._defines.LIGHTMAP = true;
  23777. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  23778. }
  23779. }
  23780. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23781. if (!this.specularTexture.isReady()) {
  23782. return false;
  23783. }
  23784. else {
  23785. needUVs = true;
  23786. this._defines.SPECULAR = true;
  23787. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  23788. }
  23789. }
  23790. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  23791. if (!this.bumpTexture.isReady()) {
  23792. return false;
  23793. }
  23794. else {
  23795. needUVs = true;
  23796. this._defines.BUMP = true;
  23797. if (this.useParallax) {
  23798. this._defines.PARALLAX = true;
  23799. if (this.useParallaxOcclusion) {
  23800. this._defines.PARALLAXOCCLUSION = true;
  23801. }
  23802. }
  23803. if (this.invertNormalMapX) {
  23804. this._defines.INVERTNORMALMAPX = true;
  23805. }
  23806. if (this.invertNormalMapY) {
  23807. this._defines.INVERTNORMALMAPY = true;
  23808. }
  23809. }
  23810. }
  23811. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23812. if (!this.refractionTexture.isReady()) {
  23813. return false;
  23814. }
  23815. else {
  23816. needUVs = true;
  23817. this._defines.REFRACTION = true;
  23818. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  23819. }
  23820. }
  23821. }
  23822. // Effect
  23823. if (scene.clipPlane) {
  23824. this._defines.CLIPPLANE = true;
  23825. }
  23826. if (engine.getAlphaTesting()) {
  23827. this._defines.ALPHATEST = true;
  23828. }
  23829. if (this._shouldUseAlphaFromDiffuseTexture()) {
  23830. this._defines.ALPHAFROMDIFFUSE = true;
  23831. }
  23832. if (this.useEmissiveAsIllumination) {
  23833. this._defines.EMISSIVEASILLUMINATION = true;
  23834. }
  23835. if (this.linkEmissiveWithDiffuse) {
  23836. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  23837. }
  23838. if (this.useLogarithmicDepth) {
  23839. this._defines.LOGARITHMICDEPTH = true;
  23840. }
  23841. // Point size
  23842. if (this.pointsCloud || scene.forcePointsCloud) {
  23843. this._defines.POINTSIZE = true;
  23844. }
  23845. // Fog
  23846. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  23847. this._defines.FOG = true;
  23848. }
  23849. if (scene.lightsEnabled && !this.disableLighting) {
  23850. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  23851. }
  23852. if (StandardMaterial.FresnelEnabled) {
  23853. // Fresnel
  23854. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  23855. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  23856. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  23857. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  23858. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23859. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23860. this._defines.DIFFUSEFRESNEL = true;
  23861. }
  23862. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23863. this._defines.OPACITYFRESNEL = true;
  23864. }
  23865. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23866. this._defines.REFLECTIONFRESNEL = true;
  23867. if (this.useReflectionFresnelFromSpecular) {
  23868. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  23869. }
  23870. }
  23871. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23872. this._defines.REFRACTIONFRESNEL = true;
  23873. }
  23874. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23875. this._defines.EMISSIVEFRESNEL = true;
  23876. }
  23877. needNormals = true;
  23878. this._defines.FRESNEL = true;
  23879. }
  23880. }
  23881. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  23882. this._defines.SPECULAROVERALPHA = true;
  23883. }
  23884. // Attribs
  23885. if (mesh) {
  23886. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23887. this._defines.NORMAL = true;
  23888. }
  23889. if (needUVs) {
  23890. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23891. this._defines.UV1 = true;
  23892. }
  23893. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23894. this._defines.UV2 = true;
  23895. }
  23896. }
  23897. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23898. this._defines.VERTEXCOLOR = true;
  23899. if (mesh.hasVertexAlpha) {
  23900. this._defines.VERTEXALPHA = true;
  23901. }
  23902. }
  23903. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23904. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  23905. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  23906. }
  23907. // Instances
  23908. if (useInstances) {
  23909. this._defines.INSTANCES = true;
  23910. }
  23911. }
  23912. // Get correct effect
  23913. if (!this._defines.isEqual(this._cachedDefines)) {
  23914. this._defines.cloneTo(this._cachedDefines);
  23915. scene.resetCachedMaterial();
  23916. // Fallbacks
  23917. var fallbacks = new BABYLON.EffectFallbacks();
  23918. if (this._defines.REFLECTION) {
  23919. fallbacks.addFallback(0, "REFLECTION");
  23920. }
  23921. if (this._defines.SPECULAR) {
  23922. fallbacks.addFallback(0, "SPECULAR");
  23923. }
  23924. if (this._defines.BUMP) {
  23925. fallbacks.addFallback(0, "BUMP");
  23926. }
  23927. if (this._defines.PARALLAX) {
  23928. fallbacks.addFallback(1, "PARALLAX");
  23929. }
  23930. if (this._defines.PARALLAXOCCLUSION) {
  23931. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  23932. }
  23933. if (this._defines.SPECULAROVERALPHA) {
  23934. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  23935. }
  23936. if (this._defines.FOG) {
  23937. fallbacks.addFallback(1, "FOG");
  23938. }
  23939. if (this._defines.POINTSIZE) {
  23940. fallbacks.addFallback(0, "POINTSIZE");
  23941. }
  23942. if (this._defines.LOGARITHMICDEPTH) {
  23943. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  23944. }
  23945. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  23946. if (this._defines.SPECULARTERM) {
  23947. fallbacks.addFallback(0, "SPECULARTERM");
  23948. }
  23949. if (this._defines.DIFFUSEFRESNEL) {
  23950. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  23951. }
  23952. if (this._defines.OPACITYFRESNEL) {
  23953. fallbacks.addFallback(2, "OPACITYFRESNEL");
  23954. }
  23955. if (this._defines.REFLECTIONFRESNEL) {
  23956. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  23957. }
  23958. if (this._defines.EMISSIVEFRESNEL) {
  23959. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  23960. }
  23961. if (this._defines.FRESNEL) {
  23962. fallbacks.addFallback(4, "FRESNEL");
  23963. }
  23964. //Attributes
  23965. var attribs = [BABYLON.VertexBuffer.PositionKind];
  23966. if (this._defines.NORMAL) {
  23967. attribs.push(BABYLON.VertexBuffer.NormalKind);
  23968. }
  23969. if (this._defines.UV1) {
  23970. attribs.push(BABYLON.VertexBuffer.UVKind);
  23971. }
  23972. if (this._defines.UV2) {
  23973. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23974. }
  23975. if (this._defines.VERTEXCOLOR) {
  23976. attribs.push(BABYLON.VertexBuffer.ColorKind);
  23977. }
  23978. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  23979. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  23980. // Legacy browser patch
  23981. var shaderName = "default";
  23982. if (!scene.getEngine().getCaps().standardDerivatives) {
  23983. shaderName = "legacydefault";
  23984. }
  23985. var join = this._defines.toString();
  23986. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  23987. "vFogInfos", "vFogColor", "pointSize",
  23988. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  23989. "mBones",
  23990. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  23991. "depthValues",
  23992. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  23993. "logarithmicDepthConstant"
  23994. ];
  23995. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  23996. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  23997. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  23998. }
  23999. if (!this._effect.isReady()) {
  24000. return false;
  24001. }
  24002. this._renderId = scene.getRenderId();
  24003. this._wasPreviouslyReady = true;
  24004. if (mesh) {
  24005. if (!mesh._materialDefines) {
  24006. mesh._materialDefines = new StandardMaterialDefines();
  24007. }
  24008. this._defines.cloneTo(mesh._materialDefines);
  24009. }
  24010. return true;
  24011. };
  24012. StandardMaterial.prototype.unbind = function () {
  24013. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  24014. this._effect.setTexture("reflection2DSampler", null);
  24015. }
  24016. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  24017. this._effect.setTexture("refraction2DSampler", null);
  24018. }
  24019. _super.prototype.unbind.call(this);
  24020. };
  24021. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24022. this._effect.setMatrix("world", world);
  24023. };
  24024. StandardMaterial.prototype.bind = function (world, mesh) {
  24025. var scene = this.getScene();
  24026. // Matrices
  24027. this.bindOnlyWorldMatrix(world);
  24028. // Bones
  24029. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  24030. if (scene.getCachedMaterial() !== this) {
  24031. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24032. if (StandardMaterial.FresnelEnabled) {
  24033. // Fresnel
  24034. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  24035. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  24036. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  24037. }
  24038. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  24039. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  24040. }
  24041. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24042. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  24043. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  24044. }
  24045. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  24046. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  24047. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  24048. }
  24049. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  24050. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  24051. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  24052. }
  24053. }
  24054. // Textures
  24055. if (scene.texturesEnabled) {
  24056. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  24057. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  24058. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  24059. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  24060. }
  24061. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  24062. this._effect.setTexture("ambientSampler", this.ambientTexture);
  24063. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  24064. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  24065. }
  24066. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  24067. this._effect.setTexture("opacitySampler", this.opacityTexture);
  24068. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  24069. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  24070. }
  24071. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  24072. if (this.reflectionTexture.isCube) {
  24073. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  24074. }
  24075. else {
  24076. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  24077. }
  24078. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  24079. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  24080. }
  24081. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  24082. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  24083. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  24084. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  24085. }
  24086. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  24087. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  24088. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  24089. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  24090. }
  24091. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  24092. this._effect.setTexture("specularSampler", this.specularTexture);
  24093. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  24094. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  24095. }
  24096. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  24097. this._effect.setTexture("bumpSampler", this.bumpTexture);
  24098. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  24099. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  24100. }
  24101. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  24102. var depth = 1.0;
  24103. if (this.refractionTexture.isCube) {
  24104. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  24105. }
  24106. else {
  24107. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  24108. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  24109. if (this.refractionTexture.depth) {
  24110. depth = this.refractionTexture.depth;
  24111. }
  24112. }
  24113. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  24114. }
  24115. }
  24116. // Clip plane
  24117. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  24118. // Point size
  24119. if (this.pointsCloud) {
  24120. this._effect.setFloat("pointSize", this.pointSize);
  24121. }
  24122. // Colors
  24123. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  24124. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  24125. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  24126. if (this._defines.SPECULARTERM) {
  24127. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  24128. }
  24129. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  24130. }
  24131. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  24132. // Diffuse
  24133. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  24134. // Lights
  24135. if (scene.lightsEnabled && !this.disableLighting) {
  24136. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  24137. }
  24138. // View
  24139. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  24140. this._effect.setMatrix("view", scene.getViewMatrix());
  24141. }
  24142. // Fog
  24143. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  24144. // Log. depth
  24145. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  24146. }
  24147. _super.prototype.bind.call(this, world, mesh);
  24148. };
  24149. StandardMaterial.prototype.getAnimatables = function () {
  24150. var results = [];
  24151. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  24152. results.push(this.diffuseTexture);
  24153. }
  24154. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  24155. results.push(this.ambientTexture);
  24156. }
  24157. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  24158. results.push(this.opacityTexture);
  24159. }
  24160. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  24161. results.push(this.reflectionTexture);
  24162. }
  24163. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  24164. results.push(this.emissiveTexture);
  24165. }
  24166. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  24167. results.push(this.specularTexture);
  24168. }
  24169. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  24170. results.push(this.bumpTexture);
  24171. }
  24172. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  24173. results.push(this.lightmapTexture);
  24174. }
  24175. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  24176. results.push(this.refractionTexture);
  24177. }
  24178. return results;
  24179. };
  24180. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24181. if (forceDisposeTextures) {
  24182. if (this.diffuseTexture) {
  24183. this.diffuseTexture.dispose();
  24184. }
  24185. if (this.ambientTexture) {
  24186. this.ambientTexture.dispose();
  24187. }
  24188. if (this.opacityTexture) {
  24189. this.opacityTexture.dispose();
  24190. }
  24191. if (this.reflectionTexture) {
  24192. this.reflectionTexture.dispose();
  24193. }
  24194. if (this.emissiveTexture) {
  24195. this.emissiveTexture.dispose();
  24196. }
  24197. if (this.specularTexture) {
  24198. this.specularTexture.dispose();
  24199. }
  24200. if (this.bumpTexture) {
  24201. this.bumpTexture.dispose();
  24202. }
  24203. if (this.lightmapTexture) {
  24204. this.lightmapTexture.dispose();
  24205. }
  24206. if (this.refractionTexture) {
  24207. this.refractionTexture.dispose();
  24208. }
  24209. }
  24210. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  24211. };
  24212. StandardMaterial.prototype.clone = function (name) {
  24213. var _this = this;
  24214. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  24215. };
  24216. StandardMaterial.prototype.serialize = function () {
  24217. return BABYLON.SerializationHelper.Serialize(this);
  24218. };
  24219. // Statics
  24220. StandardMaterial.Parse = function (source, scene, rootUrl) {
  24221. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  24222. };
  24223. // Flags used to enable or disable a type of texture for all Standard Materials
  24224. StandardMaterial.DiffuseTextureEnabled = true;
  24225. StandardMaterial.AmbientTextureEnabled = true;
  24226. StandardMaterial.OpacityTextureEnabled = true;
  24227. StandardMaterial.ReflectionTextureEnabled = true;
  24228. StandardMaterial.EmissiveTextureEnabled = true;
  24229. StandardMaterial.SpecularTextureEnabled = true;
  24230. StandardMaterial.BumpTextureEnabled = true;
  24231. StandardMaterial.FresnelEnabled = true;
  24232. StandardMaterial.LightmapTextureEnabled = true;
  24233. StandardMaterial.RefractionTextureEnabled = true;
  24234. __decorate([
  24235. BABYLON.serializeAsTexture()
  24236. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  24237. __decorate([
  24238. BABYLON.serializeAsTexture()
  24239. ], StandardMaterial.prototype, "ambientTexture", void 0);
  24240. __decorate([
  24241. BABYLON.serializeAsTexture()
  24242. ], StandardMaterial.prototype, "opacityTexture", void 0);
  24243. __decorate([
  24244. BABYLON.serializeAsTexture()
  24245. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  24246. __decorate([
  24247. BABYLON.serializeAsTexture()
  24248. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  24249. __decorate([
  24250. BABYLON.serializeAsTexture()
  24251. ], StandardMaterial.prototype, "specularTexture", void 0);
  24252. __decorate([
  24253. BABYLON.serializeAsTexture()
  24254. ], StandardMaterial.prototype, "bumpTexture", void 0);
  24255. __decorate([
  24256. BABYLON.serializeAsTexture()
  24257. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  24258. __decorate([
  24259. BABYLON.serializeAsTexture()
  24260. ], StandardMaterial.prototype, "refractionTexture", void 0);
  24261. __decorate([
  24262. BABYLON.serializeAsColor3("ambient")
  24263. ], StandardMaterial.prototype, "ambientColor", void 0);
  24264. __decorate([
  24265. BABYLON.serializeAsColor3("diffuse")
  24266. ], StandardMaterial.prototype, "diffuseColor", void 0);
  24267. __decorate([
  24268. BABYLON.serializeAsColor3("specular")
  24269. ], StandardMaterial.prototype, "specularColor", void 0);
  24270. __decorate([
  24271. BABYLON.serializeAsColor3("emissive")
  24272. ], StandardMaterial.prototype, "emissiveColor", void 0);
  24273. __decorate([
  24274. BABYLON.serialize()
  24275. ], StandardMaterial.prototype, "specularPower", void 0);
  24276. __decorate([
  24277. BABYLON.serialize()
  24278. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  24279. __decorate([
  24280. BABYLON.serialize()
  24281. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  24282. __decorate([
  24283. BABYLON.serialize()
  24284. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  24285. __decorate([
  24286. BABYLON.serialize()
  24287. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  24288. __decorate([
  24289. BABYLON.serialize()
  24290. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  24291. __decorate([
  24292. BABYLON.serialize()
  24293. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  24294. __decorate([
  24295. BABYLON.serialize()
  24296. ], StandardMaterial.prototype, "disableLighting", void 0);
  24297. __decorate([
  24298. BABYLON.serialize()
  24299. ], StandardMaterial.prototype, "useParallax", void 0);
  24300. __decorate([
  24301. BABYLON.serialize()
  24302. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  24303. __decorate([
  24304. BABYLON.serialize()
  24305. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  24306. __decorate([
  24307. BABYLON.serialize()
  24308. ], StandardMaterial.prototype, "roughness", void 0);
  24309. __decorate([
  24310. BABYLON.serialize()
  24311. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  24312. __decorate([
  24313. BABYLON.serialize()
  24314. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  24315. __decorate([
  24316. BABYLON.serialize()
  24317. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  24318. __decorate([
  24319. BABYLON.serializeAsFresnelParameters()
  24320. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  24321. __decorate([
  24322. BABYLON.serializeAsFresnelParameters()
  24323. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  24324. __decorate([
  24325. BABYLON.serializeAsFresnelParameters()
  24326. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  24327. __decorate([
  24328. BABYLON.serializeAsFresnelParameters()
  24329. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  24330. __decorate([
  24331. BABYLON.serializeAsFresnelParameters()
  24332. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  24333. __decorate([
  24334. BABYLON.serialize()
  24335. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  24336. __decorate([
  24337. BABYLON.serialize()
  24338. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  24339. __decorate([
  24340. BABYLON.serialize()
  24341. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  24342. __decorate([
  24343. BABYLON.serialize()
  24344. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  24345. __decorate([
  24346. BABYLON.serialize()
  24347. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  24348. return StandardMaterial;
  24349. })(BABYLON.Material);
  24350. BABYLON.StandardMaterial = StandardMaterial;
  24351. })(BABYLON || (BABYLON = {}));
  24352. var BABYLON;
  24353. (function (BABYLON) {
  24354. var MultiMaterial = (function (_super) {
  24355. __extends(MultiMaterial, _super);
  24356. function MultiMaterial(name, scene) {
  24357. _super.call(this, name, scene, true);
  24358. this.subMaterials = new Array();
  24359. scene.multiMaterials.push(this);
  24360. }
  24361. // Properties
  24362. MultiMaterial.prototype.getSubMaterial = function (index) {
  24363. if (index < 0 || index >= this.subMaterials.length) {
  24364. return this.getScene().defaultMaterial;
  24365. }
  24366. return this.subMaterials[index];
  24367. };
  24368. // Methods
  24369. MultiMaterial.prototype.isReady = function (mesh) {
  24370. for (var index = 0; index < this.subMaterials.length; index++) {
  24371. var subMaterial = this.subMaterials[index];
  24372. if (subMaterial) {
  24373. if (!this.subMaterials[index].isReady(mesh)) {
  24374. return false;
  24375. }
  24376. }
  24377. }
  24378. return true;
  24379. };
  24380. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  24381. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  24382. for (var index = 0; index < this.subMaterials.length; index++) {
  24383. var subMaterial = null;
  24384. if (cloneChildren) {
  24385. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  24386. }
  24387. else {
  24388. subMaterial = this.subMaterials[index];
  24389. }
  24390. newMultiMaterial.subMaterials.push(subMaterial);
  24391. }
  24392. return newMultiMaterial;
  24393. };
  24394. MultiMaterial.prototype.serialize = function () {
  24395. var serializationObject = {};
  24396. serializationObject.name = this.name;
  24397. serializationObject.id = this.id;
  24398. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24399. serializationObject.materials = [];
  24400. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  24401. var subMat = this.subMaterials[matIndex];
  24402. if (subMat) {
  24403. serializationObject.materials.push(subMat.id);
  24404. }
  24405. else {
  24406. serializationObject.materials.push(null);
  24407. }
  24408. }
  24409. return serializationObject;
  24410. };
  24411. return MultiMaterial;
  24412. })(BABYLON.Material);
  24413. BABYLON.MultiMaterial = MultiMaterial;
  24414. })(BABYLON || (BABYLON = {}));
  24415. var BABYLON;
  24416. (function (BABYLON) {
  24417. var SceneLoader = (function () {
  24418. function SceneLoader() {
  24419. }
  24420. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  24421. get: function () {
  24422. return 0;
  24423. },
  24424. enumerable: true,
  24425. configurable: true
  24426. });
  24427. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  24428. get: function () {
  24429. return 1;
  24430. },
  24431. enumerable: true,
  24432. configurable: true
  24433. });
  24434. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  24435. get: function () {
  24436. return 2;
  24437. },
  24438. enumerable: true,
  24439. configurable: true
  24440. });
  24441. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  24442. get: function () {
  24443. return 3;
  24444. },
  24445. enumerable: true,
  24446. configurable: true
  24447. });
  24448. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  24449. get: function () {
  24450. return SceneLoader._ForceFullSceneLoadingForIncremental;
  24451. },
  24452. set: function (value) {
  24453. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  24454. },
  24455. enumerable: true,
  24456. configurable: true
  24457. });
  24458. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  24459. get: function () {
  24460. return SceneLoader._ShowLoadingScreen;
  24461. },
  24462. set: function (value) {
  24463. SceneLoader._ShowLoadingScreen = value;
  24464. },
  24465. enumerable: true,
  24466. configurable: true
  24467. });
  24468. Object.defineProperty(SceneLoader, "loggingLevel", {
  24469. get: function () {
  24470. return SceneLoader._loggingLevel;
  24471. },
  24472. set: function (value) {
  24473. SceneLoader._loggingLevel = value;
  24474. },
  24475. enumerable: true,
  24476. configurable: true
  24477. });
  24478. SceneLoader._getPluginForFilename = function (sceneFilename) {
  24479. var dotPosition = sceneFilename.lastIndexOf(".");
  24480. var queryStringPosition = sceneFilename.indexOf("?");
  24481. if (queryStringPosition === -1) {
  24482. queryStringPosition = sceneFilename.length;
  24483. }
  24484. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  24485. for (var index = 0; index < this._registeredPlugins.length; index++) {
  24486. var plugin = this._registeredPlugins[index];
  24487. if (plugin.extensions.indexOf(extension) !== -1) {
  24488. return plugin;
  24489. }
  24490. }
  24491. return this._registeredPlugins[0];
  24492. };
  24493. // Public functions
  24494. SceneLoader.GetPluginForExtension = function (extension) {
  24495. for (var index = 0; index < this._registeredPlugins.length; index++) {
  24496. var plugin = this._registeredPlugins[index];
  24497. if (plugin.extensions.indexOf(extension) !== -1) {
  24498. return plugin;
  24499. }
  24500. }
  24501. return null;
  24502. };
  24503. SceneLoader.RegisterPlugin = function (plugin) {
  24504. plugin.extensions = plugin.extensions.toLowerCase();
  24505. SceneLoader._registeredPlugins.push(plugin);
  24506. };
  24507. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  24508. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24509. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24510. return;
  24511. }
  24512. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24513. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24514. return;
  24515. }
  24516. var loadingToken = {};
  24517. scene._addPendingData(loadingToken);
  24518. var manifestChecked = function (success) {
  24519. scene.database = database;
  24520. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  24521. var importMeshFromData = function (data) {
  24522. var meshes = [];
  24523. var particleSystems = [];
  24524. var skeletons = [];
  24525. try {
  24526. if (plugin.importMesh) {
  24527. var syncedPlugin = plugin;
  24528. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  24529. if (onerror) {
  24530. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  24531. }
  24532. scene._removePendingData(loadingToken);
  24533. return;
  24534. }
  24535. if (onsuccess) {
  24536. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  24537. onsuccess(meshes, particleSystems, skeletons);
  24538. scene._removePendingData(loadingToken);
  24539. }
  24540. }
  24541. else {
  24542. var asyncedPlugin = plugin;
  24543. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  24544. if (onsuccess) {
  24545. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  24546. onsuccess(meshes, particleSystems, skeletons);
  24547. scene._removePendingData(loadingToken);
  24548. }
  24549. }, function () {
  24550. if (onerror) {
  24551. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  24552. }
  24553. scene._removePendingData(loadingToken);
  24554. });
  24555. }
  24556. }
  24557. catch (e) {
  24558. if (onerror) {
  24559. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  24560. }
  24561. scene._removePendingData(loadingToken);
  24562. }
  24563. };
  24564. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  24565. // Direct load
  24566. importMeshFromData(sceneFilename.substr(5));
  24567. return;
  24568. }
  24569. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  24570. importMeshFromData(data);
  24571. }, progressCallBack, database);
  24572. };
  24573. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  24574. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  24575. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  24576. }
  24577. else {
  24578. // If the scene is a data stream or offline support is not enabled, it's a direct load
  24579. manifestChecked(true);
  24580. }
  24581. };
  24582. /**
  24583. * Load a scene
  24584. * @param rootUrl a string that defines the root url for scene and resources
  24585. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  24586. * @param engine is the instance of BABYLON.Engine to use to create the scene
  24587. */
  24588. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  24589. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  24590. };
  24591. /**
  24592. * Append a scene
  24593. * @param rootUrl a string that defines the root url for scene and resources
  24594. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  24595. * @param scene is the instance of BABYLON.Scene to append to
  24596. */
  24597. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  24598. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24599. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24600. return;
  24601. }
  24602. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  24603. var database;
  24604. var loadingToken = {};
  24605. scene._addPendingData(loadingToken);
  24606. if (SceneLoader.ShowLoadingScreen) {
  24607. scene.getEngine().displayLoadingUI();
  24608. }
  24609. var loadSceneFromData = function (data) {
  24610. scene.database = database;
  24611. if (plugin.load) {
  24612. var syncedPlugin = plugin;
  24613. if (!syncedPlugin.load(scene, data, rootUrl)) {
  24614. if (onerror) {
  24615. onerror(scene);
  24616. }
  24617. scene._removePendingData(loadingToken);
  24618. scene.getEngine().hideLoadingUI();
  24619. return;
  24620. }
  24621. if (onsuccess) {
  24622. onsuccess(scene);
  24623. }
  24624. scene._removePendingData(loadingToken);
  24625. }
  24626. else {
  24627. var asyncedPlugin = plugin;
  24628. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  24629. if (onsuccess) {
  24630. onsuccess(scene);
  24631. }
  24632. }, function () {
  24633. if (onerror) {
  24634. onerror(scene);
  24635. }
  24636. scene._removePendingData(loadingToken);
  24637. scene.getEngine().hideLoadingUI();
  24638. });
  24639. }
  24640. if (SceneLoader.ShowLoadingScreen) {
  24641. scene.executeWhenReady(function () {
  24642. scene.getEngine().hideLoadingUI();
  24643. });
  24644. }
  24645. };
  24646. var manifestChecked = function (success) {
  24647. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  24648. };
  24649. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  24650. // Direct load
  24651. loadSceneFromData(sceneFilename.substr(5));
  24652. return;
  24653. }
  24654. if (rootUrl.indexOf("file:") === -1) {
  24655. if (scene.getEngine().enableOfflineSupport) {
  24656. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  24657. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  24658. }
  24659. else {
  24660. manifestChecked(true);
  24661. }
  24662. }
  24663. else {
  24664. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  24665. }
  24666. };
  24667. // Flags
  24668. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  24669. SceneLoader._ShowLoadingScreen = true;
  24670. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  24671. // Members
  24672. SceneLoader._registeredPlugins = new Array();
  24673. return SceneLoader;
  24674. })();
  24675. BABYLON.SceneLoader = SceneLoader;
  24676. ;
  24677. })(BABYLON || (BABYLON = {}));
  24678. var BABYLON;
  24679. (function (BABYLON) {
  24680. var Internals;
  24681. (function (Internals) {
  24682. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  24683. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  24684. var parsedMaterial = parsedData.materials[index];
  24685. if (parsedMaterial.id === id) {
  24686. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  24687. }
  24688. }
  24689. return null;
  24690. };
  24691. var isDescendantOf = function (mesh, names, hierarchyIds) {
  24692. names = (names instanceof Array) ? names : [names];
  24693. for (var i in names) {
  24694. if (mesh.name === names[i]) {
  24695. hierarchyIds.push(mesh.id);
  24696. return true;
  24697. }
  24698. }
  24699. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  24700. hierarchyIds.push(mesh.id);
  24701. return true;
  24702. }
  24703. return false;
  24704. };
  24705. var logOperation = function (operation, producer) {
  24706. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  24707. };
  24708. BABYLON.SceneLoader.RegisterPlugin({
  24709. extensions: ".babylon",
  24710. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  24711. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  24712. // when SceneLoader.debugLogging = true (default), or exception encountered.
  24713. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  24714. // and avoid problems with multiple concurrent .babylon loads.
  24715. var log = "importMesh has failed JSON parse";
  24716. try {
  24717. var parsedData = JSON.parse(data);
  24718. log = "";
  24719. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  24720. var loadedSkeletonsIds = [];
  24721. var loadedMaterialsIds = [];
  24722. var hierarchyIds = [];
  24723. var index;
  24724. var cache;
  24725. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  24726. var parsedMesh = parsedData.meshes[index];
  24727. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  24728. if (meshesNames instanceof Array) {
  24729. // Remove found mesh name from list.
  24730. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  24731. }
  24732. //Geometry?
  24733. if (parsedMesh.geometryId) {
  24734. //does the file contain geometries?
  24735. if (parsedData.geometries) {
  24736. //find the correct geometry and add it to the scene
  24737. var found = false;
  24738. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  24739. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  24740. return;
  24741. }
  24742. else {
  24743. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  24744. if (parsedGeometryData.id === parsedMesh.geometryId) {
  24745. switch (geometryType) {
  24746. case "boxes":
  24747. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  24748. break;
  24749. case "spheres":
  24750. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  24751. break;
  24752. case "cylinders":
  24753. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  24754. break;
  24755. case "toruses":
  24756. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  24757. break;
  24758. case "grounds":
  24759. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  24760. break;
  24761. case "planes":
  24762. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  24763. break;
  24764. case "torusKnots":
  24765. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  24766. break;
  24767. case "vertexData":
  24768. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  24769. break;
  24770. }
  24771. found = true;
  24772. }
  24773. });
  24774. }
  24775. });
  24776. if (!found) {
  24777. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  24778. }
  24779. }
  24780. }
  24781. // Material ?
  24782. if (parsedMesh.materialId) {
  24783. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  24784. if (!materialFound && parsedData.multiMaterials) {
  24785. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  24786. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  24787. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  24788. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  24789. var subMatId = parsedMultiMaterial.materials[matIndex];
  24790. loadedMaterialsIds.push(subMatId);
  24791. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  24792. log += "\n\tMaterial " + mat.toString(fullDetails);
  24793. }
  24794. loadedMaterialsIds.push(parsedMultiMaterial.id);
  24795. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  24796. materialFound = true;
  24797. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  24798. break;
  24799. }
  24800. }
  24801. }
  24802. if (!materialFound) {
  24803. loadedMaterialsIds.push(parsedMesh.materialId);
  24804. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  24805. if (!mat) {
  24806. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  24807. }
  24808. else {
  24809. log += "\n\tMaterial " + mat.toString(fullDetails);
  24810. }
  24811. }
  24812. }
  24813. // Skeleton ?
  24814. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  24815. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  24816. if (!skeletonAlreadyLoaded) {
  24817. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  24818. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  24819. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  24820. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  24821. skeletons.push(skeleton);
  24822. loadedSkeletonsIds.push(parsedSkeleton.id);
  24823. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  24824. }
  24825. }
  24826. }
  24827. }
  24828. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  24829. meshes.push(mesh);
  24830. log += "\n\tMesh " + mesh.toString(fullDetails);
  24831. }
  24832. }
  24833. // Connecting parents
  24834. var currentMesh;
  24835. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24836. currentMesh = scene.meshes[index];
  24837. if (currentMesh._waitingParentId) {
  24838. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  24839. currentMesh._waitingParentId = undefined;
  24840. }
  24841. }
  24842. // freeze and compute world matrix application
  24843. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24844. currentMesh = scene.meshes[index];
  24845. if (currentMesh._waitingFreezeWorldMatrix) {
  24846. currentMesh.freezeWorldMatrix();
  24847. currentMesh._waitingFreezeWorldMatrix = undefined;
  24848. }
  24849. else {
  24850. currentMesh.computeWorldMatrix(true);
  24851. }
  24852. }
  24853. // Particles
  24854. if (parsedData.particleSystems) {
  24855. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24856. var parsedParticleSystem = parsedData.particleSystems[index];
  24857. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  24858. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  24859. }
  24860. }
  24861. }
  24862. return true;
  24863. }
  24864. catch (err) {
  24865. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  24866. log = null;
  24867. throw err;
  24868. }
  24869. finally {
  24870. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24871. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24872. }
  24873. }
  24874. },
  24875. load: function (scene, data, rootUrl) {
  24876. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  24877. // when SceneLoader.debugLogging = true (default), or exception encountered.
  24878. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  24879. // and avoid problems with multiple concurrent .babylon loads.
  24880. var log = "importScene has failed JSON parse";
  24881. try {
  24882. var parsedData = JSON.parse(data);
  24883. log = "";
  24884. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  24885. // Scene
  24886. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  24887. scene.autoClear = parsedData.autoClear;
  24888. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  24889. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  24890. if (parsedData.gravity) {
  24891. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  24892. }
  24893. // Fog
  24894. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  24895. scene.fogMode = parsedData.fogMode;
  24896. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  24897. scene.fogStart = parsedData.fogStart;
  24898. scene.fogEnd = parsedData.fogEnd;
  24899. scene.fogDensity = parsedData.fogDensity;
  24900. log += "\tFog mode for scene: ";
  24901. switch (scene.fogMode) {
  24902. // getters not compiling, so using hardcoded
  24903. case 1:
  24904. log += "exp\n";
  24905. break;
  24906. case 2:
  24907. log += "exp2\n";
  24908. break;
  24909. case 3:
  24910. log += "linear\n";
  24911. break;
  24912. }
  24913. }
  24914. //Physics
  24915. if (parsedData.physicsEnabled) {
  24916. var physicsPlugin;
  24917. if (parsedData.physicsEngine === "cannon") {
  24918. physicsPlugin = new BABYLON.CannonJSPlugin();
  24919. }
  24920. else if (parsedData.physicsEngine === "oimo") {
  24921. physicsPlugin = new BABYLON.OimoJSPlugin();
  24922. }
  24923. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  24924. //else - default engine, which is currently oimo
  24925. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  24926. scene.enablePhysics(physicsGravity, physicsPlugin);
  24927. }
  24928. //collisions, if defined. otherwise, default is true
  24929. if (parsedData.collisionsEnabled != undefined) {
  24930. scene.collisionsEnabled = parsedData.collisionsEnabled;
  24931. }
  24932. scene.workerCollisions = !!parsedData.workerCollisions;
  24933. var index;
  24934. var cache;
  24935. // Lights
  24936. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  24937. var parsedLight = parsedData.lights[index];
  24938. var light = BABYLON.Light.Parse(parsedLight, scene);
  24939. log += (index === 0 ? "\n\tLights:" : "");
  24940. log += "\n\t\t" + light.toString(fullDetails);
  24941. }
  24942. // Animations
  24943. if (parsedData.animations) {
  24944. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  24945. var parsedAnimation = parsedData.animations[index];
  24946. var animation = BABYLON.Animation.Parse(parsedAnimation);
  24947. scene.animations.push(animation);
  24948. log += (index === 0 ? "\n\tAnimations:" : "");
  24949. log += "\n\t\t" + animation.toString(fullDetails);
  24950. }
  24951. }
  24952. if (parsedData.autoAnimate) {
  24953. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  24954. }
  24955. // Materials
  24956. if (parsedData.materials) {
  24957. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  24958. var parsedMaterial = parsedData.materials[index];
  24959. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  24960. log += (index === 0 ? "\n\tMaterials:" : "");
  24961. log += "\n\t\t" + mat.toString(fullDetails);
  24962. }
  24963. }
  24964. if (parsedData.multiMaterials) {
  24965. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  24966. var parsedMultiMaterial = parsedData.multiMaterials[index];
  24967. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  24968. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  24969. log += "\n\t\t" + mmat.toString(fullDetails);
  24970. }
  24971. }
  24972. // Skeletons
  24973. if (parsedData.skeletons) {
  24974. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  24975. var parsedSkeleton = parsedData.skeletons[index];
  24976. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  24977. log += (index === 0 ? "\n\tSkeletons:" : "");
  24978. log += "\n\t\t" + skeleton.toString(fullDetails);
  24979. }
  24980. }
  24981. // Geometries
  24982. var geometries = parsedData.geometries;
  24983. if (geometries) {
  24984. // Boxes
  24985. var boxes = geometries.boxes;
  24986. if (boxes) {
  24987. for (index = 0, cache = boxes.length; index < cache; index++) {
  24988. var parsedBox = boxes[index];
  24989. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  24990. }
  24991. }
  24992. // Spheres
  24993. var spheres = geometries.spheres;
  24994. if (spheres) {
  24995. for (index = 0, cache = spheres.length; index < cache; index++) {
  24996. var parsedSphere = spheres[index];
  24997. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  24998. }
  24999. }
  25000. // Cylinders
  25001. var cylinders = geometries.cylinders;
  25002. if (cylinders) {
  25003. for (index = 0, cache = cylinders.length; index < cache; index++) {
  25004. var parsedCylinder = cylinders[index];
  25005. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  25006. }
  25007. }
  25008. // Toruses
  25009. var toruses = geometries.toruses;
  25010. if (toruses) {
  25011. for (index = 0, cache = toruses.length; index < cache; index++) {
  25012. var parsedTorus = toruses[index];
  25013. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  25014. }
  25015. }
  25016. // Grounds
  25017. var grounds = geometries.grounds;
  25018. if (grounds) {
  25019. for (index = 0, cache = grounds.length; index < cache; index++) {
  25020. var parsedGround = grounds[index];
  25021. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  25022. }
  25023. }
  25024. // Planes
  25025. var planes = geometries.planes;
  25026. if (planes) {
  25027. for (index = 0, cache = planes.length; index < cache; index++) {
  25028. var parsedPlane = planes[index];
  25029. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  25030. }
  25031. }
  25032. // TorusKnots
  25033. var torusKnots = geometries.torusKnots;
  25034. if (torusKnots) {
  25035. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  25036. var parsedTorusKnot = torusKnots[index];
  25037. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  25038. }
  25039. }
  25040. // VertexData
  25041. var vertexData = geometries.vertexData;
  25042. if (vertexData) {
  25043. for (index = 0, cache = vertexData.length; index < cache; index++) {
  25044. var parsedVertexData = vertexData[index];
  25045. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  25046. }
  25047. }
  25048. }
  25049. // Meshes
  25050. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  25051. var parsedMesh = parsedData.meshes[index];
  25052. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  25053. log += (index === 0 ? "\n\tMeshes:" : "");
  25054. log += "\n\t\t" + mesh.toString(fullDetails);
  25055. }
  25056. // Cameras
  25057. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  25058. var parsedCamera = parsedData.cameras[index];
  25059. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  25060. log += (index === 0 ? "\n\tCameras:" : "");
  25061. log += "\n\t\t" + camera.toString(fullDetails);
  25062. }
  25063. if (parsedData.activeCameraID) {
  25064. scene.setActiveCameraByID(parsedData.activeCameraID);
  25065. }
  25066. // Browsing all the graph to connect the dots
  25067. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  25068. var camera = scene.cameras[index];
  25069. if (camera._waitingParentId) {
  25070. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  25071. camera._waitingParentId = undefined;
  25072. }
  25073. }
  25074. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  25075. var light = scene.lights[index];
  25076. if (light._waitingParentId) {
  25077. light.parent = scene.getLastEntryByID(light._waitingParentId);
  25078. light._waitingParentId = undefined;
  25079. }
  25080. }
  25081. // Sounds
  25082. var loadedSounds = [];
  25083. var loadedSound;
  25084. if (BABYLON.AudioEngine && parsedData.sounds) {
  25085. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  25086. var parsedSound = parsedData.sounds[index];
  25087. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25088. if (!parsedSound.url)
  25089. parsedSound.url = parsedSound.name;
  25090. if (!loadedSounds[parsedSound.url]) {
  25091. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  25092. loadedSounds[parsedSound.url] = loadedSound;
  25093. }
  25094. else {
  25095. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  25096. }
  25097. }
  25098. else {
  25099. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  25100. }
  25101. }
  25102. }
  25103. loadedSounds = [];
  25104. // Connect parents & children and parse actions
  25105. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25106. var mesh = scene.meshes[index];
  25107. if (mesh._waitingParentId) {
  25108. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  25109. mesh._waitingParentId = undefined;
  25110. }
  25111. if (mesh._waitingActions) {
  25112. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  25113. mesh._waitingActions = undefined;
  25114. }
  25115. }
  25116. // freeze world matrix application
  25117. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25118. var currentMesh = scene.meshes[index];
  25119. if (currentMesh._waitingFreezeWorldMatrix) {
  25120. currentMesh.freezeWorldMatrix();
  25121. currentMesh._waitingFreezeWorldMatrix = undefined;
  25122. }
  25123. else {
  25124. currentMesh.computeWorldMatrix(true);
  25125. }
  25126. }
  25127. // Particles Systems
  25128. if (parsedData.particleSystems) {
  25129. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  25130. var parsedParticleSystem = parsedData.particleSystems[index];
  25131. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  25132. }
  25133. }
  25134. // Lens flares
  25135. if (parsedData.lensFlareSystems) {
  25136. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  25137. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  25138. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  25139. }
  25140. }
  25141. // Shadows
  25142. if (parsedData.shadowGenerators) {
  25143. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  25144. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  25145. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  25146. }
  25147. }
  25148. // Actions (scene)
  25149. if (parsedData.actions) {
  25150. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  25151. }
  25152. // Finish
  25153. return true;
  25154. }
  25155. catch (err) {
  25156. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  25157. log = null;
  25158. throw err;
  25159. }
  25160. finally {
  25161. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  25162. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  25163. }
  25164. }
  25165. }
  25166. });
  25167. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25168. })(BABYLON || (BABYLON = {}));
  25169. var BABYLON;
  25170. (function (BABYLON) {
  25171. var SpriteManager = (function () {
  25172. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  25173. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25174. this.name = name;
  25175. this.cellSize = cellSize;
  25176. this.sprites = new Array();
  25177. this.renderingGroupId = 0;
  25178. this.layerMask = 0x0FFFFFFF;
  25179. this.fogEnabled = true;
  25180. this.isPickable = false;
  25181. /**
  25182. * An event triggered when the manager is disposed.
  25183. * @type {BABYLON.Observable}
  25184. */
  25185. this.onDisposeObservable = new BABYLON.Observable();
  25186. this._vertexBuffers = {};
  25187. this._capacity = capacity;
  25188. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  25189. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25190. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25191. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  25192. this._scene = scene;
  25193. this._scene.spriteManagers.push(this);
  25194. var indices = [];
  25195. var index = 0;
  25196. for (var count = 0; count < capacity; count++) {
  25197. indices.push(index);
  25198. indices.push(index + 1);
  25199. indices.push(index + 2);
  25200. indices.push(index);
  25201. indices.push(index + 2);
  25202. indices.push(index + 3);
  25203. index += 4;
  25204. }
  25205. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  25206. // VBO
  25207. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  25208. this._vertexData = new Float32Array(capacity * 16 * 4);
  25209. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  25210. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  25211. var options = this._buffer.createVertexBuffer("options", 4, 4);
  25212. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  25213. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  25214. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  25215. this._vertexBuffers["options"] = options;
  25216. this._vertexBuffers["cellInfo"] = cellInfo;
  25217. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  25218. // Effects
  25219. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  25220. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  25221. }
  25222. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  25223. set: function (callback) {
  25224. if (this._onDisposeObserver) {
  25225. this.onDisposeObservable.remove(this._onDisposeObserver);
  25226. }
  25227. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25228. },
  25229. enumerable: true,
  25230. configurable: true
  25231. });
  25232. Object.defineProperty(SpriteManager.prototype, "texture", {
  25233. get: function () {
  25234. return this._spriteTexture;
  25235. },
  25236. set: function (value) {
  25237. this._spriteTexture = value;
  25238. },
  25239. enumerable: true,
  25240. configurable: true
  25241. });
  25242. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  25243. var arrayOffset = index * 16;
  25244. if (offsetX === 0)
  25245. offsetX = this._epsilon;
  25246. else if (offsetX === 1)
  25247. offsetX = 1 - this._epsilon;
  25248. if (offsetY === 0)
  25249. offsetY = this._epsilon;
  25250. else if (offsetY === 1)
  25251. offsetY = 1 - this._epsilon;
  25252. this._vertexData[arrayOffset] = sprite.position.x;
  25253. this._vertexData[arrayOffset + 1] = sprite.position.y;
  25254. this._vertexData[arrayOffset + 2] = sprite.position.z;
  25255. this._vertexData[arrayOffset + 3] = sprite.angle;
  25256. this._vertexData[arrayOffset + 4] = sprite.width;
  25257. this._vertexData[arrayOffset + 5] = sprite.height;
  25258. this._vertexData[arrayOffset + 6] = offsetX;
  25259. this._vertexData[arrayOffset + 7] = offsetY;
  25260. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  25261. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  25262. var offset = (sprite.cellIndex / rowSize) >> 0;
  25263. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  25264. this._vertexData[arrayOffset + 11] = offset;
  25265. // Color
  25266. this._vertexData[arrayOffset + 12] = sprite.color.r;
  25267. this._vertexData[arrayOffset + 13] = sprite.color.g;
  25268. this._vertexData[arrayOffset + 14] = sprite.color.b;
  25269. this._vertexData[arrayOffset + 15] = sprite.color.a;
  25270. };
  25271. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  25272. var count = Math.min(this._capacity, this.sprites.length);
  25273. var min = BABYLON.Vector3.Zero();
  25274. var max = BABYLON.Vector3.Zero();
  25275. var distance = Number.MAX_VALUE;
  25276. var currentSprite;
  25277. var cameraSpacePosition = BABYLON.Vector3.Zero();
  25278. var cameraView = camera.getViewMatrix();
  25279. for (var index = 0; index < count; index++) {
  25280. var sprite = this.sprites[index];
  25281. if (!sprite) {
  25282. continue;
  25283. }
  25284. if (predicate) {
  25285. if (!predicate(sprite)) {
  25286. continue;
  25287. }
  25288. }
  25289. else if (!sprite.isPickable) {
  25290. continue;
  25291. }
  25292. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  25293. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  25294. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  25295. if (ray.intersectsBoxMinMax(min, max)) {
  25296. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  25297. if (distance > currentDistance) {
  25298. distance = currentDistance;
  25299. currentSprite = sprite;
  25300. if (fastCheck) {
  25301. break;
  25302. }
  25303. }
  25304. }
  25305. }
  25306. if (currentSprite) {
  25307. var result = new BABYLON.PickingInfo();
  25308. result.hit = true;
  25309. result.pickedSprite = currentSprite;
  25310. result.distance = distance;
  25311. return result;
  25312. }
  25313. return null;
  25314. };
  25315. SpriteManager.prototype.render = function () {
  25316. // Check
  25317. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  25318. return;
  25319. var engine = this._scene.getEngine();
  25320. var baseSize = this._spriteTexture.getBaseSize();
  25321. // Sprites
  25322. var deltaTime = engine.getDeltaTime();
  25323. var max = Math.min(this._capacity, this.sprites.length);
  25324. var rowSize = baseSize.width / this.cellSize;
  25325. var offset = 0;
  25326. for (var index = 0; index < max; index++) {
  25327. var sprite = this.sprites[index];
  25328. if (!sprite) {
  25329. continue;
  25330. }
  25331. sprite._animate(deltaTime);
  25332. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  25333. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  25334. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  25335. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  25336. }
  25337. this._buffer.update(this._vertexData);
  25338. // Render
  25339. var effect = this._effectBase;
  25340. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25341. effect = this._effectFog;
  25342. }
  25343. engine.enableEffect(effect);
  25344. var viewMatrix = this._scene.getViewMatrix();
  25345. effect.setTexture("diffuseSampler", this._spriteTexture);
  25346. effect.setMatrix("view", viewMatrix);
  25347. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  25348. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  25349. // Fog
  25350. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25351. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  25352. effect.setColor3("vFogColor", this._scene.fogColor);
  25353. }
  25354. // VBOs
  25355. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  25356. // Draw order
  25357. engine.setDepthFunctionToLessOrEqual();
  25358. effect.setBool("alphaTest", true);
  25359. engine.setColorWrite(false);
  25360. engine.draw(true, 0, max * 6);
  25361. engine.setColorWrite(true);
  25362. effect.setBool("alphaTest", false);
  25363. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25364. engine.draw(true, 0, max * 6);
  25365. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25366. };
  25367. SpriteManager.prototype.dispose = function () {
  25368. if (this._buffer) {
  25369. this._buffer.dispose();
  25370. this._buffer = null;
  25371. }
  25372. if (this._indexBuffer) {
  25373. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25374. this._indexBuffer = null;
  25375. }
  25376. if (this._spriteTexture) {
  25377. this._spriteTexture.dispose();
  25378. this._spriteTexture = null;
  25379. }
  25380. // Remove from scene
  25381. var index = this._scene.spriteManagers.indexOf(this);
  25382. this._scene.spriteManagers.splice(index, 1);
  25383. // Callback
  25384. this.onDisposeObservable.notifyObservers(this);
  25385. this.onDisposeObservable.clear();
  25386. };
  25387. return SpriteManager;
  25388. })();
  25389. BABYLON.SpriteManager = SpriteManager;
  25390. })(BABYLON || (BABYLON = {}));
  25391. var BABYLON;
  25392. (function (BABYLON) {
  25393. var Sprite = (function () {
  25394. function Sprite(name, manager) {
  25395. this.name = name;
  25396. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25397. this.width = 1.0;
  25398. this.height = 1.0;
  25399. this.angle = 0;
  25400. this.cellIndex = 0;
  25401. this.invertU = 0;
  25402. this.invertV = 0;
  25403. this.animations = new Array();
  25404. this.isPickable = false;
  25405. this._animationStarted = false;
  25406. this._loopAnimation = false;
  25407. this._fromIndex = 0;
  25408. this._toIndex = 0;
  25409. this._delay = 0;
  25410. this._direction = 1;
  25411. this._frameCount = 0;
  25412. this._time = 0;
  25413. this._manager = manager;
  25414. this._manager.sprites.push(this);
  25415. this.position = BABYLON.Vector3.Zero();
  25416. }
  25417. Object.defineProperty(Sprite.prototype, "size", {
  25418. get: function () {
  25419. return this.width;
  25420. },
  25421. set: function (value) {
  25422. this.width = value;
  25423. this.height = value;
  25424. },
  25425. enumerable: true,
  25426. configurable: true
  25427. });
  25428. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  25429. this._fromIndex = from;
  25430. this._toIndex = to;
  25431. this._loopAnimation = loop;
  25432. this._delay = delay;
  25433. this._animationStarted = true;
  25434. this._direction = from < to ? 1 : -1;
  25435. this.cellIndex = from;
  25436. this._time = 0;
  25437. };
  25438. Sprite.prototype.stopAnimation = function () {
  25439. this._animationStarted = false;
  25440. };
  25441. Sprite.prototype._animate = function (deltaTime) {
  25442. if (!this._animationStarted)
  25443. return;
  25444. this._time += deltaTime;
  25445. if (this._time > this._delay) {
  25446. this._time = this._time % this._delay;
  25447. this.cellIndex += this._direction;
  25448. if (this.cellIndex == this._toIndex) {
  25449. if (this._loopAnimation) {
  25450. this.cellIndex = this._fromIndex;
  25451. }
  25452. else {
  25453. this._animationStarted = false;
  25454. if (this.disposeWhenFinishedAnimating) {
  25455. this.dispose();
  25456. }
  25457. }
  25458. }
  25459. }
  25460. };
  25461. Sprite.prototype.dispose = function () {
  25462. for (var i = 0; i < this._manager.sprites.length; i++) {
  25463. if (this._manager.sprites[i] == this) {
  25464. this._manager.sprites.splice(i, 1);
  25465. }
  25466. }
  25467. };
  25468. return Sprite;
  25469. })();
  25470. BABYLON.Sprite = Sprite;
  25471. })(BABYLON || (BABYLON = {}));
  25472. var BABYLON;
  25473. (function (BABYLON) {
  25474. var Layer = (function () {
  25475. function Layer(name, imgUrl, scene, isBackground, color) {
  25476. this.name = name;
  25477. this.scale = new BABYLON.Vector2(1, 1);
  25478. this.offset = new BABYLON.Vector2(0, 0);
  25479. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  25480. this._vertexBuffers = {};
  25481. // Events
  25482. /**
  25483. * An event triggered when the layer is disposed.
  25484. * @type {BABYLON.Observable}
  25485. */
  25486. this.onDisposeObservable = new BABYLON.Observable();
  25487. /**
  25488. * An event triggered before rendering the scene
  25489. * @type {BABYLON.Observable}
  25490. */
  25491. this.onBeforeRenderObservable = new BABYLON.Observable();
  25492. /**
  25493. * An event triggered after rendering the scene
  25494. * @type {BABYLON.Observable}
  25495. */
  25496. this.onAfterRenderObservable = new BABYLON.Observable();
  25497. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  25498. this.isBackground = isBackground === undefined ? true : isBackground;
  25499. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  25500. this._scene = scene;
  25501. this._scene.layers.push(this);
  25502. var engine = scene.getEngine();
  25503. // VBO
  25504. var vertices = [];
  25505. vertices.push(1, 1);
  25506. vertices.push(-1, 1);
  25507. vertices.push(-1, -1);
  25508. vertices.push(1, -1);
  25509. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  25510. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  25511. // Indices
  25512. var indices = [];
  25513. indices.push(0);
  25514. indices.push(1);
  25515. indices.push(2);
  25516. indices.push(0);
  25517. indices.push(2);
  25518. indices.push(3);
  25519. this._indexBuffer = engine.createIndexBuffer(indices);
  25520. // Effects
  25521. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  25522. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  25523. }
  25524. Object.defineProperty(Layer.prototype, "onDispose", {
  25525. set: function (callback) {
  25526. if (this._onDisposeObserver) {
  25527. this.onDisposeObservable.remove(this._onDisposeObserver);
  25528. }
  25529. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25530. },
  25531. enumerable: true,
  25532. configurable: true
  25533. });
  25534. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  25535. set: function (callback) {
  25536. if (this._onBeforeRenderObserver) {
  25537. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25538. }
  25539. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25540. },
  25541. enumerable: true,
  25542. configurable: true
  25543. });
  25544. Object.defineProperty(Layer.prototype, "onAfterRender", {
  25545. set: function (callback) {
  25546. if (this._onAfterRenderObserver) {
  25547. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25548. }
  25549. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25550. },
  25551. enumerable: true,
  25552. configurable: true
  25553. });
  25554. Layer.prototype.render = function () {
  25555. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  25556. // Check
  25557. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  25558. return;
  25559. var engine = this._scene.getEngine();
  25560. this.onBeforeRenderObservable.notifyObservers(this);
  25561. // Render
  25562. engine.enableEffect(currentEffect);
  25563. engine.setState(false);
  25564. // Texture
  25565. currentEffect.setTexture("textureSampler", this.texture);
  25566. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  25567. // Color
  25568. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  25569. // Scale / offset
  25570. currentEffect.setVector2("offset", this.offset);
  25571. currentEffect.setVector2("scale", this.scale);
  25572. // VBOs
  25573. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  25574. // Draw order
  25575. if (!this._alphaTestEffect) {
  25576. engine.setAlphaMode(this.alphaBlendingMode);
  25577. engine.draw(true, 0, 6);
  25578. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25579. }
  25580. else {
  25581. engine.draw(true, 0, 6);
  25582. }
  25583. this.onAfterRenderObservable.notifyObservers(this);
  25584. };
  25585. Layer.prototype.dispose = function () {
  25586. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  25587. if (vertexBuffer) {
  25588. vertexBuffer.dispose();
  25589. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  25590. }
  25591. if (this._indexBuffer) {
  25592. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25593. this._indexBuffer = null;
  25594. }
  25595. if (this.texture) {
  25596. this.texture.dispose();
  25597. this.texture = null;
  25598. }
  25599. // Remove from scene
  25600. var index = this._scene.layers.indexOf(this);
  25601. this._scene.layers.splice(index, 1);
  25602. // Callback
  25603. this.onDisposeObservable.notifyObservers(this);
  25604. this.onDisposeObservable.clear();
  25605. this.onAfterRenderObservable.clear();
  25606. this.onBeforeRenderObservable.clear();
  25607. };
  25608. return Layer;
  25609. })();
  25610. BABYLON.Layer = Layer;
  25611. })(BABYLON || (BABYLON = {}));
  25612. var BABYLON;
  25613. (function (BABYLON) {
  25614. var Particle = (function () {
  25615. function Particle() {
  25616. this.position = BABYLON.Vector3.Zero();
  25617. this.direction = BABYLON.Vector3.Zero();
  25618. this.color = new BABYLON.Color4(0, 0, 0, 0);
  25619. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  25620. this.lifeTime = 1.0;
  25621. this.age = 0;
  25622. this.size = 0;
  25623. this.angle = 0;
  25624. this.angularSpeed = 0;
  25625. }
  25626. Particle.prototype.copyTo = function (other) {
  25627. other.position.copyFrom(this.position);
  25628. other.direction.copyFrom(this.direction);
  25629. other.color.copyFrom(this.color);
  25630. other.colorStep.copyFrom(this.colorStep);
  25631. other.lifeTime = this.lifeTime;
  25632. other.age = this.age;
  25633. other.size = this.size;
  25634. other.angle = this.angle;
  25635. other.angularSpeed = this.angularSpeed;
  25636. };
  25637. return Particle;
  25638. })();
  25639. BABYLON.Particle = Particle;
  25640. })(BABYLON || (BABYLON = {}));
  25641. var BABYLON;
  25642. (function (BABYLON) {
  25643. var randomNumber = function (min, max) {
  25644. if (min === max) {
  25645. return (min);
  25646. }
  25647. var random = Math.random();
  25648. return ((random * (max - min)) + min);
  25649. };
  25650. var ParticleSystem = (function () {
  25651. function ParticleSystem(name, capacity, scene, customEffect) {
  25652. var _this = this;
  25653. this.name = name;
  25654. // Members
  25655. this.animations = [];
  25656. this.renderingGroupId = 0;
  25657. this.emitter = null;
  25658. this.emitRate = 10;
  25659. this.manualEmitCount = -1;
  25660. this.updateSpeed = 0.01;
  25661. this.targetStopDuration = 0;
  25662. this.disposeOnStop = false;
  25663. this.minEmitPower = 1;
  25664. this.maxEmitPower = 1;
  25665. this.minLifeTime = 1;
  25666. this.maxLifeTime = 1;
  25667. this.minSize = 1;
  25668. this.maxSize = 1;
  25669. this.minAngularSpeed = 0;
  25670. this.maxAngularSpeed = 0;
  25671. this.layerMask = 0x0FFFFFFF;
  25672. /**
  25673. * An event triggered when the system is disposed.
  25674. * @type {BABYLON.Observable}
  25675. */
  25676. this.onDisposeObservable = new BABYLON.Observable();
  25677. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  25678. this.forceDepthWrite = false;
  25679. this.gravity = BABYLON.Vector3.Zero();
  25680. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  25681. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  25682. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  25683. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  25684. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25685. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25686. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  25687. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25688. this.particles = new Array();
  25689. this._stockParticles = new Array();
  25690. this._newPartsExcess = 0;
  25691. this._vertexBuffers = {};
  25692. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  25693. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  25694. this._scaledDirection = BABYLON.Vector3.Zero();
  25695. this._scaledGravity = BABYLON.Vector3.Zero();
  25696. this._currentRenderId = -1;
  25697. this._started = false;
  25698. this._stopped = false;
  25699. this._actualFrame = 0;
  25700. this.id = name;
  25701. this._capacity = capacity;
  25702. this._scene = scene;
  25703. this._customEffect = customEffect;
  25704. scene.particleSystems.push(this);
  25705. var indices = [];
  25706. var index = 0;
  25707. for (var count = 0; count < capacity; count++) {
  25708. indices.push(index);
  25709. indices.push(index + 1);
  25710. indices.push(index + 2);
  25711. indices.push(index);
  25712. indices.push(index + 2);
  25713. indices.push(index + 3);
  25714. index += 4;
  25715. }
  25716. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  25717. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  25718. this._vertexData = new Float32Array(capacity * 11 * 4);
  25719. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  25720. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  25721. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  25722. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  25723. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  25724. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  25725. this._vertexBuffers["options"] = options;
  25726. // Default behaviors
  25727. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  25728. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  25729. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  25730. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  25731. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  25732. };
  25733. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  25734. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  25735. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  25736. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  25737. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  25738. };
  25739. this.updateFunction = function (particles) {
  25740. for (var index = 0; index < particles.length; index++) {
  25741. var particle = particles[index];
  25742. particle.age += _this._scaledUpdateSpeed;
  25743. if (particle.age >= particle.lifeTime) {
  25744. _this.recycleParticle(particle);
  25745. index--;
  25746. continue;
  25747. }
  25748. else {
  25749. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  25750. particle.color.addInPlace(_this._scaledColorStep);
  25751. if (particle.color.a < 0)
  25752. particle.color.a = 0;
  25753. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  25754. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  25755. particle.position.addInPlace(_this._scaledDirection);
  25756. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  25757. particle.direction.addInPlace(_this._scaledGravity);
  25758. }
  25759. }
  25760. };
  25761. }
  25762. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  25763. set: function (callback) {
  25764. if (this._onDisposeObserver) {
  25765. this.onDisposeObservable.remove(this._onDisposeObserver);
  25766. }
  25767. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25768. },
  25769. enumerable: true,
  25770. configurable: true
  25771. });
  25772. ParticleSystem.prototype.recycleParticle = function (particle) {
  25773. var lastParticle = this.particles.pop();
  25774. if (lastParticle !== particle) {
  25775. lastParticle.copyTo(particle);
  25776. this._stockParticles.push(lastParticle);
  25777. }
  25778. };
  25779. ParticleSystem.prototype.getCapacity = function () {
  25780. return this._capacity;
  25781. };
  25782. ParticleSystem.prototype.isAlive = function () {
  25783. return this._alive;
  25784. };
  25785. ParticleSystem.prototype.isStarted = function () {
  25786. return this._started;
  25787. };
  25788. ParticleSystem.prototype.start = function () {
  25789. this._started = true;
  25790. this._stopped = false;
  25791. this._actualFrame = 0;
  25792. };
  25793. ParticleSystem.prototype.stop = function () {
  25794. this._stopped = true;
  25795. };
  25796. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  25797. var offset = index * 11;
  25798. this._vertexData[offset] = particle.position.x;
  25799. this._vertexData[offset + 1] = particle.position.y;
  25800. this._vertexData[offset + 2] = particle.position.z;
  25801. this._vertexData[offset + 3] = particle.color.r;
  25802. this._vertexData[offset + 4] = particle.color.g;
  25803. this._vertexData[offset + 5] = particle.color.b;
  25804. this._vertexData[offset + 6] = particle.color.a;
  25805. this._vertexData[offset + 7] = particle.angle;
  25806. this._vertexData[offset + 8] = particle.size;
  25807. this._vertexData[offset + 9] = offsetX;
  25808. this._vertexData[offset + 10] = offsetY;
  25809. };
  25810. ParticleSystem.prototype._update = function (newParticles) {
  25811. // Update current
  25812. this._alive = this.particles.length > 0;
  25813. this.updateFunction(this.particles);
  25814. // Add new ones
  25815. var worldMatrix;
  25816. if (this.emitter.position) {
  25817. worldMatrix = this.emitter.getWorldMatrix();
  25818. }
  25819. else {
  25820. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  25821. }
  25822. var particle;
  25823. for (var index = 0; index < newParticles; index++) {
  25824. if (this.particles.length === this._capacity) {
  25825. break;
  25826. }
  25827. if (this._stockParticles.length !== 0) {
  25828. particle = this._stockParticles.pop();
  25829. particle.age = 0;
  25830. }
  25831. else {
  25832. particle = new BABYLON.Particle();
  25833. }
  25834. this.particles.push(particle);
  25835. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  25836. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  25837. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  25838. particle.size = randomNumber(this.minSize, this.maxSize);
  25839. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  25840. this.startPositionFunction(worldMatrix, particle.position, particle);
  25841. var step = randomNumber(0, 1.0);
  25842. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  25843. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  25844. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  25845. }
  25846. };
  25847. ParticleSystem.prototype._getEffect = function () {
  25848. if (this._customEffect) {
  25849. return this._customEffect;
  25850. }
  25851. ;
  25852. var defines = [];
  25853. if (this._scene.clipPlane) {
  25854. defines.push("#define CLIPPLANE");
  25855. }
  25856. // Effect
  25857. var join = defines.join("\n");
  25858. if (this._cachedDefines !== join) {
  25859. this._cachedDefines = join;
  25860. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  25861. }
  25862. return this._effect;
  25863. };
  25864. ParticleSystem.prototype.animate = function () {
  25865. if (!this._started)
  25866. return;
  25867. var effect = this._getEffect();
  25868. // Check
  25869. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  25870. return;
  25871. if (this._currentRenderId === this._scene.getRenderId()) {
  25872. return;
  25873. }
  25874. this._currentRenderId = this._scene.getRenderId();
  25875. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  25876. // determine the number of particles we need to create
  25877. var newParticles;
  25878. if (this.manualEmitCount > -1) {
  25879. newParticles = this.manualEmitCount;
  25880. this._newPartsExcess = 0;
  25881. this.manualEmitCount = 0;
  25882. }
  25883. else {
  25884. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  25885. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  25886. }
  25887. if (this._newPartsExcess > 1.0) {
  25888. newParticles += this._newPartsExcess >> 0;
  25889. this._newPartsExcess -= this._newPartsExcess >> 0;
  25890. }
  25891. this._alive = false;
  25892. if (!this._stopped) {
  25893. this._actualFrame += this._scaledUpdateSpeed;
  25894. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  25895. this.stop();
  25896. }
  25897. else {
  25898. newParticles = 0;
  25899. }
  25900. this._update(newParticles);
  25901. // Stopped?
  25902. if (this._stopped) {
  25903. if (!this._alive) {
  25904. this._started = false;
  25905. if (this.disposeOnStop) {
  25906. this._scene._toBeDisposed.push(this);
  25907. }
  25908. }
  25909. }
  25910. // Update VBO
  25911. var offset = 0;
  25912. for (var index = 0; index < this.particles.length; index++) {
  25913. var particle = this.particles[index];
  25914. this._appendParticleVertex(offset++, particle, 0, 0);
  25915. this._appendParticleVertex(offset++, particle, 1, 0);
  25916. this._appendParticleVertex(offset++, particle, 1, 1);
  25917. this._appendParticleVertex(offset++, particle, 0, 1);
  25918. }
  25919. this._vertexBuffer.update(this._vertexData);
  25920. };
  25921. ParticleSystem.prototype.render = function () {
  25922. var effect = this._getEffect();
  25923. // Check
  25924. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  25925. return 0;
  25926. var engine = this._scene.getEngine();
  25927. // Render
  25928. engine.enableEffect(effect);
  25929. engine.setState(false);
  25930. var viewMatrix = this._scene.getViewMatrix();
  25931. effect.setTexture("diffuseSampler", this.particleTexture);
  25932. effect.setMatrix("view", viewMatrix);
  25933. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  25934. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  25935. if (this._scene.clipPlane) {
  25936. var clipPlane = this._scene.clipPlane;
  25937. var invView = viewMatrix.clone();
  25938. invView.invert();
  25939. effect.setMatrix("invView", invView);
  25940. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25941. }
  25942. // VBOs
  25943. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  25944. // Draw order
  25945. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  25946. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  25947. }
  25948. else {
  25949. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25950. }
  25951. if (this.forceDepthWrite) {
  25952. engine.setDepthWrite(true);
  25953. }
  25954. engine.draw(true, 0, this.particles.length * 6);
  25955. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25956. return this.particles.length;
  25957. };
  25958. ParticleSystem.prototype.dispose = function () {
  25959. if (this._vertexBuffer) {
  25960. this._vertexBuffer.dispose();
  25961. this._vertexBuffer = null;
  25962. }
  25963. if (this._indexBuffer) {
  25964. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25965. this._indexBuffer = null;
  25966. }
  25967. if (this.particleTexture) {
  25968. this.particleTexture.dispose();
  25969. this.particleTexture = null;
  25970. }
  25971. // Remove from scene
  25972. var index = this._scene.particleSystems.indexOf(this);
  25973. this._scene.particleSystems.splice(index, 1);
  25974. // Callback
  25975. this.onDisposeObservable.notifyObservers(this);
  25976. this.onDisposeObservable.clear();
  25977. };
  25978. // Clone
  25979. ParticleSystem.prototype.clone = function (name, newEmitter) {
  25980. var result = new ParticleSystem(name, this._capacity, this._scene);
  25981. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  25982. if (newEmitter === undefined) {
  25983. newEmitter = this.emitter;
  25984. }
  25985. result.emitter = newEmitter;
  25986. if (this.particleTexture) {
  25987. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  25988. }
  25989. result.start();
  25990. return result;
  25991. };
  25992. ParticleSystem.prototype.serialize = function () {
  25993. var serializationObject = {};
  25994. serializationObject.name = this.name;
  25995. serializationObject.id = this.id;
  25996. // Emitter
  25997. if (this.emitter.position) {
  25998. serializationObject.emitterId = this.emitter.id;
  25999. }
  26000. else {
  26001. serializationObject.emitter = this.emitter.asArray();
  26002. }
  26003. serializationObject.capacity = this.getCapacity();
  26004. if (this.particleTexture) {
  26005. serializationObject.textureName = this.particleTexture.name;
  26006. }
  26007. // Animations
  26008. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26009. // Particle system
  26010. serializationObject.minAngularSpeed = this.minAngularSpeed;
  26011. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  26012. serializationObject.minSize = this.minSize;
  26013. serializationObject.maxSize = this.maxSize;
  26014. serializationObject.minEmitPower = this.minEmitPower;
  26015. serializationObject.maxEmitPower = this.maxEmitPower;
  26016. serializationObject.minLifeTime = this.minLifeTime;
  26017. serializationObject.maxLifeTime = this.maxLifeTime;
  26018. serializationObject.emitRate = this.emitRate;
  26019. serializationObject.minEmitBox = this.minEmitBox.asArray();
  26020. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  26021. serializationObject.gravity = this.gravity.asArray();
  26022. serializationObject.direction1 = this.direction1.asArray();
  26023. serializationObject.direction2 = this.direction2.asArray();
  26024. serializationObject.color1 = this.color1.asArray();
  26025. serializationObject.color2 = this.color2.asArray();
  26026. serializationObject.colorDead = this.colorDead.asArray();
  26027. serializationObject.updateSpeed = this.updateSpeed;
  26028. serializationObject.targetStopDuration = this.targetStopDuration;
  26029. serializationObject.textureMask = this.textureMask.asArray();
  26030. serializationObject.blendMode = this.blendMode;
  26031. return serializationObject;
  26032. };
  26033. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  26034. var name = parsedParticleSystem.name;
  26035. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  26036. if (parsedParticleSystem.id) {
  26037. particleSystem.id = parsedParticleSystem.id;
  26038. }
  26039. // Texture
  26040. if (parsedParticleSystem.textureName) {
  26041. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  26042. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  26043. }
  26044. // Emitter
  26045. if (parsedParticleSystem.emitterId) {
  26046. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  26047. }
  26048. else {
  26049. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  26050. }
  26051. // Animations
  26052. if (parsedParticleSystem.animations) {
  26053. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  26054. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  26055. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26056. }
  26057. }
  26058. if (parsedParticleSystem.autoAnimate) {
  26059. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  26060. }
  26061. // Particle system
  26062. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  26063. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  26064. particleSystem.minSize = parsedParticleSystem.minSize;
  26065. particleSystem.maxSize = parsedParticleSystem.maxSize;
  26066. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  26067. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  26068. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  26069. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  26070. particleSystem.emitRate = parsedParticleSystem.emitRate;
  26071. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  26072. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  26073. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  26074. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  26075. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  26076. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  26077. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  26078. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  26079. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  26080. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  26081. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  26082. particleSystem.blendMode = parsedParticleSystem.blendMode;
  26083. if (!parsedParticleSystem.preventAutoStart) {
  26084. particleSystem.start();
  26085. }
  26086. return particleSystem;
  26087. };
  26088. // Statics
  26089. ParticleSystem.BLENDMODE_ONEONE = 0;
  26090. ParticleSystem.BLENDMODE_STANDARD = 1;
  26091. return ParticleSystem;
  26092. })();
  26093. BABYLON.ParticleSystem = ParticleSystem;
  26094. })(BABYLON || (BABYLON = {}));
  26095. var BABYLON;
  26096. (function (BABYLON) {
  26097. var AnimationRange = (function () {
  26098. function AnimationRange(name, from, to) {
  26099. this.name = name;
  26100. this.from = from;
  26101. this.to = to;
  26102. }
  26103. AnimationRange.prototype.clone = function () {
  26104. return new AnimationRange(this.name, this.from, this.to);
  26105. };
  26106. return AnimationRange;
  26107. })();
  26108. BABYLON.AnimationRange = AnimationRange;
  26109. /**
  26110. * Composed of a frame, and an action function
  26111. */
  26112. var AnimationEvent = (function () {
  26113. function AnimationEvent(frame, action, onlyOnce) {
  26114. this.frame = frame;
  26115. this.action = action;
  26116. this.onlyOnce = onlyOnce;
  26117. this.isDone = false;
  26118. }
  26119. return AnimationEvent;
  26120. })();
  26121. BABYLON.AnimationEvent = AnimationEvent;
  26122. var PathCursor = (function () {
  26123. function PathCursor(path) {
  26124. this.path = path;
  26125. this._onchange = new Array();
  26126. this.value = 0;
  26127. this.animations = new Array();
  26128. }
  26129. PathCursor.prototype.getPoint = function () {
  26130. var point = this.path.getPointAtLengthPosition(this.value);
  26131. return new BABYLON.Vector3(point.x, 0, point.y);
  26132. };
  26133. PathCursor.prototype.moveAhead = function (step) {
  26134. if (step === void 0) { step = 0.002; }
  26135. this.move(step);
  26136. return this;
  26137. };
  26138. PathCursor.prototype.moveBack = function (step) {
  26139. if (step === void 0) { step = 0.002; }
  26140. this.move(-step);
  26141. return this;
  26142. };
  26143. PathCursor.prototype.move = function (step) {
  26144. if (Math.abs(step) > 1) {
  26145. throw "step size should be less than 1.";
  26146. }
  26147. this.value += step;
  26148. this.ensureLimits();
  26149. this.raiseOnChange();
  26150. return this;
  26151. };
  26152. PathCursor.prototype.ensureLimits = function () {
  26153. while (this.value > 1) {
  26154. this.value -= 1;
  26155. }
  26156. while (this.value < 0) {
  26157. this.value += 1;
  26158. }
  26159. return this;
  26160. };
  26161. // used by animation engine
  26162. PathCursor.prototype.markAsDirty = function (propertyName) {
  26163. this.ensureLimits();
  26164. this.raiseOnChange();
  26165. return this;
  26166. };
  26167. PathCursor.prototype.raiseOnChange = function () {
  26168. var _this = this;
  26169. this._onchange.forEach(function (f) { return f(_this); });
  26170. return this;
  26171. };
  26172. PathCursor.prototype.onchange = function (f) {
  26173. this._onchange.push(f);
  26174. return this;
  26175. };
  26176. return PathCursor;
  26177. })();
  26178. BABYLON.PathCursor = PathCursor;
  26179. var Animation = (function () {
  26180. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  26181. this.name = name;
  26182. this.targetProperty = targetProperty;
  26183. this.framePerSecond = framePerSecond;
  26184. this.dataType = dataType;
  26185. this.loopMode = loopMode;
  26186. this.enableBlending = enableBlending;
  26187. this._offsetsCache = {};
  26188. this._highLimitsCache = {};
  26189. this._stopped = false;
  26190. this._blendingFactor = 0;
  26191. // The set of event that will be linked to this animation
  26192. this._events = new Array();
  26193. this.allowMatricesInterpolation = false;
  26194. this.blendingSpeed = 0.01;
  26195. this._ranges = {};
  26196. this.targetPropertyPath = targetProperty.split(".");
  26197. this.dataType = dataType;
  26198. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  26199. }
  26200. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  26201. var dataType = undefined;
  26202. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  26203. dataType = Animation.ANIMATIONTYPE_FLOAT;
  26204. }
  26205. else if (from instanceof BABYLON.Quaternion) {
  26206. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  26207. }
  26208. else if (from instanceof BABYLON.Vector3) {
  26209. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  26210. }
  26211. else if (from instanceof BABYLON.Vector2) {
  26212. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  26213. }
  26214. else if (from instanceof BABYLON.Color3) {
  26215. dataType = Animation.ANIMATIONTYPE_COLOR3;
  26216. }
  26217. else if (from instanceof BABYLON.Size) {
  26218. dataType = Animation.ANIMATIONTYPE_SIZE;
  26219. }
  26220. if (dataType == undefined) {
  26221. return null;
  26222. }
  26223. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  26224. var keys = [];
  26225. keys.push({ frame: 0, value: from });
  26226. keys.push({ frame: totalFrame, value: to });
  26227. animation.setKeys(keys);
  26228. if (easingFunction !== undefined) {
  26229. animation.setEasingFunction(easingFunction);
  26230. }
  26231. return animation;
  26232. };
  26233. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  26234. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  26235. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  26236. };
  26237. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  26238. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  26239. node.animations.push(animation);
  26240. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  26241. };
  26242. // Methods
  26243. /**
  26244. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26245. */
  26246. Animation.prototype.toString = function (fullDetails) {
  26247. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  26248. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  26249. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  26250. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26251. if (fullDetails) {
  26252. ret += ", Ranges: {";
  26253. var first = true;
  26254. for (var name in this._ranges) {
  26255. if (first) {
  26256. ret += ", ";
  26257. first = false;
  26258. }
  26259. ret += name;
  26260. }
  26261. ret += "}";
  26262. }
  26263. return ret;
  26264. };
  26265. /**
  26266. * Add an event to this animation.
  26267. */
  26268. Animation.prototype.addEvent = function (event) {
  26269. this._events.push(event);
  26270. };
  26271. /**
  26272. * Remove all events found at the given frame
  26273. * @param frame
  26274. */
  26275. Animation.prototype.removeEvents = function (frame) {
  26276. for (var index = 0; index < this._events.length; index++) {
  26277. if (this._events[index].frame === frame) {
  26278. this._events.splice(index, 1);
  26279. index--;
  26280. }
  26281. }
  26282. };
  26283. Animation.prototype.createRange = function (name, from, to) {
  26284. // check name not already in use; could happen for bones after serialized
  26285. if (!this._ranges[name]) {
  26286. this._ranges[name] = new AnimationRange(name, from, to);
  26287. }
  26288. };
  26289. Animation.prototype.deleteRange = function (name, deleteFrames) {
  26290. if (deleteFrames === void 0) { deleteFrames = true; }
  26291. if (this._ranges[name]) {
  26292. if (deleteFrames) {
  26293. var from = this._ranges[name].from;
  26294. var to = this._ranges[name].to;
  26295. // this loop MUST go high to low for multiple splices to work
  26296. for (var key = this._keys.length - 1; key >= 0; key--) {
  26297. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  26298. this._keys.splice(key, 1);
  26299. }
  26300. }
  26301. }
  26302. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26303. }
  26304. };
  26305. Animation.prototype.getRange = function (name) {
  26306. return this._ranges[name];
  26307. };
  26308. Animation.prototype.reset = function () {
  26309. this._offsetsCache = {};
  26310. this._highLimitsCache = {};
  26311. this.currentFrame = 0;
  26312. this._blendingFactor = 0;
  26313. this._originalBlendValue = null;
  26314. };
  26315. Animation.prototype.isStopped = function () {
  26316. return this._stopped;
  26317. };
  26318. Animation.prototype.getKeys = function () {
  26319. return this._keys;
  26320. };
  26321. Animation.prototype.getHighestFrame = function () {
  26322. var ret = 0;
  26323. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  26324. if (ret < this._keys[key].frame) {
  26325. ret = this._keys[key].frame;
  26326. }
  26327. }
  26328. return ret;
  26329. };
  26330. Animation.prototype.getEasingFunction = function () {
  26331. return this._easingFunction;
  26332. };
  26333. Animation.prototype.setEasingFunction = function (easingFunction) {
  26334. this._easingFunction = easingFunction;
  26335. };
  26336. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  26337. return startValue + (endValue - startValue) * gradient;
  26338. };
  26339. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  26340. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  26341. };
  26342. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  26343. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  26344. };
  26345. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  26346. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  26347. };
  26348. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  26349. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  26350. };
  26351. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  26352. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  26353. };
  26354. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  26355. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  26356. };
  26357. Animation.prototype.clone = function () {
  26358. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  26359. if (this._keys) {
  26360. clone.setKeys(this._keys);
  26361. }
  26362. if (this._ranges) {
  26363. clone._ranges = {};
  26364. for (var name in this._ranges) {
  26365. clone._ranges[name] = this._ranges[name].clone();
  26366. }
  26367. }
  26368. return clone;
  26369. };
  26370. Animation.prototype.setKeys = function (values) {
  26371. this._keys = values.slice(0);
  26372. this._offsetsCache = {};
  26373. this._highLimitsCache = {};
  26374. };
  26375. Animation.prototype._getKeyValue = function (value) {
  26376. if (typeof value === "function") {
  26377. return value();
  26378. }
  26379. return value;
  26380. };
  26381. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  26382. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  26383. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  26384. }
  26385. this.currentFrame = currentFrame;
  26386. // Try to get a hash to find the right key
  26387. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  26388. if (this._keys[startKey].frame >= currentFrame) {
  26389. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  26390. startKey--;
  26391. }
  26392. }
  26393. for (var key = startKey; key < this._keys.length; key++) {
  26394. if (this._keys[key + 1].frame >= currentFrame) {
  26395. var startValue = this._getKeyValue(this._keys[key].value);
  26396. var endValue = this._getKeyValue(this._keys[key + 1].value);
  26397. // gradient : percent of currentFrame between the frame inf and the frame sup
  26398. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  26399. // check for easingFunction and correction of gradient
  26400. if (this._easingFunction != null) {
  26401. gradient = this._easingFunction.ease(gradient);
  26402. }
  26403. switch (this.dataType) {
  26404. // Float
  26405. case Animation.ANIMATIONTYPE_FLOAT:
  26406. switch (loopMode) {
  26407. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26408. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26409. return this.floatInterpolateFunction(startValue, endValue, gradient);
  26410. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26411. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  26412. }
  26413. break;
  26414. // Quaternion
  26415. case Animation.ANIMATIONTYPE_QUATERNION:
  26416. var quaternion = null;
  26417. switch (loopMode) {
  26418. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26419. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26420. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  26421. break;
  26422. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26423. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26424. break;
  26425. }
  26426. return quaternion;
  26427. // Vector3
  26428. case Animation.ANIMATIONTYPE_VECTOR3:
  26429. switch (loopMode) {
  26430. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26431. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26432. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  26433. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26434. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26435. }
  26436. // Vector2
  26437. case Animation.ANIMATIONTYPE_VECTOR2:
  26438. switch (loopMode) {
  26439. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26440. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26441. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  26442. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26443. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26444. }
  26445. // Size
  26446. case Animation.ANIMATIONTYPE_SIZE:
  26447. switch (loopMode) {
  26448. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26449. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26450. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  26451. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26452. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26453. }
  26454. // Color3
  26455. case Animation.ANIMATIONTYPE_COLOR3:
  26456. switch (loopMode) {
  26457. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26458. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26459. return this.color3InterpolateFunction(startValue, endValue, gradient);
  26460. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26461. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26462. }
  26463. // Matrix
  26464. case Animation.ANIMATIONTYPE_MATRIX:
  26465. switch (loopMode) {
  26466. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26467. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26468. if (this.allowMatricesInterpolation) {
  26469. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  26470. }
  26471. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26472. return startValue;
  26473. }
  26474. default:
  26475. break;
  26476. }
  26477. break;
  26478. }
  26479. }
  26480. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  26481. };
  26482. Animation.prototype.setValue = function (currentValue, blend) {
  26483. if (blend === void 0) { blend = false; }
  26484. // Set value
  26485. var path;
  26486. var destination;
  26487. if (this.targetPropertyPath.length > 1) {
  26488. var property = this._target[this.targetPropertyPath[0]];
  26489. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  26490. property = property[this.targetPropertyPath[index]];
  26491. }
  26492. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  26493. destination = property;
  26494. }
  26495. else {
  26496. path = this.targetPropertyPath[0];
  26497. destination = this._target;
  26498. }
  26499. // Blending
  26500. if (this.enableBlending && this._blendingFactor <= 1.0) {
  26501. if (!this._originalBlendValue) {
  26502. if (destination[path].clone) {
  26503. this._originalBlendValue = destination[path].clone();
  26504. }
  26505. else {
  26506. this._originalBlendValue = destination[path];
  26507. }
  26508. }
  26509. if (this._originalBlendValue.prototype) {
  26510. if (this._originalBlendValue.prototype.Lerp) {
  26511. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  26512. }
  26513. else {
  26514. destination[path] = currentValue;
  26515. }
  26516. }
  26517. else if (this._originalBlendValue.m) {
  26518. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  26519. }
  26520. else {
  26521. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  26522. }
  26523. this._blendingFactor += this.blendingSpeed;
  26524. }
  26525. else {
  26526. destination[path] = currentValue;
  26527. }
  26528. if (this._target.markAsDirty) {
  26529. this._target.markAsDirty(this.targetProperty);
  26530. }
  26531. };
  26532. Animation.prototype.goToFrame = function (frame) {
  26533. if (frame < this._keys[0].frame) {
  26534. frame = this._keys[0].frame;
  26535. }
  26536. else if (frame > this._keys[this._keys.length - 1].frame) {
  26537. frame = this._keys[this._keys.length - 1].frame;
  26538. }
  26539. var currentValue = this._interpolate(frame, 0, this.loopMode);
  26540. this.setValue(currentValue);
  26541. };
  26542. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  26543. if (blend === void 0) { blend = false; }
  26544. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  26545. this._stopped = true;
  26546. return false;
  26547. }
  26548. var returnValue = true;
  26549. // Adding a start key at frame 0 if missing
  26550. if (this._keys[0].frame !== 0) {
  26551. var newKey = { frame: 0, value: this._keys[0].value };
  26552. this._keys.splice(0, 0, newKey);
  26553. }
  26554. // Check limits
  26555. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  26556. from = this._keys[0].frame;
  26557. }
  26558. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  26559. to = this._keys[this._keys.length - 1].frame;
  26560. }
  26561. // Compute ratio
  26562. var range = to - from;
  26563. var offsetValue;
  26564. // ratio represents the frame delta between from and to
  26565. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  26566. var highLimitValue = 0;
  26567. if (ratio > range && !loop) {
  26568. returnValue = false;
  26569. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  26570. }
  26571. else {
  26572. // Get max value if required
  26573. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  26574. var keyOffset = to.toString() + from.toString();
  26575. if (!this._offsetsCache[keyOffset]) {
  26576. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  26577. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  26578. switch (this.dataType) {
  26579. // Float
  26580. case Animation.ANIMATIONTYPE_FLOAT:
  26581. this._offsetsCache[keyOffset] = toValue - fromValue;
  26582. break;
  26583. // Quaternion
  26584. case Animation.ANIMATIONTYPE_QUATERNION:
  26585. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26586. break;
  26587. // Vector3
  26588. case Animation.ANIMATIONTYPE_VECTOR3:
  26589. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26590. // Vector2
  26591. case Animation.ANIMATIONTYPE_VECTOR2:
  26592. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26593. // Size
  26594. case Animation.ANIMATIONTYPE_SIZE:
  26595. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26596. // Color3
  26597. case Animation.ANIMATIONTYPE_COLOR3:
  26598. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26599. default:
  26600. break;
  26601. }
  26602. this._highLimitsCache[keyOffset] = toValue;
  26603. }
  26604. highLimitValue = this._highLimitsCache[keyOffset];
  26605. offsetValue = this._offsetsCache[keyOffset];
  26606. }
  26607. }
  26608. if (offsetValue === undefined) {
  26609. switch (this.dataType) {
  26610. // Float
  26611. case Animation.ANIMATIONTYPE_FLOAT:
  26612. offsetValue = 0;
  26613. break;
  26614. // Quaternion
  26615. case Animation.ANIMATIONTYPE_QUATERNION:
  26616. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  26617. break;
  26618. // Vector3
  26619. case Animation.ANIMATIONTYPE_VECTOR3:
  26620. offsetValue = BABYLON.Vector3.Zero();
  26621. break;
  26622. // Vector2
  26623. case Animation.ANIMATIONTYPE_VECTOR2:
  26624. offsetValue = BABYLON.Vector2.Zero();
  26625. break;
  26626. // Size
  26627. case Animation.ANIMATIONTYPE_SIZE:
  26628. offsetValue = BABYLON.Size.Zero();
  26629. break;
  26630. // Color3
  26631. case Animation.ANIMATIONTYPE_COLOR3:
  26632. offsetValue = BABYLON.Color3.Black();
  26633. }
  26634. }
  26635. // Compute value
  26636. var repeatCount = (ratio / range) >> 0;
  26637. var currentFrame = returnValue ? from + ratio % range : to;
  26638. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  26639. // Set value
  26640. this.setValue(currentValue);
  26641. // Check events
  26642. for (var index = 0; index < this._events.length; index++) {
  26643. if (currentFrame >= this._events[index].frame) {
  26644. var event = this._events[index];
  26645. if (!event.isDone) {
  26646. // If event should be done only once, remove it.
  26647. if (event.onlyOnce) {
  26648. this._events.splice(index, 1);
  26649. index--;
  26650. }
  26651. event.isDone = true;
  26652. event.action();
  26653. } // Don't do anything if the event has already be done.
  26654. }
  26655. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  26656. // reset event, the animation is looping
  26657. this._events[index].isDone = false;
  26658. }
  26659. }
  26660. if (!returnValue) {
  26661. this._stopped = true;
  26662. }
  26663. return returnValue;
  26664. };
  26665. Animation.prototype.serialize = function () {
  26666. var serializationObject = {};
  26667. serializationObject.name = this.name;
  26668. serializationObject.property = this.targetProperty;
  26669. serializationObject.framePerSecond = this.framePerSecond;
  26670. serializationObject.dataType = this.dataType;
  26671. serializationObject.loopBehavior = this.loopMode;
  26672. var dataType = this.dataType;
  26673. serializationObject.keys = [];
  26674. var keys = this.getKeys();
  26675. for (var index = 0; index < keys.length; index++) {
  26676. var animationKey = keys[index];
  26677. var key = {};
  26678. key.frame = animationKey.frame;
  26679. switch (dataType) {
  26680. case Animation.ANIMATIONTYPE_FLOAT:
  26681. key.values = [animationKey.value];
  26682. break;
  26683. case Animation.ANIMATIONTYPE_QUATERNION:
  26684. case Animation.ANIMATIONTYPE_MATRIX:
  26685. case Animation.ANIMATIONTYPE_VECTOR3:
  26686. case Animation.ANIMATIONTYPE_COLOR3:
  26687. key.values = animationKey.value.asArray();
  26688. break;
  26689. }
  26690. serializationObject.keys.push(key);
  26691. }
  26692. serializationObject.ranges = [];
  26693. for (var name in this._ranges) {
  26694. var range = {};
  26695. range.name = name;
  26696. range.from = this._ranges[name].from;
  26697. range.to = this._ranges[name].to;
  26698. serializationObject.ranges.push(range);
  26699. }
  26700. return serializationObject;
  26701. };
  26702. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  26703. get: function () {
  26704. return Animation._ANIMATIONTYPE_FLOAT;
  26705. },
  26706. enumerable: true,
  26707. configurable: true
  26708. });
  26709. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  26710. get: function () {
  26711. return Animation._ANIMATIONTYPE_VECTOR3;
  26712. },
  26713. enumerable: true,
  26714. configurable: true
  26715. });
  26716. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  26717. get: function () {
  26718. return Animation._ANIMATIONTYPE_VECTOR2;
  26719. },
  26720. enumerable: true,
  26721. configurable: true
  26722. });
  26723. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  26724. get: function () {
  26725. return Animation._ANIMATIONTYPE_SIZE;
  26726. },
  26727. enumerable: true,
  26728. configurable: true
  26729. });
  26730. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  26731. get: function () {
  26732. return Animation._ANIMATIONTYPE_QUATERNION;
  26733. },
  26734. enumerable: true,
  26735. configurable: true
  26736. });
  26737. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  26738. get: function () {
  26739. return Animation._ANIMATIONTYPE_MATRIX;
  26740. },
  26741. enumerable: true,
  26742. configurable: true
  26743. });
  26744. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  26745. get: function () {
  26746. return Animation._ANIMATIONTYPE_COLOR3;
  26747. },
  26748. enumerable: true,
  26749. configurable: true
  26750. });
  26751. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  26752. get: function () {
  26753. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  26754. },
  26755. enumerable: true,
  26756. configurable: true
  26757. });
  26758. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  26759. get: function () {
  26760. return Animation._ANIMATIONLOOPMODE_CYCLE;
  26761. },
  26762. enumerable: true,
  26763. configurable: true
  26764. });
  26765. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  26766. get: function () {
  26767. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  26768. },
  26769. enumerable: true,
  26770. configurable: true
  26771. });
  26772. Animation.Parse = function (parsedAnimation) {
  26773. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  26774. var dataType = parsedAnimation.dataType;
  26775. var keys = [];
  26776. var data;
  26777. var index;
  26778. for (index = 0; index < parsedAnimation.keys.length; index++) {
  26779. var key = parsedAnimation.keys[index];
  26780. switch (dataType) {
  26781. case Animation.ANIMATIONTYPE_FLOAT:
  26782. data = key.values[0];
  26783. break;
  26784. case Animation.ANIMATIONTYPE_QUATERNION:
  26785. data = BABYLON.Quaternion.FromArray(key.values);
  26786. break;
  26787. case Animation.ANIMATIONTYPE_MATRIX:
  26788. data = BABYLON.Matrix.FromArray(key.values);
  26789. break;
  26790. case Animation.ANIMATIONTYPE_COLOR3:
  26791. data = BABYLON.Color3.FromArray(key.values);
  26792. break;
  26793. case Animation.ANIMATIONTYPE_VECTOR3:
  26794. default:
  26795. data = BABYLON.Vector3.FromArray(key.values);
  26796. break;
  26797. }
  26798. keys.push({
  26799. frame: key.frame,
  26800. value: data
  26801. });
  26802. }
  26803. animation.setKeys(keys);
  26804. if (parsedAnimation.ranges) {
  26805. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  26806. data = parsedAnimation.ranges[index];
  26807. animation.createRange(data.name, data.from, data.to);
  26808. }
  26809. }
  26810. return animation;
  26811. };
  26812. Animation.AppendSerializedAnimations = function (source, destination) {
  26813. if (source.animations) {
  26814. destination.animations = [];
  26815. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  26816. var animation = source.animations[animationIndex];
  26817. destination.animations.push(animation.serialize());
  26818. }
  26819. }
  26820. };
  26821. // Statics
  26822. Animation._ANIMATIONTYPE_FLOAT = 0;
  26823. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  26824. Animation._ANIMATIONTYPE_QUATERNION = 2;
  26825. Animation._ANIMATIONTYPE_MATRIX = 3;
  26826. Animation._ANIMATIONTYPE_COLOR3 = 4;
  26827. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  26828. Animation._ANIMATIONTYPE_SIZE = 6;
  26829. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  26830. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  26831. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  26832. return Animation;
  26833. })();
  26834. BABYLON.Animation = Animation;
  26835. })(BABYLON || (BABYLON = {}));
  26836. var BABYLON;
  26837. (function (BABYLON) {
  26838. var Animatable = (function () {
  26839. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  26840. if (fromFrame === void 0) { fromFrame = 0; }
  26841. if (toFrame === void 0) { toFrame = 100; }
  26842. if (loopAnimation === void 0) { loopAnimation = false; }
  26843. if (speedRatio === void 0) { speedRatio = 1.0; }
  26844. this.target = target;
  26845. this.fromFrame = fromFrame;
  26846. this.toFrame = toFrame;
  26847. this.loopAnimation = loopAnimation;
  26848. this.speedRatio = speedRatio;
  26849. this.onAnimationEnd = onAnimationEnd;
  26850. this._animations = new Array();
  26851. this._paused = false;
  26852. this.animationStarted = false;
  26853. if (animations) {
  26854. this.appendAnimations(target, animations);
  26855. }
  26856. this._scene = scene;
  26857. scene._activeAnimatables.push(this);
  26858. }
  26859. // Methods
  26860. Animatable.prototype.getAnimations = function () {
  26861. return this._animations;
  26862. };
  26863. Animatable.prototype.appendAnimations = function (target, animations) {
  26864. for (var index = 0; index < animations.length; index++) {
  26865. var animation = animations[index];
  26866. animation._target = target;
  26867. this._animations.push(animation);
  26868. }
  26869. };
  26870. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  26871. var animations = this._animations;
  26872. for (var index = 0; index < animations.length; index++) {
  26873. if (animations[index].targetProperty === property) {
  26874. return animations[index];
  26875. }
  26876. }
  26877. return null;
  26878. };
  26879. Animatable.prototype.reset = function () {
  26880. var animations = this._animations;
  26881. for (var index = 0; index < animations.length; index++) {
  26882. animations[index].reset();
  26883. }
  26884. this._localDelayOffset = null;
  26885. this._pausedDelay = null;
  26886. };
  26887. Animatable.prototype.enableBlending = function (blendingSpeed) {
  26888. var animations = this._animations;
  26889. for (var index = 0; index < animations.length; index++) {
  26890. animations[index].enableBlending = true;
  26891. animations[index].blendingSpeed = blendingSpeed;
  26892. }
  26893. };
  26894. Animatable.prototype.disableBlending = function () {
  26895. var animations = this._animations;
  26896. for (var index = 0; index < animations.length; index++) {
  26897. animations[index].enableBlending = false;
  26898. }
  26899. };
  26900. Animatable.prototype.goToFrame = function (frame) {
  26901. var animations = this._animations;
  26902. for (var index = 0; index < animations.length; index++) {
  26903. animations[index].goToFrame(frame);
  26904. }
  26905. };
  26906. Animatable.prototype.pause = function () {
  26907. if (this._paused) {
  26908. return;
  26909. }
  26910. this._paused = true;
  26911. };
  26912. Animatable.prototype.restart = function () {
  26913. this._paused = false;
  26914. };
  26915. Animatable.prototype.stop = function () {
  26916. var index = this._scene._activeAnimatables.indexOf(this);
  26917. if (index > -1) {
  26918. this._scene._activeAnimatables.splice(index, 1);
  26919. var animations = this._animations;
  26920. for (var index = 0; index < animations.length; index++) {
  26921. animations[index].reset();
  26922. }
  26923. if (this.onAnimationEnd) {
  26924. this.onAnimationEnd();
  26925. }
  26926. }
  26927. };
  26928. Animatable.prototype._animate = function (delay) {
  26929. if (this._paused) {
  26930. this.animationStarted = false;
  26931. if (!this._pausedDelay) {
  26932. this._pausedDelay = delay;
  26933. }
  26934. return true;
  26935. }
  26936. if (!this._localDelayOffset) {
  26937. this._localDelayOffset = delay;
  26938. }
  26939. else if (this._pausedDelay) {
  26940. this._localDelayOffset += delay - this._pausedDelay;
  26941. this._pausedDelay = null;
  26942. }
  26943. // Animating
  26944. var running = false;
  26945. var animations = this._animations;
  26946. var index;
  26947. for (index = 0; index < animations.length; index++) {
  26948. var animation = animations[index];
  26949. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  26950. running = running || isRunning;
  26951. }
  26952. this.animationStarted = running;
  26953. if (!running) {
  26954. // Remove from active animatables
  26955. index = this._scene._activeAnimatables.indexOf(this);
  26956. this._scene._activeAnimatables.splice(index, 1);
  26957. }
  26958. if (!running && this.onAnimationEnd) {
  26959. this.onAnimationEnd();
  26960. this.onAnimationEnd = null;
  26961. }
  26962. return running;
  26963. };
  26964. return Animatable;
  26965. })();
  26966. BABYLON.Animatable = Animatable;
  26967. })(BABYLON || (BABYLON = {}));
  26968. var BABYLON;
  26969. (function (BABYLON) {
  26970. var EasingFunction = (function () {
  26971. function EasingFunction() {
  26972. // Properties
  26973. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  26974. }
  26975. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  26976. get: function () {
  26977. return EasingFunction._EASINGMODE_EASEIN;
  26978. },
  26979. enumerable: true,
  26980. configurable: true
  26981. });
  26982. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  26983. get: function () {
  26984. return EasingFunction._EASINGMODE_EASEOUT;
  26985. },
  26986. enumerable: true,
  26987. configurable: true
  26988. });
  26989. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  26990. get: function () {
  26991. return EasingFunction._EASINGMODE_EASEINOUT;
  26992. },
  26993. enumerable: true,
  26994. configurable: true
  26995. });
  26996. EasingFunction.prototype.setEasingMode = function (easingMode) {
  26997. var n = Math.min(Math.max(easingMode, 0), 2);
  26998. this._easingMode = n;
  26999. };
  27000. EasingFunction.prototype.getEasingMode = function () {
  27001. return this._easingMode;
  27002. };
  27003. EasingFunction.prototype.easeInCore = function (gradient) {
  27004. throw new Error('You must implement this method');
  27005. };
  27006. EasingFunction.prototype.ease = function (gradient) {
  27007. switch (this._easingMode) {
  27008. case EasingFunction.EASINGMODE_EASEIN:
  27009. return this.easeInCore(gradient);
  27010. case EasingFunction.EASINGMODE_EASEOUT:
  27011. return (1 - this.easeInCore(1 - gradient));
  27012. }
  27013. if (gradient >= 0.5) {
  27014. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  27015. }
  27016. return (this.easeInCore(gradient * 2) * 0.5);
  27017. };
  27018. //Statics
  27019. EasingFunction._EASINGMODE_EASEIN = 0;
  27020. EasingFunction._EASINGMODE_EASEOUT = 1;
  27021. EasingFunction._EASINGMODE_EASEINOUT = 2;
  27022. return EasingFunction;
  27023. })();
  27024. BABYLON.EasingFunction = EasingFunction;
  27025. var CircleEase = (function (_super) {
  27026. __extends(CircleEase, _super);
  27027. function CircleEase() {
  27028. _super.apply(this, arguments);
  27029. }
  27030. CircleEase.prototype.easeInCore = function (gradient) {
  27031. gradient = Math.max(0, Math.min(1, gradient));
  27032. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  27033. };
  27034. return CircleEase;
  27035. })(EasingFunction);
  27036. BABYLON.CircleEase = CircleEase;
  27037. var BackEase = (function (_super) {
  27038. __extends(BackEase, _super);
  27039. function BackEase(amplitude) {
  27040. if (amplitude === void 0) { amplitude = 1; }
  27041. _super.call(this);
  27042. this.amplitude = amplitude;
  27043. }
  27044. BackEase.prototype.easeInCore = function (gradient) {
  27045. var num = Math.max(0, this.amplitude);
  27046. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  27047. };
  27048. return BackEase;
  27049. })(EasingFunction);
  27050. BABYLON.BackEase = BackEase;
  27051. var BounceEase = (function (_super) {
  27052. __extends(BounceEase, _super);
  27053. function BounceEase(bounces, bounciness) {
  27054. if (bounces === void 0) { bounces = 3; }
  27055. if (bounciness === void 0) { bounciness = 2; }
  27056. _super.call(this);
  27057. this.bounces = bounces;
  27058. this.bounciness = bounciness;
  27059. }
  27060. BounceEase.prototype.easeInCore = function (gradient) {
  27061. var y = Math.max(0.0, this.bounces);
  27062. var bounciness = this.bounciness;
  27063. if (bounciness <= 1.0) {
  27064. bounciness = 1.001;
  27065. }
  27066. var num9 = Math.pow(bounciness, y);
  27067. var num5 = 1.0 - bounciness;
  27068. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  27069. var num15 = gradient * num4;
  27070. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  27071. var num3 = Math.floor(num65);
  27072. var num13 = num3 + 1.0;
  27073. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  27074. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  27075. var num7 = (num8 + num12) * 0.5;
  27076. var num6 = gradient - num7;
  27077. var num2 = num7 - num8;
  27078. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  27079. };
  27080. return BounceEase;
  27081. })(EasingFunction);
  27082. BABYLON.BounceEase = BounceEase;
  27083. var CubicEase = (function (_super) {
  27084. __extends(CubicEase, _super);
  27085. function CubicEase() {
  27086. _super.apply(this, arguments);
  27087. }
  27088. CubicEase.prototype.easeInCore = function (gradient) {
  27089. return (gradient * gradient * gradient);
  27090. };
  27091. return CubicEase;
  27092. })(EasingFunction);
  27093. BABYLON.CubicEase = CubicEase;
  27094. var ElasticEase = (function (_super) {
  27095. __extends(ElasticEase, _super);
  27096. function ElasticEase(oscillations, springiness) {
  27097. if (oscillations === void 0) { oscillations = 3; }
  27098. if (springiness === void 0) { springiness = 3; }
  27099. _super.call(this);
  27100. this.oscillations = oscillations;
  27101. this.springiness = springiness;
  27102. }
  27103. ElasticEase.prototype.easeInCore = function (gradient) {
  27104. var num2;
  27105. var num3 = Math.max(0.0, this.oscillations);
  27106. var num = Math.max(0.0, this.springiness);
  27107. if (num == 0) {
  27108. num2 = gradient;
  27109. }
  27110. else {
  27111. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  27112. }
  27113. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  27114. };
  27115. return ElasticEase;
  27116. })(EasingFunction);
  27117. BABYLON.ElasticEase = ElasticEase;
  27118. var ExponentialEase = (function (_super) {
  27119. __extends(ExponentialEase, _super);
  27120. function ExponentialEase(exponent) {
  27121. if (exponent === void 0) { exponent = 2; }
  27122. _super.call(this);
  27123. this.exponent = exponent;
  27124. }
  27125. ExponentialEase.prototype.easeInCore = function (gradient) {
  27126. if (this.exponent <= 0) {
  27127. return gradient;
  27128. }
  27129. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  27130. };
  27131. return ExponentialEase;
  27132. })(EasingFunction);
  27133. BABYLON.ExponentialEase = ExponentialEase;
  27134. var PowerEase = (function (_super) {
  27135. __extends(PowerEase, _super);
  27136. function PowerEase(power) {
  27137. if (power === void 0) { power = 2; }
  27138. _super.call(this);
  27139. this.power = power;
  27140. }
  27141. PowerEase.prototype.easeInCore = function (gradient) {
  27142. var y = Math.max(0.0, this.power);
  27143. return Math.pow(gradient, y);
  27144. };
  27145. return PowerEase;
  27146. })(EasingFunction);
  27147. BABYLON.PowerEase = PowerEase;
  27148. var QuadraticEase = (function (_super) {
  27149. __extends(QuadraticEase, _super);
  27150. function QuadraticEase() {
  27151. _super.apply(this, arguments);
  27152. }
  27153. QuadraticEase.prototype.easeInCore = function (gradient) {
  27154. return (gradient * gradient);
  27155. };
  27156. return QuadraticEase;
  27157. })(EasingFunction);
  27158. BABYLON.QuadraticEase = QuadraticEase;
  27159. var QuarticEase = (function (_super) {
  27160. __extends(QuarticEase, _super);
  27161. function QuarticEase() {
  27162. _super.apply(this, arguments);
  27163. }
  27164. QuarticEase.prototype.easeInCore = function (gradient) {
  27165. return (gradient * gradient * gradient * gradient);
  27166. };
  27167. return QuarticEase;
  27168. })(EasingFunction);
  27169. BABYLON.QuarticEase = QuarticEase;
  27170. var QuinticEase = (function (_super) {
  27171. __extends(QuinticEase, _super);
  27172. function QuinticEase() {
  27173. _super.apply(this, arguments);
  27174. }
  27175. QuinticEase.prototype.easeInCore = function (gradient) {
  27176. return (gradient * gradient * gradient * gradient * gradient);
  27177. };
  27178. return QuinticEase;
  27179. })(EasingFunction);
  27180. BABYLON.QuinticEase = QuinticEase;
  27181. var SineEase = (function (_super) {
  27182. __extends(SineEase, _super);
  27183. function SineEase() {
  27184. _super.apply(this, arguments);
  27185. }
  27186. SineEase.prototype.easeInCore = function (gradient) {
  27187. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  27188. };
  27189. return SineEase;
  27190. })(EasingFunction);
  27191. BABYLON.SineEase = SineEase;
  27192. var BezierCurveEase = (function (_super) {
  27193. __extends(BezierCurveEase, _super);
  27194. function BezierCurveEase(x1, y1, x2, y2) {
  27195. if (x1 === void 0) { x1 = 0; }
  27196. if (y1 === void 0) { y1 = 0; }
  27197. if (x2 === void 0) { x2 = 1; }
  27198. if (y2 === void 0) { y2 = 1; }
  27199. _super.call(this);
  27200. this.x1 = x1;
  27201. this.y1 = y1;
  27202. this.x2 = x2;
  27203. this.y2 = y2;
  27204. }
  27205. BezierCurveEase.prototype.easeInCore = function (gradient) {
  27206. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  27207. };
  27208. return BezierCurveEase;
  27209. })(EasingFunction);
  27210. BABYLON.BezierCurveEase = BezierCurveEase;
  27211. })(BABYLON || (BABYLON = {}));
  27212. var BABYLON;
  27213. (function (BABYLON) {
  27214. var Bone = (function (_super) {
  27215. __extends(Bone, _super);
  27216. function Bone(name, skeleton, parentBone, matrix, restPose) {
  27217. _super.call(this, name, skeleton.getScene());
  27218. this.name = name;
  27219. this.children = new Array();
  27220. this.animations = new Array();
  27221. this._worldTransform = new BABYLON.Matrix();
  27222. this._absoluteTransform = new BABYLON.Matrix();
  27223. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  27224. this._skeleton = skeleton;
  27225. this._matrix = matrix;
  27226. this._baseMatrix = matrix;
  27227. this._restPose = restPose ? restPose : matrix.clone();
  27228. skeleton.bones.push(this);
  27229. if (parentBone) {
  27230. this._parent = parentBone;
  27231. parentBone.children.push(this);
  27232. }
  27233. else {
  27234. this._parent = null;
  27235. }
  27236. this._updateDifferenceMatrix();
  27237. }
  27238. // Members
  27239. Bone.prototype.getParent = function () {
  27240. return this._parent;
  27241. };
  27242. Bone.prototype.getLocalMatrix = function () {
  27243. return this._matrix;
  27244. };
  27245. Bone.prototype.getBaseMatrix = function () {
  27246. return this._baseMatrix;
  27247. };
  27248. Bone.prototype.getRestPose = function () {
  27249. return this._restPose;
  27250. };
  27251. Bone.prototype.returnToRest = function () {
  27252. this.updateMatrix(this._restPose.clone());
  27253. };
  27254. Bone.prototype.getWorldMatrix = function () {
  27255. return this._worldTransform;
  27256. };
  27257. Bone.prototype.getInvertedAbsoluteTransform = function () {
  27258. return this._invertedAbsoluteTransform;
  27259. };
  27260. Bone.prototype.getAbsoluteTransform = function () {
  27261. return this._absoluteTransform;
  27262. };
  27263. // Methods
  27264. Bone.prototype.updateMatrix = function (matrix) {
  27265. this._baseMatrix = matrix.clone();
  27266. this._matrix = matrix.clone();
  27267. this._skeleton._markAsDirty();
  27268. this._updateDifferenceMatrix();
  27269. };
  27270. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  27271. if (!rootMatrix) {
  27272. rootMatrix = this._baseMatrix;
  27273. }
  27274. if (this._parent) {
  27275. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  27276. }
  27277. else {
  27278. this._absoluteTransform.copyFrom(rootMatrix);
  27279. }
  27280. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  27281. for (var index = 0; index < this.children.length; index++) {
  27282. this.children[index]._updateDifferenceMatrix();
  27283. }
  27284. };
  27285. Bone.prototype.markAsDirty = function () {
  27286. this._currentRenderId++;
  27287. this._skeleton._markAsDirty();
  27288. };
  27289. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  27290. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  27291. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  27292. // all animation may be coming from a library skeleton, so may need to create animation
  27293. if (this.animations.length === 0) {
  27294. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  27295. this.animations[0].setKeys([]);
  27296. }
  27297. // get animation info / verify there is such a range from the source bone
  27298. var sourceRange = source.animations[0].getRange(rangeName);
  27299. if (!sourceRange) {
  27300. return false;
  27301. }
  27302. var from = sourceRange.from;
  27303. var to = sourceRange.to;
  27304. var sourceKeys = source.animations[0].getKeys();
  27305. // rescaling prep
  27306. var sourceBoneLength = source.length;
  27307. var sourceParent = source.getParent();
  27308. var parent = this.getParent();
  27309. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  27310. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  27311. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  27312. var destKeys = this.animations[0].getKeys();
  27313. // loop vars declaration
  27314. var orig;
  27315. var origTranslation;
  27316. var mat;
  27317. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  27318. orig = sourceKeys[key];
  27319. if (orig.frame >= from && orig.frame <= to) {
  27320. if (rescaleAsRequired) {
  27321. mat = orig.value.clone();
  27322. // scale based on parent ratio, when bone has parent
  27323. if (parentScalingReqd) {
  27324. origTranslation = mat.getTranslation();
  27325. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  27326. }
  27327. else if (dimensionsScalingReqd) {
  27328. origTranslation = mat.getTranslation();
  27329. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  27330. }
  27331. else {
  27332. mat = orig.value;
  27333. }
  27334. }
  27335. else {
  27336. mat = orig.value;
  27337. }
  27338. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  27339. }
  27340. }
  27341. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  27342. return true;
  27343. };
  27344. return Bone;
  27345. })(BABYLON.Node);
  27346. BABYLON.Bone = Bone;
  27347. })(BABYLON || (BABYLON = {}));
  27348. var BABYLON;
  27349. (function (BABYLON) {
  27350. var Skeleton = (function () {
  27351. function Skeleton(name, id, scene) {
  27352. this.name = name;
  27353. this.id = id;
  27354. this.bones = new Array();
  27355. this.needInitialSkinMatrix = false;
  27356. this._isDirty = true;
  27357. this._meshesWithPoseMatrix = new Array();
  27358. this._identity = BABYLON.Matrix.Identity();
  27359. this._ranges = {};
  27360. this.bones = [];
  27361. this._scene = scene;
  27362. scene.skeletons.push(this);
  27363. //make sure it will recalculate the matrix next time prepare is called.
  27364. this._isDirty = true;
  27365. }
  27366. // Members
  27367. Skeleton.prototype.getTransformMatrices = function (mesh) {
  27368. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  27369. return mesh._bonesTransformMatrices;
  27370. }
  27371. return this._transformMatrices;
  27372. };
  27373. Skeleton.prototype.getScene = function () {
  27374. return this._scene;
  27375. };
  27376. // Methods
  27377. /**
  27378. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27379. */
  27380. Skeleton.prototype.toString = function (fullDetails) {
  27381. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  27382. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  27383. if (fullDetails) {
  27384. ret += ", Ranges: {";
  27385. var first = true;
  27386. for (var name_1 in this._ranges) {
  27387. if (first) {
  27388. ret += ", ";
  27389. first = false;
  27390. }
  27391. ret += name_1;
  27392. }
  27393. ret += "}";
  27394. }
  27395. return ret;
  27396. };
  27397. /**
  27398. * Get bone's index searching by name
  27399. * @param {string} name is bone's name to search for
  27400. * @return {number} Indice of the bone. Returns -1 if not found
  27401. */
  27402. Skeleton.prototype.getBoneIndexByName = function (name) {
  27403. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  27404. if (this.bones[boneIndex].name === name) {
  27405. return boneIndex;
  27406. }
  27407. }
  27408. return -1;
  27409. };
  27410. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  27411. // check name not already in use
  27412. if (!this._ranges[name]) {
  27413. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  27414. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27415. if (this.bones[i].animations[0]) {
  27416. this.bones[i].animations[0].createRange(name, from, to);
  27417. }
  27418. }
  27419. }
  27420. };
  27421. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  27422. if (deleteFrames === void 0) { deleteFrames = true; }
  27423. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27424. if (this.bones[i].animations[0]) {
  27425. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  27426. }
  27427. }
  27428. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  27429. };
  27430. Skeleton.prototype.getAnimationRange = function (name) {
  27431. return this._ranges[name];
  27432. };
  27433. /**
  27434. * Returns as an Array, all AnimationRanges defined on this skeleton
  27435. */
  27436. Skeleton.prototype.getAnimationRanges = function () {
  27437. var animationRanges = [];
  27438. var name;
  27439. var i = 0;
  27440. for (name in this._ranges) {
  27441. animationRanges[i] = this._ranges[name];
  27442. i++;
  27443. }
  27444. return animationRanges;
  27445. };
  27446. /**
  27447. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  27448. */
  27449. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  27450. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  27451. if (this._ranges[name] || !source.getAnimationRange(name)) {
  27452. return false;
  27453. }
  27454. var ret = true;
  27455. var frameOffset = this._getHighestAnimationFrame() + 1;
  27456. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  27457. var boneDict = {};
  27458. var sourceBones = source.bones;
  27459. var nBones;
  27460. var i;
  27461. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  27462. boneDict[sourceBones[i].name] = sourceBones[i];
  27463. }
  27464. if (this.bones.length !== sourceBones.length) {
  27465. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  27466. ret = false;
  27467. }
  27468. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  27469. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  27470. var boneName = this.bones[i].name;
  27471. var sourceBone = boneDict[boneName];
  27472. if (sourceBone) {
  27473. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  27474. }
  27475. else {
  27476. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  27477. ret = false;
  27478. }
  27479. }
  27480. // do not call createAnimationRange(), since it also is done to bones, which was already done
  27481. var range = source.getAnimationRange(name);
  27482. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  27483. return ret;
  27484. };
  27485. Skeleton.prototype.returnToRest = function () {
  27486. for (var index = 0; index < this.bones.length; index++) {
  27487. this.bones[index].returnToRest();
  27488. }
  27489. };
  27490. Skeleton.prototype._getHighestAnimationFrame = function () {
  27491. var ret = 0;
  27492. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27493. if (this.bones[i].animations[0]) {
  27494. var highest = this.bones[i].animations[0].getHighestFrame();
  27495. if (ret < highest) {
  27496. ret = highest;
  27497. }
  27498. }
  27499. }
  27500. return ret;
  27501. };
  27502. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  27503. var range = this.getAnimationRange(name);
  27504. if (!range) {
  27505. return null;
  27506. }
  27507. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  27508. };
  27509. Skeleton.prototype._markAsDirty = function () {
  27510. this._isDirty = true;
  27511. };
  27512. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  27513. this._meshesWithPoseMatrix.push(mesh);
  27514. };
  27515. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  27516. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  27517. if (index > -1) {
  27518. this._meshesWithPoseMatrix.splice(index, 1);
  27519. }
  27520. };
  27521. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  27522. for (var index = 0; index < this.bones.length; index++) {
  27523. var bone = this.bones[index];
  27524. var parentBone = bone.getParent();
  27525. if (parentBone) {
  27526. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  27527. }
  27528. else {
  27529. if (initialSkinMatrix) {
  27530. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  27531. }
  27532. else {
  27533. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  27534. }
  27535. }
  27536. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  27537. }
  27538. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  27539. };
  27540. Skeleton.prototype.prepare = function () {
  27541. if (!this._isDirty) {
  27542. return;
  27543. }
  27544. if (this.needInitialSkinMatrix) {
  27545. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  27546. var mesh = this._meshesWithPoseMatrix[index];
  27547. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  27548. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  27549. }
  27550. var poseMatrix = mesh.getPoseMatrix();
  27551. // Prepare bones
  27552. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  27553. var bone = this.bones[boneIndex];
  27554. if (!bone.getParent()) {
  27555. var matrix = bone.getBaseMatrix();
  27556. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  27557. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  27558. }
  27559. }
  27560. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  27561. }
  27562. }
  27563. else {
  27564. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  27565. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  27566. }
  27567. this._computeTransformMatrices(this._transformMatrices, null);
  27568. }
  27569. this._isDirty = false;
  27570. this._scene._activeBones += this.bones.length;
  27571. };
  27572. Skeleton.prototype.getAnimatables = function () {
  27573. if (!this._animatables || this._animatables.length !== this.bones.length) {
  27574. this._animatables = [];
  27575. for (var index = 0; index < this.bones.length; index++) {
  27576. this._animatables.push(this.bones[index]);
  27577. }
  27578. }
  27579. return this._animatables;
  27580. };
  27581. Skeleton.prototype.clone = function (name, id) {
  27582. var result = new Skeleton(name, id || name, this._scene);
  27583. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  27584. for (var index = 0; index < this.bones.length; index++) {
  27585. var source = this.bones[index];
  27586. var parentBone = null;
  27587. if (source.getParent()) {
  27588. var parentIndex = this.bones.indexOf(source.getParent());
  27589. parentBone = result.bones[parentIndex];
  27590. }
  27591. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  27592. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  27593. }
  27594. if (this._ranges) {
  27595. result._ranges = {};
  27596. for (var rangeName in this._ranges) {
  27597. result._ranges[rangeName] = this._ranges[rangeName].clone();
  27598. }
  27599. }
  27600. this._isDirty = true;
  27601. return result;
  27602. };
  27603. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  27604. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  27605. this.bones.forEach(function (bone) {
  27606. bone.animations.forEach(function (animation) {
  27607. animation.enableBlending = true;
  27608. animation.blendingSpeed = blendingSpeed;
  27609. });
  27610. });
  27611. };
  27612. Skeleton.prototype.dispose = function () {
  27613. this._meshesWithPoseMatrix = [];
  27614. // Animations
  27615. this.getScene().stopAnimation(this);
  27616. // Remove from scene
  27617. this.getScene().removeSkeleton(this);
  27618. };
  27619. Skeleton.prototype.serialize = function () {
  27620. var serializationObject = {};
  27621. serializationObject.name = this.name;
  27622. serializationObject.id = this.id;
  27623. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  27624. serializationObject.bones = [];
  27625. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  27626. for (var index = 0; index < this.bones.length; index++) {
  27627. var bone = this.bones[index];
  27628. var serializedBone = {
  27629. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  27630. name: bone.name,
  27631. matrix: bone.getLocalMatrix().toArray(),
  27632. rest: bone.getRestPose().toArray()
  27633. };
  27634. serializationObject.bones.push(serializedBone);
  27635. if (bone.length) {
  27636. serializedBone.length = bone.length;
  27637. }
  27638. if (bone.animations && bone.animations.length > 0) {
  27639. serializedBone.animation = bone.animations[0].serialize();
  27640. }
  27641. serializationObject.ranges = [];
  27642. for (var name in this._ranges) {
  27643. var range = {};
  27644. range.name = name;
  27645. range.from = this._ranges[name].from;
  27646. range.to = this._ranges[name].to;
  27647. serializationObject.ranges.push(range);
  27648. }
  27649. }
  27650. return serializationObject;
  27651. };
  27652. Skeleton.Parse = function (parsedSkeleton, scene) {
  27653. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  27654. if (parsedSkeleton.dimensionsAtRest) {
  27655. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  27656. }
  27657. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  27658. var index;
  27659. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  27660. var parsedBone = parsedSkeleton.bones[index];
  27661. var parentBone = null;
  27662. if (parsedBone.parentBoneIndex > -1) {
  27663. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  27664. }
  27665. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  27666. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  27667. if (parsedBone.length) {
  27668. bone.length = parsedBone.length;
  27669. }
  27670. if (parsedBone.animation) {
  27671. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  27672. }
  27673. }
  27674. // placed after bones, so createAnimationRange can cascade down
  27675. if (parsedSkeleton.ranges) {
  27676. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  27677. var data = parsedSkeleton.ranges[index];
  27678. skeleton.createAnimationRange(data.name, data.from, data.to);
  27679. }
  27680. }
  27681. return skeleton;
  27682. };
  27683. return Skeleton;
  27684. })();
  27685. BABYLON.Skeleton = Skeleton;
  27686. })(BABYLON || (BABYLON = {}));
  27687. var BABYLON;
  27688. (function (BABYLON) {
  27689. var PostProcess = (function () {
  27690. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  27691. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  27692. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  27693. this.name = name;
  27694. this.width = -1;
  27695. this.height = -1;
  27696. /*
  27697. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  27698. Can only be used on a single postprocess or on the last one of a chain.
  27699. */
  27700. this.enablePixelPerfectMode = false;
  27701. this._reusable = false;
  27702. this._textures = new BABYLON.SmartArray(2);
  27703. this._currentRenderTextureInd = 0;
  27704. this._scaleRatio = new BABYLON.Vector2(1, 1);
  27705. // Events
  27706. /**
  27707. * An event triggered when the postprocess is activated.
  27708. * @type {BABYLON.Observable}
  27709. */
  27710. this.onActivateObservable = new BABYLON.Observable();
  27711. /**
  27712. * An event triggered when the postprocess changes its size.
  27713. * @type {BABYLON.Observable}
  27714. */
  27715. this.onSizeChangedObservable = new BABYLON.Observable();
  27716. /**
  27717. * An event triggered when the postprocess applies its effect.
  27718. * @type {BABYLON.Observable}
  27719. */
  27720. this.onApplyObservable = new BABYLON.Observable();
  27721. /**
  27722. * An event triggered before rendering the postprocess
  27723. * @type {BABYLON.Observable}
  27724. */
  27725. this.onBeforeRenderObservable = new BABYLON.Observable();
  27726. /**
  27727. * An event triggered after rendering the postprocess
  27728. * @type {BABYLON.Observable}
  27729. */
  27730. this.onAfterRenderObservable = new BABYLON.Observable();
  27731. if (camera != null) {
  27732. this._camera = camera;
  27733. this._scene = camera.getScene();
  27734. camera.attachPostProcess(this);
  27735. this._engine = this._scene.getEngine();
  27736. }
  27737. else {
  27738. this._engine = engine;
  27739. }
  27740. this._options = options;
  27741. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  27742. this._reusable = reusable || false;
  27743. this._textureType = textureType;
  27744. this._samplers = samplers || [];
  27745. this._samplers.push("textureSampler");
  27746. this._fragmentUrl = fragmentUrl;
  27747. this._parameters = parameters || [];
  27748. this._parameters.push("scale");
  27749. this.updateEffect(defines);
  27750. }
  27751. Object.defineProperty(PostProcess.prototype, "onActivate", {
  27752. set: function (callback) {
  27753. if (this._onActivateObserver) {
  27754. this.onActivateObservable.remove(this._onActivateObserver);
  27755. }
  27756. this._onActivateObserver = this.onActivateObservable.add(callback);
  27757. },
  27758. enumerable: true,
  27759. configurable: true
  27760. });
  27761. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  27762. set: function (callback) {
  27763. if (this._onSizeChangedObserver) {
  27764. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  27765. }
  27766. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  27767. },
  27768. enumerable: true,
  27769. configurable: true
  27770. });
  27771. Object.defineProperty(PostProcess.prototype, "onApply", {
  27772. set: function (callback) {
  27773. if (this._onApplyObserver) {
  27774. this.onApplyObservable.remove(this._onApplyObserver);
  27775. }
  27776. this._onApplyObserver = this.onApplyObservable.add(callback);
  27777. },
  27778. enumerable: true,
  27779. configurable: true
  27780. });
  27781. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  27782. set: function (callback) {
  27783. if (this._onBeforeRenderObserver) {
  27784. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27785. }
  27786. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27787. },
  27788. enumerable: true,
  27789. configurable: true
  27790. });
  27791. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  27792. set: function (callback) {
  27793. if (this._onAfterRenderObserver) {
  27794. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27795. }
  27796. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27797. },
  27798. enumerable: true,
  27799. configurable: true
  27800. });
  27801. PostProcess.prototype.updateEffect = function (defines) {
  27802. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  27803. };
  27804. PostProcess.prototype.isReusable = function () {
  27805. return this._reusable;
  27806. };
  27807. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  27808. PostProcess.prototype.markTextureDirty = function () {
  27809. this.width = -1;
  27810. };
  27811. PostProcess.prototype.activate = function (camera, sourceTexture) {
  27812. camera = camera || this._camera;
  27813. var scene = camera.getScene();
  27814. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  27815. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  27816. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  27817. var desiredWidth = this._options.width || requiredWidth;
  27818. var desiredHeight = this._options.height || requiredHeight;
  27819. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  27820. if (!this._options.width) {
  27821. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  27822. }
  27823. if (!this._options.height) {
  27824. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  27825. }
  27826. }
  27827. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  27828. if (this._textures.length > 0) {
  27829. for (var i = 0; i < this._textures.length; i++) {
  27830. this._engine._releaseTexture(this._textures.data[i]);
  27831. }
  27832. this._textures.reset();
  27833. }
  27834. this.width = desiredWidth;
  27835. this.height = desiredHeight;
  27836. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === 0, samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
  27837. if (this._reusable) {
  27838. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === 0, samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
  27839. }
  27840. this.onSizeChangedObservable.notifyObservers(this);
  27841. }
  27842. if (this.enablePixelPerfectMode) {
  27843. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  27844. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  27845. }
  27846. else {
  27847. this._scaleRatio.copyFromFloats(1, 1);
  27848. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  27849. }
  27850. this.onActivateObservable.notifyObservers(camera);
  27851. // Clear
  27852. if (this.clearColor) {
  27853. this._engine.clear(this.clearColor, true, true);
  27854. }
  27855. else {
  27856. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  27857. }
  27858. if (this._reusable) {
  27859. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  27860. }
  27861. };
  27862. Object.defineProperty(PostProcess.prototype, "isSupported", {
  27863. get: function () {
  27864. return this._effect.isSupported;
  27865. },
  27866. enumerable: true,
  27867. configurable: true
  27868. });
  27869. PostProcess.prototype.apply = function () {
  27870. // Check
  27871. if (!this._effect.isReady())
  27872. return null;
  27873. // States
  27874. this._engine.enableEffect(this._effect);
  27875. this._engine.setState(false);
  27876. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27877. this._engine.setDepthBuffer(false);
  27878. this._engine.setDepthWrite(false);
  27879. // Texture
  27880. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  27881. // Parameters
  27882. this._effect.setVector2("scale", this._scaleRatio);
  27883. this.onApplyObservable.notifyObservers(this._effect);
  27884. return this._effect;
  27885. };
  27886. PostProcess.prototype.dispose = function (camera) {
  27887. camera = camera || this._camera;
  27888. if (this._textures.length > 0) {
  27889. for (var i = 0; i < this._textures.length; i++) {
  27890. this._engine._releaseTexture(this._textures.data[i]);
  27891. }
  27892. this._textures.reset();
  27893. }
  27894. if (!camera) {
  27895. return;
  27896. }
  27897. camera.detachPostProcess(this);
  27898. var index = camera._postProcesses.indexOf(this);
  27899. if (index === 0 && camera._postProcesses.length > 0) {
  27900. this._camera._postProcesses[0].markTextureDirty();
  27901. }
  27902. this.onActivateObservable.clear();
  27903. this.onAfterRenderObservable.clear();
  27904. this.onApplyObservable.clear();
  27905. this.onBeforeRenderObservable.clear();
  27906. this.onSizeChangedObservable.clear();
  27907. };
  27908. return PostProcess;
  27909. })();
  27910. BABYLON.PostProcess = PostProcess;
  27911. })(BABYLON || (BABYLON = {}));
  27912. var BABYLON;
  27913. (function (BABYLON) {
  27914. var PostProcessManager = (function () {
  27915. function PostProcessManager(scene) {
  27916. this._vertexBuffers = {};
  27917. this._scene = scene;
  27918. }
  27919. PostProcessManager.prototype._prepareBuffers = function () {
  27920. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  27921. return;
  27922. }
  27923. // VBO
  27924. var vertices = [];
  27925. vertices.push(1, 1);
  27926. vertices.push(-1, 1);
  27927. vertices.push(-1, -1);
  27928. vertices.push(1, -1);
  27929. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27930. // Indices
  27931. var indices = [];
  27932. indices.push(0);
  27933. indices.push(1);
  27934. indices.push(2);
  27935. indices.push(0);
  27936. indices.push(2);
  27937. indices.push(3);
  27938. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  27939. };
  27940. // Methods
  27941. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  27942. var postProcesses = this._scene.activeCamera._postProcesses;
  27943. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27944. return false;
  27945. }
  27946. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  27947. return true;
  27948. };
  27949. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  27950. var engine = this._scene.getEngine();
  27951. for (var index = 0; index < postProcesses.length; index++) {
  27952. if (index < postProcesses.length - 1) {
  27953. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  27954. }
  27955. else {
  27956. if (targetTexture) {
  27957. engine.bindFramebuffer(targetTexture);
  27958. }
  27959. else {
  27960. engine.restoreDefaultFramebuffer();
  27961. }
  27962. }
  27963. var pp = postProcesses[index];
  27964. var effect = pp.apply();
  27965. if (effect) {
  27966. pp.onBeforeRenderObservable.notifyObservers(effect);
  27967. // VBOs
  27968. this._prepareBuffers();
  27969. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27970. // Draw order
  27971. engine.draw(true, 0, 6);
  27972. pp.onAfterRenderObservable.notifyObservers(effect);
  27973. }
  27974. }
  27975. // Restore depth buffer
  27976. engine.setDepthBuffer(true);
  27977. engine.setDepthWrite(true);
  27978. };
  27979. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  27980. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  27981. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27982. return;
  27983. }
  27984. var engine = this._scene.getEngine();
  27985. for (var index = 0, len = postProcesses.length; index < len; index++) {
  27986. if (index < len - 1) {
  27987. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  27988. }
  27989. else {
  27990. if (targetTexture) {
  27991. engine.bindFramebuffer(targetTexture, faceIndex);
  27992. }
  27993. else {
  27994. engine.restoreDefaultFramebuffer();
  27995. }
  27996. }
  27997. if (doNotPresent) {
  27998. break;
  27999. }
  28000. var pp = postProcesses[index];
  28001. var effect = pp.apply();
  28002. if (effect) {
  28003. pp.onBeforeRenderObservable.notifyObservers(effect);
  28004. // VBOs
  28005. this._prepareBuffers();
  28006. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28007. // Draw order
  28008. engine.draw(true, 0, 6);
  28009. pp.onAfterRenderObservable.notifyObservers(effect);
  28010. }
  28011. }
  28012. // Restore depth buffer
  28013. engine.setDepthBuffer(true);
  28014. engine.setDepthWrite(true);
  28015. };
  28016. PostProcessManager.prototype.dispose = function () {
  28017. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28018. if (buffer) {
  28019. buffer.dispose();
  28020. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28021. }
  28022. if (this._indexBuffer) {
  28023. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28024. this._indexBuffer = null;
  28025. }
  28026. };
  28027. return PostProcessManager;
  28028. })();
  28029. BABYLON.PostProcessManager = PostProcessManager;
  28030. })(BABYLON || (BABYLON = {}));
  28031. var BABYLON;
  28032. (function (BABYLON) {
  28033. var PassPostProcess = (function (_super) {
  28034. __extends(PassPostProcess, _super);
  28035. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  28036. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  28037. }
  28038. return PassPostProcess;
  28039. })(BABYLON.PostProcess);
  28040. BABYLON.PassPostProcess = PassPostProcess;
  28041. })(BABYLON || (BABYLON = {}));
  28042. var BABYLON;
  28043. (function (BABYLON) {
  28044. /**
  28045. * This is a holder class for the physics joint created by the physics plugin.
  28046. * It holds a set of functions to control the underlying joint.
  28047. */
  28048. var PhysicsJoint = (function () {
  28049. function PhysicsJoint(type, jointData) {
  28050. this.type = type;
  28051. this.jointData = jointData;
  28052. jointData.nativeParams = jointData.nativeParams || {};
  28053. }
  28054. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  28055. get: function () {
  28056. return this._physicsJoint;
  28057. },
  28058. set: function (newJoint) {
  28059. if (this._physicsJoint) {
  28060. }
  28061. this._physicsJoint = newJoint;
  28062. },
  28063. enumerable: true,
  28064. configurable: true
  28065. });
  28066. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  28067. set: function (physicsPlugin) {
  28068. this._physicsPlugin = physicsPlugin;
  28069. },
  28070. enumerable: true,
  28071. configurable: true
  28072. });
  28073. /**
  28074. * Execute a function that is physics-plugin specific.
  28075. * @param {Function} func the function that will be executed.
  28076. * It accepts two parameters: the physics world and the physics joint.
  28077. */
  28078. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  28079. func(this._physicsPlugin.world, this._physicsJoint);
  28080. };
  28081. //TODO check if the native joints are the same
  28082. //Joint Types
  28083. PhysicsJoint.DistanceJoint = 0;
  28084. PhysicsJoint.HingeJoint = 1;
  28085. PhysicsJoint.BallAndSocketJoint = 2;
  28086. PhysicsJoint.WheelJoint = 3;
  28087. PhysicsJoint.SliderJoint = 4;
  28088. //OIMO
  28089. PhysicsJoint.PrismaticJoint = 5;
  28090. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  28091. PhysicsJoint.UniversalJoint = 6;
  28092. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  28093. //Cannon
  28094. //Similar to a Ball-Joint. Different in params
  28095. PhysicsJoint.PointToPointJoint = 8;
  28096. //Cannon only at the moment
  28097. PhysicsJoint.SpringJoint = 9;
  28098. PhysicsJoint.LockJoint = 10;
  28099. return PhysicsJoint;
  28100. })();
  28101. BABYLON.PhysicsJoint = PhysicsJoint;
  28102. /**
  28103. * A class representing a physics distance joint.
  28104. */
  28105. var DistanceJoint = (function (_super) {
  28106. __extends(DistanceJoint, _super);
  28107. function DistanceJoint(jointData) {
  28108. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  28109. }
  28110. /**
  28111. * Update the predefined distance.
  28112. */
  28113. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  28114. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  28115. };
  28116. return DistanceJoint;
  28117. })(PhysicsJoint);
  28118. BABYLON.DistanceJoint = DistanceJoint;
  28119. var MotorEnabledJoint = (function (_super) {
  28120. __extends(MotorEnabledJoint, _super);
  28121. function MotorEnabledJoint(type, jointData) {
  28122. _super.call(this, type, jointData);
  28123. }
  28124. /**
  28125. * Set the motor values.
  28126. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28127. * @param {number} force the force to apply
  28128. * @param {number} maxForce max force for this motor.
  28129. */
  28130. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  28131. this._physicsPlugin.setMotor(this, force, maxForce);
  28132. };
  28133. /**
  28134. * Set the motor's limits.
  28135. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28136. */
  28137. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  28138. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  28139. };
  28140. return MotorEnabledJoint;
  28141. })(PhysicsJoint);
  28142. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  28143. /**
  28144. * This class represents a single hinge physics joint
  28145. */
  28146. var HingeJoint = (function (_super) {
  28147. __extends(HingeJoint, _super);
  28148. function HingeJoint(jointData) {
  28149. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  28150. }
  28151. /**
  28152. * Set the motor values.
  28153. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28154. * @param {number} force the force to apply
  28155. * @param {number} maxForce max force for this motor.
  28156. */
  28157. HingeJoint.prototype.setMotor = function (force, maxForce) {
  28158. this._physicsPlugin.setMotor(this, force, maxForce);
  28159. };
  28160. /**
  28161. * Set the motor's limits.
  28162. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28163. */
  28164. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  28165. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  28166. };
  28167. return HingeJoint;
  28168. })(MotorEnabledJoint);
  28169. BABYLON.HingeJoint = HingeJoint;
  28170. /**
  28171. * This class represents a dual hinge physics joint (same as wheel joint)
  28172. */
  28173. var Hinge2Joint = (function (_super) {
  28174. __extends(Hinge2Joint, _super);
  28175. function Hinge2Joint(jointData) {
  28176. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  28177. }
  28178. /**
  28179. * Set the motor values.
  28180. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28181. * @param {number} force the force to apply
  28182. * @param {number} maxForce max force for this motor.
  28183. * @param {motorIndex} the motor's index, 0 or 1.
  28184. */
  28185. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  28186. if (motorIndex === void 0) { motorIndex = 0; }
  28187. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  28188. };
  28189. /**
  28190. * Set the motor limits.
  28191. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28192. * @param {number} upperLimit the upper limit
  28193. * @param {number} lowerLimit lower limit
  28194. * @param {motorIndex} the motor's index, 0 or 1.
  28195. */
  28196. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  28197. if (motorIndex === void 0) { motorIndex = 0; }
  28198. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  28199. };
  28200. return Hinge2Joint;
  28201. })(MotorEnabledJoint);
  28202. BABYLON.Hinge2Joint = Hinge2Joint;
  28203. })(BABYLON || (BABYLON = {}));
  28204. var BABYLON;
  28205. (function (BABYLON) {
  28206. var PhysicsImpostor = (function () {
  28207. function PhysicsImpostor(object, type, _options, _scene) {
  28208. var _this = this;
  28209. if (_options === void 0) { _options = { mass: 0 }; }
  28210. this.object = object;
  28211. this.type = type;
  28212. this._options = _options;
  28213. this._scene = _scene;
  28214. this._bodyUpdateRequired = false;
  28215. this._onBeforePhysicsStepCallbacks = new Array();
  28216. this._onAfterPhysicsStepCallbacks = new Array();
  28217. this._onPhysicsCollideCallbacks = [];
  28218. this._deltaPosition = BABYLON.Vector3.Zero();
  28219. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  28220. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  28221. /**
  28222. * this function is executed by the physics engine.
  28223. */
  28224. this.beforeStep = function () {
  28225. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  28226. //conjugate deltaRotation
  28227. if (_this._deltaRotationConjugated) {
  28228. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  28229. }
  28230. else {
  28231. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  28232. }
  28233. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  28234. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  28235. func(_this);
  28236. });
  28237. };
  28238. /**
  28239. * this function is executed by the physics engine.
  28240. */
  28241. this.afterStep = function () {
  28242. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  28243. func(_this);
  28244. });
  28245. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  28246. _this.object.position.addInPlace(_this._deltaPosition);
  28247. if (_this._deltaRotation) {
  28248. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  28249. }
  28250. };
  28251. //event and body object due to cannon's event-based architecture.
  28252. this.onCollide = function (e) {
  28253. if (!_this._onPhysicsCollideCallbacks.length)
  28254. return;
  28255. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  28256. if (otherImpostor) {
  28257. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  28258. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  28259. }).forEach(function (obj) {
  28260. obj.callback(_this, otherImpostor);
  28261. });
  28262. }
  28263. };
  28264. //sanity check!
  28265. if (!this.object) {
  28266. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  28267. return;
  28268. }
  28269. //legacy support for old syntax.
  28270. if (!this._scene && object.getScene) {
  28271. this._scene = object.getScene();
  28272. }
  28273. this._physicsEngine = this._scene.getPhysicsEngine();
  28274. if (!this._physicsEngine) {
  28275. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  28276. }
  28277. else {
  28278. //set the object's quaternion, if not set
  28279. if (!this.object.rotationQuaternion) {
  28280. if (this.object.rotation) {
  28281. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  28282. }
  28283. else {
  28284. this.object.rotationQuaternion = new BABYLON.Quaternion();
  28285. }
  28286. }
  28287. //default options params
  28288. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  28289. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  28290. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  28291. this._joints = [];
  28292. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  28293. if (!this.object.parent) {
  28294. this._init();
  28295. }
  28296. }
  28297. }
  28298. /**
  28299. * This function will completly initialize this impostor.
  28300. * It will create a new body - but only if this mesh has no parent.
  28301. * If it has, this impostor will not be used other than to define the impostor
  28302. * of the child mesh.
  28303. */
  28304. PhysicsImpostor.prototype._init = function () {
  28305. this._physicsEngine.removeImpostor(this);
  28306. this.physicsBody = null;
  28307. this._parent = this._parent || this._getPhysicsParent();
  28308. if (!this.parent) {
  28309. this._physicsEngine.addImpostor(this);
  28310. }
  28311. };
  28312. PhysicsImpostor.prototype._getPhysicsParent = function () {
  28313. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  28314. var parentMesh = this.object.parent;
  28315. return parentMesh.physicsImpostor;
  28316. }
  28317. return;
  28318. };
  28319. /**
  28320. * Should a new body be generated.
  28321. */
  28322. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  28323. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  28324. };
  28325. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  28326. this.forceUpdate();
  28327. };
  28328. /**
  28329. * Force a regeneration of this or the parent's impostor's body.
  28330. * Use under cautious - This will remove all joints already implemented.
  28331. */
  28332. PhysicsImpostor.prototype.forceUpdate = function () {
  28333. this._init();
  28334. if (this.parent) {
  28335. this.parent.forceUpdate();
  28336. }
  28337. };
  28338. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  28339. /*public get mesh(): AbstractMesh {
  28340. return this._mesh;
  28341. }*/
  28342. /**
  28343. * Gets the body that holds this impostor. Either its own, or its parent.
  28344. */
  28345. get: function () {
  28346. return this._parent ? this._parent.physicsBody : this._physicsBody;
  28347. },
  28348. /**
  28349. * Set the physics body. Used mainly by the physics engine/plugin
  28350. */
  28351. set: function (physicsBody) {
  28352. if (this._physicsBody) {
  28353. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  28354. }
  28355. this._physicsBody = physicsBody;
  28356. this.resetUpdateFlags();
  28357. },
  28358. enumerable: true,
  28359. configurable: true
  28360. });
  28361. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  28362. get: function () {
  28363. return this._parent;
  28364. },
  28365. enumerable: true,
  28366. configurable: true
  28367. });
  28368. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  28369. this._bodyUpdateRequired = false;
  28370. };
  28371. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  28372. if (this.object.getBoundingInfo) {
  28373. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  28374. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  28375. }
  28376. else {
  28377. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  28378. }
  28379. };
  28380. PhysicsImpostor.prototype.getObjectCenter = function () {
  28381. if (this.object.getBoundingInfo) {
  28382. return this.object.getBoundingInfo().boundingBox.center;
  28383. }
  28384. else {
  28385. return this.object.position;
  28386. }
  28387. };
  28388. /**
  28389. * Get a specific parametes from the options parameter.
  28390. */
  28391. PhysicsImpostor.prototype.getParam = function (paramName) {
  28392. return this._options[paramName];
  28393. };
  28394. /**
  28395. * Sets a specific parameter in the options given to the physics plugin
  28396. */
  28397. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  28398. this._options[paramName] = value;
  28399. this._bodyUpdateRequired = true;
  28400. };
  28401. /**
  28402. * Specifically change the body's mass option. Won't recreate the physics body object
  28403. */
  28404. PhysicsImpostor.prototype.setMass = function (mass) {
  28405. if (this.getParam("mass") !== mass) {
  28406. this.setParam("mass", mass);
  28407. }
  28408. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  28409. };
  28410. PhysicsImpostor.prototype.getLinearVelocity = function () {
  28411. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  28412. };
  28413. /**
  28414. * Set the body's linear velocity.
  28415. */
  28416. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  28417. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  28418. };
  28419. PhysicsImpostor.prototype.getAngularVelocity = function () {
  28420. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  28421. };
  28422. /**
  28423. * Set the body's linear velocity.
  28424. */
  28425. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  28426. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  28427. };
  28428. /**
  28429. * Execute a function with the physics plugin native code.
  28430. * Provide a function the will have two variables - the world object and the physics body object.
  28431. */
  28432. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  28433. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  28434. };
  28435. /**
  28436. * Register a function that will be executed before the physics world is stepping forward.
  28437. */
  28438. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  28439. this._onBeforePhysicsStepCallbacks.push(func);
  28440. };
  28441. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  28442. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  28443. if (index > -1) {
  28444. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  28445. }
  28446. else {
  28447. BABYLON.Tools.Warn("Function to remove was not found");
  28448. }
  28449. };
  28450. /**
  28451. * Register a function that will be executed after the physics step
  28452. */
  28453. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  28454. this._onAfterPhysicsStepCallbacks.push(func);
  28455. };
  28456. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  28457. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  28458. if (index > -1) {
  28459. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  28460. }
  28461. else {
  28462. BABYLON.Tools.Warn("Function to remove was not found");
  28463. }
  28464. };
  28465. /**
  28466. * register a function that will be executed when this impostor collides against a different body.
  28467. */
  28468. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  28469. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  28470. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  28471. };
  28472. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  28473. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  28474. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  28475. if (index > -1) {
  28476. this._onPhysicsCollideCallbacks.splice(index, 1);
  28477. }
  28478. else {
  28479. BABYLON.Tools.Warn("Function to remove was not found");
  28480. }
  28481. };
  28482. /**
  28483. * Apply a force
  28484. */
  28485. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  28486. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  28487. };
  28488. /**
  28489. * Apply an impulse
  28490. */
  28491. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  28492. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  28493. };
  28494. /**
  28495. * A help function to create a joint.
  28496. */
  28497. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  28498. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  28499. this.addJoint(otherImpostor, joint);
  28500. };
  28501. /**
  28502. * Add a joint to this impostor with a different impostor.
  28503. */
  28504. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  28505. this._joints.push({
  28506. otherImpostor: otherImpostor,
  28507. joint: joint
  28508. });
  28509. this._physicsEngine.addJoint(this, otherImpostor, joint);
  28510. };
  28511. /**
  28512. * Will keep this body still, in a sleep mode.
  28513. */
  28514. PhysicsImpostor.prototype.sleep = function () {
  28515. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  28516. };
  28517. /**
  28518. * Wake the body up.
  28519. */
  28520. PhysicsImpostor.prototype.wakeUp = function () {
  28521. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  28522. };
  28523. PhysicsImpostor.prototype.clone = function (newObject) {
  28524. if (!newObject)
  28525. return null;
  28526. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  28527. };
  28528. PhysicsImpostor.prototype.dispose = function () {
  28529. var _this = this;
  28530. //no dispose if no physics engine is available.
  28531. if (!this._physicsEngine) {
  28532. return;
  28533. }
  28534. this._joints.forEach(function (j) {
  28535. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  28536. });
  28537. //dispose the physics body
  28538. this._physicsEngine.removeImpostor(this);
  28539. if (this.parent) {
  28540. this.parent.forceUpdate();
  28541. }
  28542. else {
  28543. }
  28544. };
  28545. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  28546. this._deltaPosition.copyFrom(position);
  28547. };
  28548. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  28549. if (!this._deltaRotation) {
  28550. this._deltaRotation = new BABYLON.Quaternion();
  28551. }
  28552. this._deltaRotation.copyFrom(rotation);
  28553. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  28554. };
  28555. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  28556. //Impostor types
  28557. PhysicsImpostor.NoImpostor = 0;
  28558. PhysicsImpostor.SphereImpostor = 1;
  28559. PhysicsImpostor.BoxImpostor = 2;
  28560. PhysicsImpostor.PlaneImpostor = 3;
  28561. PhysicsImpostor.MeshImpostor = 4;
  28562. PhysicsImpostor.CylinderImpostor = 7;
  28563. PhysicsImpostor.ParticleImpostor = 8;
  28564. PhysicsImpostor.HeightmapImpostor = 9;
  28565. return PhysicsImpostor;
  28566. })();
  28567. BABYLON.PhysicsImpostor = PhysicsImpostor;
  28568. })(BABYLON || (BABYLON = {}));
  28569. var BABYLON;
  28570. (function (BABYLON) {
  28571. var PhysicsEngine = (function () {
  28572. function PhysicsEngine(gravity, _physicsPlugin) {
  28573. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  28574. this._physicsPlugin = _physicsPlugin;
  28575. //new methods and parameters
  28576. this._impostors = [];
  28577. this._joints = [];
  28578. if (!this._physicsPlugin.isSupported()) {
  28579. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  28580. + "Please make sure it is included.");
  28581. }
  28582. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  28583. this.setGravity(gravity);
  28584. this.setTimeStep();
  28585. }
  28586. PhysicsEngine.prototype.setGravity = function (gravity) {
  28587. this.gravity = gravity;
  28588. this._physicsPlugin.setGravity(this.gravity);
  28589. };
  28590. /**
  28591. * Set the time step of the physics engine.
  28592. * default is 1/60.
  28593. * To slow it down, enter 1/600 for example.
  28594. * To speed it up, 1/30
  28595. * @param {number} newTimeStep the new timestep to apply to this world.
  28596. */
  28597. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  28598. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  28599. this._physicsPlugin.setTimeStep(newTimeStep);
  28600. };
  28601. PhysicsEngine.prototype.dispose = function () {
  28602. this._impostors.forEach(function (impostor) {
  28603. impostor.dispose();
  28604. });
  28605. this._physicsPlugin.dispose();
  28606. };
  28607. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  28608. return this._physicsPlugin.name;
  28609. };
  28610. /**
  28611. * Adding a new impostor for the impostor tracking.
  28612. * This will be done by the impostor itself.
  28613. * @param {PhysicsImpostor} impostor the impostor to add
  28614. */
  28615. PhysicsEngine.prototype.addImpostor = function (impostor) {
  28616. impostor.uniqueId = this._impostors.push(impostor);
  28617. //if no parent, generate the body
  28618. if (!impostor.parent) {
  28619. this._physicsPlugin.generatePhysicsBody(impostor);
  28620. }
  28621. };
  28622. /**
  28623. * Remove an impostor from the engine.
  28624. * This impostor and its mesh will not longer be updated by the physics engine.
  28625. * @param {PhysicsImpostor} impostor the impostor to remove
  28626. */
  28627. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  28628. var index = this._impostors.indexOf(impostor);
  28629. if (index > -1) {
  28630. var removed = this._impostors.splice(index, 1);
  28631. //Is it needed?
  28632. if (removed.length) {
  28633. //this will also remove it from the world.
  28634. removed[0].physicsBody = null;
  28635. }
  28636. }
  28637. };
  28638. /**
  28639. * Add a joint to the physics engine
  28640. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  28641. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  28642. * @param {PhysicsJoint} the joint that will connect both impostors.
  28643. */
  28644. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  28645. var impostorJoint = {
  28646. mainImpostor: mainImpostor,
  28647. connectedImpostor: connectedImpostor,
  28648. joint: joint
  28649. };
  28650. joint.physicsPlugin = this._physicsPlugin;
  28651. this._joints.push(impostorJoint);
  28652. this._physicsPlugin.generateJoint(impostorJoint);
  28653. };
  28654. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  28655. var matchingJoints = this._joints.filter(function (impostorJoint) {
  28656. return (impostorJoint.connectedImpostor === connectedImpostor
  28657. && impostorJoint.joint === joint
  28658. && impostorJoint.mainImpostor === mainImpostor);
  28659. });
  28660. if (matchingJoints.length) {
  28661. this._physicsPlugin.removeJoint(matchingJoints[0]);
  28662. }
  28663. };
  28664. /**
  28665. * Called by the scene. no need to call it.
  28666. */
  28667. PhysicsEngine.prototype._step = function (delta) {
  28668. var _this = this;
  28669. //check if any mesh has no body / requires an update
  28670. this._impostors.forEach(function (impostor) {
  28671. if (impostor.isBodyInitRequired()) {
  28672. _this._physicsPlugin.generatePhysicsBody(impostor);
  28673. }
  28674. });
  28675. if (delta > 0.1) {
  28676. delta = 0.1;
  28677. }
  28678. else if (delta <= 0) {
  28679. delta = 1.0 / 60.0;
  28680. }
  28681. this._physicsPlugin.executeStep(delta, this._impostors);
  28682. };
  28683. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  28684. return this._physicsPlugin;
  28685. };
  28686. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  28687. for (var i = 0; i < this._impostors.length; ++i) {
  28688. if (this._impostors[i].object === object) {
  28689. return this._impostors[i];
  28690. }
  28691. }
  28692. };
  28693. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  28694. for (var i = 0; i < this._impostors.length; ++i) {
  28695. if (this._impostors[i].physicsBody === body) {
  28696. return this._impostors[i];
  28697. }
  28698. }
  28699. };
  28700. // Statics, Legacy support.
  28701. /**
  28702. * @Deprecated
  28703. *
  28704. */
  28705. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  28706. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  28707. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  28708. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  28709. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  28710. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  28711. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  28712. PhysicsEngine.CapsuleImpostor = -1;
  28713. PhysicsEngine.ConeImpostor = -1;
  28714. PhysicsEngine.ConvexHullImpostor = -1;
  28715. PhysicsEngine.Epsilon = 0.001;
  28716. return PhysicsEngine;
  28717. })();
  28718. BABYLON.PhysicsEngine = PhysicsEngine;
  28719. })(BABYLON || (BABYLON = {}));
  28720. var BABYLON;
  28721. (function (BABYLON) {
  28722. var VertexData = (function () {
  28723. function VertexData() {
  28724. }
  28725. VertexData.prototype.set = function (data, kind) {
  28726. switch (kind) {
  28727. case BABYLON.VertexBuffer.PositionKind:
  28728. this.positions = data;
  28729. break;
  28730. case BABYLON.VertexBuffer.NormalKind:
  28731. this.normals = data;
  28732. break;
  28733. case BABYLON.VertexBuffer.UVKind:
  28734. this.uvs = data;
  28735. break;
  28736. case BABYLON.VertexBuffer.UV2Kind:
  28737. this.uvs2 = data;
  28738. break;
  28739. case BABYLON.VertexBuffer.UV3Kind:
  28740. this.uvs3 = data;
  28741. break;
  28742. case BABYLON.VertexBuffer.UV4Kind:
  28743. this.uvs4 = data;
  28744. break;
  28745. case BABYLON.VertexBuffer.UV5Kind:
  28746. this.uvs5 = data;
  28747. break;
  28748. case BABYLON.VertexBuffer.UV6Kind:
  28749. this.uvs6 = data;
  28750. break;
  28751. case BABYLON.VertexBuffer.ColorKind:
  28752. this.colors = data;
  28753. break;
  28754. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28755. this.matricesIndices = data;
  28756. break;
  28757. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28758. this.matricesWeights = data;
  28759. break;
  28760. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28761. this.matricesIndicesExtra = data;
  28762. break;
  28763. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28764. this.matricesWeightsExtra = data;
  28765. break;
  28766. }
  28767. };
  28768. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28769. this._applyTo(mesh, updatable);
  28770. };
  28771. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28772. this._applyTo(geometry, updatable);
  28773. };
  28774. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28775. this._update(mesh);
  28776. };
  28777. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28778. this._update(geometry);
  28779. };
  28780. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28781. if (this.positions) {
  28782. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28783. }
  28784. if (this.normals) {
  28785. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28786. }
  28787. if (this.uvs) {
  28788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28789. }
  28790. if (this.uvs2) {
  28791. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28792. }
  28793. if (this.uvs3) {
  28794. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28795. }
  28796. if (this.uvs4) {
  28797. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28798. }
  28799. if (this.uvs5) {
  28800. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28801. }
  28802. if (this.uvs6) {
  28803. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28804. }
  28805. if (this.colors) {
  28806. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28807. }
  28808. if (this.matricesIndices) {
  28809. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28810. }
  28811. if (this.matricesWeights) {
  28812. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28813. }
  28814. if (this.matricesIndicesExtra) {
  28815. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28816. }
  28817. if (this.matricesWeightsExtra) {
  28818. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28819. }
  28820. if (this.indices) {
  28821. meshOrGeometry.setIndices(this.indices);
  28822. }
  28823. };
  28824. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28825. if (this.positions) {
  28826. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28827. }
  28828. if (this.normals) {
  28829. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28830. }
  28831. if (this.uvs) {
  28832. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28833. }
  28834. if (this.uvs2) {
  28835. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28836. }
  28837. if (this.uvs3) {
  28838. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28839. }
  28840. if (this.uvs4) {
  28841. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28842. }
  28843. if (this.uvs5) {
  28844. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28845. }
  28846. if (this.uvs6) {
  28847. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28848. }
  28849. if (this.colors) {
  28850. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28851. }
  28852. if (this.matricesIndices) {
  28853. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28854. }
  28855. if (this.matricesWeights) {
  28856. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28857. }
  28858. if (this.matricesIndicesExtra) {
  28859. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28860. }
  28861. if (this.matricesWeightsExtra) {
  28862. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28863. }
  28864. if (this.indices) {
  28865. meshOrGeometry.setIndices(this.indices);
  28866. }
  28867. };
  28868. VertexData.prototype.transform = function (matrix) {
  28869. var transformed = BABYLON.Vector3.Zero();
  28870. var index;
  28871. if (this.positions) {
  28872. var position = BABYLON.Vector3.Zero();
  28873. for (index = 0; index < this.positions.length; index += 3) {
  28874. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28875. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28876. this.positions[index] = transformed.x;
  28877. this.positions[index + 1] = transformed.y;
  28878. this.positions[index + 2] = transformed.z;
  28879. }
  28880. }
  28881. if (this.normals) {
  28882. var normal = BABYLON.Vector3.Zero();
  28883. for (index = 0; index < this.normals.length; index += 3) {
  28884. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28885. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28886. this.normals[index] = transformed.x;
  28887. this.normals[index + 1] = transformed.y;
  28888. this.normals[index + 2] = transformed.z;
  28889. }
  28890. }
  28891. };
  28892. VertexData.prototype.merge = function (other) {
  28893. if (other.indices) {
  28894. if (!this.indices) {
  28895. this.indices = [];
  28896. }
  28897. var offset = this.positions ? this.positions.length / 3 : 0;
  28898. for (var index = 0; index < other.indices.length; index++) {
  28899. //TODO check type - if Int32Array!
  28900. this.indices.push(other.indices[index] + offset);
  28901. }
  28902. }
  28903. this.positions = this._mergeElement(this.positions, other.positions);
  28904. this.normals = this._mergeElement(this.normals, other.normals);
  28905. this.uvs = this._mergeElement(this.uvs, other.uvs);
  28906. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  28907. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  28908. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  28909. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  28910. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  28911. this.colors = this._mergeElement(this.colors, other.colors);
  28912. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  28913. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  28914. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  28915. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  28916. };
  28917. VertexData.prototype._mergeElement = function (source, other) {
  28918. if (!other)
  28919. return source;
  28920. if (!source)
  28921. return other;
  28922. var len = other.length + source.length;
  28923. var isSrcTypedArray = source instanceof Float32Array;
  28924. var isOthTypedArray = other instanceof Float32Array;
  28925. // use non-loop method when the source is Float32Array
  28926. if (isSrcTypedArray) {
  28927. var ret32 = new Float32Array(len);
  28928. ret32.set(source);
  28929. ret32.set(other, source.length);
  28930. return ret32;
  28931. }
  28932. else if (!isOthTypedArray) {
  28933. return source.concat(other);
  28934. }
  28935. else {
  28936. var ret = source.slice(0); // copy source to a separate array
  28937. for (var i = 0, len = other.length; i < len; i++) {
  28938. ret.push(other[i]);
  28939. }
  28940. return ret;
  28941. }
  28942. };
  28943. VertexData.prototype.serialize = function () {
  28944. var serializationObject = this.serialize();
  28945. if (this.positions) {
  28946. serializationObject.positions = this.positions;
  28947. }
  28948. if (this.normals) {
  28949. serializationObject.normals = this.normals;
  28950. }
  28951. if (this.uvs) {
  28952. serializationObject.uvs = this.uvs;
  28953. }
  28954. if (this.uvs2) {
  28955. serializationObject.uvs2 = this.uvs2;
  28956. }
  28957. if (this.uvs3) {
  28958. serializationObject.uvs3 = this.uvs3;
  28959. }
  28960. if (this.uvs4) {
  28961. serializationObject.uvs4 = this.uvs4;
  28962. }
  28963. if (this.uvs5) {
  28964. serializationObject.uvs5 = this.uvs5;
  28965. }
  28966. if (this.uvs6) {
  28967. serializationObject.uvs6 = this.uvs6;
  28968. }
  28969. if (this.colors) {
  28970. serializationObject.colors = this.colors;
  28971. }
  28972. if (this.matricesIndices) {
  28973. serializationObject.matricesIndices = this.matricesIndices;
  28974. serializationObject.matricesIndices._isExpanded = true;
  28975. }
  28976. if (this.matricesWeights) {
  28977. serializationObject.matricesWeights = this.matricesWeights;
  28978. }
  28979. if (this.matricesIndicesExtra) {
  28980. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28981. serializationObject.matricesIndicesExtra._isExpanded = true;
  28982. }
  28983. if (this.matricesWeightsExtra) {
  28984. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28985. }
  28986. serializationObject.indices = this.indices;
  28987. return serializationObject;
  28988. };
  28989. // Statics
  28990. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  28991. return VertexData._ExtractFrom(mesh, copyWhenShared);
  28992. };
  28993. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  28994. return VertexData._ExtractFrom(geometry, copyWhenShared);
  28995. };
  28996. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  28997. var result = new VertexData();
  28998. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28999. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  29000. }
  29001. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29002. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  29003. }
  29004. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29005. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  29006. }
  29007. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29008. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  29009. }
  29010. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29011. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  29012. }
  29013. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29014. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  29015. }
  29016. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29017. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  29018. }
  29019. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29020. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  29021. }
  29022. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29023. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  29024. }
  29025. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29026. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  29027. }
  29028. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29029. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  29030. }
  29031. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29032. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  29033. }
  29034. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29035. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  29036. }
  29037. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29038. return result;
  29039. };
  29040. VertexData.CreateRibbon = function (options) {
  29041. var pathArray = options.pathArray;
  29042. var closeArray = options.closeArray || false;
  29043. var closePath = options.closePath || false;
  29044. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29045. var offset = options.offset || defaultOffset;
  29046. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29047. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29048. var positions = [];
  29049. var indices = [];
  29050. var normals = [];
  29051. var uvs = [];
  29052. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29053. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29054. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29055. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29056. var minlg; // minimal length among all paths from pathArray
  29057. var lg = []; // array of path lengths : nb of vertex per path
  29058. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29059. var p; // path iterator
  29060. var i; // point iterator
  29061. var j; // point iterator
  29062. // if single path in pathArray
  29063. if (pathArray.length < 2) {
  29064. var ar1 = [];
  29065. var ar2 = [];
  29066. for (i = 0; i < pathArray[0].length - offset; i++) {
  29067. ar1.push(pathArray[0][i]);
  29068. ar2.push(pathArray[0][i + offset]);
  29069. }
  29070. pathArray = [ar1, ar2];
  29071. }
  29072. // positions and horizontal distances (u)
  29073. var idc = 0;
  29074. var closePathCorr = (closePath) ? 1 : 0;
  29075. var path;
  29076. var l;
  29077. minlg = pathArray[0].length;
  29078. var vectlg;
  29079. var dist;
  29080. for (p = 0; p < pathArray.length; p++) {
  29081. uTotalDistance[p] = 0;
  29082. us[p] = [0];
  29083. path = pathArray[p];
  29084. l = path.length;
  29085. minlg = (minlg < l) ? minlg : l;
  29086. j = 0;
  29087. while (j < l) {
  29088. positions.push(path[j].x, path[j].y, path[j].z);
  29089. if (j > 0) {
  29090. vectlg = path[j].subtract(path[j - 1]).length();
  29091. dist = vectlg + uTotalDistance[p];
  29092. us[p].push(dist);
  29093. uTotalDistance[p] = dist;
  29094. }
  29095. j++;
  29096. }
  29097. if (closePath) {
  29098. j--;
  29099. positions.push(path[0].x, path[0].y, path[0].z);
  29100. vectlg = path[j].subtract(path[0]).length();
  29101. dist = vectlg + uTotalDistance[p];
  29102. us[p].push(dist);
  29103. uTotalDistance[p] = dist;
  29104. }
  29105. lg[p] = l + closePathCorr;
  29106. idx[p] = idc;
  29107. idc += (l + closePathCorr);
  29108. }
  29109. // vertical distances (v)
  29110. var path1;
  29111. var path2;
  29112. var vertex1;
  29113. var vertex2;
  29114. for (i = 0; i < minlg + closePathCorr; i++) {
  29115. vTotalDistance[i] = 0;
  29116. vs[i] = [0];
  29117. for (p = 0; p < pathArray.length - 1; p++) {
  29118. path1 = pathArray[p];
  29119. path2 = pathArray[p + 1];
  29120. if (i === minlg) {
  29121. vertex1 = path1[0];
  29122. vertex2 = path2[0];
  29123. }
  29124. else {
  29125. vertex1 = path1[i];
  29126. vertex2 = path2[i];
  29127. }
  29128. vectlg = vertex2.subtract(vertex1).length();
  29129. dist = vectlg + vTotalDistance[i];
  29130. vs[i].push(dist);
  29131. vTotalDistance[i] = dist;
  29132. }
  29133. if (closeArray) {
  29134. path1 = pathArray[p];
  29135. path2 = pathArray[0];
  29136. if (i === minlg) {
  29137. vertex2 = path2[0];
  29138. }
  29139. vectlg = vertex2.subtract(vertex1).length();
  29140. dist = vectlg + vTotalDistance[i];
  29141. vTotalDistance[i] = dist;
  29142. }
  29143. }
  29144. // uvs
  29145. var u;
  29146. var v;
  29147. for (p = 0; p < pathArray.length; p++) {
  29148. for (i = 0; i < minlg + closePathCorr; i++) {
  29149. u = us[p][i] / uTotalDistance[p];
  29150. v = vs[i][p] / vTotalDistance[i];
  29151. uvs.push(u, v);
  29152. }
  29153. }
  29154. // indices
  29155. p = 0; // path index
  29156. var pi = 0; // positions array index
  29157. var l1 = lg[p] - 1; // path1 length
  29158. var l2 = lg[p + 1] - 1; // path2 length
  29159. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29160. var shft = idx[1] - idx[0]; // shift
  29161. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29162. while (pi <= min && p < path1nb) {
  29163. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  29164. indices.push(pi, pi + shft, pi + 1);
  29165. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29166. pi += 1;
  29167. if (pi === min) {
  29168. p++;
  29169. if (p === lg.length - 1) {
  29170. shft = idx[0] - idx[p];
  29171. l1 = lg[p] - 1;
  29172. l2 = lg[0] - 1;
  29173. }
  29174. else {
  29175. shft = idx[p + 1] - idx[p];
  29176. l1 = lg[p] - 1;
  29177. l2 = lg[p + 1] - 1;
  29178. }
  29179. pi = idx[p];
  29180. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29181. }
  29182. }
  29183. // normals
  29184. VertexData.ComputeNormals(positions, indices, normals);
  29185. if (closePath) {
  29186. var indexFirst = 0;
  29187. var indexLast = 0;
  29188. for (p = 0; p < pathArray.length; p++) {
  29189. indexFirst = idx[p] * 3;
  29190. if (p + 1 < pathArray.length) {
  29191. indexLast = (idx[p + 1] - 1) * 3;
  29192. }
  29193. else {
  29194. indexLast = normals.length - 3;
  29195. }
  29196. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29197. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29198. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29199. normals[indexLast] = normals[indexFirst];
  29200. normals[indexLast + 1] = normals[indexFirst + 1];
  29201. normals[indexLast + 2] = normals[indexFirst + 2];
  29202. }
  29203. }
  29204. // sides
  29205. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29206. // Result
  29207. var vertexData = new VertexData();
  29208. vertexData.indices = indices;
  29209. vertexData.positions = positions;
  29210. vertexData.normals = normals;
  29211. vertexData.uvs = uvs;
  29212. if (closePath) {
  29213. vertexData._idx = idx;
  29214. }
  29215. return vertexData;
  29216. };
  29217. VertexData.CreateBox = function (options) {
  29218. var normalsSource = [
  29219. new BABYLON.Vector3(0, 0, 1),
  29220. new BABYLON.Vector3(0, 0, -1),
  29221. new BABYLON.Vector3(1, 0, 0),
  29222. new BABYLON.Vector3(-1, 0, 0),
  29223. new BABYLON.Vector3(0, 1, 0),
  29224. new BABYLON.Vector3(0, -1, 0)
  29225. ];
  29226. var indices = [];
  29227. var positions = [];
  29228. var normals = [];
  29229. var uvs = [];
  29230. var width = options.width || options.size || 1;
  29231. var height = options.height || options.size || 1;
  29232. var depth = options.depth || options.size || 1;
  29233. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29234. var faceUV = options.faceUV || new Array(6);
  29235. var faceColors = options.faceColors;
  29236. var colors = [];
  29237. // default face colors and UV if undefined
  29238. for (var f = 0; f < 6; f++) {
  29239. if (faceUV[f] === undefined) {
  29240. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29241. }
  29242. if (faceColors && faceColors[f] === undefined) {
  29243. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29244. }
  29245. }
  29246. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29247. // Create each face in turn.
  29248. for (var index = 0; index < normalsSource.length; index++) {
  29249. var normal = normalsSource[index];
  29250. // Get two vectors perpendicular to the face normal and to each other.
  29251. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29252. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29253. // Six indices (two triangles) per face.
  29254. var verticesLength = positions.length / 3;
  29255. indices.push(verticesLength);
  29256. indices.push(verticesLength + 1);
  29257. indices.push(verticesLength + 2);
  29258. indices.push(verticesLength);
  29259. indices.push(verticesLength + 2);
  29260. indices.push(verticesLength + 3);
  29261. // Four vertices per face.
  29262. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29263. positions.push(vertex.x, vertex.y, vertex.z);
  29264. normals.push(normal.x, normal.y, normal.z);
  29265. uvs.push(faceUV[index].z, faceUV[index].w);
  29266. if (faceColors) {
  29267. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29268. }
  29269. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29270. positions.push(vertex.x, vertex.y, vertex.z);
  29271. normals.push(normal.x, normal.y, normal.z);
  29272. uvs.push(faceUV[index].x, faceUV[index].w);
  29273. if (faceColors) {
  29274. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29275. }
  29276. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29277. positions.push(vertex.x, vertex.y, vertex.z);
  29278. normals.push(normal.x, normal.y, normal.z);
  29279. uvs.push(faceUV[index].x, faceUV[index].y);
  29280. if (faceColors) {
  29281. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29282. }
  29283. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29284. positions.push(vertex.x, vertex.y, vertex.z);
  29285. normals.push(normal.x, normal.y, normal.z);
  29286. uvs.push(faceUV[index].z, faceUV[index].y);
  29287. if (faceColors) {
  29288. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29289. }
  29290. }
  29291. // sides
  29292. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29293. // Result
  29294. var vertexData = new VertexData();
  29295. vertexData.indices = indices;
  29296. vertexData.positions = positions;
  29297. vertexData.normals = normals;
  29298. vertexData.uvs = uvs;
  29299. if (faceColors) {
  29300. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29301. vertexData.colors = totalColors;
  29302. }
  29303. return vertexData;
  29304. };
  29305. VertexData.CreateSphere = function (options) {
  29306. var segments = options.segments || 32;
  29307. var diameterX = options.diameterX || options.diameter || 1;
  29308. var diameterY = options.diameterY || options.diameter || 1;
  29309. var diameterZ = options.diameterZ || options.diameter || 1;
  29310. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29311. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29312. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29313. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29314. var totalZRotationSteps = 2 + segments;
  29315. var totalYRotationSteps = 2 * totalZRotationSteps;
  29316. var indices = [];
  29317. var positions = [];
  29318. var normals = [];
  29319. var uvs = [];
  29320. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29321. var normalizedZ = zRotationStep / totalZRotationSteps;
  29322. var angleZ = normalizedZ * Math.PI * slice;
  29323. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29324. var normalizedY = yRotationStep / totalYRotationSteps;
  29325. var angleY = normalizedY * Math.PI * 2 * arc;
  29326. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29327. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29328. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29329. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29330. var vertex = complete.multiply(radius);
  29331. var normal = complete.divide(radius).normalize();
  29332. positions.push(vertex.x, vertex.y, vertex.z);
  29333. normals.push(normal.x, normal.y, normal.z);
  29334. uvs.push(normalizedY, normalizedZ);
  29335. }
  29336. if (zRotationStep > 0) {
  29337. var verticesCount = positions.length / 3;
  29338. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29339. indices.push((firstIndex));
  29340. indices.push((firstIndex + 1));
  29341. indices.push(firstIndex + totalYRotationSteps + 1);
  29342. indices.push((firstIndex + totalYRotationSteps + 1));
  29343. indices.push((firstIndex + 1));
  29344. indices.push((firstIndex + totalYRotationSteps + 2));
  29345. }
  29346. }
  29347. }
  29348. // Sides
  29349. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29350. // Result
  29351. var vertexData = new VertexData();
  29352. vertexData.indices = indices;
  29353. vertexData.positions = positions;
  29354. vertexData.normals = normals;
  29355. vertexData.uvs = uvs;
  29356. return vertexData;
  29357. };
  29358. // Cylinder and cone
  29359. VertexData.CreateCylinder = function (options) {
  29360. var height = options.height || 2;
  29361. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29362. var diameterBottom = options.diameterBottom || options.diameter || 1;
  29363. var tessellation = options.tessellation || 24;
  29364. var subdivisions = options.subdivisions || 1;
  29365. var hasRings = options.hasRings;
  29366. var enclose = options.enclose;
  29367. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29368. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29369. var faceUV = options.faceUV || new Array(3);
  29370. var faceColors = options.faceColors;
  29371. // default face colors and UV if undefined
  29372. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29373. var ringNb = (hasRings) ? subdivisions : 1;
  29374. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29375. var f;
  29376. for (f = 0; f < surfaceNb; f++) {
  29377. if (faceColors && faceColors[f] === undefined) {
  29378. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29379. }
  29380. }
  29381. for (f = 0; f < surfaceNb; f++) {
  29382. if (faceUV && faceUV[f] === undefined) {
  29383. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29384. }
  29385. }
  29386. var indices = [];
  29387. var positions = [];
  29388. var normals = [];
  29389. var uvs = [];
  29390. var colors = [];
  29391. var angle_step = Math.PI * 2 * arc / tessellation;
  29392. var angle;
  29393. var h;
  29394. var radius;
  29395. var tan = (diameterBottom - diameterTop) / 2 / height;
  29396. var ringVertex = BABYLON.Vector3.Zero();
  29397. var ringNormal = BABYLON.Vector3.Zero();
  29398. var ringFirstVertex = BABYLON.Vector3.Zero();
  29399. var ringFirstNormal = BABYLON.Vector3.Zero();
  29400. var quadNormal = BABYLON.Vector3.Zero();
  29401. var Y = BABYLON.Axis.Y;
  29402. // positions, normals, uvs
  29403. var i;
  29404. var j;
  29405. var r;
  29406. var ringIdx = 1;
  29407. var s = 1; // surface index
  29408. var cs = 0;
  29409. var v = 0;
  29410. for (i = 0; i <= subdivisions; i++) {
  29411. h = i / subdivisions;
  29412. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29413. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29414. for (r = 0; r < ringIdx; r++) {
  29415. if (hasRings) {
  29416. s += r;
  29417. }
  29418. if (enclose) {
  29419. s += 2 * r;
  29420. }
  29421. for (j = 0; j <= tessellation; j++) {
  29422. angle = j * angle_step;
  29423. // position
  29424. ringVertex.x = Math.cos(-angle) * radius;
  29425. ringVertex.y = -height / 2 + h * height;
  29426. ringVertex.z = Math.sin(-angle) * radius;
  29427. // normal
  29428. if (diameterTop === 0 && i === subdivisions) {
  29429. // if no top cap, reuse former normals
  29430. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29431. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29432. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29433. }
  29434. else {
  29435. ringNormal.x = ringVertex.x;
  29436. ringNormal.z = ringVertex.z;
  29437. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29438. ringNormal.normalize();
  29439. }
  29440. // keep first ring vertex values for enclose
  29441. if (j === 0) {
  29442. ringFirstVertex.copyFrom(ringVertex);
  29443. ringFirstNormal.copyFrom(ringNormal);
  29444. }
  29445. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29446. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29447. if (hasRings) {
  29448. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29449. }
  29450. else {
  29451. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29452. }
  29453. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29454. if (faceColors) {
  29455. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29456. }
  29457. }
  29458. // if enclose, add four vertices and their dedicated normals
  29459. if (arc !== 1 && enclose) {
  29460. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29461. positions.push(0, ringVertex.y, 0);
  29462. positions.push(0, ringVertex.y, 0);
  29463. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29464. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29465. quadNormal.normalize();
  29466. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29467. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29468. quadNormal.normalize();
  29469. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29470. if (hasRings) {
  29471. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29472. }
  29473. else {
  29474. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29475. }
  29476. uvs.push(faceUV[s + 1].x, v);
  29477. uvs.push(faceUV[s + 1].z, v);
  29478. if (hasRings) {
  29479. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29480. }
  29481. else {
  29482. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29483. }
  29484. uvs.push(faceUV[s + 2].x, v);
  29485. uvs.push(faceUV[s + 2].z, v);
  29486. if (faceColors) {
  29487. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29488. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29489. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29490. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29491. }
  29492. }
  29493. if (cs !== s) {
  29494. cs = s;
  29495. }
  29496. }
  29497. }
  29498. // indices
  29499. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29500. var s;
  29501. i = 0;
  29502. for (s = 0; s < subdivisions; s++) {
  29503. for (j = 0; j < tessellation; j++) {
  29504. var i0 = i * (e + 1) + j;
  29505. var i1 = (i + 1) * (e + 1) + j;
  29506. var i2 = i * (e + 1) + (j + 1);
  29507. var i3 = (i + 1) * (e + 1) + (j + 1);
  29508. indices.push(i0, i1, i2);
  29509. indices.push(i3, i2, i1);
  29510. }
  29511. if (arc !== 1 && enclose) {
  29512. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29513. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29514. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29515. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29516. }
  29517. i = (hasRings) ? (i + 2) : (i + 1);
  29518. }
  29519. // Caps
  29520. var createCylinderCap = function (isTop) {
  29521. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29522. if (radius === 0) {
  29523. return;
  29524. }
  29525. // Cap positions, normals & uvs
  29526. var angle;
  29527. var circleVector;
  29528. var i;
  29529. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29530. var c;
  29531. if (faceColors) {
  29532. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29533. }
  29534. // cap center
  29535. var vbase = positions.length / 3;
  29536. var offset = isTop ? height / 2 : -height / 2;
  29537. var center = new BABYLON.Vector3(0, offset, 0);
  29538. positions.push(center.x, center.y, center.z);
  29539. normals.push(0, isTop ? 1 : -1, 0);
  29540. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29541. if (faceColors) {
  29542. colors.push(c.r, c.g, c.b, c.a);
  29543. }
  29544. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29545. for (i = 0; i <= tessellation; i++) {
  29546. angle = Math.PI * 2 * i * arc / tessellation;
  29547. var cos = Math.cos(-angle);
  29548. var sin = Math.sin(-angle);
  29549. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29550. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29551. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29552. normals.push(0, isTop ? 1 : -1, 0);
  29553. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29554. if (faceColors) {
  29555. colors.push(c.r, c.g, c.b, c.a);
  29556. }
  29557. }
  29558. // Cap indices
  29559. for (i = 0; i < tessellation; i++) {
  29560. if (!isTop) {
  29561. indices.push(vbase);
  29562. indices.push(vbase + (i + 1));
  29563. indices.push(vbase + (i + 2));
  29564. }
  29565. else {
  29566. indices.push(vbase);
  29567. indices.push(vbase + (i + 2));
  29568. indices.push(vbase + (i + 1));
  29569. }
  29570. }
  29571. };
  29572. // add caps to geometry
  29573. createCylinderCap(false);
  29574. createCylinderCap(true);
  29575. // Sides
  29576. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29577. var vertexData = new VertexData();
  29578. vertexData.indices = indices;
  29579. vertexData.positions = positions;
  29580. vertexData.normals = normals;
  29581. vertexData.uvs = uvs;
  29582. if (faceColors) {
  29583. vertexData.colors = colors;
  29584. }
  29585. return vertexData;
  29586. };
  29587. VertexData.CreateTorus = function (options) {
  29588. var indices = [];
  29589. var positions = [];
  29590. var normals = [];
  29591. var uvs = [];
  29592. var diameter = options.diameter || 1;
  29593. var thickness = options.thickness || 0.5;
  29594. var tessellation = options.tessellation || 16;
  29595. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29596. var stride = tessellation + 1;
  29597. for (var i = 0; i <= tessellation; i++) {
  29598. var u = i / tessellation;
  29599. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29600. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29601. for (var j = 0; j <= tessellation; j++) {
  29602. var v = 1 - j / tessellation;
  29603. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29604. var dx = Math.cos(innerAngle);
  29605. var dy = Math.sin(innerAngle);
  29606. // Create a vertex.
  29607. var normal = new BABYLON.Vector3(dx, dy, 0);
  29608. var position = normal.scale(thickness / 2);
  29609. var textureCoordinate = new BABYLON.Vector2(u, v);
  29610. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29611. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29612. positions.push(position.x, position.y, position.z);
  29613. normals.push(normal.x, normal.y, normal.z);
  29614. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29615. // And create indices for two triangles.
  29616. var nextI = (i + 1) % stride;
  29617. var nextJ = (j + 1) % stride;
  29618. indices.push(i * stride + j);
  29619. indices.push(i * stride + nextJ);
  29620. indices.push(nextI * stride + j);
  29621. indices.push(i * stride + nextJ);
  29622. indices.push(nextI * stride + nextJ);
  29623. indices.push(nextI * stride + j);
  29624. }
  29625. }
  29626. // Sides
  29627. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29628. // Result
  29629. var vertexData = new VertexData();
  29630. vertexData.indices = indices;
  29631. vertexData.positions = positions;
  29632. vertexData.normals = normals;
  29633. vertexData.uvs = uvs;
  29634. return vertexData;
  29635. };
  29636. VertexData.CreateLineSystem = function (options) {
  29637. var indices = [];
  29638. var positions = [];
  29639. var lines = options.lines;
  29640. var idx = 0;
  29641. for (var l = 0; l < lines.length; l++) {
  29642. var points = lines[l];
  29643. for (var index = 0; index < points.length; index++) {
  29644. positions.push(points[index].x, points[index].y, points[index].z);
  29645. if (index > 0) {
  29646. indices.push(idx - 1);
  29647. indices.push(idx);
  29648. }
  29649. idx++;
  29650. }
  29651. }
  29652. var vertexData = new VertexData();
  29653. vertexData.indices = indices;
  29654. vertexData.positions = positions;
  29655. return vertexData;
  29656. };
  29657. VertexData.CreateDashedLines = function (options) {
  29658. var dashSize = options.dashSize || 3;
  29659. var gapSize = options.gapSize || 1;
  29660. var dashNb = options.dashNb || 200;
  29661. var points = options.points;
  29662. var positions = new Array();
  29663. var indices = new Array();
  29664. var curvect = BABYLON.Vector3.Zero();
  29665. var lg = 0;
  29666. var nb = 0;
  29667. var shft = 0;
  29668. var dashshft = 0;
  29669. var curshft = 0;
  29670. var idx = 0;
  29671. var i = 0;
  29672. for (i = 0; i < points.length - 1; i++) {
  29673. points[i + 1].subtractToRef(points[i], curvect);
  29674. lg += curvect.length();
  29675. }
  29676. shft = lg / dashNb;
  29677. dashshft = dashSize * shft / (dashSize + gapSize);
  29678. for (i = 0; i < points.length - 1; i++) {
  29679. points[i + 1].subtractToRef(points[i], curvect);
  29680. nb = Math.floor(curvect.length() / shft);
  29681. curvect.normalize();
  29682. for (var j = 0; j < nb; j++) {
  29683. curshft = shft * j;
  29684. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29685. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29686. indices.push(idx, idx + 1);
  29687. idx += 2;
  29688. }
  29689. }
  29690. // Result
  29691. var vertexData = new VertexData();
  29692. vertexData.positions = positions;
  29693. vertexData.indices = indices;
  29694. return vertexData;
  29695. };
  29696. VertexData.CreateGround = function (options) {
  29697. var indices = [];
  29698. var positions = [];
  29699. var normals = [];
  29700. var uvs = [];
  29701. var row, col;
  29702. var width = options.width || 1;
  29703. var height = options.height || 1;
  29704. var subdivisions = options.subdivisions || 1;
  29705. for (row = 0; row <= subdivisions; row++) {
  29706. for (col = 0; col <= subdivisions; col++) {
  29707. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  29708. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29709. positions.push(position.x, position.y, position.z);
  29710. normals.push(normal.x, normal.y, normal.z);
  29711. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  29712. }
  29713. }
  29714. for (row = 0; row < subdivisions; row++) {
  29715. for (col = 0; col < subdivisions; col++) {
  29716. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  29717. indices.push(col + 1 + row * (subdivisions + 1));
  29718. indices.push(col + row * (subdivisions + 1));
  29719. indices.push(col + (row + 1) * (subdivisions + 1));
  29720. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  29721. indices.push(col + row * (subdivisions + 1));
  29722. }
  29723. }
  29724. // Result
  29725. var vertexData = new VertexData();
  29726. vertexData.indices = indices;
  29727. vertexData.positions = positions;
  29728. vertexData.normals = normals;
  29729. vertexData.uvs = uvs;
  29730. return vertexData;
  29731. };
  29732. VertexData.CreateTiledGround = function (options) {
  29733. var xmin = options.xmin;
  29734. var zmin = options.zmin;
  29735. var xmax = options.xmax;
  29736. var zmax = options.zmax;
  29737. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29738. var precision = options.precision || { w: 1, h: 1 };
  29739. var indices = [];
  29740. var positions = [];
  29741. var normals = [];
  29742. var uvs = [];
  29743. var row, col, tileRow, tileCol;
  29744. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  29745. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29746. precision.w = (precision.w < 1) ? 1 : precision.w;
  29747. precision.h = (precision.h < 1) ? 1 : precision.h;
  29748. var tileSize = {
  29749. 'w': (xmax - xmin) / subdivisions.w,
  29750. 'h': (zmax - zmin) / subdivisions.h
  29751. };
  29752. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29753. // Indices
  29754. var base = positions.length / 3;
  29755. var rowLength = precision.w + 1;
  29756. for (row = 0; row < precision.h; row++) {
  29757. for (col = 0; col < precision.w; col++) {
  29758. var square = [
  29759. base + col + row * rowLength,
  29760. base + (col + 1) + row * rowLength,
  29761. base + (col + 1) + (row + 1) * rowLength,
  29762. base + col + (row + 1) * rowLength
  29763. ];
  29764. indices.push(square[1]);
  29765. indices.push(square[2]);
  29766. indices.push(square[3]);
  29767. indices.push(square[0]);
  29768. indices.push(square[1]);
  29769. indices.push(square[3]);
  29770. }
  29771. }
  29772. // Position, normals and uvs
  29773. var position = BABYLON.Vector3.Zero();
  29774. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29775. for (row = 0; row <= precision.h; row++) {
  29776. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29777. for (col = 0; col <= precision.w; col++) {
  29778. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29779. position.y = 0;
  29780. positions.push(position.x, position.y, position.z);
  29781. normals.push(normal.x, normal.y, normal.z);
  29782. uvs.push(col / precision.w, row / precision.h);
  29783. }
  29784. }
  29785. }
  29786. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29787. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29788. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29789. }
  29790. }
  29791. // Result
  29792. var vertexData = new VertexData();
  29793. vertexData.indices = indices;
  29794. vertexData.positions = positions;
  29795. vertexData.normals = normals;
  29796. vertexData.uvs = uvs;
  29797. return vertexData;
  29798. };
  29799. VertexData.CreateGroundFromHeightMap = function (options) {
  29800. var indices = [];
  29801. var positions = [];
  29802. var normals = [];
  29803. var uvs = [];
  29804. var row, col;
  29805. // Vertices
  29806. for (row = 0; row <= options.subdivisions; row++) {
  29807. for (col = 0; col <= options.subdivisions; col++) {
  29808. var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
  29809. // Compute height
  29810. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29811. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29812. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29813. var r = options.buffer[pos] / 255.0;
  29814. var g = options.buffer[pos + 1] / 255.0;
  29815. var b = options.buffer[pos + 2] / 255.0;
  29816. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29817. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29818. // Add vertex
  29819. positions.push(position.x, position.y, position.z);
  29820. normals.push(0, 0, 0);
  29821. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29822. }
  29823. }
  29824. // Indices
  29825. for (row = 0; row < options.subdivisions; row++) {
  29826. for (col = 0; col < options.subdivisions; col++) {
  29827. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29828. indices.push(col + 1 + row * (options.subdivisions + 1));
  29829. indices.push(col + row * (options.subdivisions + 1));
  29830. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29831. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29832. indices.push(col + row * (options.subdivisions + 1));
  29833. }
  29834. }
  29835. // Normals
  29836. VertexData.ComputeNormals(positions, indices, normals);
  29837. // Result
  29838. var vertexData = new VertexData();
  29839. vertexData.indices = indices;
  29840. vertexData.positions = positions;
  29841. vertexData.normals = normals;
  29842. vertexData.uvs = uvs;
  29843. return vertexData;
  29844. };
  29845. VertexData.CreatePlane = function (options) {
  29846. var indices = [];
  29847. var positions = [];
  29848. var normals = [];
  29849. var uvs = [];
  29850. var width = options.width || options.size || 1;
  29851. var height = options.height || options.size || 1;
  29852. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29853. // Vertices
  29854. var halfWidth = width / 2.0;
  29855. var halfHeight = height / 2.0;
  29856. positions.push(-halfWidth, -halfHeight, 0);
  29857. normals.push(0, 0, -1.0);
  29858. uvs.push(0.0, 0.0);
  29859. positions.push(halfWidth, -halfHeight, 0);
  29860. normals.push(0, 0, -1.0);
  29861. uvs.push(1.0, 0.0);
  29862. positions.push(halfWidth, halfHeight, 0);
  29863. normals.push(0, 0, -1.0);
  29864. uvs.push(1.0, 1.0);
  29865. positions.push(-halfWidth, halfHeight, 0);
  29866. normals.push(0, 0, -1.0);
  29867. uvs.push(0.0, 1.0);
  29868. // Indices
  29869. indices.push(0);
  29870. indices.push(1);
  29871. indices.push(2);
  29872. indices.push(0);
  29873. indices.push(2);
  29874. indices.push(3);
  29875. // Sides
  29876. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29877. // Result
  29878. var vertexData = new VertexData();
  29879. vertexData.indices = indices;
  29880. vertexData.positions = positions;
  29881. vertexData.normals = normals;
  29882. vertexData.uvs = uvs;
  29883. return vertexData;
  29884. };
  29885. VertexData.CreateDisc = function (options) {
  29886. var positions = [];
  29887. var indices = [];
  29888. var normals = [];
  29889. var uvs = [];
  29890. var radius = options.radius || 0.5;
  29891. var tessellation = options.tessellation || 64;
  29892. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29893. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29894. // positions and uvs
  29895. positions.push(0, 0, 0); // disc center first
  29896. uvs.push(0.5, 0.5);
  29897. var theta = Math.PI * 2 * arc;
  29898. var step = theta / tessellation;
  29899. for (var a = 0; a < theta; a += step) {
  29900. var x = Math.cos(a);
  29901. var y = Math.sin(a);
  29902. var u = (x + 1) / 2;
  29903. var v = (1 - y) / 2;
  29904. positions.push(radius * x, radius * y, 0);
  29905. uvs.push(u, v);
  29906. }
  29907. if (arc === 1) {
  29908. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29909. uvs.push(uvs[2], uvs[3]);
  29910. }
  29911. //indices
  29912. var vertexNb = positions.length / 3;
  29913. for (var i = 1; i < vertexNb - 1; i++) {
  29914. indices.push(i + 1, 0, i);
  29915. }
  29916. // result
  29917. VertexData.ComputeNormals(positions, indices, normals);
  29918. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29919. var vertexData = new VertexData();
  29920. vertexData.indices = indices;
  29921. vertexData.positions = positions;
  29922. vertexData.normals = normals;
  29923. vertexData.uvs = uvs;
  29924. return vertexData;
  29925. };
  29926. VertexData.CreateIcoSphere = function (options) {
  29927. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29928. var radius = options.radius || 1;
  29929. var flat = (options.flat === undefined) ? true : options.flat;
  29930. var subdivisions = options.subdivisions || 4;
  29931. var radiusX = options.radiusX || radius;
  29932. var radiusY = options.radiusY || radius;
  29933. var radiusZ = options.radiusZ || radius;
  29934. var t = (1 + Math.sqrt(5)) / 2;
  29935. // 12 vertex x,y,z
  29936. var ico_vertices = [
  29937. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29938. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29939. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29940. ];
  29941. // index of 3 vertex makes a face of icopshere
  29942. var ico_indices = [
  29943. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29944. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29945. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29946. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  29947. ];
  29948. // vertex for uv have aliased position, not for UV
  29949. var vertices_unalias_id = [
  29950. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  29951. // vertex alias
  29952. 0,
  29953. 2,
  29954. 3,
  29955. 3,
  29956. 3,
  29957. 4,
  29958. 7,
  29959. 8,
  29960. 9,
  29961. 9,
  29962. 10,
  29963. 11 // 23: B + 12
  29964. ];
  29965. // uv as integer step (not pixels !)
  29966. var ico_vertexuv = [
  29967. 5, 1, 3, 1, 6, 4, 0, 0,
  29968. 5, 3, 4, 2, 2, 2, 4, 0,
  29969. 2, 0, 1, 1, 6, 0, 6, 2,
  29970. // vertex alias (for same vertex on different faces)
  29971. 0, 4,
  29972. 3, 3,
  29973. 4, 4,
  29974. 3, 1,
  29975. 4, 2,
  29976. 4, 4,
  29977. 0, 2,
  29978. 1, 1,
  29979. 2, 2,
  29980. 3, 3,
  29981. 1, 3,
  29982. 2, 4 // 23: B + 12
  29983. ];
  29984. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29985. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29986. // First island of uv mapping
  29987. // v = 4h 3+ 2
  29988. // v = 3h 9+ 4
  29989. // v = 2h 9+ 5 B
  29990. // v = 1h 9 1 0
  29991. // v = 0h 3 8 7 A
  29992. // u = 0 1 2 3 4 5 6 *a
  29993. // Second island of uv mapping
  29994. // v = 4h 0+ B+ 4+
  29995. // v = 3h A+ 2+
  29996. // v = 2h 7+ 6 3+
  29997. // v = 1h 8+ 3+
  29998. // v = 0h
  29999. // u = 0 1 2 3 4 5 6 *a
  30000. // Face layout on texture UV mapping
  30001. // ============
  30002. // \ 4 /\ 16 / ======
  30003. // \ / \ / /\ 11 /
  30004. // \/ 7 \/ / \ /
  30005. // ======= / 10 \/
  30006. // /\ 17 /\ =======
  30007. // / \ / \ \ 15 /\
  30008. // / 8 \/ 12 \ \ / \
  30009. // ============ \/ 6 \
  30010. // \ 18 /\ ============
  30011. // \ / \ \ 5 /\ 0 /
  30012. // \/ 13 \ \ / \ /
  30013. // ======= \/ 1 \/
  30014. // =============
  30015. // /\ 19 /\ 2 /\
  30016. // / \ / \ / \
  30017. // / 14 \/ 9 \/ 3 \
  30018. // ===================
  30019. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30020. var ustep = 138 / 1024;
  30021. var vstep = 239 / 1024;
  30022. var uoffset = 60 / 1024;
  30023. var voffset = 26 / 1024;
  30024. // Second island should have margin, not to touch the first island
  30025. // avoid any borderline artefact in pixel rounding
  30026. var island_u_offset = -40 / 1024;
  30027. var island_v_offset = +20 / 1024;
  30028. // face is either island 0 or 1 :
  30029. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30030. var island = [
  30031. 0, 0, 0, 0, 1,
  30032. 0, 0, 1, 1, 0,
  30033. 0, 0, 1, 1, 0,
  30034. 0, 1, 1, 1, 0 // 15 - 19
  30035. ];
  30036. var indices = [];
  30037. var positions = [];
  30038. var normals = [];
  30039. var uvs = [];
  30040. var current_indice = 0;
  30041. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30042. var face_vertex_pos = new Array(3);
  30043. var face_vertex_uv = new Array(3);
  30044. var v012;
  30045. for (v012 = 0; v012 < 3; v012++) {
  30046. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30047. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30048. }
  30049. // create all with normals
  30050. for (var face = 0; face < 20; face++) {
  30051. // 3 vertex per face
  30052. for (v012 = 0; v012 < 3; v012++) {
  30053. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30054. var v_id = ico_indices[3 * face + v012];
  30055. // vertex have 3D position (x,y,z)
  30056. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
  30057. // Normalize to get normal, then scale to radius
  30058. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30059. // uv Coordinates from vertex ID
  30060. face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
  30061. }
  30062. // Subdivide the face (interpolate pos, norm, uv)
  30063. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30064. // - norm is linear interpolation of vertex corner normal
  30065. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30066. // - uv is linear interpolation
  30067. //
  30068. // Topology is as below for sub-divide by 2
  30069. // vertex shown as v0,v1,v2
  30070. // interp index is i1 to progress in range [v0,v1[
  30071. // interp index is i2 to progress in range [v0,v2[
  30072. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30073. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30074. //
  30075. //
  30076. // i2 v2
  30077. // ^ ^
  30078. // / / \
  30079. // / / \
  30080. // / / \
  30081. // / / (0,1) \
  30082. // / #---------\
  30083. // / / \ (0,0)'/ \
  30084. // / / \ / \
  30085. // / / \ / \
  30086. // / / (0,0) \ / (1,0) \
  30087. // / #---------#---------\
  30088. // v0 v1
  30089. //
  30090. // --------------------> i1
  30091. //
  30092. // interp of (i1,i2):
  30093. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30094. // along i1 : lerp(x0,x1, i1/(S-i2))
  30095. //
  30096. // centroid of triangle is needed to get help normal computation
  30097. // (c1,c2) are used for centroid location
  30098. var interp_vertex = function (i1, i2, c1, c2) {
  30099. // vertex is interpolated from
  30100. // - face_vertex_pos[0..2]
  30101. // - face_vertex_uv[0..2]
  30102. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30103. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30104. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30105. pos_interp.normalize();
  30106. var vertex_normal;
  30107. if (flat) {
  30108. // in flat mode, recalculate normal as face centroid normal
  30109. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30110. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30111. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30112. }
  30113. else {
  30114. // in smooth mode, recalculate normal from each single vertex position
  30115. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30116. }
  30117. // Vertex normal need correction due to X,Y,Z radius scaling
  30118. vertex_normal.x /= radiusX;
  30119. vertex_normal.y /= radiusY;
  30120. vertex_normal.z /= radiusZ;
  30121. vertex_normal.normalize();
  30122. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30123. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30124. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30125. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30126. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30127. uvs.push(uv_interp.x, uv_interp.y);
  30128. // push each vertex has member of a face
  30129. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30130. indices.push(current_indice);
  30131. current_indice++;
  30132. };
  30133. for (var i2 = 0; i2 < subdivisions; i2++) {
  30134. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30135. // face : (i1,i2) for /\ :
  30136. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30137. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30138. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30139. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30140. if (i1 + i2 + 1 < subdivisions) {
  30141. // face : (i1,i2)' for \/ :
  30142. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30143. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30144. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30145. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30146. }
  30147. }
  30148. }
  30149. }
  30150. // Sides
  30151. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30152. // Result
  30153. var vertexData = new VertexData();
  30154. vertexData.indices = indices;
  30155. vertexData.positions = positions;
  30156. vertexData.normals = normals;
  30157. vertexData.uvs = uvs;
  30158. return vertexData;
  30159. };
  30160. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30161. VertexData.CreatePolyhedron = function (options) {
  30162. // provided polyhedron types :
  30163. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30164. // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  30165. var polyhedra = [];
  30166. polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
  30167. polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
  30168. polyhedra[2] = {
  30169. vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
  30170. face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
  30171. };
  30172. polyhedra[3] = {
  30173. vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
  30174. face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
  30175. };
  30176. polyhedra[4] = {
  30177. vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
  30178. face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
  30179. };
  30180. polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
  30181. polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
  30182. polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
  30183. polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
  30184. polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
  30185. polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
  30186. polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
  30187. polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
  30188. polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
  30189. polyhedra[14] = {
  30190. vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
  30191. face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
  30192. };
  30193. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30194. var size = options.size;
  30195. var sizeX = options.sizeX || size || 1;
  30196. var sizeY = options.sizeY || size || 1;
  30197. var sizeZ = options.sizeZ || size || 1;
  30198. var data = options.custom || polyhedra[type];
  30199. var nbfaces = data.face.length;
  30200. var faceUV = options.faceUV || new Array(nbfaces);
  30201. var faceColors = options.faceColors;
  30202. var flat = (options.flat === undefined) ? true : options.flat;
  30203. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30204. var positions = [];
  30205. var indices = [];
  30206. var normals = [];
  30207. var uvs = [];
  30208. var colors = [];
  30209. var index = 0;
  30210. var faceIdx = 0; // face cursor in the array "indexes"
  30211. var indexes = [];
  30212. var i = 0;
  30213. var f = 0;
  30214. var u, v, ang, x, y, tmp;
  30215. // default face colors and UV if undefined
  30216. if (flat) {
  30217. for (f = 0; f < nbfaces; f++) {
  30218. if (faceColors && faceColors[f] === undefined) {
  30219. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30220. }
  30221. if (faceUV && faceUV[f] === undefined) {
  30222. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30223. }
  30224. }
  30225. }
  30226. if (!flat) {
  30227. for (i = 0; i < data.vertex.length; i++) {
  30228. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30229. uvs.push(0, 0);
  30230. }
  30231. for (f = 0; f < nbfaces; f++) {
  30232. for (i = 0; i < data.face[f].length - 2; i++) {
  30233. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30234. }
  30235. }
  30236. }
  30237. else {
  30238. for (f = 0; f < nbfaces; f++) {
  30239. var fl = data.face[f].length; // number of vertices of the current face
  30240. ang = 2 * Math.PI / fl;
  30241. x = 0.5 * Math.tan(ang / 2);
  30242. y = 0.5;
  30243. // positions, uvs, colors
  30244. for (i = 0; i < fl; i++) {
  30245. // positions
  30246. positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
  30247. indexes.push(index);
  30248. index++;
  30249. // uvs
  30250. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30251. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30252. uvs.push(u, v);
  30253. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30254. y = x * Math.sin(ang) + y * Math.cos(ang);
  30255. x = tmp;
  30256. // colors
  30257. if (faceColors) {
  30258. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30259. }
  30260. }
  30261. // indices from indexes
  30262. for (i = 0; i < fl - 2; i++) {
  30263. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30264. }
  30265. faceIdx += fl;
  30266. }
  30267. }
  30268. VertexData.ComputeNormals(positions, indices, normals);
  30269. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30270. var vertexData = new VertexData();
  30271. vertexData.positions = positions;
  30272. vertexData.indices = indices;
  30273. vertexData.normals = normals;
  30274. vertexData.uvs = uvs;
  30275. if (faceColors && flat) {
  30276. vertexData.colors = colors;
  30277. }
  30278. return vertexData;
  30279. };
  30280. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30281. VertexData.CreateTorusKnot = function (options) {
  30282. var indices = [];
  30283. var positions = [];
  30284. var normals = [];
  30285. var uvs = [];
  30286. var radius = options.radius || 2;
  30287. var tube = options.tube || 0.5;
  30288. var radialSegments = options.radialSegments || 32;
  30289. var tubularSegments = options.tubularSegments || 32;
  30290. var p = options.p || 2;
  30291. var q = options.q || 3;
  30292. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30293. // Helper
  30294. var getPos = function (angle) {
  30295. var cu = Math.cos(angle);
  30296. var su = Math.sin(angle);
  30297. var quOverP = q / p * angle;
  30298. var cs = Math.cos(quOverP);
  30299. var tx = radius * (2 + cs) * 0.5 * cu;
  30300. var ty = radius * (2 + cs) * su * 0.5;
  30301. var tz = radius * Math.sin(quOverP) * 0.5;
  30302. return new BABYLON.Vector3(tx, ty, tz);
  30303. };
  30304. // Vertices
  30305. var i;
  30306. var j;
  30307. for (i = 0; i <= radialSegments; i++) {
  30308. var modI = i % radialSegments;
  30309. var u = modI / radialSegments * 2 * p * Math.PI;
  30310. var p1 = getPos(u);
  30311. var p2 = getPos(u + 0.01);
  30312. var tang = p2.subtract(p1);
  30313. var n = p2.add(p1);
  30314. var bitan = BABYLON.Vector3.Cross(tang, n);
  30315. n = BABYLON.Vector3.Cross(bitan, tang);
  30316. bitan.normalize();
  30317. n.normalize();
  30318. for (j = 0; j < tubularSegments; j++) {
  30319. var modJ = j % tubularSegments;
  30320. var v = modJ / tubularSegments * 2 * Math.PI;
  30321. var cx = -tube * Math.cos(v);
  30322. var cy = tube * Math.sin(v);
  30323. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30324. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30325. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30326. uvs.push(i / radialSegments);
  30327. uvs.push(j / tubularSegments);
  30328. }
  30329. }
  30330. for (i = 0; i < radialSegments; i++) {
  30331. for (j = 0; j < tubularSegments; j++) {
  30332. var jNext = (j + 1) % tubularSegments;
  30333. var a = i * tubularSegments + j;
  30334. var b = (i + 1) * tubularSegments + j;
  30335. var c = (i + 1) * tubularSegments + jNext;
  30336. var d = i * tubularSegments + jNext;
  30337. indices.push(d);
  30338. indices.push(b);
  30339. indices.push(a);
  30340. indices.push(d);
  30341. indices.push(c);
  30342. indices.push(b);
  30343. }
  30344. }
  30345. // Normals
  30346. VertexData.ComputeNormals(positions, indices, normals);
  30347. // Sides
  30348. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30349. // Result
  30350. var vertexData = new VertexData();
  30351. vertexData.indices = indices;
  30352. vertexData.positions = positions;
  30353. vertexData.normals = normals;
  30354. vertexData.uvs = uvs;
  30355. return vertexData;
  30356. };
  30357. // Tools
  30358. /**
  30359. * @param {any} - positions (number[] or Float32Array)
  30360. * @param {any} - indices (number[] or Uint16Array)
  30361. * @param {any} - normals (number[] or Float32Array)
  30362. */
  30363. VertexData.ComputeNormals = function (positions, indices, normals) {
  30364. var index = 0;
  30365. var p1p2x = 0.0;
  30366. var p1p2y = 0.0;
  30367. var p1p2z = 0.0;
  30368. var p3p2x = 0.0;
  30369. var p3p2y = 0.0;
  30370. var p3p2z = 0.0;
  30371. var faceNormalx = 0.0;
  30372. var faceNormaly = 0.0;
  30373. var faceNormalz = 0.0;
  30374. var length = 0.0;
  30375. var i1 = 0;
  30376. var i2 = 0;
  30377. var i3 = 0;
  30378. for (index = 0; index < positions.length; index++) {
  30379. normals[index] = 0.0;
  30380. }
  30381. // indice triplet = 1 face
  30382. var nbFaces = indices.length / 3;
  30383. for (index = 0; index < nbFaces; index++) {
  30384. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  30385. i2 = indices[index * 3 + 1];
  30386. i3 = indices[index * 3 + 2];
  30387. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  30388. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  30389. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  30390. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  30391. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  30392. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  30393. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  30394. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  30395. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  30396. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30397. length = (length === 0) ? 1.0 : length;
  30398. faceNormalx /= length; // normalize this normal
  30399. faceNormaly /= length;
  30400. faceNormalz /= length;
  30401. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  30402. normals[i1 * 3 + 1] += faceNormaly;
  30403. normals[i1 * 3 + 2] += faceNormalz;
  30404. normals[i2 * 3] += faceNormalx;
  30405. normals[i2 * 3 + 1] += faceNormaly;
  30406. normals[i2 * 3 + 2] += faceNormalz;
  30407. normals[i3 * 3] += faceNormalx;
  30408. normals[i3 * 3 + 1] += faceNormaly;
  30409. normals[i3 * 3 + 2] += faceNormalz;
  30410. }
  30411. // last normalization of each normal
  30412. for (index = 0; index < normals.length / 3; index++) {
  30413. faceNormalx = normals[index * 3];
  30414. faceNormaly = normals[index * 3 + 1];
  30415. faceNormalz = normals[index * 3 + 2];
  30416. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30417. length = (length === 0) ? 1.0 : length;
  30418. faceNormalx /= length;
  30419. faceNormaly /= length;
  30420. faceNormalz /= length;
  30421. normals[index * 3] = faceNormalx;
  30422. normals[index * 3 + 1] = faceNormaly;
  30423. normals[index * 3 + 2] = faceNormalz;
  30424. }
  30425. };
  30426. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  30427. var li = indices.length;
  30428. var ln = normals.length;
  30429. var i;
  30430. var n;
  30431. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30432. switch (sideOrientation) {
  30433. case BABYLON.Mesh.FRONTSIDE:
  30434. // nothing changed
  30435. break;
  30436. case BABYLON.Mesh.BACKSIDE:
  30437. var tmp;
  30438. // indices
  30439. for (i = 0; i < li; i += 3) {
  30440. tmp = indices[i];
  30441. indices[i] = indices[i + 2];
  30442. indices[i + 2] = tmp;
  30443. }
  30444. // normals
  30445. for (n = 0; n < ln; n++) {
  30446. normals[n] = -normals[n];
  30447. }
  30448. break;
  30449. case BABYLON.Mesh.DOUBLESIDE:
  30450. // positions
  30451. var lp = positions.length;
  30452. var l = lp / 3;
  30453. for (var p = 0; p < lp; p++) {
  30454. positions[lp + p] = positions[p];
  30455. }
  30456. // indices
  30457. for (i = 0; i < li; i += 3) {
  30458. indices[i + li] = indices[i + 2] + l;
  30459. indices[i + 1 + li] = indices[i + 1] + l;
  30460. indices[i + 2 + li] = indices[i] + l;
  30461. }
  30462. // normals
  30463. for (n = 0; n < ln; n++) {
  30464. normals[ln + n] = -normals[n];
  30465. }
  30466. // uvs
  30467. var lu = uvs.length;
  30468. for (var u = 0; u < lu; u++) {
  30469. uvs[u + lu] = uvs[u];
  30470. }
  30471. break;
  30472. }
  30473. };
  30474. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30475. var vertexData = new VertexData();
  30476. // positions
  30477. var positions = parsedVertexData.positions;
  30478. if (positions) {
  30479. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30480. }
  30481. // normals
  30482. var normals = parsedVertexData.normals;
  30483. if (normals) {
  30484. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30485. }
  30486. // uvs
  30487. var uvs = parsedVertexData.uvs;
  30488. if (uvs) {
  30489. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30490. }
  30491. // uv2s
  30492. var uv2s = parsedVertexData.uv2s;
  30493. if (uv2s) {
  30494. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30495. }
  30496. // uv3s
  30497. var uv3s = parsedVertexData.uv3s;
  30498. if (uv3s) {
  30499. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30500. }
  30501. // uv4s
  30502. var uv4s = parsedVertexData.uv4s;
  30503. if (uv4s) {
  30504. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30505. }
  30506. // uv5s
  30507. var uv5s = parsedVertexData.uv5s;
  30508. if (uv5s) {
  30509. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30510. }
  30511. // uv6s
  30512. var uv6s = parsedVertexData.uv6s;
  30513. if (uv6s) {
  30514. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30515. }
  30516. // colors
  30517. var colors = parsedVertexData.colors;
  30518. if (colors) {
  30519. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30520. }
  30521. // matricesIndices
  30522. var matricesIndices = parsedVertexData.matricesIndices;
  30523. if (matricesIndices) {
  30524. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30525. }
  30526. // matricesWeights
  30527. var matricesWeights = parsedVertexData.matricesWeights;
  30528. if (matricesWeights) {
  30529. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30530. }
  30531. // indices
  30532. var indices = parsedVertexData.indices;
  30533. if (indices) {
  30534. vertexData.indices = indices;
  30535. }
  30536. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30537. };
  30538. return VertexData;
  30539. })();
  30540. BABYLON.VertexData = VertexData;
  30541. })(BABYLON || (BABYLON = {}));
  30542. var BABYLON;
  30543. (function (BABYLON) {
  30544. var Tags = (function () {
  30545. function Tags() {
  30546. }
  30547. Tags.EnableFor = function (obj) {
  30548. obj._tags = obj._tags || {};
  30549. obj.hasTags = function () {
  30550. return Tags.HasTags(obj);
  30551. };
  30552. obj.addTags = function (tagsString) {
  30553. return Tags.AddTagsTo(obj, tagsString);
  30554. };
  30555. obj.removeTags = function (tagsString) {
  30556. return Tags.RemoveTagsFrom(obj, tagsString);
  30557. };
  30558. obj.matchesTagsQuery = function (tagsQuery) {
  30559. return Tags.MatchesQuery(obj, tagsQuery);
  30560. };
  30561. };
  30562. Tags.DisableFor = function (obj) {
  30563. delete obj._tags;
  30564. delete obj.hasTags;
  30565. delete obj.addTags;
  30566. delete obj.removeTags;
  30567. delete obj.matchesTagsQuery;
  30568. };
  30569. Tags.HasTags = function (obj) {
  30570. if (!obj._tags) {
  30571. return false;
  30572. }
  30573. return !BABYLON.Tools.IsEmpty(obj._tags);
  30574. };
  30575. Tags.GetTags = function (obj, asString) {
  30576. if (asString === void 0) { asString = true; }
  30577. if (!obj._tags) {
  30578. return null;
  30579. }
  30580. if (asString) {
  30581. var tagsArray = [];
  30582. for (var tag in obj._tags) {
  30583. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  30584. tagsArray.push(tag);
  30585. }
  30586. }
  30587. return tagsArray.join(" ");
  30588. }
  30589. else {
  30590. return obj._tags;
  30591. }
  30592. };
  30593. // the tags 'true' and 'false' are reserved and cannot be used as tags
  30594. // a tag cannot start with '||', '&&', and '!'
  30595. // it cannot contain whitespaces
  30596. Tags.AddTagsTo = function (obj, tagsString) {
  30597. if (!tagsString) {
  30598. return;
  30599. }
  30600. if (typeof tagsString !== "string") {
  30601. return;
  30602. }
  30603. var tags = tagsString.split(" ");
  30604. for (var t in tags) {
  30605. Tags._AddTagTo(obj, tags[t]);
  30606. }
  30607. };
  30608. Tags._AddTagTo = function (obj, tag) {
  30609. tag = tag.trim();
  30610. if (tag === "" || tag === "true" || tag === "false") {
  30611. return;
  30612. }
  30613. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  30614. return;
  30615. }
  30616. Tags.EnableFor(obj);
  30617. obj._tags[tag] = true;
  30618. };
  30619. Tags.RemoveTagsFrom = function (obj, tagsString) {
  30620. if (!Tags.HasTags(obj)) {
  30621. return;
  30622. }
  30623. var tags = tagsString.split(" ");
  30624. for (var t in tags) {
  30625. Tags._RemoveTagFrom(obj, tags[t]);
  30626. }
  30627. };
  30628. Tags._RemoveTagFrom = function (obj, tag) {
  30629. delete obj._tags[tag];
  30630. };
  30631. Tags.MatchesQuery = function (obj, tagsQuery) {
  30632. if (tagsQuery === undefined) {
  30633. return true;
  30634. }
  30635. if (tagsQuery === "") {
  30636. return Tags.HasTags(obj);
  30637. }
  30638. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  30639. };
  30640. return Tags;
  30641. })();
  30642. BABYLON.Tags = Tags;
  30643. })(BABYLON || (BABYLON = {}));
  30644. var BABYLON;
  30645. (function (BABYLON) {
  30646. var Internals;
  30647. (function (Internals) {
  30648. var AndOrNotEvaluator = (function () {
  30649. function AndOrNotEvaluator() {
  30650. }
  30651. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  30652. if (!query.match(/\([^\(\)]*\)/g)) {
  30653. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  30654. }
  30655. else {
  30656. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  30657. // remove parenthesis
  30658. r = r.slice(1, r.length - 1);
  30659. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  30660. });
  30661. }
  30662. if (query === "true") {
  30663. return true;
  30664. }
  30665. if (query === "false") {
  30666. return false;
  30667. }
  30668. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  30669. };
  30670. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  30671. evaluateCallback = evaluateCallback || (function (r) {
  30672. return r === "true" ? true : false;
  30673. });
  30674. var result;
  30675. var or = parenthesisContent.split("||");
  30676. for (var i in or) {
  30677. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  30678. var and = ori.split("&&");
  30679. if (and.length > 1) {
  30680. for (var j = 0; j < and.length; ++j) {
  30681. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  30682. if (andj !== "true" && andj !== "false") {
  30683. if (andj[0] === "!") {
  30684. result = !evaluateCallback(andj.substring(1));
  30685. }
  30686. else {
  30687. result = evaluateCallback(andj);
  30688. }
  30689. }
  30690. else {
  30691. result = andj === "true" ? true : false;
  30692. }
  30693. if (!result) {
  30694. ori = "false";
  30695. break;
  30696. }
  30697. }
  30698. }
  30699. if (result || ori === "true") {
  30700. result = true;
  30701. break;
  30702. }
  30703. // result equals false (or undefined)
  30704. if (ori !== "true" && ori !== "false") {
  30705. if (ori[0] === "!") {
  30706. result = !evaluateCallback(ori.substring(1));
  30707. }
  30708. else {
  30709. result = evaluateCallback(ori);
  30710. }
  30711. }
  30712. else {
  30713. result = ori === "true" ? true : false;
  30714. }
  30715. }
  30716. // the whole parenthesis scope is replaced by 'true' or 'false'
  30717. return result ? "true" : "false";
  30718. };
  30719. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  30720. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  30721. // remove whitespaces
  30722. r = r.replace(/[\s]/g, function () { return ""; });
  30723. return r.length % 2 ? "!" : "";
  30724. });
  30725. booleanString = booleanString.trim();
  30726. if (booleanString === "!true") {
  30727. booleanString = "false";
  30728. }
  30729. else if (booleanString === "!false") {
  30730. booleanString = "true";
  30731. }
  30732. return booleanString;
  30733. };
  30734. return AndOrNotEvaluator;
  30735. })();
  30736. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  30737. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30738. })(BABYLON || (BABYLON = {}));
  30739. var BABYLON;
  30740. (function (BABYLON) {
  30741. var PostProcessRenderPass = (function () {
  30742. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  30743. this._enabled = true;
  30744. this._refCount = 0;
  30745. this._name = name;
  30746. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  30747. this.setRenderList(renderList);
  30748. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  30749. this._renderTexture.onAfterRenderObservable.add(afterRender);
  30750. this._scene = scene;
  30751. this._renderList = renderList;
  30752. }
  30753. // private
  30754. PostProcessRenderPass.prototype._incRefCount = function () {
  30755. if (this._refCount === 0) {
  30756. this._scene.customRenderTargets.push(this._renderTexture);
  30757. }
  30758. return ++this._refCount;
  30759. };
  30760. PostProcessRenderPass.prototype._decRefCount = function () {
  30761. this._refCount--;
  30762. if (this._refCount <= 0) {
  30763. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  30764. }
  30765. return this._refCount;
  30766. };
  30767. PostProcessRenderPass.prototype._update = function () {
  30768. this.setRenderList(this._renderList);
  30769. };
  30770. // public
  30771. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  30772. this._renderTexture.renderList = renderList;
  30773. };
  30774. PostProcessRenderPass.prototype.getRenderTexture = function () {
  30775. return this._renderTexture;
  30776. };
  30777. return PostProcessRenderPass;
  30778. })();
  30779. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  30780. })(BABYLON || (BABYLON = {}));
  30781. var BABYLON;
  30782. (function (BABYLON) {
  30783. var PostProcessRenderEffect = (function () {
  30784. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  30785. this._engine = engine;
  30786. this._name = name;
  30787. this._singleInstance = singleInstance || true;
  30788. this._getPostProcess = getPostProcess;
  30789. this._cameras = [];
  30790. this._indicesForCamera = [];
  30791. this._postProcesses = {};
  30792. this._renderPasses = {};
  30793. this._renderEffectAsPasses = {};
  30794. }
  30795. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  30796. get: function () {
  30797. for (var index in this._postProcesses) {
  30798. if (!this._postProcesses[index].isSupported) {
  30799. return false;
  30800. }
  30801. }
  30802. return true;
  30803. },
  30804. enumerable: true,
  30805. configurable: true
  30806. });
  30807. PostProcessRenderEffect.prototype._update = function () {
  30808. for (var renderPassName in this._renderPasses) {
  30809. this._renderPasses[renderPassName]._update();
  30810. }
  30811. };
  30812. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  30813. this._renderPasses[renderPass._name] = renderPass;
  30814. this._linkParameters();
  30815. };
  30816. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  30817. delete this._renderPasses[renderPass._name];
  30818. this._linkParameters();
  30819. };
  30820. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  30821. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  30822. this._linkParameters();
  30823. };
  30824. PostProcessRenderEffect.prototype.getPass = function (passName) {
  30825. for (var renderPassName in this._renderPasses) {
  30826. if (renderPassName === passName) {
  30827. return this._renderPasses[passName];
  30828. }
  30829. }
  30830. };
  30831. PostProcessRenderEffect.prototype.emptyPasses = function () {
  30832. this._renderPasses = {};
  30833. this._linkParameters();
  30834. };
  30835. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  30836. var cameraKey;
  30837. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30838. for (var i = 0; i < _cam.length; i++) {
  30839. var camera = _cam[i];
  30840. var cameraName = camera.name;
  30841. if (this._singleInstance) {
  30842. cameraKey = 0;
  30843. }
  30844. else {
  30845. cameraKey = cameraName;
  30846. }
  30847. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  30848. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  30849. if (!this._indicesForCamera[cameraName]) {
  30850. this._indicesForCamera[cameraName] = [];
  30851. }
  30852. this._indicesForCamera[cameraName].push(index);
  30853. if (this._cameras.indexOf(camera) === -1) {
  30854. this._cameras[cameraName] = camera;
  30855. }
  30856. for (var passName in this._renderPasses) {
  30857. this._renderPasses[passName]._incRefCount();
  30858. }
  30859. }
  30860. this._linkParameters();
  30861. };
  30862. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  30863. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30864. for (var i = 0; i < _cam.length; i++) {
  30865. var camera = _cam[i];
  30866. var cameraName = camera.name;
  30867. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  30868. var index = this._cameras.indexOf(cameraName);
  30869. this._indicesForCamera.splice(index, 1);
  30870. this._cameras.splice(index, 1);
  30871. for (var passName in this._renderPasses) {
  30872. this._renderPasses[passName]._decRefCount();
  30873. }
  30874. }
  30875. };
  30876. PostProcessRenderEffect.prototype._enable = function (cameras) {
  30877. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30878. for (var i = 0; i < _cam.length; i++) {
  30879. var camera = _cam[i];
  30880. var cameraName = camera.name;
  30881. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  30882. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  30883. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  30884. }
  30885. }
  30886. for (var passName in this._renderPasses) {
  30887. this._renderPasses[passName]._incRefCount();
  30888. }
  30889. }
  30890. };
  30891. PostProcessRenderEffect.prototype._disable = function (cameras) {
  30892. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30893. for (var i = 0; i < _cam.length; i++) {
  30894. var camera = _cam[i];
  30895. var cameraName = camera.Name;
  30896. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  30897. for (var passName in this._renderPasses) {
  30898. this._renderPasses[passName]._decRefCount();
  30899. }
  30900. }
  30901. };
  30902. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  30903. if (this._singleInstance) {
  30904. return this._postProcesses[0];
  30905. }
  30906. else {
  30907. return this._postProcesses[camera.name];
  30908. }
  30909. };
  30910. PostProcessRenderEffect.prototype._linkParameters = function () {
  30911. var _this = this;
  30912. for (var index in this._postProcesses) {
  30913. if (this.applyParameters) {
  30914. this.applyParameters(this._postProcesses[index]);
  30915. }
  30916. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  30917. _this._linkTextures(effect);
  30918. });
  30919. }
  30920. };
  30921. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  30922. for (var renderPassName in this._renderPasses) {
  30923. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  30924. }
  30925. for (var renderEffectName in this._renderEffectAsPasses) {
  30926. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  30927. }
  30928. };
  30929. return PostProcessRenderEffect;
  30930. })();
  30931. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  30932. })(BABYLON || (BABYLON = {}));
  30933. var BABYLON;
  30934. (function (BABYLON) {
  30935. var PostProcessRenderPipeline = (function () {
  30936. function PostProcessRenderPipeline(engine, name) {
  30937. this._engine = engine;
  30938. this._name = name;
  30939. this._renderEffects = {};
  30940. this._renderEffectsForIsolatedPass = {};
  30941. this._cameras = [];
  30942. }
  30943. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  30944. get: function () {
  30945. for (var renderEffectName in this._renderEffects) {
  30946. if (!this._renderEffects[renderEffectName].isSupported) {
  30947. return false;
  30948. }
  30949. }
  30950. return true;
  30951. },
  30952. enumerable: true,
  30953. configurable: true
  30954. });
  30955. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  30956. this._renderEffects[renderEffect._name] = renderEffect;
  30957. };
  30958. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  30959. var renderEffects = this._renderEffects[renderEffectName];
  30960. if (!renderEffects) {
  30961. return;
  30962. }
  30963. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  30964. };
  30965. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  30966. var renderEffects = this._renderEffects[renderEffectName];
  30967. if (!renderEffects) {
  30968. return;
  30969. }
  30970. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  30971. };
  30972. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  30973. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30974. var indicesToDelete = [];
  30975. var i;
  30976. for (i = 0; i < _cam.length; i++) {
  30977. var camera = _cam[i];
  30978. var cameraName = camera.name;
  30979. if (this._cameras.indexOf(camera) === -1) {
  30980. this._cameras[cameraName] = camera;
  30981. }
  30982. else if (unique) {
  30983. indicesToDelete.push(i);
  30984. }
  30985. }
  30986. for (i = 0; i < indicesToDelete.length; i++) {
  30987. cameras.splice(indicesToDelete[i], 1);
  30988. }
  30989. for (var renderEffectName in this._renderEffects) {
  30990. this._renderEffects[renderEffectName]._attachCameras(_cam);
  30991. }
  30992. };
  30993. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  30994. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30995. for (var renderEffectName in this._renderEffects) {
  30996. this._renderEffects[renderEffectName]._detachCameras(_cam);
  30997. }
  30998. for (var i = 0; i < _cam.length; i++) {
  30999. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  31000. }
  31001. };
  31002. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  31003. var _this = this;
  31004. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31005. var pass = null;
  31006. var renderEffectName;
  31007. for (renderEffectName in this._renderEffects) {
  31008. pass = this._renderEffects[renderEffectName].getPass(passName);
  31009. if (pass != null) {
  31010. break;
  31011. }
  31012. }
  31013. if (pass === null) {
  31014. return;
  31015. }
  31016. for (renderEffectName in this._renderEffects) {
  31017. this._renderEffects[renderEffectName]._disable(_cam);
  31018. }
  31019. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  31020. for (var i = 0; i < _cam.length; i++) {
  31021. var camera = _cam[i];
  31022. var cameraName = camera.name;
  31023. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  31024. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  31025. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  31026. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  31027. }
  31028. };
  31029. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  31030. var _this = this;
  31031. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31032. for (var i = 0; i < _cam.length; i++) {
  31033. var camera = _cam[i];
  31034. var cameraName = camera.name;
  31035. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  31036. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  31037. }
  31038. for (var renderEffectName in this._renderEffects) {
  31039. this._renderEffects[renderEffectName]._enable(_cam);
  31040. }
  31041. };
  31042. PostProcessRenderPipeline.prototype._update = function () {
  31043. for (var renderEffectName in this._renderEffects) {
  31044. this._renderEffects[renderEffectName]._update();
  31045. }
  31046. for (var i = 0; i < this._cameras.length; i++) {
  31047. var cameraName = this._cameras[i].name;
  31048. if (this._renderEffectsForIsolatedPass[cameraName]) {
  31049. this._renderEffectsForIsolatedPass[cameraName]._update();
  31050. }
  31051. }
  31052. };
  31053. PostProcessRenderPipeline.prototype.dispose = function () {
  31054. // Must be implemented by children
  31055. };
  31056. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  31057. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  31058. return PostProcessRenderPipeline;
  31059. })();
  31060. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  31061. })(BABYLON || (BABYLON = {}));
  31062. var BABYLON;
  31063. (function (BABYLON) {
  31064. var PostProcessRenderPipelineManager = (function () {
  31065. function PostProcessRenderPipelineManager() {
  31066. this._renderPipelines = {};
  31067. }
  31068. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  31069. this._renderPipelines[renderPipeline._name] = renderPipeline;
  31070. };
  31071. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  31072. var renderPipeline = this._renderPipelines[renderPipelineName];
  31073. if (!renderPipeline) {
  31074. return;
  31075. }
  31076. renderPipeline._attachCameras(cameras, unique);
  31077. };
  31078. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  31079. var renderPipeline = this._renderPipelines[renderPipelineName];
  31080. if (!renderPipeline) {
  31081. return;
  31082. }
  31083. renderPipeline._detachCameras(cameras);
  31084. };
  31085. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  31086. var renderPipeline = this._renderPipelines[renderPipelineName];
  31087. if (!renderPipeline) {
  31088. return;
  31089. }
  31090. renderPipeline._enableEffect(renderEffectName, cameras);
  31091. };
  31092. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  31093. var renderPipeline = this._renderPipelines[renderPipelineName];
  31094. if (!renderPipeline) {
  31095. return;
  31096. }
  31097. renderPipeline._disableEffect(renderEffectName, cameras);
  31098. };
  31099. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  31100. var renderPipeline = this._renderPipelines[renderPipelineName];
  31101. if (!renderPipeline) {
  31102. return;
  31103. }
  31104. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  31105. };
  31106. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  31107. var renderPipeline = this._renderPipelines[renderPipelineName];
  31108. if (!renderPipeline) {
  31109. return;
  31110. }
  31111. renderPipeline._disableDisplayOnlyPass(cameras);
  31112. };
  31113. PostProcessRenderPipelineManager.prototype.update = function () {
  31114. for (var renderPipelineName in this._renderPipelines) {
  31115. var pipeline = this._renderPipelines[renderPipelineName];
  31116. if (!pipeline.isSupported) {
  31117. pipeline.dispose();
  31118. delete this._renderPipelines[renderPipelineName];
  31119. }
  31120. else {
  31121. pipeline._update();
  31122. }
  31123. }
  31124. };
  31125. return PostProcessRenderPipelineManager;
  31126. })();
  31127. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  31128. })(BABYLON || (BABYLON = {}));
  31129. var BABYLON;
  31130. (function (BABYLON) {
  31131. var BoundingBoxRenderer = (function () {
  31132. function BoundingBoxRenderer(scene) {
  31133. this.frontColor = new BABYLON.Color3(1, 1, 1);
  31134. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  31135. this.showBackLines = true;
  31136. this.renderList = new BABYLON.SmartArray(32);
  31137. this._vertexBuffers = {};
  31138. this._scene = scene;
  31139. }
  31140. BoundingBoxRenderer.prototype._prepareRessources = function () {
  31141. if (this._colorShader) {
  31142. return;
  31143. }
  31144. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  31145. attributes: [BABYLON.VertexBuffer.PositionKind],
  31146. uniforms: ["worldViewProjection", "color"]
  31147. });
  31148. var engine = this._scene.getEngine();
  31149. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  31150. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  31151. this._indexBuffer = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
  31152. };
  31153. BoundingBoxRenderer.prototype.reset = function () {
  31154. this.renderList.reset();
  31155. };
  31156. BoundingBoxRenderer.prototype.render = function () {
  31157. if (this.renderList.length === 0) {
  31158. return;
  31159. }
  31160. this._prepareRessources();
  31161. if (!this._colorShader.isReady()) {
  31162. return;
  31163. }
  31164. var engine = this._scene.getEngine();
  31165. engine.setDepthWrite(false);
  31166. this._colorShader._preBind();
  31167. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  31168. var boundingBox = this.renderList.data[boundingBoxIndex];
  31169. var min = boundingBox.minimum;
  31170. var max = boundingBox.maximum;
  31171. var diff = max.subtract(min);
  31172. var median = min.add(diff.scale(0.5));
  31173. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  31174. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  31175. .multiply(boundingBox.getWorldMatrix());
  31176. // VBOs
  31177. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  31178. if (this.showBackLines) {
  31179. // Back
  31180. engine.setDepthFunctionToGreaterOrEqual();
  31181. this._scene.resetCachedMaterial();
  31182. this._colorShader.setColor4("color", this.backColor.toColor4());
  31183. this._colorShader.bind(worldMatrix);
  31184. // Draw order
  31185. engine.draw(false, 0, 24);
  31186. }
  31187. // Front
  31188. engine.setDepthFunctionToLess();
  31189. this._scene.resetCachedMaterial();
  31190. this._colorShader.setColor4("color", this.frontColor.toColor4());
  31191. this._colorShader.bind(worldMatrix);
  31192. // Draw order
  31193. engine.draw(false, 0, 24);
  31194. }
  31195. this._colorShader.unbind();
  31196. engine.setDepthFunctionToLessOrEqual();
  31197. engine.setDepthWrite(true);
  31198. };
  31199. BoundingBoxRenderer.prototype.dispose = function () {
  31200. if (!this._colorShader) {
  31201. return;
  31202. }
  31203. this._colorShader.dispose();
  31204. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31205. if (buffer) {
  31206. buffer.dispose();
  31207. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31208. }
  31209. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31210. };
  31211. return BoundingBoxRenderer;
  31212. })();
  31213. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  31214. })(BABYLON || (BABYLON = {}));
  31215. var BABYLON;
  31216. (function (BABYLON) {
  31217. var Condition = (function () {
  31218. function Condition(actionManager) {
  31219. this._actionManager = actionManager;
  31220. }
  31221. Condition.prototype.isValid = function () {
  31222. return true;
  31223. };
  31224. Condition.prototype._getProperty = function (propertyPath) {
  31225. return this._actionManager._getProperty(propertyPath);
  31226. };
  31227. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  31228. return this._actionManager._getEffectiveTarget(target, propertyPath);
  31229. };
  31230. Condition.prototype.serialize = function () {
  31231. };
  31232. Condition.prototype._serialize = function (serializedCondition) {
  31233. return {
  31234. type: 2,
  31235. children: [],
  31236. name: serializedCondition.name,
  31237. properties: serializedCondition.properties
  31238. };
  31239. };
  31240. return Condition;
  31241. })();
  31242. BABYLON.Condition = Condition;
  31243. var ValueCondition = (function (_super) {
  31244. __extends(ValueCondition, _super);
  31245. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  31246. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  31247. _super.call(this, actionManager);
  31248. this.propertyPath = propertyPath;
  31249. this.value = value;
  31250. this.operator = operator;
  31251. this._target = target;
  31252. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  31253. this._property = this._getProperty(this.propertyPath);
  31254. }
  31255. Object.defineProperty(ValueCondition, "IsEqual", {
  31256. get: function () {
  31257. return ValueCondition._IsEqual;
  31258. },
  31259. enumerable: true,
  31260. configurable: true
  31261. });
  31262. Object.defineProperty(ValueCondition, "IsDifferent", {
  31263. get: function () {
  31264. return ValueCondition._IsDifferent;
  31265. },
  31266. enumerable: true,
  31267. configurable: true
  31268. });
  31269. Object.defineProperty(ValueCondition, "IsGreater", {
  31270. get: function () {
  31271. return ValueCondition._IsGreater;
  31272. },
  31273. enumerable: true,
  31274. configurable: true
  31275. });
  31276. Object.defineProperty(ValueCondition, "IsLesser", {
  31277. get: function () {
  31278. return ValueCondition._IsLesser;
  31279. },
  31280. enumerable: true,
  31281. configurable: true
  31282. });
  31283. // Methods
  31284. ValueCondition.prototype.isValid = function () {
  31285. switch (this.operator) {
  31286. case ValueCondition.IsGreater:
  31287. return this._effectiveTarget[this._property] > this.value;
  31288. case ValueCondition.IsLesser:
  31289. return this._effectiveTarget[this._property] < this.value;
  31290. case ValueCondition.IsEqual:
  31291. case ValueCondition.IsDifferent:
  31292. var check;
  31293. if (this.value.equals) {
  31294. check = this.value.equals(this._effectiveTarget[this._property]);
  31295. }
  31296. else {
  31297. check = this.value === this._effectiveTarget[this._property];
  31298. }
  31299. return this.operator === ValueCondition.IsEqual ? check : !check;
  31300. }
  31301. return false;
  31302. };
  31303. ValueCondition.prototype.serialize = function () {
  31304. return this._serialize({
  31305. name: "ValueCondition",
  31306. properties: [
  31307. BABYLON.Action._GetTargetProperty(this._target),
  31308. { name: "propertyPath", value: this.propertyPath },
  31309. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  31310. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  31311. ]
  31312. });
  31313. };
  31314. ValueCondition.GetOperatorName = function (operator) {
  31315. switch (operator) {
  31316. case ValueCondition._IsEqual: return "IsEqual";
  31317. case ValueCondition._IsDifferent: return "IsDifferent";
  31318. case ValueCondition._IsGreater: return "IsGreater";
  31319. case ValueCondition._IsLesser: return "IsLesser";
  31320. default: return "";
  31321. }
  31322. };
  31323. // Statics
  31324. ValueCondition._IsEqual = 0;
  31325. ValueCondition._IsDifferent = 1;
  31326. ValueCondition._IsGreater = 2;
  31327. ValueCondition._IsLesser = 3;
  31328. return ValueCondition;
  31329. })(Condition);
  31330. BABYLON.ValueCondition = ValueCondition;
  31331. var PredicateCondition = (function (_super) {
  31332. __extends(PredicateCondition, _super);
  31333. function PredicateCondition(actionManager, predicate) {
  31334. _super.call(this, actionManager);
  31335. this.predicate = predicate;
  31336. }
  31337. PredicateCondition.prototype.isValid = function () {
  31338. return this.predicate();
  31339. };
  31340. return PredicateCondition;
  31341. })(Condition);
  31342. BABYLON.PredicateCondition = PredicateCondition;
  31343. var StateCondition = (function (_super) {
  31344. __extends(StateCondition, _super);
  31345. function StateCondition(actionManager, target, value) {
  31346. _super.call(this, actionManager);
  31347. this.value = value;
  31348. this._target = target;
  31349. }
  31350. // Methods
  31351. StateCondition.prototype.isValid = function () {
  31352. return this._target.state === this.value;
  31353. };
  31354. StateCondition.prototype.serialize = function () {
  31355. return this._serialize({
  31356. name: "StateCondition",
  31357. properties: [
  31358. BABYLON.Action._GetTargetProperty(this._target),
  31359. { name: "value", value: this.value }
  31360. ]
  31361. });
  31362. };
  31363. return StateCondition;
  31364. })(Condition);
  31365. BABYLON.StateCondition = StateCondition;
  31366. })(BABYLON || (BABYLON = {}));
  31367. var BABYLON;
  31368. (function (BABYLON) {
  31369. var Action = (function () {
  31370. function Action(triggerOptions, condition) {
  31371. this.triggerOptions = triggerOptions;
  31372. if (triggerOptions.parameter) {
  31373. this.trigger = triggerOptions.trigger;
  31374. this._triggerParameter = triggerOptions.parameter;
  31375. }
  31376. else {
  31377. this.trigger = triggerOptions;
  31378. }
  31379. this._nextActiveAction = this;
  31380. this._condition = condition;
  31381. }
  31382. // Methods
  31383. Action.prototype._prepare = function () {
  31384. };
  31385. Action.prototype.getTriggerParameter = function () {
  31386. return this._triggerParameter;
  31387. };
  31388. Action.prototype._executeCurrent = function (evt) {
  31389. if (this._nextActiveAction._condition) {
  31390. var condition = this._nextActiveAction._condition;
  31391. var currentRenderId = this._actionManager.getScene().getRenderId();
  31392. // We cache the current evaluation for the current frame
  31393. if (condition._evaluationId === currentRenderId) {
  31394. if (!condition._currentResult) {
  31395. return;
  31396. }
  31397. }
  31398. else {
  31399. condition._evaluationId = currentRenderId;
  31400. if (!condition.isValid()) {
  31401. condition._currentResult = false;
  31402. return;
  31403. }
  31404. condition._currentResult = true;
  31405. }
  31406. }
  31407. this._nextActiveAction.execute(evt);
  31408. this.skipToNextActiveAction();
  31409. };
  31410. Action.prototype.execute = function (evt) {
  31411. };
  31412. Action.prototype.skipToNextActiveAction = function () {
  31413. if (this._nextActiveAction._child) {
  31414. if (!this._nextActiveAction._child._actionManager) {
  31415. this._nextActiveAction._child._actionManager = this._actionManager;
  31416. }
  31417. this._nextActiveAction = this._nextActiveAction._child;
  31418. }
  31419. else {
  31420. this._nextActiveAction = this;
  31421. }
  31422. };
  31423. Action.prototype.then = function (action) {
  31424. this._child = action;
  31425. action._actionManager = this._actionManager;
  31426. action._prepare();
  31427. return action;
  31428. };
  31429. Action.prototype._getProperty = function (propertyPath) {
  31430. return this._actionManager._getProperty(propertyPath);
  31431. };
  31432. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  31433. return this._actionManager._getEffectiveTarget(target, propertyPath);
  31434. };
  31435. Action.prototype.serialize = function (parent) {
  31436. };
  31437. // Called by BABYLON.Action objects in serialize(...). Internal use
  31438. Action.prototype._serialize = function (serializedAction, parent) {
  31439. var serializationObject = {
  31440. type: 1,
  31441. children: [],
  31442. name: serializedAction.name,
  31443. properties: serializedAction.properties || []
  31444. };
  31445. // Serialize child
  31446. if (this._child) {
  31447. this._child.serialize(serializationObject);
  31448. }
  31449. // Check if "this" has a condition
  31450. if (this._condition) {
  31451. var serializedCondition = this._condition.serialize();
  31452. serializedCondition.children.push(serializationObject);
  31453. if (parent) {
  31454. parent.children.push(serializedCondition);
  31455. }
  31456. return serializedCondition;
  31457. }
  31458. if (parent) {
  31459. parent.children.push(serializationObject);
  31460. }
  31461. return serializationObject;
  31462. };
  31463. Action._SerializeValueAsString = function (value) {
  31464. if (typeof value === "number") {
  31465. return value.toString();
  31466. }
  31467. if (typeof value === "boolean") {
  31468. return value ? "true" : "false";
  31469. }
  31470. if (value instanceof BABYLON.Vector2) {
  31471. return value.x + ", " + value.y;
  31472. }
  31473. if (value instanceof BABYLON.Vector3) {
  31474. return value.x + ", " + value.y + ", " + value.z;
  31475. }
  31476. if (value instanceof BABYLON.Color3) {
  31477. return value.r + ", " + value.g + ", " + value.b;
  31478. }
  31479. if (value instanceof BABYLON.Color4) {
  31480. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  31481. }
  31482. return value; // string
  31483. };
  31484. Action._GetTargetProperty = function (target) {
  31485. return {
  31486. name: "target",
  31487. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  31488. : target instanceof BABYLON.Light ? "LightProperties"
  31489. : target instanceof BABYLON.Camera ? "CameraProperties"
  31490. : "SceneProperties",
  31491. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  31492. };
  31493. };
  31494. return Action;
  31495. })();
  31496. BABYLON.Action = Action;
  31497. })(BABYLON || (BABYLON = {}));
  31498. var BABYLON;
  31499. (function (BABYLON) {
  31500. /**
  31501. * ActionEvent is the event beint sent when an action is triggered.
  31502. */
  31503. var ActionEvent = (function () {
  31504. /**
  31505. * @constructor
  31506. * @param source The mesh or sprite that triggered the action.
  31507. * @param pointerX The X mouse cursor position at the time of the event
  31508. * @param pointerY The Y mouse cursor position at the time of the event
  31509. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  31510. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  31511. */
  31512. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  31513. this.source = source;
  31514. this.pointerX = pointerX;
  31515. this.pointerY = pointerY;
  31516. this.meshUnderPointer = meshUnderPointer;
  31517. this.sourceEvent = sourceEvent;
  31518. this.additionalData = additionalData;
  31519. }
  31520. /**
  31521. * Helper function to auto-create an ActionEvent from a source mesh.
  31522. * @param source The source mesh that triggered the event
  31523. * @param evt {Event} The original (browser) event
  31524. */
  31525. ActionEvent.CreateNew = function (source, evt, additionalData) {
  31526. var scene = source.getScene();
  31527. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  31528. };
  31529. /**
  31530. * Helper function to auto-create an ActionEvent from a source mesh.
  31531. * @param source The source sprite that triggered the event
  31532. * @param scene Scene associated with the sprite
  31533. * @param evt {Event} The original (browser) event
  31534. */
  31535. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  31536. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  31537. };
  31538. /**
  31539. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  31540. * @param scene the scene where the event occurred
  31541. * @param evt {Event} The original (browser) event
  31542. */
  31543. ActionEvent.CreateNewFromScene = function (scene, evt) {
  31544. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  31545. };
  31546. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  31547. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  31548. };
  31549. return ActionEvent;
  31550. })();
  31551. BABYLON.ActionEvent = ActionEvent;
  31552. /**
  31553. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  31554. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  31555. */
  31556. var ActionManager = (function () {
  31557. function ActionManager(scene) {
  31558. // Members
  31559. this.actions = new Array();
  31560. this._scene = scene;
  31561. scene._actionManagers.push(this);
  31562. }
  31563. Object.defineProperty(ActionManager, "NothingTrigger", {
  31564. get: function () {
  31565. return ActionManager._NothingTrigger;
  31566. },
  31567. enumerable: true,
  31568. configurable: true
  31569. });
  31570. Object.defineProperty(ActionManager, "OnPickTrigger", {
  31571. get: function () {
  31572. return ActionManager._OnPickTrigger;
  31573. },
  31574. enumerable: true,
  31575. configurable: true
  31576. });
  31577. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  31578. get: function () {
  31579. return ActionManager._OnLeftPickTrigger;
  31580. },
  31581. enumerable: true,
  31582. configurable: true
  31583. });
  31584. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  31585. get: function () {
  31586. return ActionManager._OnRightPickTrigger;
  31587. },
  31588. enumerable: true,
  31589. configurable: true
  31590. });
  31591. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  31592. get: function () {
  31593. return ActionManager._OnCenterPickTrigger;
  31594. },
  31595. enumerable: true,
  31596. configurable: true
  31597. });
  31598. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  31599. get: function () {
  31600. return ActionManager._OnPickDownTrigger;
  31601. },
  31602. enumerable: true,
  31603. configurable: true
  31604. });
  31605. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  31606. get: function () {
  31607. return ActionManager._OnPickUpTrigger;
  31608. },
  31609. enumerable: true,
  31610. configurable: true
  31611. });
  31612. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  31613. /// This trigger will only be raised if you also declared a OnPickDown
  31614. get: function () {
  31615. return ActionManager._OnPickOutTrigger;
  31616. },
  31617. enumerable: true,
  31618. configurable: true
  31619. });
  31620. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  31621. get: function () {
  31622. return ActionManager._OnLongPressTrigger;
  31623. },
  31624. enumerable: true,
  31625. configurable: true
  31626. });
  31627. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  31628. get: function () {
  31629. return ActionManager._OnPointerOverTrigger;
  31630. },
  31631. enumerable: true,
  31632. configurable: true
  31633. });
  31634. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  31635. get: function () {
  31636. return ActionManager._OnPointerOutTrigger;
  31637. },
  31638. enumerable: true,
  31639. configurable: true
  31640. });
  31641. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  31642. get: function () {
  31643. return ActionManager._OnEveryFrameTrigger;
  31644. },
  31645. enumerable: true,
  31646. configurable: true
  31647. });
  31648. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  31649. get: function () {
  31650. return ActionManager._OnIntersectionEnterTrigger;
  31651. },
  31652. enumerable: true,
  31653. configurable: true
  31654. });
  31655. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  31656. get: function () {
  31657. return ActionManager._OnIntersectionExitTrigger;
  31658. },
  31659. enumerable: true,
  31660. configurable: true
  31661. });
  31662. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  31663. get: function () {
  31664. return ActionManager._OnKeyDownTrigger;
  31665. },
  31666. enumerable: true,
  31667. configurable: true
  31668. });
  31669. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  31670. get: function () {
  31671. return ActionManager._OnKeyUpTrigger;
  31672. },
  31673. enumerable: true,
  31674. configurable: true
  31675. });
  31676. // Methods
  31677. ActionManager.prototype.dispose = function () {
  31678. var index = this._scene._actionManagers.indexOf(this);
  31679. if (index > -1) {
  31680. this._scene._actionManagers.splice(index, 1);
  31681. }
  31682. };
  31683. ActionManager.prototype.getScene = function () {
  31684. return this._scene;
  31685. };
  31686. /**
  31687. * Does this action manager handles actions of any of the given triggers
  31688. * @param {number[]} triggers - the triggers to be tested
  31689. * @return {boolean} whether one (or more) of the triggers is handeled
  31690. */
  31691. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  31692. for (var index = 0; index < this.actions.length; index++) {
  31693. var action = this.actions[index];
  31694. if (triggers.indexOf(action.trigger) > -1) {
  31695. return true;
  31696. }
  31697. }
  31698. return false;
  31699. };
  31700. /**
  31701. * Does this action manager handles actions of a given trigger
  31702. * @param {number} trigger - the trigger to be tested
  31703. * @return {boolean} whether the trigger is handeled
  31704. */
  31705. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  31706. for (var index = 0; index < this.actions.length; index++) {
  31707. var action = this.actions[index];
  31708. if (action.trigger === trigger) {
  31709. return true;
  31710. }
  31711. }
  31712. return false;
  31713. };
  31714. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  31715. /**
  31716. * Does this action manager has pointer triggers
  31717. * @return {boolean} whether or not it has pointer triggers
  31718. */
  31719. get: function () {
  31720. for (var index = 0; index < this.actions.length; index++) {
  31721. var action = this.actions[index];
  31722. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  31723. return true;
  31724. }
  31725. }
  31726. return false;
  31727. },
  31728. enumerable: true,
  31729. configurable: true
  31730. });
  31731. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  31732. /**
  31733. * Does this action manager has pick triggers
  31734. * @return {boolean} whether or not it has pick triggers
  31735. */
  31736. get: function () {
  31737. for (var index = 0; index < this.actions.length; index++) {
  31738. var action = this.actions[index];
  31739. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  31740. return true;
  31741. }
  31742. }
  31743. return false;
  31744. },
  31745. enumerable: true,
  31746. configurable: true
  31747. });
  31748. /**
  31749. * Registers an action to this action manager
  31750. * @param {BABYLON.Action} action - the action to be registered
  31751. * @return {BABYLON.Action} the action amended (prepared) after registration
  31752. */
  31753. ActionManager.prototype.registerAction = function (action) {
  31754. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  31755. if (this.getScene().actionManager !== this) {
  31756. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  31757. return null;
  31758. }
  31759. }
  31760. this.actions.push(action);
  31761. action._actionManager = this;
  31762. action._prepare();
  31763. return action;
  31764. };
  31765. /**
  31766. * Process a specific trigger
  31767. * @param {number} trigger - the trigger to process
  31768. * @param evt {BABYLON.ActionEvent} the event details to be processed
  31769. */
  31770. ActionManager.prototype.processTrigger = function (trigger, evt) {
  31771. for (var index = 0; index < this.actions.length; index++) {
  31772. var action = this.actions[index];
  31773. if (action.trigger === trigger) {
  31774. if (trigger === ActionManager.OnKeyUpTrigger
  31775. || trigger === ActionManager.OnKeyDownTrigger) {
  31776. var parameter = action.getTriggerParameter();
  31777. if (parameter) {
  31778. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  31779. var actualkey = String.fromCharCode(unicode).toLowerCase();
  31780. if (actualkey !== parameter.toLowerCase()) {
  31781. continue;
  31782. }
  31783. }
  31784. }
  31785. action._executeCurrent(evt);
  31786. }
  31787. }
  31788. };
  31789. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  31790. var properties = propertyPath.split(".");
  31791. for (var index = 0; index < properties.length - 1; index++) {
  31792. target = target[properties[index]];
  31793. }
  31794. return target;
  31795. };
  31796. ActionManager.prototype._getProperty = function (propertyPath) {
  31797. var properties = propertyPath.split(".");
  31798. return properties[properties.length - 1];
  31799. };
  31800. ActionManager.prototype.serialize = function (name) {
  31801. var root = {
  31802. children: [],
  31803. name: name,
  31804. type: 3,
  31805. properties: [] // Empty for root but required
  31806. };
  31807. for (var i = 0; i < this.actions.length; i++) {
  31808. var triggerObject = {
  31809. type: 0,
  31810. children: [],
  31811. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  31812. properties: []
  31813. };
  31814. var triggerOptions = this.actions[i].triggerOptions;
  31815. if (triggerOptions && typeof triggerOptions !== "number") {
  31816. if (triggerOptions.parameter instanceof BABYLON.Node) {
  31817. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  31818. }
  31819. else {
  31820. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  31821. }
  31822. }
  31823. // Serialize child action, recursively
  31824. this.actions[i].serialize(triggerObject);
  31825. // Add serialized trigger
  31826. root.children.push(triggerObject);
  31827. }
  31828. return root;
  31829. };
  31830. ActionManager.Parse = function (parsedActions, object, scene) {
  31831. var actionManager = new BABYLON.ActionManager(scene);
  31832. if (object === null)
  31833. scene.actionManager = actionManager;
  31834. else
  31835. object.actionManager = actionManager;
  31836. // instanciate a new object
  31837. var instanciate = function (name, params) {
  31838. var newInstance = Object.create(BABYLON[name].prototype);
  31839. newInstance.constructor.apply(newInstance, params);
  31840. return newInstance;
  31841. };
  31842. var parseParameter = function (name, value, target, propertyPath) {
  31843. if (propertyPath === null) {
  31844. // String, boolean or float
  31845. var floatValue = parseFloat(value);
  31846. if (value === "true" || value === "false")
  31847. return value === "true";
  31848. else
  31849. return isNaN(floatValue) ? value : floatValue;
  31850. }
  31851. var effectiveTarget = propertyPath.split(".");
  31852. var values = value.split(",");
  31853. // Get effective Target
  31854. for (var i = 0; i < effectiveTarget.length; i++) {
  31855. target = target[effectiveTarget[i]];
  31856. }
  31857. // Return appropriate value with its type
  31858. if (typeof (target) === "boolean")
  31859. return values[0] === "true";
  31860. if (typeof (target) === "string")
  31861. return values[0];
  31862. // Parameters with multiple values such as Vector3 etc.
  31863. var split = new Array();
  31864. for (var i = 0; i < values.length; i++)
  31865. split.push(parseFloat(values[i]));
  31866. if (target instanceof BABYLON.Vector3)
  31867. return BABYLON.Vector3.FromArray(split);
  31868. if (target instanceof BABYLON.Vector4)
  31869. return BABYLON.Vector4.FromArray(split);
  31870. if (target instanceof BABYLON.Color3)
  31871. return BABYLON.Color3.FromArray(split);
  31872. if (target instanceof BABYLON.Color4)
  31873. return BABYLON.Color4.FromArray(split);
  31874. return parseFloat(values[0]);
  31875. };
  31876. // traverse graph per trigger
  31877. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  31878. if (combineArray === void 0) { combineArray = null; }
  31879. if (parsedAction.detached)
  31880. return;
  31881. var parameters = new Array();
  31882. var target = null;
  31883. var propertyPath = null;
  31884. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  31885. // Parameters
  31886. if (parsedAction.type === 2)
  31887. parameters.push(actionManager);
  31888. else
  31889. parameters.push(trigger);
  31890. if (combine) {
  31891. var actions = new Array();
  31892. for (var j = 0; j < parsedAction.combine.length; j++) {
  31893. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  31894. }
  31895. parameters.push(actions);
  31896. }
  31897. else {
  31898. for (var i = 0; i < parsedAction.properties.length; i++) {
  31899. var value = parsedAction.properties[i].value;
  31900. var name = parsedAction.properties[i].name;
  31901. var targetType = parsedAction.properties[i].targetType;
  31902. if (name === "target")
  31903. if (targetType !== null && targetType === "SceneProperties")
  31904. value = target = scene;
  31905. else
  31906. value = target = scene.getNodeByName(value);
  31907. else if (name === "parent")
  31908. value = scene.getNodeByName(value);
  31909. else if (name === "sound")
  31910. value = scene.getSoundByName(value);
  31911. else if (name !== "propertyPath") {
  31912. if (parsedAction.type === 2 && name === "operator")
  31913. value = BABYLON.ValueCondition[value];
  31914. else
  31915. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  31916. }
  31917. else {
  31918. propertyPath = value;
  31919. }
  31920. parameters.push(value);
  31921. }
  31922. }
  31923. if (combineArray === null) {
  31924. parameters.push(condition);
  31925. }
  31926. else {
  31927. parameters.push(null);
  31928. }
  31929. // If interpolate value action
  31930. if (parsedAction.name === "InterpolateValueAction") {
  31931. var param = parameters[parameters.length - 2];
  31932. parameters[parameters.length - 1] = param;
  31933. parameters[parameters.length - 2] = condition;
  31934. }
  31935. // Action or condition(s) and not CombineAction
  31936. var newAction = instanciate(parsedAction.name, parameters);
  31937. if (newAction instanceof BABYLON.Condition && condition !== null) {
  31938. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  31939. if (action)
  31940. action.then(nothing);
  31941. else
  31942. actionManager.registerAction(nothing);
  31943. action = nothing;
  31944. }
  31945. if (combineArray === null) {
  31946. if (newAction instanceof BABYLON.Condition) {
  31947. condition = newAction;
  31948. newAction = action;
  31949. }
  31950. else {
  31951. condition = null;
  31952. if (action)
  31953. action.then(newAction);
  31954. else
  31955. actionManager.registerAction(newAction);
  31956. }
  31957. }
  31958. else {
  31959. combineArray.push(newAction);
  31960. }
  31961. for (var i = 0; i < parsedAction.children.length; i++)
  31962. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  31963. };
  31964. // triggers
  31965. for (var i = 0; i < parsedActions.children.length; i++) {
  31966. var triggerParams;
  31967. var trigger = parsedActions.children[i];
  31968. if (trigger.properties.length > 0) {
  31969. var param = trigger.properties[0].value;
  31970. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  31971. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  31972. }
  31973. else
  31974. triggerParams = BABYLON.ActionManager[trigger.name];
  31975. for (var j = 0; j < trigger.children.length; j++) {
  31976. if (!trigger.detached)
  31977. traverse(trigger.children[j], triggerParams, null, null);
  31978. }
  31979. }
  31980. };
  31981. ActionManager.GetTriggerName = function (trigger) {
  31982. switch (trigger) {
  31983. case 0: return "NothingTrigger";
  31984. case 1: return "OnPickTrigger";
  31985. case 2: return "OnLeftPickTrigger";
  31986. case 3: return "OnRightPickTrigger";
  31987. case 4: return "OnCenterPickTrigger";
  31988. case 5: return "OnPickDownTrigger";
  31989. case 6: return "OnPickUpTrigger";
  31990. case 7: return "OnLongPressTrigger";
  31991. case 8: return "OnPointerOverTrigger";
  31992. case 9: return "OnPointerOutTrigger";
  31993. case 10: return "OnEveryFrameTrigger";
  31994. case 11: return "OnIntersectionEnterTrigger";
  31995. case 12: return "OnIntersectionExitTrigger";
  31996. case 13: return "OnKeyDownTrigger";
  31997. case 14: return "OnKeyUpTrigger";
  31998. case 15: return "OnPickOutTrigger";
  31999. default: return "";
  32000. }
  32001. };
  32002. // Statics
  32003. ActionManager._NothingTrigger = 0;
  32004. ActionManager._OnPickTrigger = 1;
  32005. ActionManager._OnLeftPickTrigger = 2;
  32006. ActionManager._OnRightPickTrigger = 3;
  32007. ActionManager._OnCenterPickTrigger = 4;
  32008. ActionManager._OnPickDownTrigger = 5;
  32009. ActionManager._OnPickUpTrigger = 6;
  32010. ActionManager._OnLongPressTrigger = 7;
  32011. ActionManager._OnPointerOverTrigger = 8;
  32012. ActionManager._OnPointerOutTrigger = 9;
  32013. ActionManager._OnEveryFrameTrigger = 10;
  32014. ActionManager._OnIntersectionEnterTrigger = 11;
  32015. ActionManager._OnIntersectionExitTrigger = 12;
  32016. ActionManager._OnKeyDownTrigger = 13;
  32017. ActionManager._OnKeyUpTrigger = 14;
  32018. ActionManager._OnPickOutTrigger = 15;
  32019. ActionManager.DragMovementThreshold = 10; // in pixels
  32020. ActionManager.LongPressDelay = 500; // in milliseconds
  32021. return ActionManager;
  32022. })();
  32023. BABYLON.ActionManager = ActionManager;
  32024. })(BABYLON || (BABYLON = {}));
  32025. var BABYLON;
  32026. (function (BABYLON) {
  32027. var InterpolateValueAction = (function (_super) {
  32028. __extends(InterpolateValueAction, _super);
  32029. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  32030. if (duration === void 0) { duration = 1000; }
  32031. _super.call(this, triggerOptions, condition);
  32032. this.propertyPath = propertyPath;
  32033. this.value = value;
  32034. this.duration = duration;
  32035. this.stopOtherAnimations = stopOtherAnimations;
  32036. this.onInterpolationDone = onInterpolationDone;
  32037. this._target = this._effectiveTarget = target;
  32038. }
  32039. InterpolateValueAction.prototype._prepare = function () {
  32040. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32041. this._property = this._getProperty(this.propertyPath);
  32042. };
  32043. InterpolateValueAction.prototype.execute = function () {
  32044. var scene = this._actionManager.getScene();
  32045. var keys = [
  32046. {
  32047. frame: 0,
  32048. value: this._effectiveTarget[this._property]
  32049. }, {
  32050. frame: 100,
  32051. value: this.value
  32052. }
  32053. ];
  32054. var dataType;
  32055. if (typeof this.value === "number") {
  32056. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  32057. }
  32058. else if (this.value instanceof BABYLON.Color3) {
  32059. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  32060. }
  32061. else if (this.value instanceof BABYLON.Vector3) {
  32062. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  32063. }
  32064. else if (this.value instanceof BABYLON.Matrix) {
  32065. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  32066. }
  32067. else if (this.value instanceof BABYLON.Quaternion) {
  32068. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  32069. }
  32070. else {
  32071. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  32072. return;
  32073. }
  32074. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  32075. animation.setKeys(keys);
  32076. if (this.stopOtherAnimations) {
  32077. scene.stopAnimation(this._effectiveTarget);
  32078. }
  32079. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  32080. };
  32081. InterpolateValueAction.prototype.serialize = function (parent) {
  32082. return _super.prototype._serialize.call(this, {
  32083. name: "InterpolateValueAction",
  32084. properties: [
  32085. BABYLON.Action._GetTargetProperty(this._target),
  32086. { name: "propertyPath", value: this.propertyPath },
  32087. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32088. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  32089. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  32090. ]
  32091. }, parent);
  32092. };
  32093. return InterpolateValueAction;
  32094. })(BABYLON.Action);
  32095. BABYLON.InterpolateValueAction = InterpolateValueAction;
  32096. })(BABYLON || (BABYLON = {}));
  32097. var BABYLON;
  32098. (function (BABYLON) {
  32099. var SwitchBooleanAction = (function (_super) {
  32100. __extends(SwitchBooleanAction, _super);
  32101. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  32102. _super.call(this, triggerOptions, condition);
  32103. this.propertyPath = propertyPath;
  32104. this._target = this._effectiveTarget = target;
  32105. }
  32106. SwitchBooleanAction.prototype._prepare = function () {
  32107. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32108. this._property = this._getProperty(this.propertyPath);
  32109. };
  32110. SwitchBooleanAction.prototype.execute = function () {
  32111. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  32112. };
  32113. SwitchBooleanAction.prototype.serialize = function (parent) {
  32114. return _super.prototype._serialize.call(this, {
  32115. name: "SwitchBooleanAction",
  32116. properties: [
  32117. BABYLON.Action._GetTargetProperty(this._target),
  32118. { name: "propertyPath", value: this.propertyPath }
  32119. ]
  32120. }, parent);
  32121. };
  32122. return SwitchBooleanAction;
  32123. })(BABYLON.Action);
  32124. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  32125. var SetStateAction = (function (_super) {
  32126. __extends(SetStateAction, _super);
  32127. function SetStateAction(triggerOptions, target, value, condition) {
  32128. _super.call(this, triggerOptions, condition);
  32129. this.value = value;
  32130. this._target = target;
  32131. }
  32132. SetStateAction.prototype.execute = function () {
  32133. this._target.state = this.value;
  32134. };
  32135. SetStateAction.prototype.serialize = function (parent) {
  32136. return _super.prototype._serialize.call(this, {
  32137. name: "SetStateAction",
  32138. properties: [
  32139. BABYLON.Action._GetTargetProperty(this._target),
  32140. { name: "value", value: this.value }
  32141. ]
  32142. }, parent);
  32143. };
  32144. return SetStateAction;
  32145. })(BABYLON.Action);
  32146. BABYLON.SetStateAction = SetStateAction;
  32147. var SetValueAction = (function (_super) {
  32148. __extends(SetValueAction, _super);
  32149. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  32150. _super.call(this, triggerOptions, condition);
  32151. this.propertyPath = propertyPath;
  32152. this.value = value;
  32153. this._target = this._effectiveTarget = target;
  32154. }
  32155. SetValueAction.prototype._prepare = function () {
  32156. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32157. this._property = this._getProperty(this.propertyPath);
  32158. };
  32159. SetValueAction.prototype.execute = function () {
  32160. this._effectiveTarget[this._property] = this.value;
  32161. if (this._target.markAsDirty) {
  32162. this._target.markAsDirty(this._property);
  32163. }
  32164. };
  32165. SetValueAction.prototype.serialize = function (parent) {
  32166. return _super.prototype._serialize.call(this, {
  32167. name: "SetValueAction",
  32168. properties: [
  32169. BABYLON.Action._GetTargetProperty(this._target),
  32170. { name: "propertyPath", value: this.propertyPath },
  32171. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  32172. ]
  32173. }, parent);
  32174. };
  32175. return SetValueAction;
  32176. })(BABYLON.Action);
  32177. BABYLON.SetValueAction = SetValueAction;
  32178. var IncrementValueAction = (function (_super) {
  32179. __extends(IncrementValueAction, _super);
  32180. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  32181. _super.call(this, triggerOptions, condition);
  32182. this.propertyPath = propertyPath;
  32183. this.value = value;
  32184. this._target = this._effectiveTarget = target;
  32185. }
  32186. IncrementValueAction.prototype._prepare = function () {
  32187. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32188. this._property = this._getProperty(this.propertyPath);
  32189. if (typeof this._effectiveTarget[this._property] !== "number") {
  32190. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  32191. }
  32192. };
  32193. IncrementValueAction.prototype.execute = function () {
  32194. this._effectiveTarget[this._property] += this.value;
  32195. if (this._target.markAsDirty) {
  32196. this._target.markAsDirty(this._property);
  32197. }
  32198. };
  32199. IncrementValueAction.prototype.serialize = function (parent) {
  32200. return _super.prototype._serialize.call(this, {
  32201. name: "IncrementValueAction",
  32202. properties: [
  32203. BABYLON.Action._GetTargetProperty(this._target),
  32204. { name: "propertyPath", value: this.propertyPath },
  32205. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  32206. ]
  32207. }, parent);
  32208. };
  32209. return IncrementValueAction;
  32210. })(BABYLON.Action);
  32211. BABYLON.IncrementValueAction = IncrementValueAction;
  32212. var PlayAnimationAction = (function (_super) {
  32213. __extends(PlayAnimationAction, _super);
  32214. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  32215. _super.call(this, triggerOptions, condition);
  32216. this.from = from;
  32217. this.to = to;
  32218. this.loop = loop;
  32219. this._target = target;
  32220. }
  32221. PlayAnimationAction.prototype._prepare = function () {
  32222. };
  32223. PlayAnimationAction.prototype.execute = function () {
  32224. var scene = this._actionManager.getScene();
  32225. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  32226. };
  32227. PlayAnimationAction.prototype.serialize = function (parent) {
  32228. return _super.prototype._serialize.call(this, {
  32229. name: "PlayAnimationAction",
  32230. properties: [
  32231. BABYLON.Action._GetTargetProperty(this._target),
  32232. { name: "from", value: String(this.from) },
  32233. { name: "to", value: String(this.to) },
  32234. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  32235. ]
  32236. }, parent);
  32237. };
  32238. return PlayAnimationAction;
  32239. })(BABYLON.Action);
  32240. BABYLON.PlayAnimationAction = PlayAnimationAction;
  32241. var StopAnimationAction = (function (_super) {
  32242. __extends(StopAnimationAction, _super);
  32243. function StopAnimationAction(triggerOptions, target, condition) {
  32244. _super.call(this, triggerOptions, condition);
  32245. this._target = target;
  32246. }
  32247. StopAnimationAction.prototype._prepare = function () {
  32248. };
  32249. StopAnimationAction.prototype.execute = function () {
  32250. var scene = this._actionManager.getScene();
  32251. scene.stopAnimation(this._target);
  32252. };
  32253. StopAnimationAction.prototype.serialize = function (parent) {
  32254. return _super.prototype._serialize.call(this, {
  32255. name: "StopAnimationAction",
  32256. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  32257. }, parent);
  32258. };
  32259. return StopAnimationAction;
  32260. })(BABYLON.Action);
  32261. BABYLON.StopAnimationAction = StopAnimationAction;
  32262. var DoNothingAction = (function (_super) {
  32263. __extends(DoNothingAction, _super);
  32264. function DoNothingAction(triggerOptions, condition) {
  32265. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  32266. _super.call(this, triggerOptions, condition);
  32267. }
  32268. DoNothingAction.prototype.execute = function () {
  32269. };
  32270. DoNothingAction.prototype.serialize = function (parent) {
  32271. return _super.prototype._serialize.call(this, {
  32272. name: "DoNothingAction",
  32273. properties: []
  32274. }, parent);
  32275. };
  32276. return DoNothingAction;
  32277. })(BABYLON.Action);
  32278. BABYLON.DoNothingAction = DoNothingAction;
  32279. var CombineAction = (function (_super) {
  32280. __extends(CombineAction, _super);
  32281. function CombineAction(triggerOptions, children, condition) {
  32282. _super.call(this, triggerOptions, condition);
  32283. this.children = children;
  32284. }
  32285. CombineAction.prototype._prepare = function () {
  32286. for (var index = 0; index < this.children.length; index++) {
  32287. this.children[index]._actionManager = this._actionManager;
  32288. this.children[index]._prepare();
  32289. }
  32290. };
  32291. CombineAction.prototype.execute = function (evt) {
  32292. for (var index = 0; index < this.children.length; index++) {
  32293. this.children[index].execute(evt);
  32294. }
  32295. };
  32296. CombineAction.prototype.serialize = function (parent) {
  32297. var serializationObject = _super.prototype._serialize.call(this, {
  32298. name: "CombineAction",
  32299. properties: [],
  32300. combine: []
  32301. }, parent);
  32302. for (var i = 0; i < this.children.length; i++) {
  32303. serializationObject.combine.push(this.children[i].serialize(null));
  32304. }
  32305. return serializationObject;
  32306. };
  32307. return CombineAction;
  32308. })(BABYLON.Action);
  32309. BABYLON.CombineAction = CombineAction;
  32310. var ExecuteCodeAction = (function (_super) {
  32311. __extends(ExecuteCodeAction, _super);
  32312. function ExecuteCodeAction(triggerOptions, func, condition) {
  32313. _super.call(this, triggerOptions, condition);
  32314. this.func = func;
  32315. }
  32316. ExecuteCodeAction.prototype.execute = function (evt) {
  32317. this.func(evt);
  32318. };
  32319. return ExecuteCodeAction;
  32320. })(BABYLON.Action);
  32321. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  32322. var SetParentAction = (function (_super) {
  32323. __extends(SetParentAction, _super);
  32324. function SetParentAction(triggerOptions, target, parent, condition) {
  32325. _super.call(this, triggerOptions, condition);
  32326. this._target = target;
  32327. this._parent = parent;
  32328. }
  32329. SetParentAction.prototype._prepare = function () {
  32330. };
  32331. SetParentAction.prototype.execute = function () {
  32332. if (this._target.parent === this._parent) {
  32333. return;
  32334. }
  32335. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  32336. invertParentWorldMatrix.invert();
  32337. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  32338. this._target.parent = this._parent;
  32339. };
  32340. SetParentAction.prototype.serialize = function (parent) {
  32341. return _super.prototype._serialize.call(this, {
  32342. name: "SetParentAction",
  32343. properties: [
  32344. BABYLON.Action._GetTargetProperty(this._target),
  32345. BABYLON.Action._GetTargetProperty(this._parent),
  32346. ]
  32347. }, parent);
  32348. };
  32349. return SetParentAction;
  32350. })(BABYLON.Action);
  32351. BABYLON.SetParentAction = SetParentAction;
  32352. var PlaySoundAction = (function (_super) {
  32353. __extends(PlaySoundAction, _super);
  32354. function PlaySoundAction(triggerOptions, sound, condition) {
  32355. _super.call(this, triggerOptions, condition);
  32356. this._sound = sound;
  32357. }
  32358. PlaySoundAction.prototype._prepare = function () {
  32359. };
  32360. PlaySoundAction.prototype.execute = function () {
  32361. if (this._sound !== undefined)
  32362. this._sound.play();
  32363. };
  32364. PlaySoundAction.prototype.serialize = function (parent) {
  32365. return _super.prototype._serialize.call(this, {
  32366. name: "PlaySoundAction",
  32367. properties: [{ name: "sound", value: this._sound.name }]
  32368. }, parent);
  32369. };
  32370. return PlaySoundAction;
  32371. })(BABYLON.Action);
  32372. BABYLON.PlaySoundAction = PlaySoundAction;
  32373. var StopSoundAction = (function (_super) {
  32374. __extends(StopSoundAction, _super);
  32375. function StopSoundAction(triggerOptions, sound, condition) {
  32376. _super.call(this, triggerOptions, condition);
  32377. this._sound = sound;
  32378. }
  32379. StopSoundAction.prototype._prepare = function () {
  32380. };
  32381. StopSoundAction.prototype.execute = function () {
  32382. if (this._sound !== undefined)
  32383. this._sound.stop();
  32384. };
  32385. StopSoundAction.prototype.serialize = function (parent) {
  32386. return _super.prototype._serialize.call(this, {
  32387. name: "StopSoundAction",
  32388. properties: [{ name: "sound", value: this._sound.name }]
  32389. }, parent);
  32390. };
  32391. return StopSoundAction;
  32392. })(BABYLON.Action);
  32393. BABYLON.StopSoundAction = StopSoundAction;
  32394. })(BABYLON || (BABYLON = {}));
  32395. var BABYLON;
  32396. (function (BABYLON) {
  32397. var Geometry = (function () {
  32398. function Geometry(id, scene, vertexData, updatable, mesh) {
  32399. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32400. this._totalVertices = 0;
  32401. this._isDisposed = false;
  32402. this.id = id;
  32403. this._engine = scene.getEngine();
  32404. this._meshes = [];
  32405. this._scene = scene;
  32406. //Init vertex buffer cache
  32407. this._vertexBuffers = {};
  32408. this._indices = [];
  32409. // vertexData
  32410. if (vertexData) {
  32411. this.setAllVerticesData(vertexData, updatable);
  32412. }
  32413. else {
  32414. this._totalVertices = 0;
  32415. this._indices = [];
  32416. }
  32417. // applyToMesh
  32418. if (mesh) {
  32419. if (mesh instanceof BABYLON.LinesMesh) {
  32420. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32421. this.updateExtend();
  32422. }
  32423. this.applyToMesh(mesh);
  32424. mesh.computeWorldMatrix(true);
  32425. }
  32426. }
  32427. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32428. /**
  32429. * The Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  32430. * @returns The Bias Vector
  32431. */
  32432. get: function () {
  32433. return this._boundingBias;
  32434. },
  32435. set: function (value) {
  32436. if (this._boundingBias && this._boundingBias.equals(value)) {
  32437. return;
  32438. }
  32439. this._boundingBias = value.clone();
  32440. this.updateBoundingInfo(true, null);
  32441. },
  32442. enumerable: true,
  32443. configurable: true
  32444. });
  32445. Object.defineProperty(Geometry.prototype, "extend", {
  32446. get: function () {
  32447. return this._extend;
  32448. },
  32449. enumerable: true,
  32450. configurable: true
  32451. });
  32452. Geometry.prototype.getScene = function () {
  32453. return this._scene;
  32454. };
  32455. Geometry.prototype.getEngine = function () {
  32456. return this._engine;
  32457. };
  32458. Geometry.prototype.isReady = function () {
  32459. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32460. };
  32461. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32462. vertexData.applyToGeometry(this, updatable);
  32463. this.notifyUpdate();
  32464. };
  32465. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32466. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32467. this.setVerticesBuffer(buffer);
  32468. };
  32469. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32470. var kind = buffer.getKind();
  32471. if (this._vertexBuffers[kind]) {
  32472. this._vertexBuffers[kind].dispose();
  32473. }
  32474. this._vertexBuffers[kind] = buffer;
  32475. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32476. var data = buffer.getData();
  32477. var stride = buffer.getStrideSize();
  32478. this._totalVertices = data.length / stride;
  32479. this.updateExtend(data, stride);
  32480. var meshes = this._meshes;
  32481. var numOfMeshes = meshes.length;
  32482. for (var index = 0; index < numOfMeshes; index++) {
  32483. var mesh = meshes[index];
  32484. mesh._resetPointsArrayCache();
  32485. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32486. mesh._createGlobalSubMesh();
  32487. mesh.computeWorldMatrix(true);
  32488. }
  32489. }
  32490. this.notifyUpdate(kind);
  32491. };
  32492. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32493. var vertexBuffer = this.getVertexBuffer(kind);
  32494. if (!vertexBuffer) {
  32495. return;
  32496. }
  32497. vertexBuffer.updateDirectly(data, offset);
  32498. this.notifyUpdate(kind);
  32499. };
  32500. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32501. var vertexBuffer = this.getVertexBuffer(kind);
  32502. if (!vertexBuffer) {
  32503. return;
  32504. }
  32505. vertexBuffer.update(data);
  32506. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32507. var stride = vertexBuffer.getStrideSize();
  32508. this._totalVertices = data.length / stride;
  32509. this.updateBoundingInfo(updateExtends, data);
  32510. }
  32511. this.notifyUpdate(kind);
  32512. };
  32513. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32514. if (updateExtends) {
  32515. this.updateExtend(data);
  32516. }
  32517. var meshes = this._meshes;
  32518. var numOfMeshes = meshes.length;
  32519. for (var index = 0; index < numOfMeshes; index++) {
  32520. var mesh = meshes[index];
  32521. mesh._resetPointsArrayCache();
  32522. if (updateExtends) {
  32523. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32524. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32525. var subMesh = mesh.subMeshes[subIndex];
  32526. subMesh.refreshBoundingInfo();
  32527. }
  32528. }
  32529. }
  32530. };
  32531. Geometry.prototype.getTotalVertices = function () {
  32532. if (!this.isReady()) {
  32533. return 0;
  32534. }
  32535. return this._totalVertices;
  32536. };
  32537. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  32538. var vertexBuffer = this.getVertexBuffer(kind);
  32539. if (!vertexBuffer) {
  32540. return null;
  32541. }
  32542. var orig = vertexBuffer.getData();
  32543. if (!copyWhenShared || this._meshes.length === 1) {
  32544. return orig;
  32545. }
  32546. else {
  32547. var len = orig.length;
  32548. var copy = [];
  32549. for (var i = 0; i < len; i++) {
  32550. copy.push(orig[i]);
  32551. }
  32552. return copy;
  32553. }
  32554. };
  32555. Geometry.prototype.getVertexBuffer = function (kind) {
  32556. if (!this.isReady()) {
  32557. return null;
  32558. }
  32559. return this._vertexBuffers[kind];
  32560. };
  32561. Geometry.prototype.getVertexBuffers = function () {
  32562. if (!this.isReady()) {
  32563. return null;
  32564. }
  32565. return this._vertexBuffers;
  32566. };
  32567. Geometry.prototype.isVerticesDataPresent = function (kind) {
  32568. if (!this._vertexBuffers) {
  32569. if (this._delayInfo) {
  32570. return this._delayInfo.indexOf(kind) !== -1;
  32571. }
  32572. return false;
  32573. }
  32574. return this._vertexBuffers[kind] !== undefined;
  32575. };
  32576. Geometry.prototype.getVerticesDataKinds = function () {
  32577. var result = [];
  32578. var kind;
  32579. if (!this._vertexBuffers && this._delayInfo) {
  32580. for (kind in this._delayInfo) {
  32581. result.push(kind);
  32582. }
  32583. }
  32584. else {
  32585. for (kind in this._vertexBuffers) {
  32586. result.push(kind);
  32587. }
  32588. }
  32589. return result;
  32590. };
  32591. Geometry.prototype.setIndices = function (indices, totalVertices) {
  32592. if (this._indexBuffer) {
  32593. this._engine._releaseBuffer(this._indexBuffer);
  32594. }
  32595. this._indices = indices;
  32596. if (this._meshes.length !== 0 && this._indices) {
  32597. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32598. }
  32599. if (totalVertices !== undefined) {
  32600. this._totalVertices = totalVertices;
  32601. }
  32602. var meshes = this._meshes;
  32603. var numOfMeshes = meshes.length;
  32604. for (var index = 0; index < numOfMeshes; index++) {
  32605. meshes[index]._createGlobalSubMesh();
  32606. }
  32607. this.notifyUpdate();
  32608. };
  32609. Geometry.prototype.getTotalIndices = function () {
  32610. if (!this.isReady()) {
  32611. return 0;
  32612. }
  32613. return this._indices.length;
  32614. };
  32615. Geometry.prototype.getIndices = function (copyWhenShared) {
  32616. if (!this.isReady()) {
  32617. return null;
  32618. }
  32619. var orig = this._indices;
  32620. if (!copyWhenShared || this._meshes.length === 1) {
  32621. return orig;
  32622. }
  32623. else {
  32624. var len = orig.length;
  32625. var copy = [];
  32626. for (var i = 0; i < len; i++) {
  32627. copy.push(orig[i]);
  32628. }
  32629. return copy;
  32630. }
  32631. };
  32632. Geometry.prototype.getIndexBuffer = function () {
  32633. if (!this.isReady()) {
  32634. return null;
  32635. }
  32636. return this._indexBuffer;
  32637. };
  32638. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  32639. var meshes = this._meshes;
  32640. var index = meshes.indexOf(mesh);
  32641. if (index === -1) {
  32642. return;
  32643. }
  32644. for (var kind in this._vertexBuffers) {
  32645. this._vertexBuffers[kind].dispose();
  32646. }
  32647. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  32648. this._indexBuffer = null;
  32649. }
  32650. meshes.splice(index, 1);
  32651. mesh._geometry = null;
  32652. if (meshes.length === 0 && shouldDispose) {
  32653. this.dispose();
  32654. }
  32655. };
  32656. Geometry.prototype.applyToMesh = function (mesh) {
  32657. if (mesh._geometry === this) {
  32658. return;
  32659. }
  32660. var previousGeometry = mesh._geometry;
  32661. if (previousGeometry) {
  32662. previousGeometry.releaseForMesh(mesh);
  32663. }
  32664. var meshes = this._meshes;
  32665. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  32666. mesh._geometry = this;
  32667. this._scene.pushGeometry(this);
  32668. meshes.push(mesh);
  32669. if (this.isReady()) {
  32670. this._applyToMesh(mesh);
  32671. }
  32672. else {
  32673. mesh._boundingInfo = this._boundingInfo;
  32674. }
  32675. };
  32676. Geometry.prototype.updateExtend = function (data, stride) {
  32677. if (data === void 0) { data = null; }
  32678. if (!data) {
  32679. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  32680. }
  32681. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  32682. };
  32683. Geometry.prototype._applyToMesh = function (mesh) {
  32684. var numOfMeshes = this._meshes.length;
  32685. // vertexBuffers
  32686. for (var kind in this._vertexBuffers) {
  32687. if (numOfMeshes === 1) {
  32688. this._vertexBuffers[kind].create();
  32689. }
  32690. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  32691. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32692. mesh._resetPointsArrayCache();
  32693. if (!this._extend) {
  32694. this.updateExtend(this._vertexBuffers[kind].getData());
  32695. }
  32696. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32697. mesh._createGlobalSubMesh();
  32698. //bounding info was just created again, world matrix should be applied again.
  32699. mesh._updateBoundingInfo();
  32700. }
  32701. }
  32702. // indexBuffer
  32703. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  32704. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32705. }
  32706. if (this._indexBuffer) {
  32707. this._indexBuffer.references = numOfMeshes;
  32708. }
  32709. };
  32710. Geometry.prototype.notifyUpdate = function (kind) {
  32711. if (this.onGeometryUpdated) {
  32712. this.onGeometryUpdated(this, kind);
  32713. }
  32714. };
  32715. Geometry.prototype.load = function (scene, onLoaded) {
  32716. var _this = this;
  32717. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32718. return;
  32719. }
  32720. if (this.isReady()) {
  32721. if (onLoaded) {
  32722. onLoaded();
  32723. }
  32724. return;
  32725. }
  32726. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32727. scene._addPendingData(this);
  32728. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32729. _this._delayLoadingFunction(JSON.parse(data), _this);
  32730. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32731. _this._delayInfo = [];
  32732. scene._removePendingData(_this);
  32733. var meshes = _this._meshes;
  32734. var numOfMeshes = meshes.length;
  32735. for (var index = 0; index < numOfMeshes; index++) {
  32736. _this._applyToMesh(meshes[index]);
  32737. }
  32738. if (onLoaded) {
  32739. onLoaded();
  32740. }
  32741. }, function () { }, scene.database);
  32742. };
  32743. /**
  32744. * Invert the geometry to move from a right handed system to a left handed one.
  32745. */
  32746. Geometry.prototype.toLeftHanded = function () {
  32747. // Flip faces
  32748. var tIndices = this.getIndices(false);
  32749. if (tIndices != null && tIndices.length > 0) {
  32750. for (var i = 0; i < tIndices.length; i += 3) {
  32751. var tTemp = tIndices[i + 0];
  32752. tIndices[i + 0] = tIndices[i + 2];
  32753. tIndices[i + 2] = tTemp;
  32754. }
  32755. this.setIndices(tIndices);
  32756. }
  32757. // Negate position.z
  32758. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  32759. if (tPositions != null && tPositions.length > 0) {
  32760. for (var i = 0; i < tPositions.length; i += 3) {
  32761. tPositions[i + 2] = -tPositions[i + 2];
  32762. }
  32763. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  32764. }
  32765. // Negate normal.z
  32766. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  32767. if (tNormals != null && tNormals.length > 0) {
  32768. for (var i = 0; i < tNormals.length; i += 3) {
  32769. tNormals[i + 2] = -tNormals[i + 2];
  32770. }
  32771. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  32772. }
  32773. };
  32774. Geometry.prototype.isDisposed = function () {
  32775. return this._isDisposed;
  32776. };
  32777. Geometry.prototype.dispose = function () {
  32778. var meshes = this._meshes;
  32779. var numOfMeshes = meshes.length;
  32780. var index;
  32781. for (index = 0; index < numOfMeshes; index++) {
  32782. this.releaseForMesh(meshes[index]);
  32783. }
  32784. this._meshes = [];
  32785. for (var kind in this._vertexBuffers) {
  32786. this._vertexBuffers[kind].dispose();
  32787. }
  32788. this._vertexBuffers = {};
  32789. this._totalVertices = 0;
  32790. if (this._indexBuffer) {
  32791. this._engine._releaseBuffer(this._indexBuffer);
  32792. }
  32793. this._indexBuffer = null;
  32794. this._indices = [];
  32795. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32796. this.delayLoadingFile = null;
  32797. this._delayLoadingFunction = null;
  32798. this._delayInfo = [];
  32799. this._boundingInfo = null;
  32800. this._scene.removeGeometry(this);
  32801. this._isDisposed = true;
  32802. };
  32803. Geometry.prototype.copy = function (id) {
  32804. var vertexData = new BABYLON.VertexData();
  32805. vertexData.indices = [];
  32806. var indices = this.getIndices();
  32807. for (var index = 0; index < indices.length; index++) {
  32808. vertexData.indices.push(indices[index]);
  32809. }
  32810. var updatable = false;
  32811. var stopChecking = false;
  32812. var kind;
  32813. for (kind in this._vertexBuffers) {
  32814. // using slice() to make a copy of the array and not just reference it
  32815. var data = this.getVerticesData(kind);
  32816. if (data instanceof Float32Array) {
  32817. vertexData.set(new Float32Array(data), kind);
  32818. }
  32819. else {
  32820. vertexData.set(data.slice(0), kind);
  32821. }
  32822. if (!stopChecking) {
  32823. updatable = this.getVertexBuffer(kind).isUpdatable();
  32824. stopChecking = !updatable;
  32825. }
  32826. }
  32827. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  32828. geometry.delayLoadState = this.delayLoadState;
  32829. geometry.delayLoadingFile = this.delayLoadingFile;
  32830. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32831. for (kind in this._delayInfo) {
  32832. geometry._delayInfo = geometry._delayInfo || [];
  32833. geometry._delayInfo.push(kind);
  32834. }
  32835. // Bounding info
  32836. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32837. return geometry;
  32838. };
  32839. Geometry.prototype.serialize = function () {
  32840. var serializationObject = {};
  32841. serializationObject.id = this.id;
  32842. if (BABYLON.Tags.HasTags(this)) {
  32843. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32844. }
  32845. return serializationObject;
  32846. };
  32847. Geometry.prototype.serializeVerticeData = function () {
  32848. var serializationObject = this.serialize();
  32849. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32850. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32851. }
  32852. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32853. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32854. }
  32855. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32856. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32857. }
  32858. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32859. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  32860. }
  32861. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32862. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  32863. }
  32864. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32865. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  32866. }
  32867. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32868. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  32869. }
  32870. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32871. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  32872. }
  32873. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32874. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  32875. }
  32876. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32877. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32878. serializationObject.matricesIndices._isExpanded = true;
  32879. }
  32880. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32881. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32882. }
  32883. serializationObject.indices = this.getIndices();
  32884. return serializationObject;
  32885. };
  32886. // Statics
  32887. Geometry.ExtractFromMesh = function (mesh, id) {
  32888. var geometry = mesh._geometry;
  32889. if (!geometry) {
  32890. return null;
  32891. }
  32892. return geometry.copy(id);
  32893. };
  32894. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  32895. // be aware Math.random() could cause collisions
  32896. Geometry.RandomId = function () {
  32897. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  32898. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  32899. return v.toString(16);
  32900. });
  32901. };
  32902. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  32903. var scene = mesh.getScene();
  32904. // Geometry
  32905. var geometryId = parsedGeometry.geometryId;
  32906. if (geometryId) {
  32907. var geometry = scene.getGeometryByID(geometryId);
  32908. if (geometry) {
  32909. geometry.applyToMesh(mesh);
  32910. }
  32911. }
  32912. else if (parsedGeometry instanceof ArrayBuffer) {
  32913. var binaryInfo = mesh._binaryInfo;
  32914. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  32915. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  32916. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  32917. }
  32918. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32919. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32920. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32921. }
  32922. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32923. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32924. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32925. }
  32926. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32927. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32928. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32929. }
  32930. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32931. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32932. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32933. }
  32934. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32935. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32936. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32937. }
  32938. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32939. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32940. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32941. }
  32942. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32943. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32944. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32945. }
  32946. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32947. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32948. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32949. }
  32950. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32951. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32952. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32953. }
  32954. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32955. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32956. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32957. }
  32958. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  32959. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  32960. mesh.setIndices(indicesData);
  32961. }
  32962. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  32963. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  32964. mesh.subMeshes = [];
  32965. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  32966. var materialIndex = subMeshesData[(i * 5) + 0];
  32967. var verticesStart = subMeshesData[(i * 5) + 1];
  32968. var verticesCount = subMeshesData[(i * 5) + 2];
  32969. var indexStart = subMeshesData[(i * 5) + 3];
  32970. var indexCount = subMeshesData[(i * 5) + 4];
  32971. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  32972. }
  32973. }
  32974. }
  32975. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  32976. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  32977. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  32978. if (parsedGeometry.uvs) {
  32979. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  32980. }
  32981. if (parsedGeometry.uvs2) {
  32982. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  32983. }
  32984. if (parsedGeometry.uvs3) {
  32985. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  32986. }
  32987. if (parsedGeometry.uvs4) {
  32988. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  32989. }
  32990. if (parsedGeometry.uvs5) {
  32991. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  32992. }
  32993. if (parsedGeometry.uvs6) {
  32994. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  32995. }
  32996. if (parsedGeometry.colors) {
  32997. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  32998. }
  32999. if (parsedGeometry.matricesIndices) {
  33000. if (!parsedGeometry.matricesIndices._isExpanded) {
  33001. var floatIndices = [];
  33002. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33003. var matricesIndex = parsedGeometry.matricesIndices[i];
  33004. floatIndices.push(matricesIndex & 0x000000FF);
  33005. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33006. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33007. floatIndices.push(matricesIndex >> 24);
  33008. }
  33009. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  33010. }
  33011. else {
  33012. delete parsedGeometry.matricesIndices._isExpanded;
  33013. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  33014. }
  33015. }
  33016. if (parsedGeometry.matricesIndicesExtra) {
  33017. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33018. var floatIndices = [];
  33019. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33020. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33021. floatIndices.push(matricesIndex & 0x000000FF);
  33022. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33023. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33024. floatIndices.push(matricesIndex >> 24);
  33025. }
  33026. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  33027. }
  33028. else {
  33029. delete parsedGeometry.matricesIndices._isExpanded;
  33030. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  33031. }
  33032. }
  33033. if (parsedGeometry.matricesWeights) {
  33034. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  33035. }
  33036. if (parsedGeometry.matricesWeightsExtra) {
  33037. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  33038. }
  33039. mesh.setIndices(parsedGeometry.indices);
  33040. }
  33041. // SubMeshes
  33042. if (parsedGeometry.subMeshes) {
  33043. mesh.subMeshes = [];
  33044. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33045. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33046. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33047. }
  33048. }
  33049. // Flat shading
  33050. if (mesh._shouldGenerateFlatShading) {
  33051. mesh.convertToFlatShadedMesh();
  33052. delete mesh._shouldGenerateFlatShading;
  33053. }
  33054. // Update
  33055. mesh.computeWorldMatrix(true);
  33056. // Octree
  33057. if (scene['_selectionOctree']) {
  33058. scene['_selectionOctree'].addMesh(mesh);
  33059. }
  33060. };
  33061. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33062. if (scene.getGeometryByID(parsedVertexData.id)) {
  33063. return null; // null since geometry could be something else than a box...
  33064. }
  33065. var geometry = new Geometry(parsedVertexData.id, scene);
  33066. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33067. if (parsedVertexData.delayLoadingFile) {
  33068. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33069. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33070. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33071. geometry._delayInfo = [];
  33072. if (parsedVertexData.hasUVs) {
  33073. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33074. }
  33075. if (parsedVertexData.hasUVs2) {
  33076. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33077. }
  33078. if (parsedVertexData.hasUVs3) {
  33079. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33080. }
  33081. if (parsedVertexData.hasUVs4) {
  33082. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33083. }
  33084. if (parsedVertexData.hasUVs5) {
  33085. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33086. }
  33087. if (parsedVertexData.hasUVs6) {
  33088. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33089. }
  33090. if (parsedVertexData.hasColors) {
  33091. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33092. }
  33093. if (parsedVertexData.hasMatricesIndices) {
  33094. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33095. }
  33096. if (parsedVertexData.hasMatricesWeights) {
  33097. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33098. }
  33099. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33100. }
  33101. else {
  33102. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33103. }
  33104. scene.pushGeometry(geometry, true);
  33105. return geometry;
  33106. };
  33107. return Geometry;
  33108. })();
  33109. BABYLON.Geometry = Geometry;
  33110. /////// Primitives //////////////////////////////////////////////
  33111. var Geometry;
  33112. (function (Geometry) {
  33113. var Primitives;
  33114. (function (Primitives) {
  33115. /// Abstract class
  33116. var _Primitive = (function (_super) {
  33117. __extends(_Primitive, _super);
  33118. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  33119. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  33120. this._canBeRegenerated = _canBeRegenerated;
  33121. this._beingRegenerated = true;
  33122. this.regenerate();
  33123. this._beingRegenerated = false;
  33124. }
  33125. _Primitive.prototype.canBeRegenerated = function () {
  33126. return this._canBeRegenerated;
  33127. };
  33128. _Primitive.prototype.regenerate = function () {
  33129. if (!this._canBeRegenerated) {
  33130. return;
  33131. }
  33132. this._beingRegenerated = true;
  33133. this.setAllVerticesData(this._regenerateVertexData(), false);
  33134. this._beingRegenerated = false;
  33135. };
  33136. _Primitive.prototype.asNewGeometry = function (id) {
  33137. return _super.prototype.copy.call(this, id);
  33138. };
  33139. // overrides
  33140. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  33141. if (!this._beingRegenerated) {
  33142. return;
  33143. }
  33144. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33145. };
  33146. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  33147. if (!this._beingRegenerated) {
  33148. return;
  33149. }
  33150. _super.prototype.setVerticesData.call(this, kind, data, false);
  33151. };
  33152. // to override
  33153. // protected
  33154. _Primitive.prototype._regenerateVertexData = function () {
  33155. throw new Error("Abstract method");
  33156. };
  33157. _Primitive.prototype.copy = function (id) {
  33158. throw new Error("Must be overriden in sub-classes.");
  33159. };
  33160. _Primitive.prototype.serialize = function () {
  33161. var serializationObject = _super.prototype.serialize.call(this);
  33162. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33163. return serializationObject;
  33164. };
  33165. return _Primitive;
  33166. })(Geometry);
  33167. Primitives._Primitive = _Primitive;
  33168. var Ribbon = (function (_super) {
  33169. __extends(Ribbon, _super);
  33170. // Members
  33171. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  33172. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33173. _super.call(this, id, scene, canBeRegenerated, mesh);
  33174. this.pathArray = pathArray;
  33175. this.closeArray = closeArray;
  33176. this.closePath = closePath;
  33177. this.offset = offset;
  33178. this.side = side;
  33179. }
  33180. Ribbon.prototype._regenerateVertexData = function () {
  33181. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33182. };
  33183. Ribbon.prototype.copy = function (id) {
  33184. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  33185. };
  33186. return Ribbon;
  33187. })(_Primitive);
  33188. Primitives.Ribbon = Ribbon;
  33189. var Box = (function (_super) {
  33190. __extends(Box, _super);
  33191. // Members
  33192. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  33193. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33194. _super.call(this, id, scene, canBeRegenerated, mesh);
  33195. this.size = size;
  33196. this.side = side;
  33197. }
  33198. Box.prototype._regenerateVertexData = function () {
  33199. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33200. };
  33201. Box.prototype.copy = function (id) {
  33202. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33203. };
  33204. Box.prototype.serialize = function () {
  33205. var serializationObject = _super.prototype.serialize.call(this);
  33206. serializationObject.size = this.size;
  33207. return serializationObject;
  33208. };
  33209. Box.Parse = function (parsedBox, scene) {
  33210. if (scene.getGeometryByID(parsedBox.id)) {
  33211. return null; // null since geometry could be something else than a box...
  33212. }
  33213. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33214. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33215. scene.pushGeometry(box, true);
  33216. return box;
  33217. };
  33218. return Box;
  33219. })(_Primitive);
  33220. Primitives.Box = Box;
  33221. var Sphere = (function (_super) {
  33222. __extends(Sphere, _super);
  33223. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  33224. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33225. _super.call(this, id, scene, canBeRegenerated, mesh);
  33226. this.segments = segments;
  33227. this.diameter = diameter;
  33228. this.side = side;
  33229. }
  33230. Sphere.prototype._regenerateVertexData = function () {
  33231. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  33232. };
  33233. Sphere.prototype.copy = function (id) {
  33234. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  33235. };
  33236. Sphere.prototype.serialize = function () {
  33237. var serializationObject = _super.prototype.serialize.call(this);
  33238. serializationObject.segments = this.segments;
  33239. serializationObject.diameter = this.diameter;
  33240. return serializationObject;
  33241. };
  33242. Sphere.Parse = function (parsedSphere, scene) {
  33243. if (scene.getGeometryByID(parsedSphere.id)) {
  33244. return null; // null since geometry could be something else than a sphere...
  33245. }
  33246. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  33247. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  33248. scene.pushGeometry(sphere, true);
  33249. return sphere;
  33250. };
  33251. return Sphere;
  33252. })(_Primitive);
  33253. Primitives.Sphere = Sphere;
  33254. var Disc = (function (_super) {
  33255. __extends(Disc, _super);
  33256. // Members
  33257. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  33258. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33259. _super.call(this, id, scene, canBeRegenerated, mesh);
  33260. this.radius = radius;
  33261. this.tessellation = tessellation;
  33262. this.side = side;
  33263. }
  33264. Disc.prototype._regenerateVertexData = function () {
  33265. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  33266. };
  33267. Disc.prototype.copy = function (id) {
  33268. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  33269. };
  33270. return Disc;
  33271. })(_Primitive);
  33272. Primitives.Disc = Disc;
  33273. var Cylinder = (function (_super) {
  33274. __extends(Cylinder, _super);
  33275. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  33276. if (subdivisions === void 0) { subdivisions = 1; }
  33277. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33278. _super.call(this, id, scene, canBeRegenerated, mesh);
  33279. this.height = height;
  33280. this.diameterTop = diameterTop;
  33281. this.diameterBottom = diameterBottom;
  33282. this.tessellation = tessellation;
  33283. this.subdivisions = subdivisions;
  33284. this.side = side;
  33285. }
  33286. Cylinder.prototype._regenerateVertexData = function () {
  33287. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  33288. };
  33289. Cylinder.prototype.copy = function (id) {
  33290. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  33291. };
  33292. Cylinder.prototype.serialize = function () {
  33293. var serializationObject = _super.prototype.serialize.call(this);
  33294. serializationObject.height = this.height;
  33295. serializationObject.diameterTop = this.diameterTop;
  33296. serializationObject.diameterBottom = this.diameterBottom;
  33297. serializationObject.tessellation = this.tessellation;
  33298. return serializationObject;
  33299. };
  33300. Cylinder.Parse = function (parsedCylinder, scene) {
  33301. if (scene.getGeometryByID(parsedCylinder.id)) {
  33302. return null; // null since geometry could be something else than a cylinder...
  33303. }
  33304. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  33305. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  33306. scene.pushGeometry(cylinder, true);
  33307. return cylinder;
  33308. };
  33309. return Cylinder;
  33310. })(_Primitive);
  33311. Primitives.Cylinder = Cylinder;
  33312. var Torus = (function (_super) {
  33313. __extends(Torus, _super);
  33314. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  33315. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33316. _super.call(this, id, scene, canBeRegenerated, mesh);
  33317. this.diameter = diameter;
  33318. this.thickness = thickness;
  33319. this.tessellation = tessellation;
  33320. this.side = side;
  33321. }
  33322. Torus.prototype._regenerateVertexData = function () {
  33323. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  33324. };
  33325. Torus.prototype.copy = function (id) {
  33326. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  33327. };
  33328. Torus.prototype.serialize = function () {
  33329. var serializationObject = _super.prototype.serialize.call(this);
  33330. serializationObject.diameter = this.diameter;
  33331. serializationObject.thickness = this.thickness;
  33332. serializationObject.tessellation = this.tessellation;
  33333. return serializationObject;
  33334. };
  33335. Torus.Parse = function (parsedTorus, scene) {
  33336. if (scene.getGeometryByID(parsedTorus.id)) {
  33337. return null; // null since geometry could be something else than a torus...
  33338. }
  33339. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  33340. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  33341. scene.pushGeometry(torus, true);
  33342. return torus;
  33343. };
  33344. return Torus;
  33345. })(_Primitive);
  33346. Primitives.Torus = Torus;
  33347. var Ground = (function (_super) {
  33348. __extends(Ground, _super);
  33349. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  33350. _super.call(this, id, scene, canBeRegenerated, mesh);
  33351. this.width = width;
  33352. this.height = height;
  33353. this.subdivisions = subdivisions;
  33354. }
  33355. Ground.prototype._regenerateVertexData = function () {
  33356. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  33357. };
  33358. Ground.prototype.copy = function (id) {
  33359. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  33360. };
  33361. Ground.prototype.serialize = function () {
  33362. var serializationObject = _super.prototype.serialize.call(this);
  33363. serializationObject.width = this.width;
  33364. serializationObject.height = this.height;
  33365. serializationObject.subdivisions = this.subdivisions;
  33366. return serializationObject;
  33367. };
  33368. Ground.Parse = function (parsedGround, scene) {
  33369. if (scene.getGeometryByID(parsedGround.id)) {
  33370. return null; // null since geometry could be something else than a ground...
  33371. }
  33372. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  33373. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  33374. scene.pushGeometry(ground, true);
  33375. return ground;
  33376. };
  33377. return Ground;
  33378. })(_Primitive);
  33379. Primitives.Ground = Ground;
  33380. var TiledGround = (function (_super) {
  33381. __extends(TiledGround, _super);
  33382. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  33383. _super.call(this, id, scene, canBeRegenerated, mesh);
  33384. this.xmin = xmin;
  33385. this.zmin = zmin;
  33386. this.xmax = xmax;
  33387. this.zmax = zmax;
  33388. this.subdivisions = subdivisions;
  33389. this.precision = precision;
  33390. }
  33391. TiledGround.prototype._regenerateVertexData = function () {
  33392. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  33393. };
  33394. TiledGround.prototype.copy = function (id) {
  33395. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  33396. };
  33397. return TiledGround;
  33398. })(_Primitive);
  33399. Primitives.TiledGround = TiledGround;
  33400. var Plane = (function (_super) {
  33401. __extends(Plane, _super);
  33402. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  33403. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33404. _super.call(this, id, scene, canBeRegenerated, mesh);
  33405. this.size = size;
  33406. this.side = side;
  33407. }
  33408. Plane.prototype._regenerateVertexData = function () {
  33409. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  33410. };
  33411. Plane.prototype.copy = function (id) {
  33412. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33413. };
  33414. Plane.prototype.serialize = function () {
  33415. var serializationObject = _super.prototype.serialize.call(this);
  33416. serializationObject.size = this.size;
  33417. return serializationObject;
  33418. };
  33419. Plane.Parse = function (parsedPlane, scene) {
  33420. if (scene.getGeometryByID(parsedPlane.id)) {
  33421. return null; // null since geometry could be something else than a ground...
  33422. }
  33423. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  33424. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  33425. scene.pushGeometry(plane, true);
  33426. return plane;
  33427. };
  33428. return Plane;
  33429. })(_Primitive);
  33430. Primitives.Plane = Plane;
  33431. var TorusKnot = (function (_super) {
  33432. __extends(TorusKnot, _super);
  33433. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  33434. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33435. _super.call(this, id, scene, canBeRegenerated, mesh);
  33436. this.radius = radius;
  33437. this.tube = tube;
  33438. this.radialSegments = radialSegments;
  33439. this.tubularSegments = tubularSegments;
  33440. this.p = p;
  33441. this.q = q;
  33442. this.side = side;
  33443. }
  33444. TorusKnot.prototype._regenerateVertexData = function () {
  33445. return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  33446. };
  33447. TorusKnot.prototype.copy = function (id) {
  33448. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  33449. };
  33450. TorusKnot.prototype.serialize = function () {
  33451. var serializationObject = _super.prototype.serialize.call(this);
  33452. serializationObject.radius = this.radius;
  33453. serializationObject.tube = this.tube;
  33454. serializationObject.radialSegments = this.radialSegments;
  33455. serializationObject.tubularSegments = this.tubularSegments;
  33456. serializationObject.p = this.p;
  33457. serializationObject.q = this.q;
  33458. return serializationObject;
  33459. };
  33460. ;
  33461. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  33462. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  33463. return null; // null since geometry could be something else than a ground...
  33464. }
  33465. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  33466. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  33467. scene.pushGeometry(torusKnot, true);
  33468. return torusKnot;
  33469. };
  33470. return TorusKnot;
  33471. })(_Primitive);
  33472. Primitives.TorusKnot = TorusKnot;
  33473. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  33474. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  33475. })(BABYLON || (BABYLON = {}));
  33476. var BABYLON;
  33477. (function (BABYLON) {
  33478. var GroundMesh = (function (_super) {
  33479. __extends(GroundMesh, _super);
  33480. function GroundMesh(name, scene) {
  33481. _super.call(this, name, scene);
  33482. this.generateOctree = false;
  33483. this._worldInverse = new BABYLON.Matrix();
  33484. }
  33485. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  33486. get: function () {
  33487. return this._subdivisions;
  33488. },
  33489. enumerable: true,
  33490. configurable: true
  33491. });
  33492. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  33493. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  33494. this._subdivisions = chunksCount;
  33495. this.subdivide(this._subdivisions);
  33496. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  33497. };
  33498. /**
  33499. * Returns a height (y) value in the Worl system :
  33500. * the ground altitude at the coordinates (x, z) expressed in the World system.
  33501. * Returns the ground y position if (x, z) are outside the ground surface.
  33502. * Not pertinent if the ground is rotated.
  33503. */
  33504. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  33505. // express x and y in the ground local system
  33506. x -= this.position.x;
  33507. z -= this.position.z;
  33508. x /= this.scaling.x;
  33509. z /= this.scaling.z;
  33510. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  33511. return this.position.y;
  33512. }
  33513. if (!this._heightQuads || this._heightQuads.length == 0) {
  33514. this._initHeightQuads();
  33515. this._computeHeightQuads();
  33516. }
  33517. var facet = this._getFacetAt(x, z);
  33518. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  33519. // return y in the World system
  33520. return y * this.scaling.y + this.position.y;
  33521. };
  33522. /**
  33523. * Returns a normalized vector (Vector3) orthogonal to the ground
  33524. * at the ground coordinates (x, z) expressed in the World system.
  33525. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  33526. * Not pertinent if the ground is rotated.
  33527. */
  33528. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  33529. var normal = new BABYLON.Vector3(0, 1, 0);
  33530. this.getNormalAtCoordinatesToRef(x, z, normal);
  33531. return normal;
  33532. };
  33533. /**
  33534. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  33535. * at the ground coordinates (x, z) expressed in the World system.
  33536. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  33537. * Not pertinent if the ground is rotated.
  33538. */
  33539. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  33540. // express x and y in the ground local system
  33541. x -= this.position.x;
  33542. z -= this.position.z;
  33543. x /= this.scaling.x;
  33544. z /= this.scaling.z;
  33545. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  33546. return;
  33547. }
  33548. if (!this._heightQuads || this._heightQuads.length == 0) {
  33549. this._initHeightQuads();
  33550. this._computeHeightQuads();
  33551. }
  33552. var facet = this._getFacetAt(x, z);
  33553. ref.x = facet.x;
  33554. ref.y = facet.y;
  33555. ref.z = facet.z;
  33556. };
  33557. /**
  33558. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  33559. * if the ground has been updated.
  33560. * This can be used in the render loop
  33561. */
  33562. GroundMesh.prototype.updateCoordinateHeights = function () {
  33563. if (!this._heightQuads || this._heightQuads.length == 0) {
  33564. this._initHeightQuads();
  33565. }
  33566. this._computeHeightQuads();
  33567. };
  33568. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  33569. GroundMesh.prototype._getFacetAt = function (x, z) {
  33570. // retrieve col and row from x, z coordinates in the ground local system
  33571. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  33572. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  33573. var quad = this._heightQuads[row * this._subdivisions + col];
  33574. var facet;
  33575. if (z < quad.slope.x * x + quad.slope.y) {
  33576. facet = quad.facet1;
  33577. }
  33578. else {
  33579. facet = quad.facet2;
  33580. }
  33581. return facet;
  33582. };
  33583. // Creates and populates the heightMap array with "facet" elements :
  33584. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  33585. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  33586. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  33587. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  33588. GroundMesh.prototype._initHeightQuads = function () {
  33589. this._heightQuads = new Array();
  33590. for (var row = 0; row < this._subdivisions; row++) {
  33591. for (var col = 0; col < this._subdivisions; col++) {
  33592. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  33593. this._heightQuads[row * this._subdivisions + col] = quad;
  33594. }
  33595. }
  33596. };
  33597. // Compute each quad element values and update the the heightMap array :
  33598. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  33599. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  33600. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  33601. GroundMesh.prototype._computeHeightQuads = function () {
  33602. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33603. var v1 = BABYLON.Tmp.Vector3[0];
  33604. var v2 = BABYLON.Tmp.Vector3[1];
  33605. var v3 = BABYLON.Tmp.Vector3[2];
  33606. var v4 = BABYLON.Tmp.Vector3[3];
  33607. var v1v2 = BABYLON.Tmp.Vector3[4];
  33608. var v1v3 = BABYLON.Tmp.Vector3[5];
  33609. var v1v4 = BABYLON.Tmp.Vector3[6];
  33610. var norm1 = BABYLON.Tmp.Vector3[7];
  33611. var norm2 = BABYLON.Tmp.Vector3[8];
  33612. var i = 0;
  33613. var j = 0;
  33614. var k = 0;
  33615. var cd = 0; // 2D slope coefficient : z = cd * x + h
  33616. var h = 0;
  33617. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  33618. var d2 = 0;
  33619. for (var row = 0; row < this._subdivisions; row++) {
  33620. for (var col = 0; col < this._subdivisions; col++) {
  33621. i = col * 3;
  33622. j = row * (this._subdivisions + 1) * 3;
  33623. k = (row + 1) * (this._subdivisions + 1) * 3;
  33624. v1.x = positions[j + i];
  33625. v1.y = positions[j + i + 1];
  33626. v1.z = positions[j + i + 2];
  33627. v2.x = positions[j + i + 3];
  33628. v2.y = positions[j + i + 4];
  33629. v2.z = positions[j + i + 5];
  33630. v3.x = positions[k + i];
  33631. v3.y = positions[k + i + 1];
  33632. v3.z = positions[k + i + 2];
  33633. v4.x = positions[k + i + 3];
  33634. v4.y = positions[k + i + 4];
  33635. v4.z = positions[k + i + 5];
  33636. // 2D slope V1V4
  33637. cd = (v4.z - v1.z) / (v4.x - v1.x);
  33638. h = v1.z - cd * v1.x; // v1 belongs to the slope
  33639. // facet equations :
  33640. // we compute each facet normal vector
  33641. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  33642. // we compute the value d by applying the equation to v1 which belongs to the plane
  33643. // then we store the facet equation in a Vector4
  33644. v2.subtractToRef(v1, v1v2);
  33645. v3.subtractToRef(v1, v1v3);
  33646. v4.subtractToRef(v1, v1v4);
  33647. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  33648. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  33649. norm1.normalize();
  33650. norm2.normalize();
  33651. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  33652. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  33653. var quad = this._heightQuads[row * this._subdivisions + col];
  33654. quad.slope.copyFromFloats(cd, h);
  33655. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  33656. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  33657. }
  33658. }
  33659. };
  33660. return GroundMesh;
  33661. })(BABYLON.Mesh);
  33662. BABYLON.GroundMesh = GroundMesh;
  33663. })(BABYLON || (BABYLON = {}));
  33664. var BABYLON;
  33665. (function (BABYLON) {
  33666. var LinesMesh = (function (_super) {
  33667. __extends(LinesMesh, _super);
  33668. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  33669. if (parent === void 0) { parent = null; }
  33670. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  33671. this.color = new BABYLON.Color3(1, 1, 1);
  33672. this.alpha = 1;
  33673. this._positionBuffer = {};
  33674. if (source) {
  33675. this.color = source.color.clone();
  33676. this.alpha = source.alpha;
  33677. }
  33678. this._intersectionThreshold = 0.1;
  33679. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  33680. attributes: [BABYLON.VertexBuffer.PositionKind],
  33681. uniforms: ["worldViewProjection", "color"],
  33682. needAlphaBlending: true
  33683. });
  33684. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  33685. }
  33686. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  33687. /**
  33688. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  33689. * This margin is expressed in world space coordinates, so its value may vary.
  33690. * Default value is 0.1
  33691. * @returns the intersection Threshold value.
  33692. */
  33693. get: function () {
  33694. return this._intersectionThreshold;
  33695. },
  33696. /**
  33697. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  33698. * This margin is expressed in world space coordinates, so its value may vary.
  33699. * @param value the new threshold to apply
  33700. */
  33701. set: function (value) {
  33702. if (this._intersectionThreshold === value) {
  33703. return;
  33704. }
  33705. this._intersectionThreshold = value;
  33706. if (this.geometry) {
  33707. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  33708. }
  33709. },
  33710. enumerable: true,
  33711. configurable: true
  33712. });
  33713. Object.defineProperty(LinesMesh.prototype, "material", {
  33714. get: function () {
  33715. return this._colorShader;
  33716. },
  33717. enumerable: true,
  33718. configurable: true
  33719. });
  33720. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  33721. get: function () {
  33722. return false;
  33723. },
  33724. enumerable: true,
  33725. configurable: true
  33726. });
  33727. LinesMesh.prototype.createInstance = function (name) {
  33728. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  33729. return null;
  33730. };
  33731. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  33732. var engine = this.getScene().getEngine();
  33733. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  33734. // VBOs
  33735. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  33736. // Color
  33737. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  33738. };
  33739. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  33740. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  33741. return;
  33742. }
  33743. var engine = this.getScene().getEngine();
  33744. // Draw order
  33745. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  33746. };
  33747. LinesMesh.prototype.dispose = function (doNotRecurse) {
  33748. this._colorShader.dispose();
  33749. _super.prototype.dispose.call(this, doNotRecurse);
  33750. };
  33751. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  33752. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  33753. };
  33754. return LinesMesh;
  33755. })(BABYLON.Mesh);
  33756. BABYLON.LinesMesh = LinesMesh;
  33757. })(BABYLON || (BABYLON = {}));
  33758. var BABYLON;
  33759. (function (BABYLON) {
  33760. var DefaultLoadingScreen = (function () {
  33761. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  33762. var _this = this;
  33763. if (_loadingText === void 0) { _loadingText = ""; }
  33764. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  33765. this._renderingCanvas = _renderingCanvas;
  33766. this._loadingText = _loadingText;
  33767. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  33768. // Resize
  33769. this._resizeLoadingUI = function () {
  33770. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  33771. _this._loadingDiv.style.position = "absolute";
  33772. _this._loadingDiv.style.left = canvasRect.left + "px";
  33773. _this._loadingDiv.style.top = canvasRect.top + "px";
  33774. _this._loadingDiv.style.width = canvasRect.width + "px";
  33775. _this._loadingDiv.style.height = canvasRect.height + "px";
  33776. };
  33777. }
  33778. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  33779. var _this = this;
  33780. if (this._loadingDiv) {
  33781. // Do not add a loading screen if there is already one
  33782. return;
  33783. }
  33784. this._loadingDiv = document.createElement("div");
  33785. this._loadingDiv.id = "babylonjsLoadingDiv";
  33786. this._loadingDiv.style.opacity = "0";
  33787. this._loadingDiv.style.transition = "opacity 1.5s ease";
  33788. // Loading text
  33789. this._loadingTextDiv = document.createElement("div");
  33790. this._loadingTextDiv.style.position = "absolute";
  33791. this._loadingTextDiv.style.left = "0";
  33792. this._loadingTextDiv.style.top = "50%";
  33793. this._loadingTextDiv.style.marginTop = "80px";
  33794. this._loadingTextDiv.style.width = "100%";
  33795. this._loadingTextDiv.style.height = "20px";
  33796. this._loadingTextDiv.style.fontFamily = "Arial";
  33797. this._loadingTextDiv.style.fontSize = "14px";
  33798. this._loadingTextDiv.style.color = "white";
  33799. this._loadingTextDiv.style.textAlign = "center";
  33800. this._loadingTextDiv.innerHTML = "Loading";
  33801. this._loadingDiv.appendChild(this._loadingTextDiv);
  33802. //set the predefined text
  33803. this._loadingTextDiv.innerHTML = this._loadingText;
  33804. // Loading img
  33805. var imgBack = new Image();
  33806. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
  33807. imgBack.style.position = "absolute";
  33808. imgBack.style.left = "50%";
  33809. imgBack.style.top = "50%";
  33810. imgBack.style.marginLeft = "-50px";
  33811. imgBack.style.marginTop = "-50px";
  33812. imgBack.style.transition = "transform 1.0s ease";
  33813. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  33814. var deg = 360;
  33815. var onTransitionEnd = function () {
  33816. deg += 360;
  33817. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  33818. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  33819. };
  33820. imgBack.addEventListener("transitionend", onTransitionEnd);
  33821. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  33822. this._loadingDiv.appendChild(imgBack);
  33823. // front image
  33824. var imgFront = new Image();
  33825. imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
  33826. imgFront.style.position = "absolute";
  33827. imgFront.style.left = "50%";
  33828. imgFront.style.top = "50%";
  33829. imgFront.style.marginLeft = "-50px";
  33830. imgFront.style.marginTop = "-50px";
  33831. this._loadingDiv.appendChild(imgFront);
  33832. this._resizeLoadingUI();
  33833. window.addEventListener("resize", this._resizeLoadingUI);
  33834. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33835. document.body.appendChild(this._loadingDiv);
  33836. setTimeout(function () {
  33837. _this._loadingDiv.style.opacity = "1";
  33838. imgBack.style.transform = "rotateZ(360deg)";
  33839. imgBack.style.webkitTransform = "rotateZ(360deg)";
  33840. }, 0);
  33841. };
  33842. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  33843. var _this = this;
  33844. if (!this._loadingDiv) {
  33845. return;
  33846. }
  33847. var onTransitionEnd = function () {
  33848. if (!_this._loadingDiv) {
  33849. return;
  33850. }
  33851. document.body.removeChild(_this._loadingDiv);
  33852. window.removeEventListener("resize", _this._resizeLoadingUI);
  33853. _this._loadingDiv = null;
  33854. };
  33855. this._loadingDiv.style.opacity = "0";
  33856. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  33857. };
  33858. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  33859. set: function (text) {
  33860. this._loadingText = text;
  33861. if (this._loadingTextDiv) {
  33862. this._loadingTextDiv.innerHTML = this._loadingText;
  33863. }
  33864. },
  33865. enumerable: true,
  33866. configurable: true
  33867. });
  33868. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  33869. get: function () {
  33870. return this._loadingDivBackgroundColor;
  33871. },
  33872. set: function (color) {
  33873. this._loadingDivBackgroundColor = color;
  33874. if (!this._loadingDiv) {
  33875. return;
  33876. }
  33877. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33878. },
  33879. enumerable: true,
  33880. configurable: true
  33881. });
  33882. return DefaultLoadingScreen;
  33883. })();
  33884. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  33885. })(BABYLON || (BABYLON = {}));
  33886. var BABYLON;
  33887. (function (BABYLON) {
  33888. var AudioEngine = (function () {
  33889. function AudioEngine() {
  33890. this._audioContext = null;
  33891. this._audioContextInitialized = false;
  33892. this.canUseWebAudio = false;
  33893. this.WarnedWebAudioUnsupported = false;
  33894. this.unlocked = false;
  33895. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33896. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33897. this.canUseWebAudio = true;
  33898. }
  33899. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  33900. this._unlockiOSaudio();
  33901. }
  33902. else {
  33903. this.unlocked = true;
  33904. }
  33905. }
  33906. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33907. get: function () {
  33908. if (!this._audioContextInitialized) {
  33909. this._initializeAudioContext();
  33910. }
  33911. return this._audioContext;
  33912. },
  33913. enumerable: true,
  33914. configurable: true
  33915. });
  33916. AudioEngine.prototype._unlockiOSaudio = function () {
  33917. var _this = this;
  33918. var unlockaudio = function () {
  33919. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  33920. var source = _this.audioContext.createBufferSource();
  33921. source.buffer = buffer;
  33922. source.connect(_this.audioContext.destination);
  33923. source.start(0);
  33924. setTimeout(function () {
  33925. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  33926. _this.unlocked = true;
  33927. window.removeEventListener('touchend', unlockaudio, false);
  33928. if (_this.onAudioUnlocked) {
  33929. _this.onAudioUnlocked();
  33930. }
  33931. }
  33932. }, 0);
  33933. };
  33934. window.addEventListener('touchend', unlockaudio, false);
  33935. };
  33936. AudioEngine.prototype._initializeAudioContext = function () {
  33937. try {
  33938. if (this.canUseWebAudio) {
  33939. this._audioContext = new AudioContext();
  33940. // create a global volume gain node
  33941. this.masterGain = this._audioContext.createGain();
  33942. this.masterGain.gain.value = 1;
  33943. this.masterGain.connect(this._audioContext.destination);
  33944. this._audioContextInitialized = true;
  33945. }
  33946. }
  33947. catch (e) {
  33948. this.canUseWebAudio = false;
  33949. BABYLON.Tools.Error("Web Audio: " + e.message);
  33950. }
  33951. };
  33952. AudioEngine.prototype.dispose = function () {
  33953. if (this.canUseWebAudio && this._audioContextInitialized) {
  33954. if (this._connectedAnalyser) {
  33955. this._connectedAnalyser.stopDebugCanvas();
  33956. this._connectedAnalyser.dispose();
  33957. this.masterGain.disconnect();
  33958. this.masterGain.connect(this._audioContext.destination);
  33959. this._connectedAnalyser = null;
  33960. }
  33961. this.masterGain.gain.value = 1;
  33962. }
  33963. this.WarnedWebAudioUnsupported = false;
  33964. };
  33965. AudioEngine.prototype.getGlobalVolume = function () {
  33966. if (this.canUseWebAudio && this._audioContextInitialized) {
  33967. return this.masterGain.gain.value;
  33968. }
  33969. else {
  33970. return -1;
  33971. }
  33972. };
  33973. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33974. if (this.canUseWebAudio && this._audioContextInitialized) {
  33975. this.masterGain.gain.value = newVolume;
  33976. }
  33977. };
  33978. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33979. if (this._connectedAnalyser) {
  33980. this._connectedAnalyser.stopDebugCanvas();
  33981. }
  33982. if (this.canUseWebAudio && this._audioContextInitialized) {
  33983. this._connectedAnalyser = analyser;
  33984. this.masterGain.disconnect();
  33985. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33986. }
  33987. };
  33988. return AudioEngine;
  33989. })();
  33990. BABYLON.AudioEngine = AudioEngine;
  33991. })(BABYLON || (BABYLON = {}));
  33992. var BABYLON;
  33993. (function (BABYLON) {
  33994. var Sound = (function () {
  33995. /**
  33996. * Create a sound and attach it to a scene
  33997. * @param name Name of your sound
  33998. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33999. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  34000. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  34001. */
  34002. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  34003. var _this = this;
  34004. this.autoplay = false;
  34005. this.loop = false;
  34006. this.useCustomAttenuation = false;
  34007. this.spatialSound = false;
  34008. this.refDistance = 1;
  34009. this.rolloffFactor = 1;
  34010. this.maxDistance = 100;
  34011. this.distanceModel = "linear";
  34012. this._panningModel = "equalpower";
  34013. this._playbackRate = 1;
  34014. this._streaming = false;
  34015. this._startTime = 0;
  34016. this._startOffset = 0;
  34017. this._position = BABYLON.Vector3.Zero();
  34018. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  34019. this._volume = 1;
  34020. this._isLoaded = false;
  34021. this._isReadyToPlay = false;
  34022. this.isPlaying = false;
  34023. this.isPaused = false;
  34024. this._isDirectional = false;
  34025. // Used if you'd like to create a directional sound.
  34026. // If not set, the sound will be omnidirectional
  34027. this._coneInnerAngle = 360;
  34028. this._coneOuterAngle = 360;
  34029. this._coneOuterGain = 0;
  34030. this._isOutputConnected = false;
  34031. this.name = name;
  34032. this._scene = scene;
  34033. this._readyToPlayCallback = readyToPlayCallback;
  34034. // Default custom attenuation function is a linear attenuation
  34035. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34036. if (currentDistance < maxDistance) {
  34037. return currentVolume * (1 - currentDistance / maxDistance);
  34038. }
  34039. else {
  34040. return 0;
  34041. }
  34042. };
  34043. if (options) {
  34044. this.autoplay = options.autoplay || false;
  34045. this.loop = options.loop || false;
  34046. // if volume === 0, we need another way to check this option
  34047. if (options.volume !== undefined) {
  34048. this._volume = options.volume;
  34049. }
  34050. this.spatialSound = options.spatialSound || false;
  34051. this.maxDistance = options.maxDistance || 100;
  34052. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34053. this.rolloffFactor = options.rolloffFactor || 1;
  34054. this.refDistance = options.refDistance || 1;
  34055. this.distanceModel = options.distanceModel || "linear";
  34056. this._playbackRate = options.playbackRate || 1;
  34057. this._streaming = options.streaming || false;
  34058. }
  34059. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34060. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34061. this._soundGain.gain.value = this._volume;
  34062. this._inputAudioNode = this._soundGain;
  34063. this._ouputAudioNode = this._soundGain;
  34064. if (this.spatialSound) {
  34065. this._createSpatialParameters();
  34066. }
  34067. this._scene.mainSoundTrack.AddSound(this);
  34068. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34069. if (urlOrArrayBuffer) {
  34070. // If it's an URL
  34071. if (typeof (urlOrArrayBuffer) === "string") {
  34072. // Loading sound using XHR2
  34073. if (!this._streaming) {
  34074. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  34075. }
  34076. else {
  34077. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  34078. this._htmlAudioElement.controls = false;
  34079. this._htmlAudioElement.loop = this.loop;
  34080. this._htmlAudioElement.crossOrigin = "anonymous";
  34081. this._htmlAudioElement.preload = "auto";
  34082. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  34083. _this._isReadyToPlay = true;
  34084. if (_this.autoplay) {
  34085. _this.play();
  34086. }
  34087. if (_this._readyToPlayCallback) {
  34088. _this._readyToPlayCallback();
  34089. }
  34090. });
  34091. document.body.appendChild(this._htmlAudioElement);
  34092. }
  34093. }
  34094. else {
  34095. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34096. if (urlOrArrayBuffer.byteLength > 0) {
  34097. this._soundLoaded(urlOrArrayBuffer);
  34098. }
  34099. }
  34100. else {
  34101. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34102. }
  34103. }
  34104. }
  34105. }
  34106. else {
  34107. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34108. this._scene.mainSoundTrack.AddSound(this);
  34109. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34110. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34111. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34112. }
  34113. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34114. if (this._readyToPlayCallback) {
  34115. window.setTimeout(function () {
  34116. _this._readyToPlayCallback();
  34117. }, 1000);
  34118. }
  34119. }
  34120. }
  34121. Sound.prototype.dispose = function () {
  34122. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34123. if (this.isPlaying) {
  34124. this.stop();
  34125. }
  34126. this._isReadyToPlay = false;
  34127. if (this.soundTrackId === -1) {
  34128. this._scene.mainSoundTrack.RemoveSound(this);
  34129. }
  34130. else {
  34131. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34132. }
  34133. if (this._soundGain) {
  34134. this._soundGain.disconnect();
  34135. this._soundGain = null;
  34136. }
  34137. if (this._soundPanner) {
  34138. this._soundPanner.disconnect();
  34139. this._soundPanner = null;
  34140. }
  34141. if (this._soundSource) {
  34142. this._soundSource.disconnect();
  34143. this._soundSource = null;
  34144. }
  34145. this._audioBuffer = null;
  34146. if (this._htmlAudioElement) {
  34147. this._htmlAudioElement.pause();
  34148. this._htmlAudioElement.src = "";
  34149. document.body.removeChild(this._htmlAudioElement);
  34150. }
  34151. if (this._connectedMesh) {
  34152. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34153. this._connectedMesh = null;
  34154. }
  34155. }
  34156. };
  34157. Sound.prototype._soundLoaded = function (audioData) {
  34158. var _this = this;
  34159. this._isLoaded = true;
  34160. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34161. _this._audioBuffer = buffer;
  34162. _this._isReadyToPlay = true;
  34163. if (_this.autoplay) {
  34164. _this.play();
  34165. }
  34166. if (_this._readyToPlayCallback) {
  34167. _this._readyToPlayCallback();
  34168. }
  34169. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34170. };
  34171. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34172. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34173. this._audioBuffer = audioBuffer;
  34174. this._isReadyToPlay = true;
  34175. }
  34176. };
  34177. Sound.prototype.updateOptions = function (options) {
  34178. if (options) {
  34179. this.loop = options.loop || this.loop;
  34180. this.maxDistance = options.maxDistance || this.maxDistance;
  34181. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34182. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34183. this.refDistance = options.refDistance || this.refDistance;
  34184. this.distanceModel = options.distanceModel || this.distanceModel;
  34185. this._playbackRate = options.playbackRate || this._playbackRate;
  34186. this._updateSpatialParameters();
  34187. if (this.isPlaying) {
  34188. if (this._streaming) {
  34189. this._htmlAudioElement.playbackRate = this._playbackRate;
  34190. }
  34191. else {
  34192. this._soundSource.playbackRate.value = this._playbackRate;
  34193. }
  34194. }
  34195. }
  34196. };
  34197. Sound.prototype._createSpatialParameters = function () {
  34198. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34199. if (this._scene.headphone) {
  34200. this._panningModel = "HRTF";
  34201. }
  34202. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34203. this._updateSpatialParameters();
  34204. this._soundPanner.connect(this._ouputAudioNode);
  34205. this._inputAudioNode = this._soundPanner;
  34206. }
  34207. };
  34208. Sound.prototype._updateSpatialParameters = function () {
  34209. if (this.spatialSound) {
  34210. if (this.useCustomAttenuation) {
  34211. // Tricks to disable in a way embedded Web Audio attenuation
  34212. this._soundPanner.distanceModel = "linear";
  34213. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34214. this._soundPanner.refDistance = 1;
  34215. this._soundPanner.rolloffFactor = 1;
  34216. this._soundPanner.panningModel = this._panningModel;
  34217. }
  34218. else {
  34219. this._soundPanner.distanceModel = this.distanceModel;
  34220. this._soundPanner.maxDistance = this.maxDistance;
  34221. this._soundPanner.refDistance = this.refDistance;
  34222. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34223. this._soundPanner.panningModel = this._panningModel;
  34224. }
  34225. }
  34226. };
  34227. Sound.prototype.switchPanningModelToHRTF = function () {
  34228. this._panningModel = "HRTF";
  34229. this._switchPanningModel();
  34230. };
  34231. Sound.prototype.switchPanningModelToEqualPower = function () {
  34232. this._panningModel = "equalpower";
  34233. this._switchPanningModel();
  34234. };
  34235. Sound.prototype._switchPanningModel = function () {
  34236. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34237. this._soundPanner.panningModel = this._panningModel;
  34238. }
  34239. };
  34240. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34241. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34242. if (this._isOutputConnected) {
  34243. this._ouputAudioNode.disconnect();
  34244. }
  34245. this._ouputAudioNode.connect(soundTrackAudioNode);
  34246. this._isOutputConnected = true;
  34247. }
  34248. };
  34249. /**
  34250. * Transform this sound into a directional source
  34251. * @param coneInnerAngle Size of the inner cone in degree
  34252. * @param coneOuterAngle Size of the outer cone in degree
  34253. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34254. */
  34255. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34256. if (coneOuterAngle < coneInnerAngle) {
  34257. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34258. return;
  34259. }
  34260. this._coneInnerAngle = coneInnerAngle;
  34261. this._coneOuterAngle = coneOuterAngle;
  34262. this._coneOuterGain = coneOuterGain;
  34263. this._isDirectional = true;
  34264. if (this.isPlaying && this.loop) {
  34265. this.stop();
  34266. this.play();
  34267. }
  34268. };
  34269. Sound.prototype.setPosition = function (newPosition) {
  34270. this._position = newPosition;
  34271. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34272. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34273. }
  34274. };
  34275. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34276. this._localDirection = newLocalDirection;
  34277. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34278. this._updateDirection();
  34279. }
  34280. };
  34281. Sound.prototype._updateDirection = function () {
  34282. var mat = this._connectedMesh.getWorldMatrix();
  34283. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34284. direction.normalize();
  34285. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34286. };
  34287. Sound.prototype.updateDistanceFromListener = function () {
  34288. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34289. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34290. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34291. }
  34292. };
  34293. Sound.prototype.setAttenuationFunction = function (callback) {
  34294. this._customAttenuationFunction = callback;
  34295. };
  34296. /**
  34297. * Play the sound
  34298. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34299. */
  34300. Sound.prototype.play = function (time) {
  34301. var _this = this;
  34302. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34303. try {
  34304. if (this._startOffset < 0) {
  34305. time = -this._startOffset;
  34306. this._startOffset = 0;
  34307. }
  34308. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34309. if (!this._soundSource || !this._streamingSource) {
  34310. if (this.spatialSound) {
  34311. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34312. if (this._isDirectional) {
  34313. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34314. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34315. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34316. if (this._connectedMesh) {
  34317. this._updateDirection();
  34318. }
  34319. else {
  34320. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34321. }
  34322. }
  34323. }
  34324. }
  34325. if (this._streaming) {
  34326. if (!this._streamingSource) {
  34327. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34328. this._htmlAudioElement.onended = function () { _this._onended(); };
  34329. this._htmlAudioElement.playbackRate = this._playbackRate;
  34330. }
  34331. this._streamingSource.disconnect();
  34332. this._streamingSource.connect(this._inputAudioNode);
  34333. this._htmlAudioElement.play();
  34334. }
  34335. else {
  34336. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34337. this._soundSource.buffer = this._audioBuffer;
  34338. this._soundSource.connect(this._inputAudioNode);
  34339. this._soundSource.loop = this.loop;
  34340. this._soundSource.playbackRate.value = this._playbackRate;
  34341. this._soundSource.onended = function () { _this._onended(); };
  34342. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  34343. }
  34344. this._startTime = startTime;
  34345. this.isPlaying = true;
  34346. this.isPaused = false;
  34347. }
  34348. catch (ex) {
  34349. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34350. }
  34351. }
  34352. };
  34353. Sound.prototype._onended = function () {
  34354. this.isPlaying = false;
  34355. if (this.onended) {
  34356. this.onended();
  34357. }
  34358. };
  34359. /**
  34360. * Stop the sound
  34361. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34362. */
  34363. Sound.prototype.stop = function (time) {
  34364. if (this.isPlaying) {
  34365. if (this._streaming) {
  34366. this._htmlAudioElement.pause();
  34367. // Test needed for Firefox or it will generate an Invalid State Error
  34368. if (this._htmlAudioElement.currentTime > 0) {
  34369. this._htmlAudioElement.currentTime = 0;
  34370. }
  34371. }
  34372. else {
  34373. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34374. this._soundSource.stop(stopTime);
  34375. this._soundSource.onended = null;
  34376. if (!this.isPaused) {
  34377. this._startOffset = 0;
  34378. }
  34379. }
  34380. this.isPlaying = false;
  34381. }
  34382. };
  34383. Sound.prototype.pause = function () {
  34384. if (this.isPlaying) {
  34385. this.isPaused = true;
  34386. if (this._streaming) {
  34387. this._htmlAudioElement.pause();
  34388. }
  34389. else {
  34390. this.stop(0);
  34391. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34392. }
  34393. }
  34394. };
  34395. Sound.prototype.setVolume = function (newVolume, time) {
  34396. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34397. if (time) {
  34398. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  34399. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34400. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  34401. }
  34402. else {
  34403. this._soundGain.gain.value = newVolume;
  34404. }
  34405. }
  34406. this._volume = newVolume;
  34407. };
  34408. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34409. this._playbackRate = newPlaybackRate;
  34410. if (this.isPlaying) {
  34411. if (this._streaming) {
  34412. this._htmlAudioElement.playbackRate = this._playbackRate;
  34413. }
  34414. else {
  34415. this._soundSource.playbackRate.value = this._playbackRate;
  34416. }
  34417. }
  34418. };
  34419. Sound.prototype.getVolume = function () {
  34420. return this._volume;
  34421. };
  34422. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34423. var _this = this;
  34424. if (this._connectedMesh) {
  34425. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34426. this._registerFunc = null;
  34427. }
  34428. this._connectedMesh = meshToConnectTo;
  34429. if (!this.spatialSound) {
  34430. this.spatialSound = true;
  34431. this._createSpatialParameters();
  34432. if (this.isPlaying && this.loop) {
  34433. this.stop();
  34434. this.play();
  34435. }
  34436. }
  34437. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34438. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34439. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34440. };
  34441. Sound.prototype.detachFromMesh = function () {
  34442. if (this._connectedMesh) {
  34443. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34444. this._registerFunc = null;
  34445. this._connectedMesh = null;
  34446. }
  34447. };
  34448. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34449. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34450. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34451. this._updateDirection();
  34452. }
  34453. };
  34454. Sound.prototype.clone = function () {
  34455. var _this = this;
  34456. if (!this._streaming) {
  34457. var setBufferAndRun = function () {
  34458. if (_this._isReadyToPlay) {
  34459. clonedSound._audioBuffer = _this.getAudioBuffer();
  34460. clonedSound._isReadyToPlay = true;
  34461. if (clonedSound.autoplay) {
  34462. clonedSound.play();
  34463. }
  34464. }
  34465. else {
  34466. window.setTimeout(setBufferAndRun, 300);
  34467. }
  34468. };
  34469. var currentOptions = {
  34470. autoplay: this.autoplay, loop: this.loop,
  34471. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34472. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34473. refDistance: this.refDistance, distanceModel: this.distanceModel
  34474. };
  34475. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34476. if (this.useCustomAttenuation) {
  34477. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34478. }
  34479. clonedSound.setPosition(this._position);
  34480. clonedSound.setPlaybackRate(this._playbackRate);
  34481. setBufferAndRun();
  34482. return clonedSound;
  34483. }
  34484. else {
  34485. return null;
  34486. }
  34487. };
  34488. Sound.prototype.getAudioBuffer = function () {
  34489. return this._audioBuffer;
  34490. };
  34491. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34492. var soundName = parsedSound.name;
  34493. var soundUrl;
  34494. if (parsedSound.url) {
  34495. soundUrl = rootUrl + parsedSound.url;
  34496. }
  34497. else {
  34498. soundUrl = rootUrl + soundName;
  34499. }
  34500. var options = {
  34501. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34502. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34503. rolloffFactor: parsedSound.rolloffFactor,
  34504. refDistance: parsedSound.refDistance,
  34505. distanceModel: parsedSound.distanceModel,
  34506. playbackRate: parsedSound.playbackRate
  34507. };
  34508. var newSound;
  34509. if (!sourceSound) {
  34510. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34511. scene._addPendingData(newSound);
  34512. }
  34513. else {
  34514. var setBufferAndRun = function () {
  34515. if (sourceSound._isReadyToPlay) {
  34516. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34517. newSound._isReadyToPlay = true;
  34518. if (newSound.autoplay) {
  34519. newSound.play();
  34520. }
  34521. }
  34522. else {
  34523. window.setTimeout(setBufferAndRun, 300);
  34524. }
  34525. };
  34526. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34527. setBufferAndRun();
  34528. }
  34529. if (parsedSound.position) {
  34530. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34531. newSound.setPosition(soundPosition);
  34532. }
  34533. if (parsedSound.isDirectional) {
  34534. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34535. if (parsedSound.localDirectionToMesh) {
  34536. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34537. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34538. }
  34539. }
  34540. if (parsedSound.connectedMeshId) {
  34541. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34542. if (connectedMesh) {
  34543. newSound.attachToMesh(connectedMesh);
  34544. }
  34545. }
  34546. return newSound;
  34547. };
  34548. return Sound;
  34549. })();
  34550. BABYLON.Sound = Sound;
  34551. })(BABYLON || (BABYLON = {}));
  34552. var BABYLON;
  34553. (function (BABYLON) {
  34554. var SoundTrack = (function () {
  34555. function SoundTrack(scene, options) {
  34556. this.id = -1;
  34557. this._isMainTrack = false;
  34558. this._isInitialized = false;
  34559. this._scene = scene;
  34560. this.soundCollection = new Array();
  34561. this._options = options;
  34562. if (!this._isMainTrack) {
  34563. this._scene.soundTracks.push(this);
  34564. this.id = this._scene.soundTracks.length - 1;
  34565. }
  34566. }
  34567. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34568. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34569. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34570. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34571. if (this._options) {
  34572. if (this._options.volume) {
  34573. this._outputAudioNode.gain.value = this._options.volume;
  34574. }
  34575. if (this._options.mainTrack) {
  34576. this._isMainTrack = this._options.mainTrack;
  34577. }
  34578. }
  34579. this._isInitialized = true;
  34580. }
  34581. };
  34582. SoundTrack.prototype.dispose = function () {
  34583. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34584. if (this._connectedAnalyser) {
  34585. this._connectedAnalyser.stopDebugCanvas();
  34586. }
  34587. while (this.soundCollection.length) {
  34588. this.soundCollection[0].dispose();
  34589. }
  34590. if (this._outputAudioNode) {
  34591. this._outputAudioNode.disconnect();
  34592. }
  34593. this._outputAudioNode = null;
  34594. }
  34595. };
  34596. SoundTrack.prototype.AddSound = function (sound) {
  34597. if (!this._isInitialized) {
  34598. this._initializeSoundTrackAudioGraph();
  34599. }
  34600. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34601. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34602. }
  34603. if (sound.soundTrackId) {
  34604. if (sound.soundTrackId === -1) {
  34605. this._scene.mainSoundTrack.RemoveSound(sound);
  34606. }
  34607. else {
  34608. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34609. }
  34610. }
  34611. this.soundCollection.push(sound);
  34612. sound.soundTrackId = this.id;
  34613. };
  34614. SoundTrack.prototype.RemoveSound = function (sound) {
  34615. var index = this.soundCollection.indexOf(sound);
  34616. if (index !== -1) {
  34617. this.soundCollection.splice(index, 1);
  34618. }
  34619. };
  34620. SoundTrack.prototype.setVolume = function (newVolume) {
  34621. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34622. this._outputAudioNode.gain.value = newVolume;
  34623. }
  34624. };
  34625. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34626. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34627. for (var i = 0; i < this.soundCollection.length; i++) {
  34628. this.soundCollection[i].switchPanningModelToHRTF();
  34629. }
  34630. }
  34631. };
  34632. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34633. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34634. for (var i = 0; i < this.soundCollection.length; i++) {
  34635. this.soundCollection[i].switchPanningModelToEqualPower();
  34636. }
  34637. }
  34638. };
  34639. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34640. if (this._connectedAnalyser) {
  34641. this._connectedAnalyser.stopDebugCanvas();
  34642. }
  34643. this._connectedAnalyser = analyser;
  34644. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34645. this._outputAudioNode.disconnect();
  34646. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34647. }
  34648. };
  34649. return SoundTrack;
  34650. })();
  34651. BABYLON.SoundTrack = SoundTrack;
  34652. })(BABYLON || (BABYLON = {}));
  34653. var BABYLON;
  34654. (function (BABYLON) {
  34655. var SIMDVector3 = (function () {
  34656. function SIMDVector3() {
  34657. }
  34658. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  34659. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  34660. var m0 = SIMD.float32x4.load(transformation.m, 0);
  34661. var m1 = SIMD.float32x4.load(transformation.m, 4);
  34662. var m2 = SIMD.float32x4.load(transformation.m, 8);
  34663. var m3 = SIMD.float32x4.load(transformation.m, 12);
  34664. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  34665. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  34666. SIMD.float32x4.storeXYZ(result._data, 0, r);
  34667. };
  34668. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  34669. var v0 = SIMD.float32x4.splat(x);
  34670. var v1 = SIMD.float32x4.splat(y);
  34671. var v2 = SIMD.float32x4.splat(z);
  34672. var m0 = SIMD.float32x4.load(transformation.m, 0);
  34673. var m1 = SIMD.float32x4.load(transformation.m, 4);
  34674. var m2 = SIMD.float32x4.load(transformation.m, 8);
  34675. var m3 = SIMD.float32x4.load(transformation.m, 12);
  34676. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  34677. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  34678. SIMD.float32x4.storeXYZ(result._data, 0, r);
  34679. };
  34680. return SIMDVector3;
  34681. })();
  34682. BABYLON.SIMDVector3 = SIMDVector3;
  34683. var SIMDMatrix = (function () {
  34684. function SIMDMatrix() {
  34685. }
  34686. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  34687. if (offset === void 0) { offset = 0; }
  34688. var tm = this.m;
  34689. var om = other.m;
  34690. var om0 = SIMD.float32x4.load(om, 0);
  34691. var om1 = SIMD.float32x4.load(om, 4);
  34692. var om2 = SIMD.float32x4.load(om, 8);
  34693. var om3 = SIMD.float32x4.load(om, 12);
  34694. var tm0 = SIMD.float32x4.load(tm, 0);
  34695. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  34696. var tm1 = SIMD.float32x4.load(tm, 4);
  34697. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  34698. var tm2 = SIMD.float32x4.load(tm, 8);
  34699. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  34700. var tm3 = SIMD.float32x4.load(tm, 12);
  34701. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  34702. };
  34703. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  34704. var src = this.m;
  34705. var dest = other.m;
  34706. var row0, row1, row2, row3;
  34707. var tmp1;
  34708. var minor0, minor1, minor2, minor3;
  34709. var det;
  34710. // Load the 4 rows
  34711. var src0 = SIMD.float32x4.load(src, 0);
  34712. var src1 = SIMD.float32x4.load(src, 4);
  34713. var src2 = SIMD.float32x4.load(src, 8);
  34714. var src3 = SIMD.float32x4.load(src, 12);
  34715. // Transpose the source matrix. Sort of. Not a true transpose operation
  34716. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  34717. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  34718. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  34719. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  34720. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  34721. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  34722. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  34723. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  34724. // This is a true transposition, but it will lead to an incorrect result
  34725. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  34726. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  34727. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  34728. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  34729. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  34730. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  34731. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  34732. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  34733. // ----
  34734. tmp1 = SIMD.float32x4.mul(row2, row3);
  34735. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34736. minor0 = SIMD.float32x4.mul(row1, tmp1);
  34737. minor1 = SIMD.float32x4.mul(row0, tmp1);
  34738. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34739. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  34740. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  34741. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  34742. // ----
  34743. tmp1 = SIMD.float32x4.mul(row1, row2);
  34744. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34745. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  34746. minor3 = SIMD.float32x4.mul(row0, tmp1);
  34747. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34748. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  34749. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  34750. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  34751. // ----
  34752. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  34753. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34754. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  34755. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  34756. minor2 = SIMD.float32x4.mul(row0, tmp1);
  34757. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34758. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  34759. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  34760. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  34761. // ----
  34762. tmp1 = SIMD.float32x4.mul(row0, row1);
  34763. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34764. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  34765. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  34766. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34767. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  34768. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  34769. // ----
  34770. tmp1 = SIMD.float32x4.mul(row0, row3);
  34771. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34772. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  34773. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  34774. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34775. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  34776. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  34777. // ----
  34778. tmp1 = SIMD.float32x4.mul(row0, row2);
  34779. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34780. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  34781. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  34782. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34783. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  34784. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  34785. // Compute determinant
  34786. det = SIMD.float32x4.mul(row0, minor0);
  34787. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  34788. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  34789. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  34790. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  34791. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  34792. // These shuffles aren't necessary if the faulty transposition is done
  34793. // up at the top of this function.
  34794. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  34795. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  34796. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  34797. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  34798. // Compute final values by multiplying with 1/det
  34799. minor0 = SIMD.float32x4.mul(det, minor0);
  34800. minor1 = SIMD.float32x4.mul(det, minor1);
  34801. minor2 = SIMD.float32x4.mul(det, minor2);
  34802. minor3 = SIMD.float32x4.mul(det, minor3);
  34803. SIMD.float32x4.store(dest, 0, minor0);
  34804. SIMD.float32x4.store(dest, 4, minor1);
  34805. SIMD.float32x4.store(dest, 8, minor2);
  34806. SIMD.float32x4.store(dest, 12, minor3);
  34807. return this;
  34808. };
  34809. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  34810. var out = result.m;
  34811. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  34812. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  34813. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  34814. // cc.kmVec3Subtract(f, pCenter, pEye);
  34815. var f = SIMD.float32x4.sub(center, eye);
  34816. // cc.kmVec3Normalize(f, f);
  34817. var tmp = SIMD.float32x4.mul(f, f);
  34818. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34819. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34820. // cc.kmVec3Assign(up, pUp);
  34821. // cc.kmVec3Normalize(up, up);
  34822. tmp = SIMD.float32x4.mul(up, up);
  34823. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34824. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34825. // cc.kmVec3Cross(s, f, up);
  34826. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  34827. // cc.kmVec3Normalize(s, s);
  34828. tmp = SIMD.float32x4.mul(s, s);
  34829. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34830. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34831. // cc.kmVec3Cross(u, s, f);
  34832. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  34833. // cc.kmVec3Normalize(s, s);
  34834. tmp = SIMD.float32x4.mul(s, s);
  34835. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34836. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34837. var zero = SIMD.float32x4.splat(0.0);
  34838. s = SIMD.float32x4.neg(s);
  34839. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  34840. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  34841. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  34842. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  34843. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  34844. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  34845. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  34846. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  34847. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  34848. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  34849. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  34850. var b3 = SIMD.float32x4.neg(eye);
  34851. b3 = SIMD.float32x4.withW(b3, 1.0);
  34852. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  34853. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  34854. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  34855. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  34856. };
  34857. return SIMDMatrix;
  34858. })();
  34859. BABYLON.SIMDMatrix = SIMDMatrix;
  34860. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  34861. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  34862. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  34863. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  34864. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  34865. var SIMDHelper = (function () {
  34866. function SIMDHelper() {
  34867. }
  34868. Object.defineProperty(SIMDHelper, "IsEnabled", {
  34869. get: function () {
  34870. return SIMDHelper._isEnabled;
  34871. },
  34872. enumerable: true,
  34873. configurable: true
  34874. });
  34875. SIMDHelper.DisableSIMD = function () {
  34876. // Replace functions
  34877. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  34878. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  34879. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  34880. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  34881. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  34882. SIMDHelper._isEnabled = false;
  34883. };
  34884. SIMDHelper.EnableSIMD = function () {
  34885. if (window.SIMD === undefined) {
  34886. return;
  34887. }
  34888. // Replace functions
  34889. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  34890. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  34891. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  34892. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  34893. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  34894. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  34895. get: function () { return this._data[0]; },
  34896. set: function (value) {
  34897. if (!this._data) {
  34898. this._data = new Float32Array(3);
  34899. }
  34900. this._data[0] = value;
  34901. }
  34902. });
  34903. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  34904. get: function () { return this._data[1]; },
  34905. set: function (value) {
  34906. this._data[1] = value;
  34907. }
  34908. });
  34909. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  34910. get: function () { return this._data[2]; },
  34911. set: function (value) {
  34912. this._data[2] = value;
  34913. }
  34914. });
  34915. SIMDHelper._isEnabled = true;
  34916. };
  34917. SIMDHelper._isEnabled = false;
  34918. return SIMDHelper;
  34919. })();
  34920. BABYLON.SIMDHelper = SIMDHelper;
  34921. })(BABYLON || (BABYLON = {}));
  34922. var BABYLON;
  34923. (function (BABYLON) {
  34924. /**
  34925. * This class describe a rectangle that were added to the map.
  34926. * You have access to its coordinates either in pixel or normalized (UV)
  34927. */
  34928. var PackedRect = (function () {
  34929. function PackedRect(root, parent, pos, size) {
  34930. this._pos = pos;
  34931. this._size = size;
  34932. this._root = root;
  34933. this._parent = parent;
  34934. }
  34935. Object.defineProperty(PackedRect.prototype, "pos", {
  34936. /**
  34937. * @returns the position of this node into the map
  34938. */
  34939. get: function () {
  34940. return this._pos;
  34941. },
  34942. enumerable: true,
  34943. configurable: true
  34944. });
  34945. Object.defineProperty(PackedRect.prototype, "contentSize", {
  34946. /**
  34947. * @returns the size of the rectangle this node handles
  34948. */
  34949. get: function () {
  34950. return this._contentSize;
  34951. },
  34952. enumerable: true,
  34953. configurable: true
  34954. });
  34955. Object.defineProperty(PackedRect.prototype, "UVs", {
  34956. /**
  34957. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  34958. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  34959. */
  34960. get: function () {
  34961. var mainWidth = this._root._size.width;
  34962. var mainHeight = this._root._size.height;
  34963. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  34964. var rightBottom = new BABYLON.Vector2((this._pos.x + this._contentSize.width - 1) / mainWidth, (this._pos.y + this._contentSize.height - 1) / mainHeight);
  34965. var uvs = new Array();
  34966. uvs.push(topLeft);
  34967. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  34968. uvs.push(rightBottom);
  34969. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  34970. return uvs;
  34971. },
  34972. enumerable: true,
  34973. configurable: true
  34974. });
  34975. /**
  34976. * Free this rectangle from the map.
  34977. * Call this method when you no longer need the rectangle to be in the map.
  34978. */
  34979. PackedRect.prototype.freeContent = function () {
  34980. if (!this.contentSize) {
  34981. return;
  34982. }
  34983. this._contentSize = null;
  34984. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  34985. this.attemptDefrag();
  34986. };
  34987. Object.defineProperty(PackedRect.prototype, "isUsed", {
  34988. get: function () {
  34989. return this._contentSize != null || this._leftNode != null;
  34990. },
  34991. enumerable: true,
  34992. configurable: true
  34993. });
  34994. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  34995. var node = this.findNode(contentSize);
  34996. // Not enough space...
  34997. if (!node) {
  34998. return null;
  34999. }
  35000. node.splitNode(contentSize);
  35001. return node;
  35002. };
  35003. PackedRect.prototype.findNode = function (size) {
  35004. var resNode = null;
  35005. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  35006. if (this.isUsed) {
  35007. if (this._leftNode) {
  35008. resNode = this._leftNode.findNode(size);
  35009. }
  35010. if (!resNode && this._rightNode) {
  35011. resNode = this._rightNode.findNode(size);
  35012. }
  35013. if (!resNode && this._bottomNode) {
  35014. resNode = this._bottomNode.findNode(size);
  35015. }
  35016. }
  35017. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  35018. resNode = this;
  35019. }
  35020. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  35021. resNode = this;
  35022. }
  35023. return resNode;
  35024. };
  35025. PackedRect.prototype.splitNode = function (contentSize) {
  35026. // If there's no contentSize but an initialSize it means this node were previously allocated, but freed, we need to create a _leftNode as subNode and use to allocate the space we need (and this node will have a right/bottom subNode for the space left as this._initialSize may be greater than contentSize)
  35027. if (!this._contentSize && this._initialSize) {
  35028. this._leftNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y), new BABYLON.Size(this._initialSize.width, this._initialSize.height));
  35029. return this._leftNode.splitNode(contentSize);
  35030. }
  35031. else {
  35032. this._contentSize = contentSize.clone();
  35033. this._initialSize = contentSize.clone();
  35034. if (contentSize.width !== this._size.width) {
  35035. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + contentSize.width, this._pos.y), new BABYLON.Size(this._size.width - contentSize.width, contentSize.height));
  35036. }
  35037. if (contentSize.height !== this._size.height) {
  35038. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + contentSize.height), new BABYLON.Size(this._size.width, this._size.height - contentSize.height));
  35039. }
  35040. return this;
  35041. }
  35042. };
  35043. PackedRect.prototype.attemptDefrag = function () {
  35044. if (!this.isUsed && this.isRecursiveFree) {
  35045. this.clearNode();
  35046. if (this._parent) {
  35047. this._parent.attemptDefrag();
  35048. }
  35049. }
  35050. };
  35051. PackedRect.prototype.clearNode = function () {
  35052. this._initialSize = null;
  35053. this._rightNode = null;
  35054. this._bottomNode = null;
  35055. };
  35056. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  35057. get: function () {
  35058. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  35059. },
  35060. enumerable: true,
  35061. configurable: true
  35062. });
  35063. PackedRect.prototype.evalFreeSize = function (size) {
  35064. var levelSize = 0;
  35065. if (!this.isUsed) {
  35066. if (this._initialSize) {
  35067. levelSize = this._initialSize.surface;
  35068. }
  35069. else {
  35070. levelSize = this._size.surface;
  35071. }
  35072. }
  35073. if (this._rightNode) {
  35074. levelSize += this._rightNode.evalFreeSize(0);
  35075. }
  35076. if (this._bottomNode) {
  35077. levelSize += this._bottomNode.evalFreeSize(0);
  35078. }
  35079. return levelSize + size;
  35080. };
  35081. return PackedRect;
  35082. })();
  35083. BABYLON.PackedRect = PackedRect;
  35084. /**
  35085. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  35086. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  35087. * Note that this class allows allocated Rectangles to be freed: that is the map is dynamically maintained so you can add/remove rectangle based on their life-cycle.
  35088. */
  35089. var RectPackingMap = (function (_super) {
  35090. __extends(RectPackingMap, _super);
  35091. /**
  35092. * Create an instance of the object with a dimension using the given size
  35093. * @param size The dimension of the rectangle that will contain all the sub ones.
  35094. */
  35095. function RectPackingMap(size) {
  35096. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  35097. this._root = this;
  35098. }
  35099. /**
  35100. * Add a rectangle, finding the best location to store it into the map
  35101. * @param size the dimension of the rectangle to store
  35102. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  35103. */
  35104. RectPackingMap.prototype.addRect = function (size) {
  35105. var node = this.findAndSplitNode(size);
  35106. return node;
  35107. };
  35108. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  35109. /**
  35110. * Return the current space free normalized between [0;1]
  35111. * @returns {}
  35112. */
  35113. get: function () {
  35114. var freeSize = 0;
  35115. freeSize = this.evalFreeSize(freeSize);
  35116. return freeSize / (this._size.width * this._size.height);
  35117. },
  35118. enumerable: true,
  35119. configurable: true
  35120. });
  35121. return RectPackingMap;
  35122. })(PackedRect);
  35123. BABYLON.RectPackingMap = RectPackingMap;
  35124. })(BABYLON || (BABYLON = {}));
  35125. var BABYLON;
  35126. (function (BABYLON) {
  35127. var DynamicFloatArrayElementInfo = (function () {
  35128. function DynamicFloatArrayElementInfo() {
  35129. }
  35130. return DynamicFloatArrayElementInfo;
  35131. })();
  35132. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  35133. /**
  35134. * The purpose of this class is to store float32 based elements of a given size (defined by the stride argument) in a dynamic fashion, that is, you can add/free elements. You can then access to a defragmented/packed version of the underlying Float32Array by calling the pack() method.
  35135. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  35136. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  35137. * Allocating an Element will return a instance of DynamicFloatArrayElement which contains the offset into the Float32Array of where the element starts, you are then responsible to copy your data using this offset.
  35138. * Beware, calling pack() may change the offset of some Entries because this method will defragment the Float32Array to replace empty elements by moving allocated ones at their location.
  35139. * This method will return an ArrayBufferView on the existing Float32Array that describes the used elements. Use this View to update the WebGLBuffer and NOT the "buffer" field of the class. The pack() method won't shrink/reallocate the buffer to keep it GC friendly, all the empty space will be put at the end of the buffer, the method just ensure there are no "free holes".
  35140. */
  35141. var DynamicFloatArray = (function () {
  35142. /**
  35143. * Construct an instance of the dynamic float array
  35144. * @param stride size of one element in float (i.e. not bytes!)
  35145. * @param initialElementCount the number of available entries at construction
  35146. */
  35147. function DynamicFloatArray(stride, initialElementCount) {
  35148. this.compareValueOffset = null;
  35149. this.sortingAscending = true;
  35150. this._stride = stride;
  35151. this.buffer = new Float32Array(stride * initialElementCount);
  35152. this._lastUsed = 0;
  35153. this._firstFree = 0;
  35154. this._allEntries = new Array(initialElementCount);
  35155. this._freeEntries = new Array(initialElementCount);
  35156. for (var i = 0; i < initialElementCount; i++) {
  35157. var element = new DynamicFloatArrayElementInfo();
  35158. element.offset = i * stride;
  35159. this._allEntries[i] = element;
  35160. this._freeEntries[initialElementCount - i - 1] = element;
  35161. }
  35162. }
  35163. /**
  35164. * Allocate an element in the array.
  35165. * @return the element info instance that contains the offset into the main buffer of the element's location.
  35166. * Beware, this offset may change when you call pack()
  35167. */
  35168. DynamicFloatArray.prototype.allocElement = function () {
  35169. if (this._freeEntries.length === 0) {
  35170. this._growBuffer();
  35171. }
  35172. var el = this._freeEntries.pop();
  35173. this._lastUsed = Math.max(el.offset, this._lastUsed);
  35174. if (el.offset === this._firstFree) {
  35175. if (this._freeEntries.length > 0) {
  35176. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  35177. }
  35178. else {
  35179. this._firstFree += this._stride;
  35180. }
  35181. }
  35182. return el;
  35183. };
  35184. /**
  35185. * Free the element corresponding to the given element info
  35186. * @param elInfo the element that describe the allocated element
  35187. */
  35188. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  35189. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  35190. this._freeEntries.push(elInfo);
  35191. };
  35192. /**
  35193. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  35194. * Instances of DynamicFloatArrayElement may have their 'offset' member changed as data could be copied from one location to another, so be sure to read/write your data based on the value inside this member after you called pack().
  35195. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  35196. */
  35197. DynamicFloatArray.prototype.pack = function () {
  35198. // no free slot? no need to pack
  35199. if (this._freeEntries.length === 0) {
  35200. return this.buffer;
  35201. }
  35202. // If the buffer is already packed the last used will always be lower than the first free
  35203. // The opposite may not be true, we can have a lastUsed greater than firstFree but the array still packed, because when an element is freed, lastUsed is not updated (for speed reason) so we may have a lastUsed of a freed element. But that's ok, well soon realize this case.
  35204. if (this._lastUsed < this._firstFree) {
  35205. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  35206. return elementsBuffer_1;
  35207. }
  35208. var s = this._stride;
  35209. // Make sure there's a free element at the very end, we need it to create a range where we'll move the used elements that may appear before
  35210. var lastFree = new DynamicFloatArrayElementInfo();
  35211. lastFree.offset = this.totalElementCount * s;
  35212. this._freeEntries.push(lastFree);
  35213. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  35214. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  35215. var firstFreeSlotOffset = sortedFree[0].offset;
  35216. var freeZoneSize = 1;
  35217. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  35218. var prevOffset = sortedFree[0].offset;
  35219. for (var i = 1; i < sortedFree.length; i++) {
  35220. // If the first free (which means everything before is occupied) is greater or equal the occupied zone size, it means everything is defragmented, we can quit
  35221. if (firstFreeSlotOffset >= occupiedZoneSize) {
  35222. break;
  35223. }
  35224. var curFree = sortedFree[i];
  35225. var curOffset = curFree.offset;
  35226. // Compute the distance between this offset and the previous
  35227. var distance = curOffset - prevOffset;
  35228. // If the distance is the stride size, they are adjacent, it good, move to the next
  35229. if (distance === s) {
  35230. // Free zone is one element bigger
  35231. ++freeZoneSize;
  35232. // as we're about to iterate to the next, the cur becomes the previous...
  35233. prevOffset = curOffset;
  35234. continue;
  35235. }
  35236. // Distance is bigger, which means there's x element between the previous free and this one
  35237. var usedRange = (distance / s) - 1;
  35238. // Two cases the free zone is smaller than the data to move or bigger
  35239. // Copy what can fit in the free zone
  35240. var curMoveOffset = curOffset - s;
  35241. var copyCount = Math.min(freeZoneSize, usedRange);
  35242. for (var j = 0; j < copyCount; j++) {
  35243. var freeI = firstFreeSlotOffset / s;
  35244. var curI = curMoveOffset / s;
  35245. var moveEl = sortedAll[curI];
  35246. this._moveElement(moveEl, firstFreeSlotOffset);
  35247. var replacedEl = sortedAll[freeI];
  35248. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  35249. replacedEl.offset = curMoveOffset;
  35250. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  35251. sortedAll[freeI] = moveEl;
  35252. sortedAll[curI] = replacedEl;
  35253. curMoveOffset -= s;
  35254. firstFreeSlotOffset += s;
  35255. }
  35256. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  35257. if (freeZoneSize <= usedRange) {
  35258. firstFreeSlotOffset = curMoveOffset + s;
  35259. freeZoneSize = 1 + copyCount;
  35260. }
  35261. else {
  35262. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  35263. }
  35264. // as we're about to iterate to the next, the cur becomes the previous...
  35265. prevOffset = curOffset;
  35266. }
  35267. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  35268. this._lastUsed = firstFreeSlotOffset - s;
  35269. this._firstFree = firstFreeSlotOffset;
  35270. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  35271. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  35272. this._allEntries = sortedAll;
  35273. return elementsBuffer;
  35274. };
  35275. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  35276. for (var i = 0; i < this._stride; i++) {
  35277. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  35278. }
  35279. element.offset = destOffset;
  35280. };
  35281. DynamicFloatArray.prototype._growBuffer = function () {
  35282. // Allocate the new buffer with 50% more entries, copy the content of the current one
  35283. var newElCount = Math.floor(this.totalElementCount * 1.5);
  35284. var newBuffer = new Float32Array(newElCount * this._stride);
  35285. newBuffer.set(this.buffer);
  35286. var curCount = this.totalElementCount;
  35287. var addedCount = newElCount - this.totalElementCount;
  35288. for (var i = 0; i < addedCount; i++) {
  35289. var element = new DynamicFloatArrayElementInfo();
  35290. element.offset = (curCount + i) * this.stride;
  35291. this._allEntries.push(element);
  35292. this._freeEntries[addedCount - i - 1] = element;
  35293. }
  35294. this._firstFree = curCount * this.stride;
  35295. this.buffer = newBuffer;
  35296. };
  35297. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  35298. /**
  35299. * Get the total count of entries that can fit in the current buffer
  35300. * @returns the elements count
  35301. */
  35302. get: function () {
  35303. return this._allEntries.length;
  35304. },
  35305. enumerable: true,
  35306. configurable: true
  35307. });
  35308. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  35309. /**
  35310. * Get the count of free entries that can still be allocated without resizing the buffer
  35311. * @returns the free elements count
  35312. */
  35313. get: function () {
  35314. return this._freeEntries.length;
  35315. },
  35316. enumerable: true,
  35317. configurable: true
  35318. });
  35319. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  35320. /**
  35321. * Get the count of allocated elements
  35322. * @returns the allocated elements count
  35323. */
  35324. get: function () {
  35325. return this._allEntries.length - this._freeEntries.length;
  35326. },
  35327. enumerable: true,
  35328. configurable: true
  35329. });
  35330. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  35331. /**
  35332. * Return the size of one element in float
  35333. * @returns the size in float
  35334. */
  35335. get: function () {
  35336. return this._stride;
  35337. },
  35338. enumerable: true,
  35339. configurable: true
  35340. });
  35341. DynamicFloatArray.prototype.sort = function () {
  35342. var _this = this;
  35343. if (!this.compareValueOffset) {
  35344. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  35345. }
  35346. var count = this.usedElementCount;
  35347. // Do we have to (re)create the sort table?
  35348. if (!this._sortTable || this._sortTable.length < count) {
  35349. // Small heuristic... We don't want to allocate totalElementCount right away because it may have 50 for 3 used elements, but on the other side we don't want to allocate just 3 when we just need 2, so double this value to give us some air to breath...
  35350. var newCount = Math.min(this.totalElementCount, count * 2);
  35351. this._sortTable = new Array(newCount);
  35352. this._sortedTable = new Array(newCount);
  35353. }
  35354. // Because, you know...
  35355. this.pack();
  35356. //let stride = this.stride;
  35357. //for (let i = 0; i < count; i++) {
  35358. // let si = this._sortTable[i];
  35359. // if (!si) {
  35360. // si = new SortInfo();
  35361. // this._sortTable[i] = si;
  35362. // }
  35363. // si.entry = this._allEntries[i];
  35364. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  35365. // si.swapedOffset = null;
  35366. // this._sortedTable[i] = si;
  35367. //}
  35368. var curOffset = 0;
  35369. var stride = this.stride;
  35370. for (var i = 0; i < count; i++, curOffset += stride) {
  35371. var si = this._sortTable[i];
  35372. if (!si) {
  35373. si = new SortInfo();
  35374. this._sortTable[i] = si;
  35375. }
  35376. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  35377. si.offset = curOffset;
  35378. si.swapedOffset = null;
  35379. this._sortedTable[i] = si;
  35380. }
  35381. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  35382. if (this.sortingAscending) {
  35383. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  35384. }
  35385. else {
  35386. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  35387. }
  35388. var swapElements = function (src, dst) {
  35389. for (var i = 0; i < stride; i++) {
  35390. var tps = _this.buffer[dst + i];
  35391. _this.buffer[dst + i] = _this.buffer[src + i];
  35392. _this.buffer[src + i] = tps;
  35393. }
  35394. };
  35395. // The fun part begin, sortedTable give us the ordered layout to obtain, to get that we have to move elements, but when we move an element:
  35396. // it replaces an existing one.I don't want to allocate a new Float32Array and do a raw copy, because it's awful (GC - wise),
  35397. // and I still want something with a good algorithm complexity.
  35398. // So here's the deal: we are going to swap elements, but we have to track the change of location of the element being replaced,
  35399. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  35400. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  35401. // When we'll look for and element, we'll check if its swapedOffset is set, if so we reiterate the operation with the one there
  35402. // until we find a SortInfo object without a swapedOffset which means we got the right location
  35403. // Yes, we may have to do multiple iterations to find the right location, but hey, it won't be huge: <3 in most cases, and it's better
  35404. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  35405. for (var i = 0; i < count; i++) {
  35406. // Get the element to move
  35407. var sourceSI = this._sortedTable[i];
  35408. var destSI = this._sortTable[i];
  35409. var sourceOff = sourceSI.offset;
  35410. // If the source changed location, find the new one
  35411. if (sourceSI.swapedOffset) {
  35412. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  35413. var curSI = sourceSI;
  35414. while (curSI.swapedOffset) {
  35415. curSI = this._sortTable[curSI.swapedOffset / stride];
  35416. }
  35417. // Finally get the right location
  35418. sourceOff = curSI.offset;
  35419. }
  35420. // Tag the element being replaced with its new location
  35421. destSI.swapedOffset = sourceOff;
  35422. // Swap elements (only if needed)
  35423. if (sourceOff !== destSI.offset) {
  35424. swapElements(sourceOff, destSI.offset);
  35425. }
  35426. // Update the offset in the corresponding DFAE
  35427. //sourceSI.entry.offset = destSI.entry.offset;
  35428. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  35429. }
  35430. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  35431. return true;
  35432. };
  35433. return DynamicFloatArray;
  35434. })();
  35435. BABYLON.DynamicFloatArray = DynamicFloatArray;
  35436. var SortInfo = (function () {
  35437. function SortInfo() {
  35438. this.compareData = this.offset = this.swapedOffset = null;
  35439. }
  35440. return SortInfo;
  35441. })();
  35442. })(BABYLON || (BABYLON = {}));
  35443. var BABYLON;
  35444. (function (BABYLON) {
  35445. /**
  35446. * This class given information about a given character.
  35447. */
  35448. var CharInfo = (function () {
  35449. function CharInfo() {
  35450. }
  35451. return CharInfo;
  35452. })();
  35453. BABYLON.CharInfo = CharInfo;
  35454. var FontTexture = (function (_super) {
  35455. __extends(FontTexture, _super);
  35456. /**
  35457. * Create a new instance of the FontTexture class
  35458. * @param name the name of the texture
  35459. * @param font the font to use, use the W3C CSS notation
  35460. * @param scene the scene that owns the texture
  35461. * @param maxCharCount the approximative maximum count of characters that could fit in the texture. This is an approximation because most of the fonts are proportional (each char has its own Width). The 'W' character's width is used to compute the size of the texture based on the given maxCharCount
  35462. * @param samplingMode the texture sampling mode
  35463. */
  35464. function FontTexture(name, font, scene, maxCharCount, samplingMode) {
  35465. if (maxCharCount === void 0) { maxCharCount = 200; }
  35466. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  35467. _super.call(this, null, scene, true, false, samplingMode);
  35468. this._charInfos = {};
  35469. this._curCharCount = 0;
  35470. this._lastUpdateCharCount = -1;
  35471. this._usedCounter = 1;
  35472. this.name = name;
  35473. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35474. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35475. // First canvas creation to determine the size of the texture to create
  35476. this._canvas = document.createElement("canvas");
  35477. this._context = this._canvas.getContext("2d");
  35478. this._context.font = font;
  35479. this._context.fillStyle = "white";
  35480. var res = this.getFontHeight(font);
  35481. this._lineHeight = res.height;
  35482. this._offset = res.offset - 1;
  35483. var maxCharWidth = this._context.measureText("W").width;
  35484. this._spaceWidth = this._context.measureText(" ").width;
  35485. // This is an approximate size, but should always be able to fit at least the maxCharCount
  35486. var totalEstSurface = this._lineHeight * maxCharWidth * maxCharCount;
  35487. var edge = Math.sqrt(totalEstSurface);
  35488. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  35489. // Create the texture that will store the font characters
  35490. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  35491. var textureSize = this.getSize();
  35492. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  35493. this._canvas = document.createElement("canvas");
  35494. this._canvas.width = textureSize.width;
  35495. this._canvas.height = textureSize.height;
  35496. this._context = this._canvas.getContext("2d");
  35497. this._context.textBaseline = "top";
  35498. this._context.font = font;
  35499. this._context.fillStyle = "white";
  35500. this._context.imageSmoothingEnabled = false;
  35501. this._currentFreePosition = BABYLON.Vector2.Zero();
  35502. // Add the basic ASCII based characters
  35503. for (var i = 0x20; i < 0x7F; i++) {
  35504. var c = String.fromCharCode(i);
  35505. this.getChar(c);
  35506. }
  35507. this.update();
  35508. }
  35509. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  35510. get: function () {
  35511. return this._spaceWidth;
  35512. },
  35513. enumerable: true,
  35514. configurable: true
  35515. });
  35516. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  35517. get: function () {
  35518. return this._lineHeight;
  35519. },
  35520. enumerable: true,
  35521. configurable: true
  35522. });
  35523. FontTexture.GetCachedFontTexture = function (scene, fontName) {
  35524. var s = scene;
  35525. if (!s.__fontTextureCache__) {
  35526. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  35527. }
  35528. var dic = s.__fontTextureCache__;
  35529. var lfn = fontName.toLocaleLowerCase();
  35530. var ft = dic.get(lfn);
  35531. if (ft) {
  35532. ++ft._usedCounter;
  35533. return ft;
  35534. }
  35535. ft = new FontTexture(null, lfn, scene, 200, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  35536. dic.add(lfn, ft);
  35537. return ft;
  35538. };
  35539. FontTexture.ReleaseCachedFontTexture = function (scene, fontName) {
  35540. var s = scene;
  35541. var dic = s.__fontTextureCache__;
  35542. if (!dic) {
  35543. return;
  35544. }
  35545. var lfn = fontName.toLocaleLowerCase();
  35546. var font = dic.get(lfn);
  35547. if (--font._usedCounter === 0) {
  35548. dic.remove(lfn);
  35549. font.dispose();
  35550. }
  35551. };
  35552. /**
  35553. * Make sure the given char is present in the font map.
  35554. * @param char the character to get or add
  35555. * @return the CharInfo instance corresponding to the given character
  35556. */
  35557. FontTexture.prototype.getChar = function (char) {
  35558. if (char.length !== 1) {
  35559. return null;
  35560. }
  35561. var info = this._charInfos[char];
  35562. if (info) {
  35563. return info;
  35564. }
  35565. info = new CharInfo();
  35566. var measure = this._context.measureText(char);
  35567. var textureSize = this.getSize();
  35568. // we reached the end of the current line?
  35569. var xMargin = 2;
  35570. var yMargin = 2;
  35571. var width = measure.width;
  35572. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  35573. this._currentFreePosition.x = 0;
  35574. this._currentFreePosition.y += this._lineHeight + yMargin; // +2 for safety margin
  35575. // No more room?
  35576. if (this._currentFreePosition.y > textureSize.height) {
  35577. return this.getChar("!");
  35578. }
  35579. }
  35580. // Draw the character in the texture
  35581. this._context.fillText(char, this._currentFreePosition.x - 0.5, this._currentFreePosition.y - this._offset - 0.5);
  35582. // Fill the CharInfo object
  35583. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  35584. info.bottomRightUV = new BABYLON.Vector2(info.topLeftUV.x + (width / textureSize.width), info.topLeftUV.y + ((this._lineHeight + 2) / textureSize.height));
  35585. info.charWidth = width;
  35586. // Add the info structure
  35587. this._charInfos[char] = info;
  35588. this._curCharCount++;
  35589. // Set the next position
  35590. this._currentFreePosition.x += width + xMargin;
  35591. return info;
  35592. };
  35593. FontTexture.prototype.measureText = function (text, tabulationSize) {
  35594. if (tabulationSize === void 0) { tabulationSize = 4; }
  35595. var maxWidth = 0;
  35596. var curWidth = 0;
  35597. var lineCount = 1;
  35598. var charxpos = 0;
  35599. // Parse each char of the string
  35600. for (var _i = 0; _i < text.length; _i++) {
  35601. var char = text[_i];
  35602. // Next line feed?
  35603. if (char === "\n") {
  35604. maxWidth = Math.max(maxWidth, curWidth);
  35605. charxpos = 0;
  35606. curWidth = 0;
  35607. ++lineCount;
  35608. continue;
  35609. }
  35610. // Tabulation ?
  35611. if (char === "\t") {
  35612. var nextPos = charxpos + tabulationSize;
  35613. nextPos = nextPos - (nextPos % tabulationSize);
  35614. curWidth += (nextPos - charxpos) * this.spaceWidth;
  35615. charxpos = nextPos;
  35616. continue;
  35617. }
  35618. if (char < " ") {
  35619. continue;
  35620. }
  35621. curWidth += this.getChar(char).charWidth;
  35622. ++charxpos;
  35623. }
  35624. maxWidth = Math.max(maxWidth, curWidth);
  35625. return new BABYLON.Size(maxWidth, lineCount * this._lineHeight);
  35626. };
  35627. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  35628. FontTexture.prototype.getFontHeight = function (font) {
  35629. var fontDraw = document.createElement("canvas");
  35630. var ctx = fontDraw.getContext('2d');
  35631. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  35632. ctx.textBaseline = 'top';
  35633. ctx.fillStyle = 'white';
  35634. ctx.font = font;
  35635. ctx.fillText('jH|', 0, 0);
  35636. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  35637. var start = -1;
  35638. var end = -1;
  35639. for (var row = 0; row < fontDraw.height; row++) {
  35640. for (var column = 0; column < fontDraw.width; column++) {
  35641. var index = (row * fontDraw.width + column) * 4;
  35642. if (pixels[index] === 0) {
  35643. if (column === fontDraw.width - 1 && start !== -1) {
  35644. end = row;
  35645. row = fontDraw.height;
  35646. break;
  35647. }
  35648. continue;
  35649. }
  35650. else {
  35651. if (start === -1) {
  35652. start = row;
  35653. }
  35654. break;
  35655. }
  35656. }
  35657. }
  35658. return { height: end - start, offset: start - 1 };
  35659. };
  35660. Object.defineProperty(FontTexture.prototype, "canRescale", {
  35661. get: function () {
  35662. return false;
  35663. },
  35664. enumerable: true,
  35665. configurable: true
  35666. });
  35667. FontTexture.prototype.getContext = function () {
  35668. return this._context;
  35669. };
  35670. /**
  35671. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  35672. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  35673. */
  35674. FontTexture.prototype.update = function () {
  35675. // Update only if there's new char added since the previous update
  35676. if (this._lastUpdateCharCount < this._curCharCount) {
  35677. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  35678. this._lastUpdateCharCount = this._curCharCount;
  35679. }
  35680. };
  35681. // cloning should be prohibited, there's no point to duplicate this texture at all
  35682. FontTexture.prototype.clone = function () {
  35683. return null;
  35684. };
  35685. return FontTexture;
  35686. })(BABYLON.Texture);
  35687. BABYLON.FontTexture = FontTexture;
  35688. })(BABYLON || (BABYLON = {}));
  35689. var BABYLON;
  35690. (function (BABYLON) {
  35691. var MapTexture = (function (_super) {
  35692. __extends(MapTexture, _super);
  35693. function MapTexture(name, scene, size, samplingMode) {
  35694. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  35695. _super.call(this, null, scene, true, false, samplingMode);
  35696. this.name = name;
  35697. this._size = size;
  35698. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35699. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35700. // Create the rectPackMap that will allocate portion of the texture
  35701. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  35702. // Create the texture that will store the content
  35703. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  35704. }
  35705. /**
  35706. * Allocate a rectangle of a given size in the texture map
  35707. * @param size the size of the rectangle to allocation
  35708. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  35709. */
  35710. MapTexture.prototype.allocateRect = function (size) {
  35711. return this._rectPackingMap.addRect(size);
  35712. };
  35713. /**
  35714. * Free a given rectangle from the texture map
  35715. * @param rectInfo the instance corresponding to the rect to free.
  35716. */
  35717. MapTexture.prototype.freeRect = function (rectInfo) {
  35718. if (rectInfo) {
  35719. rectInfo.freeContent();
  35720. }
  35721. };
  35722. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  35723. /**
  35724. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  35725. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  35726. * @returns {}
  35727. */
  35728. get: function () {
  35729. return this._rectPackingMap.freeSpace;
  35730. },
  35731. enumerable: true,
  35732. configurable: true
  35733. });
  35734. /**
  35735. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  35736. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  35737. * Don't forget to call unbindTexture when you're done rendering
  35738. * @param rect the zone to render to
  35739. * @param clear true to clear the portion's color/depth data
  35740. */
  35741. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  35742. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  35743. };
  35744. /**
  35745. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  35746. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  35747. * Don't forget to call unbindTexture when you're done rendering
  35748. * @param pos the position into the texture
  35749. * @param size the portion to fit the clip space to
  35750. * @param clear true to clear the portion's color/depth data
  35751. */
  35752. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  35753. var engine = this.getScene().getEngine();
  35754. engine.bindFramebuffer(this._texture);
  35755. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  35756. if (clear) {
  35757. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  35758. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  35759. }
  35760. };
  35761. /**
  35762. * Unbind the texture map from the rendering engine.
  35763. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  35764. * @param dumpForDebug if set to true the content of the texture map will be dumped to a picture file that will be sent to the internet browser.
  35765. */
  35766. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  35767. // Dump ?
  35768. if (dumpForDebug) {
  35769. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  35770. }
  35771. var engine = this.getScene().getEngine();
  35772. if (this._replacedViewport) {
  35773. engine.setViewport(this._replacedViewport);
  35774. this._replacedViewport = null;
  35775. }
  35776. engine.unBindFramebuffer(this._texture);
  35777. };
  35778. Object.defineProperty(MapTexture.prototype, "canRescale", {
  35779. get: function () {
  35780. return false;
  35781. },
  35782. enumerable: true,
  35783. configurable: true
  35784. });
  35785. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  35786. // Anyway, there's not much point to use this method for this kind of texture I guess
  35787. MapTexture.prototype.clone = function () {
  35788. return null;
  35789. };
  35790. return MapTexture;
  35791. })(BABYLON.Texture);
  35792. BABYLON.MapTexture = MapTexture;
  35793. })(BABYLON || (BABYLON = {}));
  35794. var BABYLON;
  35795. (function (BABYLON) {
  35796. /**
  35797. * Stores 2D Bounding Information.
  35798. * This class handles a circle area and a bounding rectangle one.
  35799. */
  35800. var BoundingInfo2D = (function () {
  35801. function BoundingInfo2D() {
  35802. this.radius = 0;
  35803. this.center = BABYLON.Vector2.Zero();
  35804. this.extent = BABYLON.Vector2.Zero();
  35805. }
  35806. /**
  35807. * Create a BoundingInfo2D object from a given size
  35808. * @param size the size that will be used to set the extend, radius will be computed from it.
  35809. */
  35810. BoundingInfo2D.CreateFromSize = function (size) {
  35811. var r = new BoundingInfo2D();
  35812. BoundingInfo2D.CreateFromSizeToRef(size, r);
  35813. return r;
  35814. };
  35815. /**
  35816. * Create a BoundingInfo2D object from a given radius
  35817. * @param radius the radius to use, the extent will be computed from it.
  35818. */
  35819. BoundingInfo2D.CreateFromRadius = function (radius) {
  35820. var r = new BoundingInfo2D();
  35821. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  35822. return r;
  35823. };
  35824. /**
  35825. * Create a BoundingInfo2D object from a list of points.
  35826. * The resulted object will be the smallest bounding area that includes all the given points.
  35827. * @param points an array of points to compute the bounding object from.
  35828. */
  35829. BoundingInfo2D.CreateFromPoints = function (points) {
  35830. var r = new BoundingInfo2D();
  35831. BoundingInfo2D.CreateFromPointsToRef(points, r);
  35832. return r;
  35833. };
  35834. /**
  35835. * Update a BoundingInfo2D object using the given Size as input
  35836. * @param size the bounding data will be computed from this size.
  35837. * @param b must be a valid/allocated object, it will contain the result of the operation
  35838. */
  35839. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  35840. if (!size) {
  35841. size = BABYLON.Size.Zero();
  35842. }
  35843. b.center.x = +size.width / 2;
  35844. b.center.y = +size.height / 2;
  35845. b.extent.x = b.center.x;
  35846. b.extent.y = b.center.y;
  35847. b.radius = b.extent.length();
  35848. };
  35849. /**
  35850. * Update a BoundingInfo2D object using the given radius as input
  35851. * @param radius the bounding data will be computed from this radius
  35852. * @param b must be a valid/allocated object, it will contain the result of the operation
  35853. */
  35854. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  35855. b.center.x = b.center.y = 0;
  35856. var r = +radius;
  35857. b.extent.x = r;
  35858. b.extent.y = r;
  35859. b.radius = r;
  35860. };
  35861. /**
  35862. * Update a BoundingInfo2D object using the given points array as input
  35863. * @param points the point array to use to update the bounding data
  35864. * @param b must be a valid/allocated object, it will contain the result of the operation
  35865. */
  35866. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  35867. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  35868. for (var _i = 0; _i < points.length; _i++) {
  35869. var p = points[_i];
  35870. xmin = Math.min(p.x, xmin);
  35871. xmax = Math.max(p.x, xmax);
  35872. ymin = Math.min(p.y, ymin);
  35873. ymax = Math.max(p.y, ymax);
  35874. }
  35875. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  35876. };
  35877. /**
  35878. * Update a BoundingInfo2D object using the given min/max values as input
  35879. * @param xmin the smallest x coordinate
  35880. * @param xmax the biggest x coordinate
  35881. * @param ymin the smallest y coordinate
  35882. * @param ymax the buggest y coordinate
  35883. * @param b must be a valid/allocated object, it will contain the result of the operation
  35884. */
  35885. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  35886. var w = xmax - xmin;
  35887. var h = ymax - ymin;
  35888. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  35889. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  35890. b.radius = b.extent.length();
  35891. };
  35892. /**
  35893. * Duplicate this instance and return a new one
  35894. * @return the duplicated instance
  35895. */
  35896. BoundingInfo2D.prototype.clone = function () {
  35897. var r = new BoundingInfo2D();
  35898. r.center = this.center.clone();
  35899. r.radius = this.radius;
  35900. r.extent = this.extent.clone();
  35901. return r;
  35902. };
  35903. /**
  35904. * return the max extend of the bounding info
  35905. */
  35906. BoundingInfo2D.prototype.max = function () {
  35907. var r = BABYLON.Vector2.Zero();
  35908. this.maxToRef(r);
  35909. return r;
  35910. };
  35911. /**
  35912. * Update a vector2 with the max extend of the bounding info
  35913. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  35914. */
  35915. BoundingInfo2D.prototype.maxToRef = function (result) {
  35916. result.x = this.center.x + this.extent.x;
  35917. result.y = this.center.y + this.extent.y;
  35918. };
  35919. /**
  35920. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  35921. * @param matrix the transformation matrix to apply
  35922. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  35923. */
  35924. BoundingInfo2D.prototype.transform = function (matrix) {
  35925. var r = new BoundingInfo2D();
  35926. this.transformToRef(matrix, r);
  35927. return r;
  35928. };
  35929. /**
  35930. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  35931. * @param other the second BoundingInfo2D to compute the union with this one
  35932. * @return a new instance containing the result of the union
  35933. */
  35934. BoundingInfo2D.prototype.union = function (other) {
  35935. var r = new BoundingInfo2D();
  35936. this.unionToRef(other, r);
  35937. return r;
  35938. };
  35939. /**
  35940. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  35941. * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
  35942. * @param matrix The matrix to use to compute the transformation
  35943. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  35944. */
  35945. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  35946. // Construct a bounding box based on the extent values
  35947. var p = BoundingInfo2D._transform;
  35948. p[0].x = this.center.x + this.extent.x;
  35949. p[0].y = this.center.y + this.extent.y;
  35950. p[1].x = this.center.x + this.extent.x;
  35951. p[1].y = this.center.y - this.extent.y;
  35952. p[2].x = this.center.x - this.extent.x;
  35953. p[2].y = this.center.y - this.extent.y;
  35954. p[3].x = this.center.x - this.extent.x;
  35955. p[3].y = this.center.y + this.extent.y;
  35956. // Transform the four points of the bounding box with the matrix
  35957. for (var i = 0; i < 4; i++) {
  35958. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  35959. }
  35960. BoundingInfo2D.CreateFromPointsToRef(p, result);
  35961. };
  35962. /**
  35963. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  35964. * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
  35965. * @param other the second object used to compute the union
  35966. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  35967. */
  35968. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  35969. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  35970. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  35971. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  35972. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  35973. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  35974. };
  35975. /**
  35976. * Check if the given point is inside the BoundingInfo.
  35977. * The test is first made on the radius, then inside the rectangle described by the extent
  35978. * @param pickPosition the position to test
  35979. * @return true if the point is inside, false otherwise
  35980. */
  35981. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  35982. // is it inside the radius?
  35983. var pickLocal = pickPosition.subtract(this.center);
  35984. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  35985. // is it inside the rectangle?
  35986. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  35987. }
  35988. return false;
  35989. };
  35990. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  35991. return BoundingInfo2D;
  35992. })();
  35993. BABYLON.BoundingInfo2D = BoundingInfo2D;
  35994. })(BABYLON || (BABYLON = {}));
  35995. var BABYLON;
  35996. (function (BABYLON) {
  35997. /**
  35998. * Base class implementing the ILocable interface.
  35999. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  36000. */
  36001. var LockableBase = (function () {
  36002. function LockableBase() {
  36003. }
  36004. LockableBase.prototype.isLocked = function () {
  36005. return this._isLocked;
  36006. };
  36007. LockableBase.prototype.lock = function () {
  36008. if (this._isLocked) {
  36009. return true;
  36010. }
  36011. this.onLock();
  36012. this._isLocked = true;
  36013. return false;
  36014. };
  36015. /**
  36016. * Protected handler that will be called when the instance is about to be locked.
  36017. */
  36018. LockableBase.prototype.onLock = function () {
  36019. };
  36020. return LockableBase;
  36021. })();
  36022. BABYLON.LockableBase = LockableBase;
  36023. var SolidColorBrush2D = (function (_super) {
  36024. __extends(SolidColorBrush2D, _super);
  36025. function SolidColorBrush2D(color, lock) {
  36026. if (lock === void 0) { lock = false; }
  36027. _super.call(this);
  36028. this._color = color;
  36029. if (lock) {
  36030. {
  36031. this.lock();
  36032. }
  36033. }
  36034. }
  36035. /**
  36036. * Return true if the brush is transparent, false if it's totally opaque
  36037. */
  36038. SolidColorBrush2D.prototype.isTransparent = function () {
  36039. return this._color && this._color.a < 1.0;
  36040. };
  36041. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  36042. /**
  36043. * The color used by this instance to render
  36044. * @returns the color object. Note that it's not a clone of the actual object stored in the instance so you MUST NOT modify it, otherwise unexpected behavior might occurs.
  36045. */
  36046. get: function () {
  36047. return this._color;
  36048. },
  36049. set: function (value) {
  36050. if (this.isLocked()) {
  36051. return;
  36052. }
  36053. this._color = value;
  36054. },
  36055. enumerable: true,
  36056. configurable: true
  36057. });
  36058. /**
  36059. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  36060. */
  36061. SolidColorBrush2D.prototype.toString = function () {
  36062. return this._color.toHexString();
  36063. };
  36064. SolidColorBrush2D = __decorate([
  36065. BABYLON.className("SolidColorBrush2D")
  36066. ], SolidColorBrush2D);
  36067. return SolidColorBrush2D;
  36068. })(LockableBase);
  36069. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  36070. var GradientColorBrush2D = (function (_super) {
  36071. __extends(GradientColorBrush2D, _super);
  36072. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  36073. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  36074. if (rotation === void 0) { rotation = 0; }
  36075. if (scale === void 0) { scale = 1; }
  36076. if (lock === void 0) { lock = false; }
  36077. _super.call(this);
  36078. this._color1 = color1;
  36079. this._color2 = color2;
  36080. this._translation = translation;
  36081. this._rotation = rotation;
  36082. this._scale = scale;
  36083. if (lock) {
  36084. this.lock();
  36085. }
  36086. }
  36087. /**
  36088. * Return true if the brush is transparent, false if it's totally opaque
  36089. */
  36090. GradientColorBrush2D.prototype.isTransparent = function () {
  36091. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  36092. };
  36093. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  36094. /**
  36095. * First color, the blend will start from this color
  36096. */
  36097. get: function () {
  36098. return this._color1;
  36099. },
  36100. set: function (value) {
  36101. if (this.isLocked()) {
  36102. return;
  36103. }
  36104. this._color1 = value;
  36105. },
  36106. enumerable: true,
  36107. configurable: true
  36108. });
  36109. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  36110. /**
  36111. * Second color, the blend will end to this color
  36112. */
  36113. get: function () {
  36114. return this._color2;
  36115. },
  36116. set: function (value) {
  36117. if (this.isLocked()) {
  36118. return;
  36119. }
  36120. this._color2 = value;
  36121. },
  36122. enumerable: true,
  36123. configurable: true
  36124. });
  36125. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  36126. /**
  36127. * Translation vector to apply on the blend
  36128. * Default is [0;0]
  36129. */
  36130. get: function () {
  36131. return this._translation;
  36132. },
  36133. set: function (value) {
  36134. if (this.isLocked()) {
  36135. return;
  36136. }
  36137. this._translation = value;
  36138. },
  36139. enumerable: true,
  36140. configurable: true
  36141. });
  36142. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  36143. /**
  36144. * Rotation in radian to apply to the brush
  36145. * Default direction of the brush is vertical, you can change this using this property.
  36146. * Default is 0.
  36147. */
  36148. get: function () {
  36149. return this._rotation;
  36150. },
  36151. set: function (value) {
  36152. if (this.isLocked()) {
  36153. return;
  36154. }
  36155. this._rotation = value;
  36156. },
  36157. enumerable: true,
  36158. configurable: true
  36159. });
  36160. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  36161. /**
  36162. * Scale factor to apply to the gradient.
  36163. * Default is 1: no scale.
  36164. */
  36165. get: function () {
  36166. return this._scale;
  36167. },
  36168. set: function (value) {
  36169. if (this.isLocked()) {
  36170. return;
  36171. }
  36172. this._scale = value;
  36173. },
  36174. enumerable: true,
  36175. configurable: true
  36176. });
  36177. /**
  36178. * Return a string describing the brush
  36179. */
  36180. GradientColorBrush2D.prototype.toString = function () {
  36181. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  36182. };
  36183. /**
  36184. * Build a unique key string for the given parameters
  36185. */
  36186. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  36187. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  36188. };
  36189. GradientColorBrush2D = __decorate([
  36190. BABYLON.className("GradientColorBrush2D")
  36191. ], GradientColorBrush2D);
  36192. return GradientColorBrush2D;
  36193. })(LockableBase);
  36194. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  36195. })(BABYLON || (BABYLON = {}));
  36196. var BABYLON;
  36197. (function (BABYLON) {
  36198. var Prim2DClassInfo = (function () {
  36199. function Prim2DClassInfo() {
  36200. }
  36201. return Prim2DClassInfo;
  36202. })();
  36203. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  36204. var Prim2DPropInfo = (function () {
  36205. function Prim2DPropInfo() {
  36206. }
  36207. Prim2DPropInfo.PROPKIND_MODEL = 1;
  36208. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  36209. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  36210. return Prim2DPropInfo;
  36211. })();
  36212. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  36213. /**
  36214. * Custom type of the propertyChanged observable
  36215. */
  36216. var PropertyChangedInfo = (function () {
  36217. function PropertyChangedInfo() {
  36218. }
  36219. return PropertyChangedInfo;
  36220. })();
  36221. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  36222. var ClassTreeInfo = (function () {
  36223. function ClassTreeInfo(baseClass, type, classContentFactory) {
  36224. this._baseClass = baseClass;
  36225. this._type = type;
  36226. this._subClasses = new Array();
  36227. this._levelContent = new BABYLON.StringDictionary();
  36228. this._classContentFactory = classContentFactory;
  36229. }
  36230. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  36231. get: function () {
  36232. if (!this._classContent) {
  36233. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  36234. }
  36235. return this._classContent;
  36236. },
  36237. enumerable: true,
  36238. configurable: true
  36239. });
  36240. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  36241. get: function () {
  36242. return this._type;
  36243. },
  36244. enumerable: true,
  36245. configurable: true
  36246. });
  36247. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  36248. get: function () {
  36249. return this._levelContent;
  36250. },
  36251. enumerable: true,
  36252. configurable: true
  36253. });
  36254. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  36255. get: function () {
  36256. if (!this._fullContent) {
  36257. var dic = new BABYLON.StringDictionary();
  36258. var curLevel = this;
  36259. while (curLevel) {
  36260. curLevel.levelContent.forEach(function (k, v) { return dic.add(k, v); });
  36261. curLevel = curLevel._baseClass;
  36262. }
  36263. this._fullContent = dic;
  36264. }
  36265. return this._fullContent;
  36266. },
  36267. enumerable: true,
  36268. configurable: true
  36269. });
  36270. ClassTreeInfo.prototype.getLevelOf = function (type) {
  36271. // Are we already there?
  36272. if (type === this._type) {
  36273. return this;
  36274. }
  36275. var baseProto = Object.getPrototypeOf(type);
  36276. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  36277. if (!curProtoContent) {
  36278. this.getLevelOf(baseProto);
  36279. }
  36280. return this.getOrAddType(baseProto, type);
  36281. };
  36282. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  36283. // Are we at the level corresponding to the baseType?
  36284. // If so, get or add the level we're looking for
  36285. if (baseType === this._type) {
  36286. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  36287. var subType = _a[_i];
  36288. if (subType.type === type) {
  36289. return subType.node;
  36290. }
  36291. }
  36292. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  36293. var info = { type: type, node: node };
  36294. this._subClasses.push(info);
  36295. return info.node;
  36296. }
  36297. // Recurse down to keep looking for the node corresponding to the baseTypeName
  36298. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  36299. var subType = _c[_b];
  36300. var info = subType.node.getOrAddType(baseType, type);
  36301. if (info) {
  36302. return info;
  36303. }
  36304. }
  36305. return null;
  36306. };
  36307. ClassTreeInfo.get = function (type) {
  36308. var dic = type["__classTreeInfo"];
  36309. if (!dic) {
  36310. return null;
  36311. }
  36312. return dic.getLevelOf(type);
  36313. };
  36314. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  36315. var dic = type["__classTreeInfo"];
  36316. if (!dic) {
  36317. dic = new ClassTreeInfo(null, type, classContentFactory);
  36318. type["__classTreeInfo"] = dic;
  36319. }
  36320. return dic;
  36321. };
  36322. return ClassTreeInfo;
  36323. })();
  36324. BABYLON.ClassTreeInfo = ClassTreeInfo;
  36325. var SmartPropertyPrim = (function () {
  36326. function SmartPropertyPrim() {
  36327. this._flags = 0;
  36328. this._modelKey = null;
  36329. this._instanceDirtyFlags = 0;
  36330. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  36331. this.animations = new Array();
  36332. }
  36333. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  36334. /**
  36335. * Check if the object is disposed or not.
  36336. * @returns true if the object is dispose, false otherwise.
  36337. */
  36338. get: function () {
  36339. return this._isFlagSet(SmartPropertyPrim.flagIsDisposed);
  36340. },
  36341. enumerable: true,
  36342. configurable: true
  36343. });
  36344. /**
  36345. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  36346. * @returns false if the object is already dispose, true otherwise. Your implementation must call super.dispose() and check for a false return and return immediately if it's the case.
  36347. */
  36348. SmartPropertyPrim.prototype.dispose = function () {
  36349. if (this.isDisposed) {
  36350. return false;
  36351. }
  36352. // Don't set to null, it may upset somebody...
  36353. this.animations.splice(0);
  36354. this._setFlags(SmartPropertyPrim.flagIsDisposed);
  36355. return true;
  36356. };
  36357. /**
  36358. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  36359. * Look at Sprite2D for more information
  36360. */
  36361. SmartPropertyPrim.prototype.getAnimatables = function () {
  36362. return new Array();
  36363. };
  36364. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  36365. /**
  36366. * Property giving the Model Key associated to the property.
  36367. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  36368. * @returns the model key string.
  36369. */
  36370. get: function () {
  36371. var _this = this;
  36372. // No need to compute it?
  36373. if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
  36374. return this._modelKey;
  36375. }
  36376. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  36377. var propDic = this.propDic;
  36378. propDic.forEach(function (k, v) {
  36379. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  36380. var propVal = _this[v.name];
  36381. // Special case, array, this WON'T WORK IN ALL CASES, all entries have to be of the same type and it must be a BJS well known one
  36382. if (propVal && propVal.constructor === Array) {
  36383. var firstVal = propVal[0];
  36384. if (!firstVal) {
  36385. propVal = 0;
  36386. }
  36387. else {
  36388. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  36389. }
  36390. }
  36391. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  36392. }
  36393. });
  36394. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  36395. this._modelKey = modelKey;
  36396. return modelKey;
  36397. },
  36398. enumerable: true,
  36399. configurable: true
  36400. });
  36401. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  36402. /**
  36403. * States if the Primitive is dirty and should be rendered again next time.
  36404. * @returns true is dirty, false otherwise
  36405. */
  36406. get: function () {
  36407. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
  36408. },
  36409. enumerable: true,
  36410. configurable: true
  36411. });
  36412. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  36413. /**
  36414. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  36415. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  36416. */
  36417. get: function () {
  36418. if (!this._propInfo) {
  36419. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  36420. if (!cti) {
  36421. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  36422. }
  36423. this._propInfo = cti.fullContent;
  36424. }
  36425. return this._propInfo;
  36426. },
  36427. enumerable: true,
  36428. configurable: true
  36429. });
  36430. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, typeLevelCompare, kind) {
  36431. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  36432. var node = dic.getLevelOf(target);
  36433. var propInfo = node.levelContent.get(propId.toString());
  36434. if (propInfo) {
  36435. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  36436. }
  36437. // Create, setup and add the PropInfo object to our prop dictionary
  36438. propInfo = new Prim2DPropInfo();
  36439. propInfo.id = propId;
  36440. propInfo.flagId = Math.pow(2, propId);
  36441. propInfo.kind = kind;
  36442. propInfo.name = propName;
  36443. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  36444. propInfo.typeLevelCompare = typeLevelCompare;
  36445. node.levelContent.add(propName, propInfo);
  36446. return propInfo;
  36447. };
  36448. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  36449. // Nothing to nothing: nothing to do!
  36450. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  36451. return true;
  36452. }
  36453. // Check value unchanged
  36454. if ((curValue != null) && (newValue != null)) {
  36455. if (typeof (curValue.equals) == "function") {
  36456. if (curValue.equals(newValue)) {
  36457. return true;
  36458. }
  36459. }
  36460. else {
  36461. if (curValue === newValue) {
  36462. return true;
  36463. }
  36464. }
  36465. }
  36466. return false;
  36467. };
  36468. SmartPropertyPrim.prototype.markAsDirty = function (propertyName) {
  36469. if (this.isDisposed) {
  36470. return;
  36471. }
  36472. var i = propertyName.indexOf(".");
  36473. if (i !== -1) {
  36474. propertyName = propertyName.substr(0, i);
  36475. }
  36476. var propInfo = this.propDic.get(propertyName);
  36477. if (!propInfo) {
  36478. return;
  36479. }
  36480. var newValue = this[propertyName];
  36481. this._handlePropChanged(undefined, newValue, propertyName, propInfo, propInfo.typeLevelCompare);
  36482. };
  36483. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  36484. this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  36485. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  36486. if (this instanceof BABYLON.Prim2DBase) {
  36487. var curprim = this;
  36488. while (curprim) {
  36489. curprim._boundingSize = null;
  36490. curprim._setFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  36491. if (curprim.isSizeAuto) {
  36492. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  36493. }
  36494. if (curprim instanceof BABYLON.Group2D) {
  36495. if (curprim.isRenderableGroup) {
  36496. break;
  36497. }
  36498. }
  36499. curprim = curprim.parent;
  36500. }
  36501. }
  36502. };
  36503. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  36504. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  36505. if (propInfo.dirtyBoundingInfo) {
  36506. this._boundingBoxDirty();
  36507. }
  36508. // Trigger property changed
  36509. var info = SmartPropertyPrim.propChangedInfo;
  36510. info.oldValue = curValue;
  36511. info.newValue = newValue;
  36512. info.propertyName = propName;
  36513. var propMask = propInfo.flagId;
  36514. this.propertyChanged.notifyObservers(info, propMask);
  36515. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  36516. if (this instanceof BABYLON.Group2D) {
  36517. this.handleGroupChanged(propInfo);
  36518. }
  36519. // Check for parent layout dirty
  36520. if (this instanceof BABYLON.Prim2DBase) {
  36521. var p = this._parent;
  36522. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  36523. p._setLayoutDirty();
  36524. }
  36525. }
  36526. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  36527. var instanceDirty = false;
  36528. if (typeLevelCompare && curValue != null && newValue != null) {
  36529. var cvProto = curValue.__proto__;
  36530. var nvProto = newValue.__proto__;
  36531. instanceDirty = (cvProto === nvProto);
  36532. }
  36533. // Set the dirty flags
  36534. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  36535. this.onPrimitivePropertyDirty(SmartPropertyPrim.flagModelDirty);
  36536. }
  36537. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  36538. this.onPrimitivePropertyDirty(propMask);
  36539. }
  36540. };
  36541. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  36542. if (!this.isDirty) {
  36543. this.onPrimBecomesDirty();
  36544. }
  36545. this._instanceDirtyFlags |= propFlagId;
  36546. };
  36547. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  36548. };
  36549. /**
  36550. * Check if a given set of properties are dirty or not.
  36551. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  36552. * @return true if at least one property is dirty, false if none of them are.
  36553. */
  36554. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  36555. return (this._instanceDirtyFlags & flags) !== 0;
  36556. };
  36557. /**
  36558. * Clear a given set of properties.
  36559. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  36560. * @return the new set of property still marked as dirty
  36561. */
  36562. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  36563. this._instanceDirtyFlags &= ~flags;
  36564. return this._instanceDirtyFlags;
  36565. };
  36566. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  36567. this._instanceDirtyFlags = 0;
  36568. };
  36569. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  36570. /**
  36571. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  36572. */
  36573. get: function () {
  36574. if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  36575. this.updateLevelBoundingInfo();
  36576. this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  36577. }
  36578. return this._levelBoundingInfo;
  36579. },
  36580. enumerable: true,
  36581. configurable: true
  36582. });
  36583. /**
  36584. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  36585. */
  36586. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  36587. };
  36588. /**
  36589. * Property method called when the Primitive becomes dirty
  36590. */
  36591. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  36592. };
  36593. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, kind) {
  36594. return function (target, propName, descriptor) {
  36595. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, typeLevelCompare, kind);
  36596. if (piStore) {
  36597. piStore(propInfo);
  36598. }
  36599. var getter = descriptor.get, setter = descriptor.set;
  36600. // Overload the property setter implementation to add our own logic
  36601. descriptor.set = function (val) {
  36602. // check for disposed first, do nothing
  36603. if (this.isDisposed) {
  36604. return;
  36605. }
  36606. var curVal = getter.call(this);
  36607. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  36608. return;
  36609. }
  36610. // Cast the object we're working one
  36611. var prim = this;
  36612. // Change the value
  36613. setter.call(this, val);
  36614. // Notify change, dirty flags update
  36615. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  36616. };
  36617. };
  36618. };
  36619. /**
  36620. * Add an externally attached data from its key.
  36621. * This method call will fail and return false, if such key already exists.
  36622. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  36623. * @param key the unique key that identifies the data
  36624. * @param data the data object to associate to the key for this Engine instance
  36625. * @return true if no such key were already present and the data was added successfully, false otherwise
  36626. */
  36627. SmartPropertyPrim.prototype.addExternalData = function (key, data) {
  36628. if (!this._externalData) {
  36629. this._externalData = new BABYLON.StringDictionary();
  36630. }
  36631. return this._externalData.add(key, data);
  36632. };
  36633. /**
  36634. * Get an externally attached data from its key
  36635. * @param key the unique key that identifies the data
  36636. * @return the associated data, if present (can be null), or undefined if not present
  36637. */
  36638. SmartPropertyPrim.prototype.getExternalData = function (key) {
  36639. if (!this._externalData) {
  36640. return null;
  36641. }
  36642. return this._externalData.get(key);
  36643. };
  36644. /**
  36645. * Get an externally attached data from its key, create it using a factory if it's not already present
  36646. * @param key the unique key that identifies the data
  36647. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  36648. * @return the associated data, can be null if the factory returned null.
  36649. */
  36650. SmartPropertyPrim.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  36651. if (!this._externalData) {
  36652. this._externalData = new BABYLON.StringDictionary();
  36653. }
  36654. return this._externalData.getOrAddWithFactory(key, factory);
  36655. };
  36656. /**
  36657. * Remove an externally attached data from the Engine instance
  36658. * @param key the unique key that identifies the data
  36659. * @return true if the data was successfully removed, false if it doesn't exist
  36660. */
  36661. SmartPropertyPrim.prototype.removeExternalData = function (key) {
  36662. if (!this._externalData) {
  36663. return false;
  36664. }
  36665. return this._externalData.remove(key);
  36666. };
  36667. /**
  36668. * Check if a given flag is set
  36669. * @param flag the flag value
  36670. * @return true if set, false otherwise
  36671. */
  36672. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  36673. return (this._flags & flag) !== 0;
  36674. };
  36675. /**
  36676. * Check if all given flags are set
  36677. * @param flags the flags ORed
  36678. * @return true if all the flags are set, false otherwise
  36679. */
  36680. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  36681. return (this._flags & flags) === flags;
  36682. };
  36683. /**
  36684. * Check if at least one flag of the given flags is set
  36685. * @param flags the flags ORed
  36686. * @return true if at least one flag is set, false otherwise
  36687. */
  36688. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  36689. return (this._flags & flags) !== 0;
  36690. };
  36691. /**
  36692. * Clear the given flags
  36693. * @param flags the flags to clear
  36694. */
  36695. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  36696. this._flags &= ~flags;
  36697. };
  36698. /**
  36699. * Set the given flags to true state
  36700. * @param flags the flags ORed to set
  36701. * @return the flags state before this call
  36702. */
  36703. SmartPropertyPrim.prototype._setFlags = function (flags) {
  36704. var cur = this._flags;
  36705. this._flags |= flags;
  36706. return cur;
  36707. };
  36708. /**
  36709. * Change the state of the given flags
  36710. * @param flags the flags ORed to change
  36711. * @param state true to set them, false to clear them
  36712. */
  36713. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  36714. if (state) {
  36715. this._flags |= flags;
  36716. }
  36717. else {
  36718. this._flags &= ~flags;
  36719. }
  36720. };
  36721. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  36722. SmartPropertyPrim.flagIsDisposed = 0x0000001; // set if the object is already disposed
  36723. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  36724. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  36725. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  36726. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  36727. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  36728. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  36729. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  36730. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  36731. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  36732. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  36733. SmartPropertyPrim = __decorate([
  36734. BABYLON.className("SmartPropertyPrim")
  36735. ], SmartPropertyPrim);
  36736. return SmartPropertyPrim;
  36737. })();
  36738. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  36739. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  36740. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  36741. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  36742. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_MODEL);
  36743. }
  36744. BABYLON.modelLevelProperty = modelLevelProperty;
  36745. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  36746. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  36747. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  36748. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_INSTANCE);
  36749. }
  36750. BABYLON.instanceLevelProperty = instanceLevelProperty;
  36751. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  36752. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  36753. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  36754. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_DYNAMIC);
  36755. }
  36756. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  36757. })(BABYLON || (BABYLON = {}));
  36758. var BABYLON;
  36759. (function (BABYLON) {
  36760. var PrepareRender2DContext = (function () {
  36761. function PrepareRender2DContext() {
  36762. this.forceRefreshPrimitive = false;
  36763. }
  36764. return PrepareRender2DContext;
  36765. })();
  36766. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  36767. var Render2DContext = (function () {
  36768. function Render2DContext(renderMode) {
  36769. this._renderMode = renderMode;
  36770. this.useInstancing = false;
  36771. this.groupInfoPartData = null;
  36772. this.partDataStartIndex = this.partDataEndIndex = null;
  36773. }
  36774. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  36775. /**
  36776. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  36777. */
  36778. get: function () {
  36779. return this._renderMode;
  36780. },
  36781. enumerable: true,
  36782. configurable: true
  36783. });
  36784. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  36785. /**
  36786. * The set of primitives to render is opaque.
  36787. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  36788. */
  36789. get: function () {
  36790. return Render2DContext._renderModeOpaque;
  36791. },
  36792. enumerable: true,
  36793. configurable: true
  36794. });
  36795. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  36796. /**
  36797. * The set of primitives to render is using Alpha Test (aka masking).
  36798. * Alpha Blend is enabled, the AlphaMode must be manually set, the render occurs after the RenderModeOpaque and is depth independent (i.e. primitives are not sorted by depth). Depth Compare and Write are both enabled.
  36799. */
  36800. get: function () {
  36801. return Render2DContext._renderModeAlphaTest;
  36802. },
  36803. enumerable: true,
  36804. configurable: true
  36805. });
  36806. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  36807. /**
  36808. * The set of primitives to render is transparent.
  36809. * Alpha Blend is enabled, the AlphaMode must be manually set, the render occurs after the RenderModeAlphaTest and is depth dependent (i.e. primitives are stored by depth and rendered back to front). Depth Compare is on, but Depth write is Off.
  36810. */
  36811. get: function () {
  36812. return Render2DContext._renderModeTransparent;
  36813. },
  36814. enumerable: true,
  36815. configurable: true
  36816. });
  36817. Render2DContext._renderModeOpaque = 1;
  36818. Render2DContext._renderModeAlphaTest = 2;
  36819. Render2DContext._renderModeTransparent = 3;
  36820. return Render2DContext;
  36821. })();
  36822. BABYLON.Render2DContext = Render2DContext;
  36823. /**
  36824. * This class store information for the pointerEventObservable Observable.
  36825. * The Observable is divided into many sub events (using the Mask feature of the Observable pattern): PointerOver, PointerEnter, PointerDown, PointerMouseWheel, PointerMove, PointerUp, PointerDown, PointerLeave, PointerGotCapture and PointerLostCapture.
  36826. */
  36827. var PrimitivePointerInfo = (function () {
  36828. function PrimitivePointerInfo() {
  36829. this.primitivePointerPos = BABYLON.Vector2.Zero();
  36830. this.tilt = BABYLON.Vector2.Zero();
  36831. this.cancelBubble = false;
  36832. }
  36833. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  36834. // The behavior is based on the HTML specifications of the Pointer Events (https://www.w3.org/TR/pointerevents/#list-of-pointer-events). This is not 100% compliant and not meant to be, but still, it's based on these specs for most use cases to be programmed the same way (as closest as possible) as it would have been in HTML.
  36835. /**
  36836. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  36837. * Bubbles: yes
  36838. */
  36839. get: function () {
  36840. return PrimitivePointerInfo._pointerOver;
  36841. },
  36842. enumerable: true,
  36843. configurable: true
  36844. });
  36845. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  36846. /**
  36847. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  36848. * Bubbles: no
  36849. */
  36850. get: function () {
  36851. return PrimitivePointerInfo._pointerEnter;
  36852. },
  36853. enumerable: true,
  36854. configurable: true
  36855. });
  36856. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  36857. /**
  36858. * This event type is raised when a pointer enters the active button state (non-zero value in the buttons property). For mouse it's when the device transitions from no buttons depressed to at least one button depressed. For touch/pen this is when a physical contact is made.
  36859. * Bubbles: yes
  36860. */
  36861. get: function () {
  36862. return PrimitivePointerInfo._pointerDown;
  36863. },
  36864. enumerable: true,
  36865. configurable: true
  36866. });
  36867. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  36868. /**
  36869. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  36870. * Bubbles: yes
  36871. */
  36872. get: function () {
  36873. return PrimitivePointerInfo._pointerMouseWheel;
  36874. },
  36875. enumerable: true,
  36876. configurable: true
  36877. });
  36878. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  36879. /**
  36880. * This event type is raised when a pointer change coordinates or when a pointer changes button state, pressure, tilt, or contact geometry and the circumstances produce no other pointers events.
  36881. * Bubbles: yes
  36882. */
  36883. get: function () {
  36884. return PrimitivePointerInfo._pointerMove;
  36885. },
  36886. enumerable: true,
  36887. configurable: true
  36888. });
  36889. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  36890. /**
  36891. * This event type is raised when the pointer leaves the active buttons states (zero value in the buttons property). For mouse, this is when the device transitions from at least one button depressed to no buttons depressed. For touch/pen, this is when physical contact is removed.
  36892. * Bubbles: yes
  36893. */
  36894. get: function () {
  36895. return PrimitivePointerInfo._pointerUp;
  36896. },
  36897. enumerable: true,
  36898. configurable: true
  36899. });
  36900. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  36901. /**
  36902. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  36903. * Bubbles: yes
  36904. */
  36905. get: function () {
  36906. return PrimitivePointerInfo._pointerOut;
  36907. },
  36908. enumerable: true,
  36909. configurable: true
  36910. });
  36911. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  36912. /**
  36913. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  36914. * Bubbles: no
  36915. */
  36916. get: function () {
  36917. return PrimitivePointerInfo._pointerLeave;
  36918. },
  36919. enumerable: true,
  36920. configurable: true
  36921. });
  36922. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  36923. /**
  36924. * This event type is raised when a primitive receives the pointer capture. This event is fired at the element that is receiving pointer capture. Subsequent events for that pointer will be fired at this element.
  36925. * Bubbles: yes
  36926. */
  36927. get: function () {
  36928. return PrimitivePointerInfo._pointerGotCapture;
  36929. },
  36930. enumerable: true,
  36931. configurable: true
  36932. });
  36933. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  36934. /**
  36935. * This event type is raised after pointer capture is released for a pointer.
  36936. * Bubbles: yes
  36937. */
  36938. get: function () {
  36939. return PrimitivePointerInfo._pointerLostCapture;
  36940. },
  36941. enumerable: true,
  36942. configurable: true
  36943. });
  36944. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  36945. get: function () {
  36946. return PrimitivePointerInfo._mouseWheelPrecision;
  36947. },
  36948. enumerable: true,
  36949. configurable: true
  36950. });
  36951. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  36952. this.relatedTarget = prim;
  36953. this.relatedTargetPointerPos = primPointerPos;
  36954. };
  36955. PrimitivePointerInfo.getEventTypeName = function (mask) {
  36956. switch (mask) {
  36957. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  36958. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  36959. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  36960. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  36961. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  36962. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  36963. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  36964. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  36965. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  36966. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  36967. }
  36968. };
  36969. PrimitivePointerInfo._pointerOver = 0x0001;
  36970. PrimitivePointerInfo._pointerEnter = 0x0002;
  36971. PrimitivePointerInfo._pointerDown = 0x0004;
  36972. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  36973. PrimitivePointerInfo._pointerMove = 0x0010;
  36974. PrimitivePointerInfo._pointerUp = 0x0020;
  36975. PrimitivePointerInfo._pointerOut = 0x0040;
  36976. PrimitivePointerInfo._pointerLeave = 0x0080;
  36977. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  36978. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  36979. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  36980. return PrimitivePointerInfo;
  36981. })();
  36982. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  36983. /**
  36984. * Defines the horizontal and vertical alignment information for a Primitive.
  36985. */
  36986. var PrimitiveAlignment = (function () {
  36987. function PrimitiveAlignment(changeCallback) {
  36988. this._changedCallback = changeCallback;
  36989. this._horizontal = PrimitiveAlignment.AlignLeft;
  36990. this._vertical = PrimitiveAlignment.AlignBottom;
  36991. }
  36992. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  36993. /**
  36994. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  36995. */
  36996. get: function () { return PrimitiveAlignment._AlignLeft; },
  36997. enumerable: true,
  36998. configurable: true
  36999. });
  37000. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  37001. /**
  37002. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  37003. */
  37004. get: function () { return PrimitiveAlignment._AlignTop; },
  37005. enumerable: true,
  37006. configurable: true
  37007. });
  37008. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  37009. /**
  37010. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  37011. */
  37012. get: function () { return PrimitiveAlignment._AlignRight; },
  37013. enumerable: true,
  37014. configurable: true
  37015. });
  37016. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  37017. /**
  37018. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  37019. */
  37020. get: function () { return PrimitiveAlignment._AlignBottom; },
  37021. enumerable: true,
  37022. configurable: true
  37023. });
  37024. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  37025. /**
  37026. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  37027. */
  37028. get: function () { return PrimitiveAlignment._AlignCenter; },
  37029. enumerable: true,
  37030. configurable: true
  37031. });
  37032. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  37033. /**
  37034. * The content is stretched toward the opposite edges of the Primitive
  37035. */
  37036. get: function () { return PrimitiveAlignment._AlignStretch; },
  37037. enumerable: true,
  37038. configurable: true
  37039. });
  37040. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  37041. /**
  37042. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  37043. */
  37044. get: function () {
  37045. return this._horizontal;
  37046. },
  37047. set: function (value) {
  37048. if (this._horizontal === value) {
  37049. return;
  37050. }
  37051. this._horizontal = value;
  37052. this._changedCallback();
  37053. },
  37054. enumerable: true,
  37055. configurable: true
  37056. });
  37057. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  37058. /**
  37059. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  37060. */
  37061. get: function () {
  37062. return this._vertical;
  37063. },
  37064. set: function (value) {
  37065. if (this._vertical === value) {
  37066. return;
  37067. }
  37068. this._vertical = value;
  37069. this._changedCallback();
  37070. },
  37071. enumerable: true,
  37072. configurable: true
  37073. });
  37074. /**
  37075. * Set the horizontal alignment from a string value.
  37076. * @param text can be either: 'left','right','center','stretch'
  37077. */
  37078. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  37079. var v = text.trim().toLocaleLowerCase();
  37080. switch (v) {
  37081. case "left":
  37082. this.horizontal = PrimitiveAlignment.AlignLeft;
  37083. return;
  37084. case "right":
  37085. this.horizontal = PrimitiveAlignment.AlignRight;
  37086. return;
  37087. case "center":
  37088. this.horizontal = PrimitiveAlignment.AlignCenter;
  37089. return;
  37090. case "stretch":
  37091. this.horizontal = PrimitiveAlignment.AlignStretch;
  37092. return;
  37093. }
  37094. };
  37095. /**
  37096. * Set the vertical alignment from a string value.
  37097. * @param text can be either: 'top','bottom','center','stretch'
  37098. */
  37099. PrimitiveAlignment.prototype.setVertical = function (text) {
  37100. var v = text.trim().toLocaleLowerCase();
  37101. switch (v) {
  37102. case "top":
  37103. this.vertical = PrimitiveAlignment.AlignTop;
  37104. return;
  37105. case "bottom":
  37106. this.vertical = PrimitiveAlignment.AlignBottom;
  37107. return;
  37108. case "center":
  37109. this.vertical = PrimitiveAlignment.AlignCenter;
  37110. return;
  37111. case "stretch":
  37112. this.vertical = PrimitiveAlignment.AlignStretch;
  37113. return;
  37114. }
  37115. };
  37116. /**
  37117. * Set the horizontal and or vertical alignments from a string value.
  37118. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  37119. */
  37120. PrimitiveAlignment.prototype.fromString = function (value) {
  37121. var m = value.trim().split(",");
  37122. for (var _i = 0; _i < m.length; _i++) {
  37123. var v = m[_i];
  37124. v = v.toLocaleLowerCase().trim();
  37125. // Horizontal
  37126. var i = v.indexOf("h:");
  37127. if (i === -1) {
  37128. i = v.indexOf("horizontal:");
  37129. }
  37130. if (i !== -1) {
  37131. v = v.substr(v.indexOf(":") + 1);
  37132. this.setHorizontal(v);
  37133. continue;
  37134. }
  37135. // Vertical
  37136. i = v.indexOf("v:");
  37137. if (i === -1) {
  37138. i = v.indexOf("vertical:");
  37139. }
  37140. if (i !== -1) {
  37141. v = v.substr(v.indexOf(":") + 1);
  37142. this.setVertical(v);
  37143. continue;
  37144. }
  37145. }
  37146. };
  37147. PrimitiveAlignment._AlignLeft = 1;
  37148. PrimitiveAlignment._AlignTop = 1; // Same as left
  37149. PrimitiveAlignment._AlignRight = 2;
  37150. PrimitiveAlignment._AlignBottom = 2; // Same as right
  37151. PrimitiveAlignment._AlignCenter = 3;
  37152. PrimitiveAlignment._AlignStretch = 4;
  37153. return PrimitiveAlignment;
  37154. })();
  37155. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  37156. /**
  37157. * Stores information about a Primitive that was intersected
  37158. */
  37159. var PrimitiveIntersectedInfo = (function () {
  37160. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  37161. this.prim = prim;
  37162. this.intersectionLocation = intersectionLocation;
  37163. }
  37164. return PrimitiveIntersectedInfo;
  37165. })();
  37166. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  37167. /**
  37168. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  37169. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  37170. */
  37171. var PrimitiveThickness = (function () {
  37172. function PrimitiveThickness(parentAccess, changedCallback) {
  37173. this._parentAccess = parentAccess;
  37174. this._changedCallback = changedCallback;
  37175. this._pixels = new Array(4);
  37176. this._percentages = new Array(4);
  37177. this._setType(0, PrimitiveThickness.Auto);
  37178. this._setType(1, PrimitiveThickness.Auto);
  37179. this._setType(2, PrimitiveThickness.Auto);
  37180. this._setType(3, PrimitiveThickness.Auto);
  37181. this._pixels[0] = 0;
  37182. this._pixels[1] = 0;
  37183. this._pixels[2] = 0;
  37184. this._pixels[3] = 0;
  37185. }
  37186. /**
  37187. * Set the thickness from a string value
  37188. * @param thickness format is "top: <value>, left:<value>, right:<value>, bottom:<value>" each are optional, auto will be set if it's omitted.
  37189. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  37190. */
  37191. PrimitiveThickness.prototype.fromString = function (thickness) {
  37192. this._clear();
  37193. var m = thickness.trim().split(",");
  37194. var res = false;
  37195. for (var _i = 0; _i < m.length; _i++) {
  37196. var cm = m[_i];
  37197. res = this._extractString(cm, false) || res;
  37198. }
  37199. if (!res) {
  37200. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  37201. }
  37202. // Check the margin that weren't set and set them in auto
  37203. if ((this._flags & 0x000F) === 0)
  37204. this._flags |= PrimitiveThickness.Pixel << 0;
  37205. if ((this._flags & 0x00F0) === 0)
  37206. this._flags |= PrimitiveThickness.Pixel << 4;
  37207. if ((this._flags & 0x0F00) === 0)
  37208. this._flags |= PrimitiveThickness.Pixel << 8;
  37209. if ((this._flags & 0xF000) === 0)
  37210. this._flags |= PrimitiveThickness.Pixel << 12;
  37211. this._changedCallback();
  37212. };
  37213. /**
  37214. * Set the thickness from multiple string
  37215. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  37216. * @param top the top thickness to set
  37217. * @param left the left thickness to set
  37218. * @param right the right thickness to set
  37219. * @param bottom the bottom thickness to set
  37220. */
  37221. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  37222. this._clear();
  37223. this._setStringValue(top, 0, false);
  37224. this._setStringValue(left, 1, false);
  37225. this._setStringValue(right, 2, false);
  37226. this._setStringValue(bottom, 3, false);
  37227. this._changedCallback();
  37228. return this;
  37229. };
  37230. /**
  37231. * Set the thickness from pixel values
  37232. * @param top the top thickness in pixels to set
  37233. * @param left the left thickness in pixels to set
  37234. * @param right the right thickness in pixels to set
  37235. * @param bottom the bottom thickness in pixels to set
  37236. */
  37237. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  37238. this._clear();
  37239. this._pixels[0] = top;
  37240. this._pixels[1] = left;
  37241. this._pixels[2] = right;
  37242. this._pixels[3] = bottom;
  37243. this._changedCallback();
  37244. return this;
  37245. };
  37246. /**
  37247. * Apply the same pixel value to all edges
  37248. * @param margin the value to set, in pixels.
  37249. */
  37250. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  37251. this._clear();
  37252. this._pixels[0] = margin;
  37253. this._pixels[1] = margin;
  37254. this._pixels[2] = margin;
  37255. this._pixels[3] = margin;
  37256. this._changedCallback();
  37257. return this;
  37258. };
  37259. /**
  37260. * Set all edges in auto
  37261. */
  37262. PrimitiveThickness.prototype.auto = function () {
  37263. this._clear();
  37264. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  37265. this._pixels[0] = 0;
  37266. this._pixels[1] = 0;
  37267. this._pixels[2] = 0;
  37268. this._pixels[3] = 0;
  37269. this._changedCallback();
  37270. return this;
  37271. };
  37272. PrimitiveThickness.prototype._clear = function () {
  37273. this._flags = 0;
  37274. this._pixels[0] = 0;
  37275. this._pixels[1] = 0;
  37276. this._pixels[2] = 0;
  37277. this._pixels[3] = 0;
  37278. this._percentages[0] = null;
  37279. this._percentages[1] = null;
  37280. this._percentages[2] = null;
  37281. this._percentages[3] = null;
  37282. };
  37283. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  37284. var v = value.trim().toLocaleLowerCase();
  37285. if (v.indexOf("top:") === 0) {
  37286. v = v.substr(4).trim();
  37287. return this._setStringValue(v, 0, emitChanged);
  37288. }
  37289. if (v.indexOf("left:") === 0) {
  37290. v = v.substr(5).trim();
  37291. return this._setStringValue(v, 1, emitChanged);
  37292. }
  37293. if (v.indexOf("right:") === 0) {
  37294. v = v.substr(6).trim();
  37295. return this._setStringValue(v, 2, emitChanged);
  37296. }
  37297. if (v.indexOf("bottom:") === 0) {
  37298. v = v.substr(7).trim();
  37299. return this._setStringValue(v, 3, emitChanged);
  37300. }
  37301. return false;
  37302. };
  37303. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  37304. // Check for auto
  37305. var v = value.trim().toLocaleLowerCase();
  37306. if (v === "auto") {
  37307. if (this._isType(index, PrimitiveThickness.Auto)) {
  37308. return true;
  37309. }
  37310. this._setType(index, PrimitiveThickness.Auto);
  37311. this._pixels[index] = 0;
  37312. if (emitChanged) {
  37313. this._changedCallback();
  37314. }
  37315. }
  37316. else if (v === "inherit") {
  37317. if (this._isType(index, PrimitiveThickness.Inherit)) {
  37318. return true;
  37319. }
  37320. this._setType(index, PrimitiveThickness.Inherit);
  37321. this._pixels[index] = null;
  37322. if (emitChanged) {
  37323. this._changedCallback();
  37324. }
  37325. }
  37326. else {
  37327. var pI = v.indexOf("%");
  37328. // Check for percentage
  37329. if (pI !== -1) {
  37330. var n_1 = v.substr(0, pI);
  37331. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  37332. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number_1)) {
  37333. return true;
  37334. }
  37335. this._setType(index, PrimitiveThickness.Percentage);
  37336. if (isNaN(number_1)) {
  37337. return false;
  37338. }
  37339. this._percentages[index] = number_1;
  37340. if (emitChanged) {
  37341. this._changedCallback();
  37342. }
  37343. return true;
  37344. }
  37345. // Check for pixel
  37346. var n;
  37347. pI = v.indexOf("px");
  37348. if (pI !== -1) {
  37349. n = v.substr(0, pI).trim();
  37350. }
  37351. else {
  37352. n = v;
  37353. }
  37354. var number = Number(n);
  37355. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  37356. return true;
  37357. }
  37358. if (isNaN(number)) {
  37359. return false;
  37360. }
  37361. this._pixels[index] = number;
  37362. this._setType(index, PrimitiveThickness.Pixel);
  37363. if (emitChanged) {
  37364. this._changedCallback();
  37365. }
  37366. return true;
  37367. }
  37368. };
  37369. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  37370. // Round the value because, well, it's the thing to do! Otherwise we'll have sub-pixel stuff, and the no change comparison just below will almost never work for PrimitiveThickness values inside a hierarchy of Primitives
  37371. value = Math.round(value);
  37372. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  37373. return;
  37374. }
  37375. this._setType(index, PrimitiveThickness.Pixel);
  37376. this._pixels[index] = value;
  37377. if (emitChanged) {
  37378. this._changedCallback();
  37379. }
  37380. };
  37381. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  37382. // Clip Value to bounds
  37383. value = Math.min(1, value);
  37384. value = Math.max(0, value);
  37385. value = Math.round(value * 100) / 100; // 0.01 precision
  37386. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  37387. return;
  37388. }
  37389. this._setType(index, PrimitiveThickness.Percentage);
  37390. this._percentages[index] = value;
  37391. if (emitChanged) {
  37392. this._changedCallback();
  37393. }
  37394. };
  37395. PrimitiveThickness.prototype._getStringValue = function (index) {
  37396. var f = (this._flags >> (index * 4)) & 0xF;
  37397. switch (f) {
  37398. case PrimitiveThickness.Auto:
  37399. return "auto";
  37400. case PrimitiveThickness.Pixel:
  37401. return this._pixels[index] + "px";
  37402. case PrimitiveThickness.Percentage:
  37403. return this._percentages[index] * 100 + "%";
  37404. case PrimitiveThickness.Inherit:
  37405. return "inherit";
  37406. }
  37407. return "";
  37408. };
  37409. PrimitiveThickness.prototype._isType = function (index, type) {
  37410. var f = (this._flags >> (index * 4)) & 0xF;
  37411. return f === type;
  37412. };
  37413. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  37414. var t = (this._flags >> (index * 4)) & 0xF;
  37415. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  37416. var p = this._parentAccess();
  37417. if (p) {
  37418. return p._getType(index, true);
  37419. }
  37420. return PrimitiveThickness.Auto;
  37421. }
  37422. return t;
  37423. };
  37424. PrimitiveThickness.prototype._setType = function (index, type) {
  37425. this._flags &= ~(0xF << (index * 4));
  37426. this._flags |= type << (index * 4);
  37427. };
  37428. PrimitiveThickness.prototype.setTop = function (value) {
  37429. if (typeof value === "string") {
  37430. this._setStringValue(value, 0, true);
  37431. }
  37432. else {
  37433. this.topPixels = value;
  37434. }
  37435. };
  37436. PrimitiveThickness.prototype.setLeft = function (value) {
  37437. if (typeof value === "string") {
  37438. this._setStringValue(value, 1, true);
  37439. }
  37440. else {
  37441. this.leftPixels = value;
  37442. }
  37443. };
  37444. PrimitiveThickness.prototype.setRight = function (value) {
  37445. if (typeof value === "string") {
  37446. this._setStringValue(value, 2, true);
  37447. }
  37448. else {
  37449. this.rightPixels = value;
  37450. }
  37451. };
  37452. PrimitiveThickness.prototype.setBottom = function (value) {
  37453. if (typeof value === "string") {
  37454. this._setStringValue(value, 3, true);
  37455. }
  37456. else {
  37457. this.bottomPixels = value;
  37458. }
  37459. };
  37460. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  37461. /**
  37462. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  37463. */
  37464. get: function () {
  37465. return this._getStringValue(0);
  37466. },
  37467. set: function (value) {
  37468. this._setStringValue(value, 0, true);
  37469. },
  37470. enumerable: true,
  37471. configurable: true
  37472. });
  37473. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  37474. /**
  37475. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  37476. */
  37477. get: function () {
  37478. return this._getStringValue(1);
  37479. },
  37480. set: function (value) {
  37481. this._setStringValue(value, 1, true);
  37482. },
  37483. enumerable: true,
  37484. configurable: true
  37485. });
  37486. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  37487. /**
  37488. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  37489. */
  37490. get: function () {
  37491. return this._getStringValue(2);
  37492. },
  37493. set: function (value) {
  37494. this._setStringValue(value, 2, true);
  37495. },
  37496. enumerable: true,
  37497. configurable: true
  37498. });
  37499. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  37500. /**
  37501. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  37502. */
  37503. get: function () {
  37504. return this._getStringValue(3);
  37505. },
  37506. set: function (value) {
  37507. this._setStringValue(value, 3, true);
  37508. },
  37509. enumerable: true,
  37510. configurable: true
  37511. });
  37512. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  37513. /**
  37514. * Get/set the top thickness in pixel.
  37515. */
  37516. get: function () {
  37517. return this._pixels[0];
  37518. },
  37519. set: function (value) {
  37520. this._setPixels(value, 0, true);
  37521. },
  37522. enumerable: true,
  37523. configurable: true
  37524. });
  37525. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  37526. /**
  37527. * Get/set the left thickness in pixel.
  37528. */
  37529. get: function () {
  37530. return this._pixels[1];
  37531. },
  37532. set: function (value) {
  37533. this._setPixels(value, 1, true);
  37534. },
  37535. enumerable: true,
  37536. configurable: true
  37537. });
  37538. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  37539. /**
  37540. * Get/set the right thickness in pixel.
  37541. */
  37542. get: function () {
  37543. return this._pixels[2];
  37544. },
  37545. set: function (value) {
  37546. this._setPixels(value, 2, true);
  37547. },
  37548. enumerable: true,
  37549. configurable: true
  37550. });
  37551. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  37552. /**
  37553. * Get/set the bottom thickness in pixel.
  37554. */
  37555. get: function () {
  37556. return this._pixels[3];
  37557. },
  37558. set: function (value) {
  37559. this._setPixels(value, 3, true);
  37560. },
  37561. enumerable: true,
  37562. configurable: true
  37563. });
  37564. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  37565. /**
  37566. * Get/set the top thickness in percentage.
  37567. * The get will return a valid value only if the edge type is percentage.
  37568. * The Set will change the edge mode if needed
  37569. */
  37570. get: function () {
  37571. return this._percentages[0];
  37572. },
  37573. set: function (value) {
  37574. this._setPercentage(value, 0, true);
  37575. },
  37576. enumerable: true,
  37577. configurable: true
  37578. });
  37579. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  37580. /**
  37581. * Get/set the left thickness in percentage.
  37582. * The get will return a valid value only if the edge mode is percentage.
  37583. * The Set will change the edge mode if needed
  37584. */
  37585. get: function () {
  37586. return this._percentages[1];
  37587. },
  37588. set: function (value) {
  37589. this._setPercentage(value, 1, true);
  37590. },
  37591. enumerable: true,
  37592. configurable: true
  37593. });
  37594. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  37595. /**
  37596. * Get/set the right thickness in percentage.
  37597. * The get will return a valid value only if the edge mode is percentage.
  37598. * The Set will change the edge mode if needed
  37599. */
  37600. get: function () {
  37601. return this._percentages[2];
  37602. },
  37603. set: function (value) {
  37604. this._setPercentage(value, 2, true);
  37605. },
  37606. enumerable: true,
  37607. configurable: true
  37608. });
  37609. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  37610. /**
  37611. * Get/set the bottom thickness in percentage.
  37612. * The get will return a valid value only if the edge mode is percentage.
  37613. * The Set will change the edge mode if needed
  37614. */
  37615. get: function () {
  37616. return this._percentages[3];
  37617. },
  37618. set: function (value) {
  37619. this._setPercentage(value, 3, true);
  37620. },
  37621. enumerable: true,
  37622. configurable: true
  37623. });
  37624. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  37625. /**
  37626. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  37627. */
  37628. get: function () {
  37629. return this._getType(0, false);
  37630. },
  37631. set: function (mode) {
  37632. this._setType(0, mode);
  37633. },
  37634. enumerable: true,
  37635. configurable: true
  37636. });
  37637. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  37638. /**
  37639. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  37640. */
  37641. get: function () {
  37642. return this._getType(1, false);
  37643. },
  37644. set: function (mode) {
  37645. this._setType(1, mode);
  37646. },
  37647. enumerable: true,
  37648. configurable: true
  37649. });
  37650. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  37651. /**
  37652. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  37653. */
  37654. get: function () {
  37655. return this._getType(2, false);
  37656. },
  37657. set: function (mode) {
  37658. this._setType(2, mode);
  37659. },
  37660. enumerable: true,
  37661. configurable: true
  37662. });
  37663. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  37664. /**
  37665. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  37666. */
  37667. get: function () {
  37668. return this._getType(3, false);
  37669. },
  37670. set: function (mode) {
  37671. this._setType(3, mode);
  37672. },
  37673. enumerable: true,
  37674. configurable: true
  37675. });
  37676. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  37677. var type = this._getType(index, false);
  37678. if (type === PrimitiveThickness.Inherit) {
  37679. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  37680. return;
  37681. }
  37682. if (type !== PrimitiveThickness.Percentage) {
  37683. return;
  37684. }
  37685. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  37686. this._pixels[index] = pixels;
  37687. if (emitChanged) {
  37688. this._changedCallback();
  37689. }
  37690. };
  37691. /**
  37692. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  37693. * @param sourceArea the source area
  37694. * @param contentSize the content size to position/resize
  37695. * @param alignment the alignment setting
  37696. * @param dstOffset the position of the content
  37697. * @param dstArea the new size of the content
  37698. */
  37699. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea) {
  37700. // Fetch some data
  37701. var topType = this._getType(0, true);
  37702. var leftType = this._getType(1, true);
  37703. var rightType = this._getType(2, true);
  37704. var bottomType = this._getType(3, true);
  37705. var hasWidth = contentSize && (contentSize.width != null);
  37706. var hasHeight = contentSize && (contentSize.height != null);
  37707. var width = hasWidth ? contentSize.width : 0;
  37708. var height = hasHeight ? contentSize.height : 0;
  37709. var isTopAuto = topType === PrimitiveThickness.Auto;
  37710. var isLeftAuto = leftType === PrimitiveThickness.Auto;
  37711. var isRightAuto = rightType === PrimitiveThickness.Auto;
  37712. var isBottomAuto = bottomType === PrimitiveThickness.Auto;
  37713. switch (alignment.horizontal) {
  37714. case PrimitiveAlignment.AlignLeft:
  37715. {
  37716. if (isLeftAuto) {
  37717. dstOffset.x = 0;
  37718. }
  37719. else {
  37720. this._computePixels(1, sourceArea, true);
  37721. dstOffset.x = this.leftPixels;
  37722. }
  37723. dstArea.width = width;
  37724. break;
  37725. }
  37726. case PrimitiveAlignment.AlignRight:
  37727. {
  37728. if (isRightAuto) {
  37729. dstOffset.x = Math.round(sourceArea.width - width);
  37730. }
  37731. else {
  37732. this._computePixels(2, sourceArea, true);
  37733. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  37734. }
  37735. dstArea.width = width;
  37736. break;
  37737. }
  37738. case PrimitiveAlignment.AlignStretch:
  37739. {
  37740. if (isLeftAuto) {
  37741. dstOffset.x = 0;
  37742. }
  37743. else {
  37744. this._computePixels(1, sourceArea, true);
  37745. dstOffset.x = this.leftPixels;
  37746. }
  37747. var right = 0;
  37748. if (!isRightAuto) {
  37749. this._computePixels(2, sourceArea, true);
  37750. right = this.rightPixels;
  37751. }
  37752. dstArea.width = sourceArea.width - (dstOffset.x + right);
  37753. break;
  37754. }
  37755. case PrimitiveAlignment.AlignCenter:
  37756. {
  37757. if (!isLeftAuto) {
  37758. this._computePixels(1, sourceArea, true);
  37759. }
  37760. if (!isRightAuto) {
  37761. this._computePixels(2, sourceArea, true);
  37762. }
  37763. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  37764. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  37765. dstArea.width = width;
  37766. break;
  37767. }
  37768. }
  37769. switch (alignment.vertical) {
  37770. case PrimitiveAlignment.AlignTop:
  37771. {
  37772. if (isTopAuto) {
  37773. dstOffset.y = sourceArea.height - height;
  37774. }
  37775. else {
  37776. this._computePixels(0, sourceArea, true);
  37777. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  37778. }
  37779. dstArea.height = height;
  37780. break;
  37781. }
  37782. case PrimitiveAlignment.AlignBottom:
  37783. {
  37784. if (isBottomAuto) {
  37785. dstOffset.y = 0;
  37786. }
  37787. else {
  37788. this._computePixels(3, sourceArea, true);
  37789. dstOffset.y = this.bottomPixels;
  37790. }
  37791. dstArea.height = height;
  37792. break;
  37793. }
  37794. case PrimitiveAlignment.AlignStretch:
  37795. {
  37796. if (isBottomAuto) {
  37797. dstOffset.y = 0;
  37798. }
  37799. else {
  37800. this._computePixels(3, sourceArea, true);
  37801. dstOffset.y = this.bottomPixels;
  37802. }
  37803. var top_1 = 0;
  37804. if (!isTopAuto) {
  37805. this._computePixels(0, sourceArea, true);
  37806. top_1 = this.topPixels;
  37807. }
  37808. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  37809. break;
  37810. }
  37811. case PrimitiveAlignment.AlignCenter:
  37812. {
  37813. if (!isTopAuto) {
  37814. this._computePixels(0, sourceArea, true);
  37815. }
  37816. if (!isBottomAuto) {
  37817. this._computePixels(3, sourceArea, true);
  37818. }
  37819. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  37820. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  37821. dstArea.height = height;
  37822. break;
  37823. }
  37824. }
  37825. };
  37826. /**
  37827. * Compute an area and its position considering this thickness properties based on a given source area
  37828. * @param sourceArea the source area
  37829. * @param dstOffset the position of the resulting area
  37830. * @param dstArea the size of the resulting area
  37831. */
  37832. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  37833. this._computePixels(0, sourceArea, true);
  37834. this._computePixels(1, sourceArea, true);
  37835. this._computePixels(2, sourceArea, true);
  37836. this._computePixels(3, sourceArea, true);
  37837. dstOffset.x = this.leftPixels;
  37838. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  37839. dstOffset.y = this.bottomPixels;
  37840. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  37841. };
  37842. /**
  37843. * Compute an area considering this thickness properties based on a given source area
  37844. * @param sourceArea the source area
  37845. * @param result the resulting area
  37846. */
  37847. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  37848. this._computePixels(0, sourceArea, true);
  37849. this._computePixels(1, sourceArea, true);
  37850. this._computePixels(2, sourceArea, true);
  37851. this._computePixels(3, sourceArea, true);
  37852. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  37853. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  37854. };
  37855. PrimitiveThickness.Auto = 0x1;
  37856. PrimitiveThickness.Inherit = 0x2;
  37857. PrimitiveThickness.Percentage = 0x4;
  37858. PrimitiveThickness.Pixel = 0x8;
  37859. return PrimitiveThickness;
  37860. })();
  37861. BABYLON.PrimitiveThickness = PrimitiveThickness;
  37862. /**
  37863. * Main class used for the Primitive Intersection API
  37864. */
  37865. var IntersectInfo2D = (function () {
  37866. function IntersectInfo2D() {
  37867. this.findFirstOnly = false;
  37868. this.intersectHidden = false;
  37869. this.pickPosition = BABYLON.Vector2.Zero();
  37870. }
  37871. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  37872. /**
  37873. * true if at least one primitive intersected during the test
  37874. */
  37875. get: function () {
  37876. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  37877. },
  37878. enumerable: true,
  37879. configurable: true
  37880. });
  37881. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  37882. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  37883. var cur = _a[_i];
  37884. if (cur.prim === prim) {
  37885. return cur.intersectionLocation;
  37886. }
  37887. }
  37888. return null;
  37889. };
  37890. // Internals, don't use
  37891. IntersectInfo2D.prototype._exit = function (firstLevel) {
  37892. if (firstLevel) {
  37893. this._globalPickPosition = null;
  37894. }
  37895. };
  37896. return IntersectInfo2D;
  37897. })();
  37898. BABYLON.IntersectInfo2D = IntersectInfo2D;
  37899. var Prim2DBase = (function (_super) {
  37900. __extends(Prim2DBase, _super);
  37901. function Prim2DBase(settings) {
  37902. // Avoid checking every time if the object exists
  37903. if (settings == null) {
  37904. settings = {};
  37905. }
  37906. // BASE CLASS CALL
  37907. _super.call(this);
  37908. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  37909. var owner;
  37910. var parent;
  37911. if (Prim2DBase._isCanvasInit) {
  37912. owner = this;
  37913. parent = null;
  37914. this._canvasPreInit(settings);
  37915. }
  37916. else {
  37917. if (settings.parent != null) {
  37918. parent = settings.parent;
  37919. owner = settings.parent.owner;
  37920. if (!owner) {
  37921. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  37922. }
  37923. if (!(this instanceof BABYLON.Group2D) && !(this instanceof BABYLON.Sprite2D && settings.id !== null && settings.id.indexOf("__cachedSpriteOfGroup__") === 0) && (owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) && (parent === owner)) {
  37924. throw new Error("Can't create a primitive with the canvas as direct parent when the caching strategy is TOPLEVELGROUPS. You need to create a Group below the canvas and use it as the parent for the primitive");
  37925. }
  37926. }
  37927. }
  37928. // Fields initialization
  37929. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  37930. this._size = null; //Size.Zero();
  37931. this._actualSize = null;
  37932. this._boundingSize = null;
  37933. this._layoutArea = BABYLON.Size.Zero();
  37934. this._layoutAreaPos = BABYLON.Vector2.Zero();
  37935. this._marginOffset = BABYLON.Vector2.Zero();
  37936. this._parentMargingOffset = BABYLON.Vector2.Zero();
  37937. this._parentContentArea = BABYLON.Size.Zero();
  37938. this._contentArea = new BABYLON.Size(null, null);
  37939. this._pointerEventObservable = new BABYLON.Observable();
  37940. this._siblingDepthOffset = this._hierarchyDepthOffset = 0;
  37941. this._boundingInfo = new BABYLON.BoundingInfo2D();
  37942. this._owner = owner;
  37943. this._parent = null;
  37944. this._margin = null;
  37945. this._padding = null;
  37946. this._marginAlignment = null;
  37947. this._id = settings.id;
  37948. this.propertyChanged = new BABYLON.Observable();
  37949. this._children = new Array();
  37950. this._localTransform = new BABYLON.Matrix();
  37951. this._globalTransform = null;
  37952. this._invGlobalTransform = null;
  37953. this._globalTransformProcessStep = 0;
  37954. this._globalTransformStep = 0;
  37955. this._hierarchyDepth = 0;
  37956. this._renderGroup = null;
  37957. this._setFlags(BABYLON.SmartPropertyPrim.flagIsPickable | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  37958. // If the parent is given, initialize the hierarchy/owner related data
  37959. if (parent != null) {
  37960. parent.addChild(this);
  37961. this._patchHierarchy(parent.owner);
  37962. }
  37963. // If it's a group, detect its own states
  37964. if (this.owner && this instanceof BABYLON.Group2D) {
  37965. var group = this;
  37966. group.detectGroupStates();
  37967. }
  37968. // Time to insert children if some are specified
  37969. if (settings.children != null) {
  37970. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  37971. var child = _a[_i];
  37972. this.addChild(child);
  37973. // Good time to patch the hierarchy, it won't go very far if there's no need to
  37974. child._patchHierarchy(this.owner);
  37975. }
  37976. }
  37977. // Set the model related properties
  37978. if (settings.position != null) {
  37979. this.position = settings.position;
  37980. }
  37981. else if (settings.x != null || settings.y != null) {
  37982. this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  37983. }
  37984. else {
  37985. this._position = null;
  37986. }
  37987. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  37988. this.scale = (settings.scale == null) ? 1 : settings.scale;
  37989. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  37990. this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  37991. // Layout Engine
  37992. if (settings.layoutEngine != null) {
  37993. if (typeof settings.layoutEngine === "string") {
  37994. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  37995. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  37996. this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  37997. }
  37998. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  37999. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  38000. }
  38001. else if (name_1.indexOf("verticalstackpanel") === 0) {
  38002. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  38003. }
  38004. }
  38005. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  38006. this.layoutEngine = settings.layoutEngine;
  38007. }
  38008. }
  38009. // Set the layout/margin stuffs
  38010. if (settings.marginTop) {
  38011. this.margin.setTop(settings.marginTop);
  38012. }
  38013. if (settings.marginLeft) {
  38014. this.margin.setLeft(settings.marginLeft);
  38015. }
  38016. if (settings.marginRight) {
  38017. this.margin.setRight(settings.marginRight);
  38018. }
  38019. if (settings.marginBottom) {
  38020. this.margin.setBottom(settings.marginBottom);
  38021. }
  38022. if (settings.margin) {
  38023. if (typeof settings.margin === "string") {
  38024. this.margin.fromString(settings.margin);
  38025. }
  38026. else {
  38027. this.margin.fromUniformPixels(settings.margin);
  38028. }
  38029. }
  38030. if (settings.marginHAlignment) {
  38031. this.marginAlignment.horizontal = settings.marginHAlignment;
  38032. }
  38033. if (settings.marginVAlignment) {
  38034. this.marginAlignment.vertical = settings.marginVAlignment;
  38035. }
  38036. if (settings.marginAlignment) {
  38037. this.marginAlignment.fromString(settings.marginAlignment);
  38038. }
  38039. if (settings.paddingTop) {
  38040. this.padding.setTop(settings.paddingTop);
  38041. }
  38042. if (settings.paddingLeft) {
  38043. this.padding.setLeft(settings.paddingLeft);
  38044. }
  38045. if (settings.paddingRight) {
  38046. this.padding.setRight(settings.paddingRight);
  38047. }
  38048. if (settings.paddingBottom) {
  38049. this.padding.setBottom(settings.paddingBottom);
  38050. }
  38051. if (settings.padding) {
  38052. this.padding.fromString(settings.padding);
  38053. }
  38054. // Dirty layout and positioning
  38055. this._parentLayoutDirty();
  38056. this._positioningDirty();
  38057. }
  38058. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  38059. get: function () {
  38060. if (!this._actionManager) {
  38061. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  38062. }
  38063. return this._actionManager;
  38064. },
  38065. enumerable: true,
  38066. configurable: true
  38067. });
  38068. /**
  38069. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  38070. * @param predicate the predicate to test on each parent
  38071. * @return the first primitive where the predicate was successful
  38072. */
  38073. Prim2DBase.prototype.traverseUp = function (predicate) {
  38074. var p = this;
  38075. while (p != null) {
  38076. if (predicate(p)) {
  38077. return p;
  38078. }
  38079. p = p._parent;
  38080. }
  38081. return null;
  38082. };
  38083. Object.defineProperty(Prim2DBase.prototype, "owner", {
  38084. /**
  38085. * Retrieve the owner Canvas2D
  38086. */
  38087. get: function () {
  38088. return this._owner;
  38089. },
  38090. enumerable: true,
  38091. configurable: true
  38092. });
  38093. Object.defineProperty(Prim2DBase.prototype, "parent", {
  38094. /**
  38095. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  38096. */
  38097. get: function () {
  38098. return this._parent;
  38099. },
  38100. enumerable: true,
  38101. configurable: true
  38102. });
  38103. Object.defineProperty(Prim2DBase.prototype, "children", {
  38104. /**
  38105. * The array of direct children primitives
  38106. */
  38107. get: function () {
  38108. return this._children;
  38109. },
  38110. enumerable: true,
  38111. configurable: true
  38112. });
  38113. Object.defineProperty(Prim2DBase.prototype, "id", {
  38114. /**
  38115. * The identifier of this primitive, may not be unique, it's for information purpose only
  38116. */
  38117. get: function () {
  38118. return this._id;
  38119. },
  38120. enumerable: true,
  38121. configurable: true
  38122. });
  38123. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  38124. get: function () {
  38125. if (this._actualPosition != null) {
  38126. return this._actualPosition;
  38127. }
  38128. if (this._position != null) {
  38129. return this._position;
  38130. }
  38131. // At least return 0,0, we can't return null on actualPosition
  38132. return Prim2DBase._nullPosition;
  38133. },
  38134. /**
  38135. * DO NOT INVOKE for internal purpose only
  38136. */
  38137. set: function (val) {
  38138. this._actualPosition = val;
  38139. },
  38140. enumerable: true,
  38141. configurable: true
  38142. });
  38143. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  38144. /**
  38145. * Shortcut to actualPosition.x
  38146. */
  38147. get: function () {
  38148. return this.actualPosition.x;
  38149. },
  38150. enumerable: true,
  38151. configurable: true
  38152. });
  38153. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  38154. /**
  38155. * Shortcut to actualPosition.y
  38156. */
  38157. get: function () {
  38158. return this.actualPosition.y;
  38159. },
  38160. enumerable: true,
  38161. configurable: true
  38162. });
  38163. Object.defineProperty(Prim2DBase.prototype, "position", {
  38164. /**
  38165. * Position of the primitive, relative to its parent.
  38166. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  38167. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  38168. * Setting this property may have no effect is specific alignment are in effect.
  38169. */
  38170. get: function () {
  38171. return this._position;
  38172. },
  38173. set: function (value) {
  38174. if (!this._checkPositionChange()) {
  38175. return;
  38176. }
  38177. this._position = value;
  38178. },
  38179. enumerable: true,
  38180. configurable: true
  38181. });
  38182. Object.defineProperty(Prim2DBase.prototype, "x", {
  38183. /**
  38184. * Direct access to the position.x value of the primitive
  38185. * Use this property when you only want to change one component of the position property
  38186. */
  38187. get: function () {
  38188. if (!this._position) {
  38189. return null;
  38190. }
  38191. return this._position.x;
  38192. },
  38193. set: function (value) {
  38194. if (!this._checkPositionChange()) {
  38195. return;
  38196. }
  38197. if (!this._position) {
  38198. this._position = BABYLON.Vector2.Zero();
  38199. }
  38200. if (this._position.x === value) {
  38201. return;
  38202. }
  38203. this._position.x = value;
  38204. this.markAsDirty("position");
  38205. },
  38206. enumerable: true,
  38207. configurable: true
  38208. });
  38209. Object.defineProperty(Prim2DBase.prototype, "y", {
  38210. /**
  38211. * Direct access to the position.y value of the primitive
  38212. * Use this property when you only want to change one component of the position property
  38213. */
  38214. get: function () {
  38215. if (!this._position) {
  38216. return null;
  38217. }
  38218. return this._position.y;
  38219. },
  38220. set: function (value) {
  38221. if (!this._checkPositionChange()) {
  38222. return;
  38223. }
  38224. if (!this._position) {
  38225. this._position = BABYLON.Vector2.Zero();
  38226. }
  38227. if (this._position.y === value) {
  38228. return;
  38229. }
  38230. this._position.y = value;
  38231. this.markAsDirty("position");
  38232. },
  38233. enumerable: true,
  38234. configurable: true
  38235. });
  38236. Object.defineProperty(Prim2DBase.prototype, "size", {
  38237. /**
  38238. * Size of the primitive or its bounding area
  38239. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  38240. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  38241. */
  38242. get: function () {
  38243. if (!this._size || this._size.width == null || this._size.height == null) {
  38244. if (Prim2DBase.boundinbBoxReentrency) {
  38245. return Prim2DBase.nullSize;
  38246. }
  38247. if (this._boundingSize) {
  38248. return this._boundingSize;
  38249. }
  38250. Prim2DBase.boundinbBoxReentrency = true;
  38251. var b = this.boundingInfo;
  38252. Prim2DBase.boundinbBoxReentrency = false;
  38253. return this._boundingSize;
  38254. }
  38255. return this._size;
  38256. },
  38257. set: function (value) {
  38258. this._size = value;
  38259. },
  38260. enumerable: true,
  38261. configurable: true
  38262. });
  38263. Object.defineProperty(Prim2DBase.prototype, "width", {
  38264. /**
  38265. * Direct access to the size.width value of the primitive
  38266. * Use this property when you only want to change one component of the size property
  38267. */
  38268. get: function () {
  38269. if (!this.size) {
  38270. return null;
  38271. }
  38272. return this.size.width;
  38273. },
  38274. set: function (value) {
  38275. if (!this.size) {
  38276. this.size = new BABYLON.Size(value, 0);
  38277. return;
  38278. }
  38279. if (this.size.width === value) {
  38280. return;
  38281. }
  38282. this.size.width = value;
  38283. this.markAsDirty("size");
  38284. this._positioningDirty();
  38285. },
  38286. enumerable: true,
  38287. configurable: true
  38288. });
  38289. Object.defineProperty(Prim2DBase.prototype, "height", {
  38290. /**
  38291. * Direct access to the size.height value of the primitive
  38292. * Use this property when you only want to change one component of the size property
  38293. */
  38294. get: function () {
  38295. if (!this.size) {
  38296. return null;
  38297. }
  38298. return this.size.height;
  38299. },
  38300. set: function (value) {
  38301. if (!this.size) {
  38302. this.size = new BABYLON.Size(0, value);
  38303. return;
  38304. }
  38305. if (this.size.height === value) {
  38306. return;
  38307. }
  38308. this.size.height = value;
  38309. this.markAsDirty("size");
  38310. this._positioningDirty();
  38311. },
  38312. enumerable: true,
  38313. configurable: true
  38314. });
  38315. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  38316. get: function () {
  38317. return this._rotation;
  38318. },
  38319. set: function (value) {
  38320. this._rotation = value;
  38321. },
  38322. enumerable: true,
  38323. configurable: true
  38324. });
  38325. Object.defineProperty(Prim2DBase.prototype, "scale", {
  38326. get: function () {
  38327. return this._scale;
  38328. },
  38329. set: function (value) {
  38330. this._scale = value;
  38331. },
  38332. enumerable: true,
  38333. configurable: true
  38334. });
  38335. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  38336. /**
  38337. * Return the size of the primitive as it's being rendered into the target.
  38338. * This value may be different of the size property when layout/alignment is used or specific primitive types can implement a custom logic through this property.
  38339. * BEWARE: don't use the setter, it's for internal purpose only
  38340. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  38341. */
  38342. get: function () {
  38343. if (this._actualSize) {
  38344. return this._actualSize;
  38345. }
  38346. return this._size;
  38347. },
  38348. set: function (value) {
  38349. if (this._actualSize.equals(value)) {
  38350. return;
  38351. }
  38352. this._actualSize = value;
  38353. },
  38354. enumerable: true,
  38355. configurable: true
  38356. });
  38357. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  38358. get: function () {
  38359. return this._zOrder || (1 - this._hierarchyDepthOffset);
  38360. },
  38361. enumerable: true,
  38362. configurable: true
  38363. });
  38364. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  38365. /**
  38366. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  38367. * The Primitive's size won't be less than specified.
  38368. * The default value depends of the Primitive type
  38369. */
  38370. get: function () {
  38371. return this._minSize;
  38372. },
  38373. set: function (value) {
  38374. if (this._minSize && value && this._minSize.equals(value)) {
  38375. return;
  38376. }
  38377. this._minSize = value;
  38378. this._parentLayoutDirty();
  38379. },
  38380. enumerable: true,
  38381. configurable: true
  38382. });
  38383. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  38384. /**
  38385. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  38386. * The Primitive's size won't be more than specified.
  38387. * The default value depends of the Primitive type
  38388. */
  38389. get: function () {
  38390. return this._maxSize;
  38391. },
  38392. set: function (value) {
  38393. if (this._maxSize && value && this._maxSize.equals(value)) {
  38394. return;
  38395. }
  38396. this._maxSize = value;
  38397. this._parentLayoutDirty();
  38398. },
  38399. enumerable: true,
  38400. configurable: true
  38401. });
  38402. Object.defineProperty(Prim2DBase.prototype, "origin", {
  38403. /**
  38404. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  38405. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  38406. * For instance:
  38407. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  38408. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  38409. * 0,1 means the center is top/left
  38410. * @returns The normalized center.
  38411. */
  38412. get: function () {
  38413. return this._origin;
  38414. },
  38415. set: function (value) {
  38416. this._origin = value;
  38417. },
  38418. enumerable: true,
  38419. configurable: true
  38420. });
  38421. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  38422. get: function () {
  38423. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  38424. },
  38425. set: function (value) {
  38426. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  38427. },
  38428. enumerable: true,
  38429. configurable: true
  38430. });
  38431. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  38432. get: function () {
  38433. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  38434. },
  38435. set: function (value) {
  38436. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  38437. },
  38438. enumerable: true,
  38439. configurable: true
  38440. });
  38441. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  38442. get: function () {
  38443. return this._zOrder;
  38444. },
  38445. set: function (value) {
  38446. this._zOrder = value;
  38447. this.onZOrderChanged();
  38448. },
  38449. enumerable: true,
  38450. configurable: true
  38451. });
  38452. Object.defineProperty(Prim2DBase.prototype, "margin", {
  38453. get: function () {
  38454. var _this = this;
  38455. if (!this._margin) {
  38456. this._margin = new PrimitiveThickness(function () {
  38457. if (!_this.parent) {
  38458. return null;
  38459. }
  38460. return _this.parent.margin;
  38461. }, function () { return _this._positioningDirty(); });
  38462. }
  38463. return this._margin;
  38464. },
  38465. enumerable: true,
  38466. configurable: true
  38467. });
  38468. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  38469. get: function () {
  38470. return (this._margin !== null) || (this._marginAlignment !== null);
  38471. },
  38472. enumerable: true,
  38473. configurable: true
  38474. });
  38475. Object.defineProperty(Prim2DBase.prototype, "padding", {
  38476. get: function () {
  38477. var _this = this;
  38478. if (!this._padding) {
  38479. this._padding = new PrimitiveThickness(function () {
  38480. if (!_this.parent) {
  38481. return null;
  38482. }
  38483. return _this.parent.padding;
  38484. }, function () { return _this._positioningDirty(); });
  38485. }
  38486. return this._padding;
  38487. },
  38488. enumerable: true,
  38489. configurable: true
  38490. });
  38491. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  38492. get: function () {
  38493. return this._padding !== null;
  38494. },
  38495. enumerable: true,
  38496. configurable: true
  38497. });
  38498. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  38499. get: function () {
  38500. var _this = this;
  38501. if (!this._marginAlignment) {
  38502. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  38503. }
  38504. return this._marginAlignment;
  38505. },
  38506. enumerable: true,
  38507. configurable: true
  38508. });
  38509. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  38510. /**
  38511. * Get/set the layout engine to use for this primitive.
  38512. * The default layout engine is the CanvasLayoutEngine.
  38513. */
  38514. get: function () {
  38515. if (!this._layoutEngine) {
  38516. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  38517. }
  38518. return this._layoutEngine;
  38519. },
  38520. set: function (value) {
  38521. if (this._layoutEngine === value) {
  38522. return;
  38523. }
  38524. this._changeLayoutEngine(value);
  38525. },
  38526. enumerable: true,
  38527. configurable: true
  38528. });
  38529. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  38530. /**
  38531. * Get/set the layout are of this primitive.
  38532. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  38533. * The setter should only be called by a Layout Engine class.
  38534. */
  38535. get: function () {
  38536. return this._layoutArea;
  38537. },
  38538. set: function (val) {
  38539. if (this._layoutArea.equals(val)) {
  38540. return;
  38541. }
  38542. this._positioningDirty();
  38543. this._layoutArea = val;
  38544. },
  38545. enumerable: true,
  38546. configurable: true
  38547. });
  38548. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  38549. /**
  38550. * Get/set the layout area position (relative to the parent primitive).
  38551. * The setter should only be called by a Layout Engine class.
  38552. */
  38553. get: function () {
  38554. return this._layoutAreaPos;
  38555. },
  38556. set: function (val) {
  38557. if (this._layoutAreaPos.equals(val)) {
  38558. return;
  38559. }
  38560. this._positioningDirty();
  38561. this._layoutAreaPos = val;
  38562. },
  38563. enumerable: true,
  38564. configurable: true
  38565. });
  38566. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  38567. /**
  38568. * Define if the Primitive can be subject to intersection test or not (default is true)
  38569. */
  38570. get: function () {
  38571. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  38572. },
  38573. set: function (value) {
  38574. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  38575. },
  38576. enumerable: true,
  38577. configurable: true
  38578. });
  38579. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  38580. /**
  38581. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  38582. */
  38583. get: function () {
  38584. return this._hierarchyDepth;
  38585. },
  38586. enumerable: true,
  38587. configurable: true
  38588. });
  38589. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  38590. /**
  38591. * Retrieve the Group that is responsible to render this primitive
  38592. */
  38593. get: function () {
  38594. return this._renderGroup;
  38595. },
  38596. enumerable: true,
  38597. configurable: true
  38598. });
  38599. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  38600. /**
  38601. * Get the global transformation matrix of the primitive
  38602. */
  38603. get: function () {
  38604. return this._globalTransform;
  38605. },
  38606. enumerable: true,
  38607. configurable: true
  38608. });
  38609. /**
  38610. * return the global position of the primitive, relative to its canvas
  38611. */
  38612. Prim2DBase.prototype.getGlobalPosition = function () {
  38613. var v = new BABYLON.Vector2(0, 0);
  38614. this.getGlobalPositionByRef(v);
  38615. return v;
  38616. };
  38617. /**
  38618. * return the global position of the primitive, relative to its canvas
  38619. * @param v the valid Vector2 object where the global position will be stored
  38620. */
  38621. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  38622. v.x = this.globalTransform.m[12];
  38623. v.y = this.globalTransform.m[13];
  38624. };
  38625. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  38626. /**
  38627. * Get invert of the global transformation matrix of the primitive
  38628. */
  38629. get: function () {
  38630. return this._invGlobalTransform;
  38631. },
  38632. enumerable: true,
  38633. configurable: true
  38634. });
  38635. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  38636. /**
  38637. * Get the local transformation of the primitive
  38638. */
  38639. get: function () {
  38640. this._updateLocalTransform();
  38641. return this._localTransform;
  38642. },
  38643. enumerable: true,
  38644. configurable: true
  38645. });
  38646. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  38647. /**
  38648. * Get the boundingInfo associated to the primitive and its children.
  38649. * The value is supposed to be always up to date
  38650. */
  38651. get: function () {
  38652. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  38653. this._boundingInfo = this.levelBoundingInfo.clone();
  38654. var bi = this._boundingInfo;
  38655. var tps = new BABYLON.BoundingInfo2D();
  38656. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  38657. var curChild = _a[_i];
  38658. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  38659. bi.unionToRef(tps, bi);
  38660. }
  38661. this._boundingSize = BABYLON.Size.Zero();
  38662. var m = this._boundingInfo.max();
  38663. this._boundingSize = new BABYLON.Size((!this._size || this._size.width == null) ? Math.ceil(m.x) : this._size.width, (!this._size || this._size.height == null) ? Math.ceil(m.y) : this._size.height);
  38664. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  38665. }
  38666. return this._boundingInfo;
  38667. },
  38668. enumerable: true,
  38669. configurable: true
  38670. });
  38671. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  38672. /**
  38673. * Determine if the size is automatically computed or fixed because manually specified.
  38674. * Use the actualSize property to get the final/real size of the primitive
  38675. * @returns true if the size is automatically computed, false if it were manually specified.
  38676. */
  38677. get: function () {
  38678. return this._size == null;
  38679. },
  38680. enumerable: true,
  38681. configurable: true
  38682. });
  38683. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  38684. /**
  38685. * Determine if the position is automatically computed or fixed because manually specified.
  38686. * Use the actualPosition property to get the final/real position of the primitive
  38687. * @returns true if the position is automatically computed, false if it were manually specified.
  38688. */
  38689. get: function () {
  38690. return this._position == null;
  38691. },
  38692. enumerable: true,
  38693. configurable: true
  38694. });
  38695. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  38696. /**
  38697. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  38698. */
  38699. get: function () {
  38700. return this._pointerEventObservable;
  38701. },
  38702. enumerable: true,
  38703. configurable: true
  38704. });
  38705. Prim2DBase.prototype.findById = function (id) {
  38706. if (this._id === id) {
  38707. return this;
  38708. }
  38709. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  38710. var child = _a[_i];
  38711. var r = child.findById(id);
  38712. if (r != null) {
  38713. return r;
  38714. }
  38715. }
  38716. };
  38717. Prim2DBase.prototype.onZOrderChanged = function () {
  38718. };
  38719. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  38720. return false;
  38721. };
  38722. /**
  38723. * Capture all the Events of the given PointerId for this primitive.
  38724. * Don't forget to call releasePointerEventsCapture when done.
  38725. * @param pointerId the Id of the pointer to capture the events from.
  38726. */
  38727. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  38728. return this.owner._setPointerCapture(pointerId, this);
  38729. };
  38730. /**
  38731. * Release a captured pointer made with setPointerEventCapture.
  38732. * @param pointerId the Id of the pointer to release the capture from.
  38733. */
  38734. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  38735. return this.owner._releasePointerCapture(pointerId, this);
  38736. };
  38737. /**
  38738. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  38739. * @param intersectInfo contains the settings of the intersection to perform, to setup before calling this method as well as the result, available after a call to this method.
  38740. */
  38741. Prim2DBase.prototype.intersect = function (intersectInfo) {
  38742. if (!intersectInfo) {
  38743. return false;
  38744. }
  38745. // If this is null it means this method is call for the first level, initialize stuffs
  38746. var firstLevel = !intersectInfo._globalPickPosition;
  38747. if (firstLevel) {
  38748. // Compute the pickPosition in global space and use it to find the local position for each level down, always relative from the world to get the maximum accuracy (and speed). The other way would have been to compute in local every level down relative to its parent's local, which wouldn't be as accurate (even if javascript number is 80bits accurate).
  38749. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  38750. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  38751. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  38752. intersectInfo.intersectedPrimitives = new Array();
  38753. intersectInfo.topMostIntersectedPrimitive = null;
  38754. }
  38755. if (!intersectInfo.intersectHidden && !this.isVisible) {
  38756. return false;
  38757. }
  38758. // Fast rejection test with boundingInfo
  38759. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  38760. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  38761. intersectInfo._exit(firstLevel);
  38762. return false;
  38763. }
  38764. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  38765. var levelIntersectRes = false;
  38766. if (this.isPickable) {
  38767. levelIntersectRes = this.levelIntersect(intersectInfo);
  38768. if (levelIntersectRes) {
  38769. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  38770. intersectInfo.intersectedPrimitives.push(pii);
  38771. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  38772. intersectInfo.topMostIntersectedPrimitive = pii;
  38773. }
  38774. // If we must stop at the first intersection, we're done, quit!
  38775. if (intersectInfo.findFirstOnly) {
  38776. intersectInfo._exit(firstLevel);
  38777. return true;
  38778. }
  38779. }
  38780. }
  38781. // Recurse to children if needed
  38782. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  38783. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  38784. var curChild = _a[_i];
  38785. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  38786. if (!curChild.isPickable || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  38787. continue;
  38788. }
  38789. // Must compute the localPickLocation for the children level
  38790. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  38791. // If we got an intersection with the child and we only need to find the first one, quit!
  38792. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  38793. intersectInfo._exit(firstLevel);
  38794. return true;
  38795. }
  38796. }
  38797. }
  38798. intersectInfo._exit(firstLevel);
  38799. return intersectInfo.isIntersected;
  38800. };
  38801. Prim2DBase.prototype.moveChild = function (child, previous) {
  38802. if (child.parent !== this) {
  38803. return false;
  38804. }
  38805. var prevOffset, nextOffset;
  38806. var childIndex = this._children.indexOf(child);
  38807. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  38808. // Move to first position
  38809. if (!previous) {
  38810. prevOffset = 1;
  38811. nextOffset = this._children[1]._siblingDepthOffset;
  38812. }
  38813. else {
  38814. prevOffset = this._children[prevIndex]._siblingDepthOffset;
  38815. nextOffset = this._children[prevIndex + 1]._siblingDepthOffset;
  38816. }
  38817. child._siblingDepthOffset = (nextOffset - prevOffset) / 2;
  38818. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  38819. };
  38820. Prim2DBase.prototype.addChild = function (child) {
  38821. child._parent = this;
  38822. this._boundingBoxDirty();
  38823. this._patchHierarchyDepth(child);
  38824. this._children.push(child);
  38825. };
  38826. /**
  38827. * Dispose the primitive, remove it from its parent.
  38828. */
  38829. Prim2DBase.prototype.dispose = function () {
  38830. if (!_super.prototype.dispose.call(this)) {
  38831. return false;
  38832. }
  38833. if (this._actionManager) {
  38834. this._actionManager.dispose();
  38835. this._actionManager = null;
  38836. }
  38837. // If there's a parent, remove this object from its parent list
  38838. if (this._parent) {
  38839. var i = this._parent._children.indexOf(this);
  38840. if (i !== undefined) {
  38841. this._parent._children.splice(i, 1);
  38842. }
  38843. this._parent = null;
  38844. }
  38845. // Recurse dispose to children
  38846. if (this._children) {
  38847. while (this._children.length > 0) {
  38848. this._children[this._children.length - 1].dispose();
  38849. }
  38850. }
  38851. return true;
  38852. };
  38853. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  38854. if (this._renderGroup) {
  38855. this._renderGroup._addPrimToDirtyList(this);
  38856. }
  38857. };
  38858. Prim2DBase.prototype._needPrepare = function () {
  38859. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  38860. };
  38861. Prim2DBase.prototype._prepareRender = function (context) {
  38862. this._prepareRenderPre(context);
  38863. this._prepareRenderPost(context);
  38864. };
  38865. Prim2DBase.prototype._prepareRenderPre = function (context) {
  38866. };
  38867. Prim2DBase.prototype._prepareRenderPost = function (context) {
  38868. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  38869. if (this instanceof BABYLON.Group2D) {
  38870. var self = this;
  38871. if (self.isRenderableGroup) {
  38872. return;
  38873. }
  38874. }
  38875. // Check if we need to recurse the prepare to children primitives
  38876. // - must have children
  38877. // - the global transform of this level have changed, or
  38878. // - the visible state of primitive has changed
  38879. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  38880. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  38881. this._children.forEach(function (c) {
  38882. // As usual stop the recursion if we meet a renderable group
  38883. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  38884. c._prepareRender(context);
  38885. }
  38886. });
  38887. }
  38888. // Finally reset the dirty flags as we've processed everything
  38889. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  38890. this._instanceDirtyFlags = 0;
  38891. };
  38892. Prim2DBase.prototype._canvasPreInit = function (settings) {
  38893. };
  38894. Prim2DBase.CheckParent = function (parent) {
  38895. //if (!Prim2DBase._isCanvasInit && !parent) {
  38896. // throw new Error("A Primitive needs a valid Parent, it can be any kind of Primitives based types, even the Canvas (with the exception that only Group2D can be direct child of a Canvas if the cache strategy used is TOPLEVELGROUPS)");
  38897. //}
  38898. };
  38899. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  38900. for (var _i = 0; _i < list.length; _i++) {
  38901. var cur = list[_i];
  38902. cur.updateCachedStates(recurse);
  38903. }
  38904. };
  38905. Prim2DBase.prototype._parentLayoutDirty = function () {
  38906. if (!this._parent || this._parent.isDisposed) {
  38907. return;
  38908. }
  38909. this._parent._setLayoutDirty();
  38910. };
  38911. Prim2DBase.prototype._setLayoutDirty = function () {
  38912. if (!this.isDirty) {
  38913. this.onPrimBecomesDirty();
  38914. }
  38915. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  38916. };
  38917. Prim2DBase.prototype._checkPositionChange = function () {
  38918. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  38919. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  38920. return false;
  38921. }
  38922. return true;
  38923. };
  38924. Prim2DBase.prototype._positioningDirty = function () {
  38925. if (!this.isDirty) {
  38926. this.onPrimBecomesDirty();
  38927. }
  38928. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  38929. };
  38930. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  38931. this._layoutEngine = engine;
  38932. };
  38933. Prim2DBase.prototype._updateLocalTransform = function () {
  38934. var parentMarginOffsetChanged = false;
  38935. var parentMarginOffset = null;
  38936. if (this._parent) {
  38937. parentMarginOffset = this._parent._marginOffset;
  38938. parentMarginOffsetChanged = !parentMarginOffset.equals(this._parentMargingOffset);
  38939. this._parentMargingOffset.copyFrom(parentMarginOffset);
  38940. }
  38941. else {
  38942. parentMarginOffset = Prim2DBase._v0;
  38943. }
  38944. var tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.originProperty.flagId;
  38945. if (parentMarginOffsetChanged || this.checkPropertiesDirty(tflags)) {
  38946. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  38947. var local;
  38948. if (this._origin.x === 0 && this._origin.y === 0) {
  38949. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale, this._scale, 1), rot, new BABYLON.Vector3(this.actualPosition.x + parentMarginOffset.x, this.actualPosition.y + parentMarginOffset.y, 0));
  38950. this._localTransform = local;
  38951. }
  38952. else {
  38953. // -Origin offset
  38954. var as = this.actualSize;
  38955. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  38956. // -Origin * rotation
  38957. rot.toRotationMatrix(Prim2DBase._t1);
  38958. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  38959. // -Origin * rotation * scale
  38960. BABYLON.Matrix.ScalingToRef(this._scale, this._scale, 1, Prim2DBase._t0);
  38961. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  38962. // -Origin * rotation * scale * (Origin + Position + Parent Margin Offset)
  38963. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + this.actualPosition.x + parentMarginOffset.x, (as.height * this._origin.y) + this.actualPosition.y + parentMarginOffset.y, 0, Prim2DBase._t2);
  38964. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  38965. }
  38966. this.clearPropertiesDirty(tflags);
  38967. return true;
  38968. }
  38969. return false;
  38970. };
  38971. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  38972. if (this.isDisposed) {
  38973. return;
  38974. }
  38975. // Check if the parent is synced
  38976. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty))) {
  38977. this._parent.updateCachedStates(false);
  38978. }
  38979. // Update actualSize only if there' not positioning to recompute and the size changed
  38980. // Otherwise positioning will take care of it.
  38981. var sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  38982. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && sizeDirty) {
  38983. var size = this.size;
  38984. if (size) {
  38985. if (this.size.width != null) {
  38986. this.actualSize.width = this.size.width;
  38987. }
  38988. if (this.size.height != null) {
  38989. this.actualSize.height = this.size.height;
  38990. }
  38991. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  38992. }
  38993. }
  38994. // Check for layout update
  38995. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  38996. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  38997. this._layoutEngine.updateLayout(this);
  38998. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  38999. }
  39000. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39001. // Check for positioning update
  39002. if (!positioningComputed && (sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  39003. this._updatePositioning();
  39004. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39005. positioningComputed = true;
  39006. }
  39007. if (positioningComputed && this._parent) {
  39008. this._parentContentArea.copyFrom(this._parent.contentArea);
  39009. }
  39010. // Check if we must update this prim
  39011. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  39012. var curVisibleState = this.isVisible;
  39013. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  39014. // Detect a change of visibility
  39015. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  39016. // Get/compute the localTransform
  39017. var localDirty = this._updateLocalTransform();
  39018. // Check if there are changes in the parent that will force us to update the global matrix
  39019. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  39020. // Check if we have to update the globalTransform
  39021. if (!this._globalTransform || localDirty || parentDirty) {
  39022. var globalTransform = this._parent ? this._parent._globalTransform : null;
  39023. this._globalTransform = this._parent ? this._localTransform.multiply(globalTransform) : this._localTransform;
  39024. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  39025. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  39026. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  39027. }
  39028. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  39029. }
  39030. if (recurse) {
  39031. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39032. var child = _a[_i];
  39033. // Stop the recursion if we meet a renderable group
  39034. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  39035. }
  39036. }
  39037. };
  39038. Prim2DBase.prototype._updatePositioning = function () {
  39039. // From this point we assume that the primitive layoutArea is computed and up to date.
  39040. // We know have to :
  39041. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  39042. // 2. Determine the contentArea based on the padding property.
  39043. // Auto Create PaddingArea if there's no actualSize on width&|height to allocate the whole content available to the paddingArea where the actualSize is null
  39044. if (!this._hasMargin && (this.actualSize.width == null || this.actualSize.height == null)) {
  39045. if (this.actualSize.width == null) {
  39046. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  39047. }
  39048. if (this.actualSize.height == null) {
  39049. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  39050. }
  39051. }
  39052. // Apply margin
  39053. if (this._hasMargin) {
  39054. this.margin.computeWithAlignment(this.layoutArea, this.size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  39055. this.actualPosition = this._marginOffset.add(this._layoutAreaPos);
  39056. if (this.size.width != null) {
  39057. this.size.width = Prim2DBase._size.width;
  39058. }
  39059. if (this.size.height != null) {
  39060. this.size.height = Prim2DBase._size.height;
  39061. }
  39062. this.actualSize.copyFrom(Prim2DBase._size.clone());
  39063. }
  39064. if (this._hasPadding) {
  39065. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  39066. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  39067. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  39068. this.padding.compute(Prim2DBase._icArea, this._marginOffset, Prim2DBase._size);
  39069. this._marginOffset.x += Prim2DBase._icPos.x;
  39070. this._marginOffset.y += Prim2DBase._icPos.y;
  39071. this._contentArea.copyFrom(Prim2DBase._size);
  39072. }
  39073. else {
  39074. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  39075. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  39076. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  39077. this._marginOffset.copyFrom(Prim2DBase._icPos);
  39078. this._contentArea.copyFrom(Prim2DBase._icArea);
  39079. }
  39080. };
  39081. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  39082. /**
  39083. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  39084. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  39085. */
  39086. get: function () {
  39087. // Check for positioning update
  39088. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  39089. this._updatePositioning();
  39090. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39091. }
  39092. return this._contentArea;
  39093. },
  39094. enumerable: true,
  39095. configurable: true
  39096. });
  39097. Prim2DBase.prototype._patchHierarchy = function (owner) {
  39098. this._owner = owner;
  39099. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  39100. if (this._renderGroup != null) {
  39101. return;
  39102. }
  39103. if (this instanceof BABYLON.Group2D) {
  39104. var group = this;
  39105. group.detectGroupStates();
  39106. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  39107. group.owner._registerTrackedNode(this);
  39108. }
  39109. }
  39110. if (this._parent) {
  39111. this._renderGroup = this.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  39112. this._parentLayoutDirty();
  39113. }
  39114. // Make sure the prim is in the dirtyList if it should be
  39115. if (this._renderGroup && this.isDirty) {
  39116. var list = this._renderGroup._renderableData._primDirtyList;
  39117. var i = list.indexOf(this);
  39118. if (i === -1) {
  39119. list.push(this);
  39120. }
  39121. }
  39122. // Recurse
  39123. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39124. var child = _a[_i];
  39125. this._patchHierarchyDepth(child);
  39126. child._patchHierarchy(owner);
  39127. }
  39128. };
  39129. Prim2DBase.prototype._patchHierarchyDepth = function (child) {
  39130. child._hierarchyDepth = this._hierarchyDepth + 1;
  39131. child._hierarchyDepthOffset = this._hierarchyDepthOffset + ((this._children.length + 1) * this._siblingDepthOffset);
  39132. child._siblingDepthOffset = this._siblingDepthOffset / BABYLON.Canvas2D.hierarchyLevelMaxSiblingCount;
  39133. };
  39134. /**
  39135. * This method is used to alter the contentArea of the Primitive before margin is applied.
  39136. * In most of the case you won't need to override this method, but it can prove some usefulness, check the Rectangle2D class for a concrete application.
  39137. * @param primSize the current size of the primitive
  39138. * @param initialContentPosition the position of the initial content area to compute, a valid object is passed, you have to set its properties. PLEASE ROUND the values, we're talking about pixels and fraction of them is not a good thing!
  39139. * @param initialContentArea the size of the initial content area to compute, a valid object is passed, you have to set its properties. PLEASE ROUND the values, we're talking about pixels and fraction of them is not a good thing!
  39140. */
  39141. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  39142. initialContentArea.width = primSize.width;
  39143. initialContentArea.height = primSize.height;
  39144. initialContentPosition.x = initialContentPosition.y = 0;
  39145. };
  39146. Prim2DBase.PRIM2DBASE_PROPCOUNT = 15;
  39147. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  39148. Prim2DBase.boundinbBoxReentrency = false;
  39149. Prim2DBase.nullSize = BABYLON.Size.Zero();
  39150. Prim2DBase._isCanvasInit = false;
  39151. Prim2DBase._t0 = new BABYLON.Matrix();
  39152. Prim2DBase._t1 = new BABYLON.Matrix();
  39153. Prim2DBase._t2 = new BABYLON.Matrix();
  39154. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  39155. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  39156. Prim2DBase._icArea = BABYLON.Size.Zero();
  39157. Prim2DBase._size = BABYLON.Size.Zero();
  39158. __decorate([
  39159. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.actualPositionProperty = pi; }, false, true)
  39160. ], Prim2DBase.prototype, "actualPosition", null);
  39161. __decorate([
  39162. BABYLON.dynamicLevelProperty(1, function (pi) { return Prim2DBase.positionProperty = pi; }, false, true)
  39163. ], Prim2DBase.prototype, "position", null);
  39164. __decorate([
  39165. BABYLON.dynamicLevelProperty(2, function (pi) { return Prim2DBase.sizeProperty = pi; }, false, true)
  39166. ], Prim2DBase.prototype, "size", null);
  39167. __decorate([
  39168. BABYLON.instanceLevelProperty(3, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  39169. ], Prim2DBase.prototype, "rotation", null);
  39170. __decorate([
  39171. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  39172. ], Prim2DBase.prototype, "scale", null);
  39173. __decorate([
  39174. BABYLON.dynamicLevelProperty(5, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  39175. ], Prim2DBase.prototype, "origin", null);
  39176. __decorate([
  39177. BABYLON.dynamicLevelProperty(6, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  39178. ], Prim2DBase.prototype, "levelVisible", null);
  39179. __decorate([
  39180. BABYLON.instanceLevelProperty(7, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  39181. ], Prim2DBase.prototype, "isVisible", null);
  39182. __decorate([
  39183. BABYLON.instanceLevelProperty(8, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  39184. ], Prim2DBase.prototype, "zOrder", null);
  39185. __decorate([
  39186. BABYLON.dynamicLevelProperty(9, function (pi) { return Prim2DBase.marginProperty = pi; })
  39187. ], Prim2DBase.prototype, "margin", null);
  39188. __decorate([
  39189. BABYLON.dynamicLevelProperty(10, function (pi) { return Prim2DBase.paddingProperty = pi; })
  39190. ], Prim2DBase.prototype, "padding", null);
  39191. __decorate([
  39192. BABYLON.dynamicLevelProperty(11, function (pi) { return Prim2DBase.marginAlignmentProperty = pi; })
  39193. ], Prim2DBase.prototype, "marginAlignment", null);
  39194. Prim2DBase = __decorate([
  39195. BABYLON.className("Prim2DBase")
  39196. ], Prim2DBase);
  39197. return Prim2DBase;
  39198. })(BABYLON.SmartPropertyPrim);
  39199. BABYLON.Prim2DBase = Prim2DBase;
  39200. })(BABYLON || (BABYLON = {}));
  39201. var BABYLON;
  39202. (function (BABYLON) {
  39203. var GroupInstanceInfo = (function () {
  39204. function GroupInstanceInfo(owner, mrc, partCount) {
  39205. this._partCount = partCount;
  39206. this.owner = owner;
  39207. this.modelRenderCache = mrc;
  39208. this.modelRenderCache.addRef();
  39209. this.partIndexFromId = new BABYLON.StringDictionary();
  39210. this._usedShaderCategories = new Array(partCount);
  39211. this._strides = new Array(partCount);
  39212. this._opaqueData = null;
  39213. this._alphaTestData = null;
  39214. this._transparentData = null;
  39215. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  39216. }
  39217. GroupInstanceInfo.prototype.dispose = function () {
  39218. if (this._isDisposed) {
  39219. return false;
  39220. }
  39221. if (this.modelRenderCache) {
  39222. this.modelRenderCache.dispose();
  39223. }
  39224. var engine = this.owner.owner.engine;
  39225. if (this.opaqueData) {
  39226. this.opaqueData.forEach(function (d) { return d.dispose(engine); });
  39227. this.opaqueData = null;
  39228. }
  39229. this.partIndexFromId = null;
  39230. this._isDisposed = true;
  39231. return true;
  39232. };
  39233. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  39234. get: function () {
  39235. return this._opaqueData != null;
  39236. },
  39237. enumerable: true,
  39238. configurable: true
  39239. });
  39240. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  39241. get: function () {
  39242. return this._alphaTestData != null;
  39243. },
  39244. enumerable: true,
  39245. configurable: true
  39246. });
  39247. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  39248. get: function () {
  39249. return this._transparentData != null;
  39250. },
  39251. enumerable: true,
  39252. configurable: true
  39253. });
  39254. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  39255. get: function () {
  39256. if (!this._opaqueData) {
  39257. this._opaqueData = new Array(this._partCount);
  39258. for (var i = 0; i < this._partCount; i++) {
  39259. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  39260. }
  39261. }
  39262. return this._opaqueData;
  39263. },
  39264. enumerable: true,
  39265. configurable: true
  39266. });
  39267. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  39268. get: function () {
  39269. if (!this._alphaTestData) {
  39270. this._alphaTestData = new Array(this._partCount);
  39271. for (var i = 0; i < this._partCount; i++) {
  39272. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  39273. }
  39274. }
  39275. return this._alphaTestData;
  39276. },
  39277. enumerable: true,
  39278. configurable: true
  39279. });
  39280. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  39281. get: function () {
  39282. if (!this._transparentData) {
  39283. this._transparentData = new Array(this._partCount);
  39284. for (var i = 0; i < this._partCount; i++) {
  39285. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  39286. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  39287. }
  39288. }
  39289. return this._transparentData;
  39290. },
  39291. enumerable: true,
  39292. configurable: true
  39293. });
  39294. GroupInstanceInfo.prototype.sortTransparentData = function () {
  39295. if (!this.transparentOrderDirty) {
  39296. return;
  39297. }
  39298. for (var i = 0; i < this._transparentData.length; i++) {
  39299. var td = this._transparentData[i];
  39300. td._partData.sort();
  39301. }
  39302. this.transparentOrderDirty = false;
  39303. };
  39304. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  39305. get: function () {
  39306. return this._usedShaderCategories;
  39307. },
  39308. enumerable: true,
  39309. configurable: true
  39310. });
  39311. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  39312. get: function () {
  39313. return this._strides;
  39314. },
  39315. enumerable: true,
  39316. configurable: true
  39317. });
  39318. return GroupInstanceInfo;
  39319. })();
  39320. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  39321. var TransparentSegment = (function () {
  39322. function TransparentSegment() {
  39323. }
  39324. return TransparentSegment;
  39325. })();
  39326. BABYLON.TransparentSegment = TransparentSegment;
  39327. var GroupInfoPartData = (function () {
  39328. function GroupInfoPartData(stride) {
  39329. this._partData = null;
  39330. this._partBuffer = null;
  39331. this._partBufferSize = 0;
  39332. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  39333. this._isDisposed = false;
  39334. }
  39335. GroupInfoPartData.prototype.dispose = function (engine) {
  39336. if (this._isDisposed) {
  39337. return false;
  39338. }
  39339. if (this._partBuffer) {
  39340. engine._releaseBuffer(this._partBuffer);
  39341. this._partBuffer = null;
  39342. }
  39343. this._partData = null;
  39344. this._isDisposed = true;
  39345. };
  39346. return GroupInfoPartData;
  39347. })();
  39348. BABYLON.GroupInfoPartData = GroupInfoPartData;
  39349. var TransparentGroupInfoPartData = (function (_super) {
  39350. __extends(TransparentGroupInfoPartData, _super);
  39351. function TransparentGroupInfoPartData(stride, zoff) {
  39352. _super.call(this, stride);
  39353. this._partData.compareValueOffset = zoff;
  39354. this._partData.sortingAscending = false;
  39355. }
  39356. return TransparentGroupInfoPartData;
  39357. })(GroupInfoPartData);
  39358. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  39359. var ModelRenderCache = (function () {
  39360. function ModelRenderCache(engine, modelKey) {
  39361. this._engine = engine;
  39362. this._modelKey = modelKey;
  39363. this._nextKey = 1;
  39364. this._refCounter = 1;
  39365. this._instancesData = new BABYLON.StringDictionary();
  39366. this._partData = null;
  39367. }
  39368. ModelRenderCache.prototype.dispose = function () {
  39369. if (--this._refCounter !== 0) {
  39370. return false;
  39371. }
  39372. // Remove the Model Render Cache from the global dictionary
  39373. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  39374. if (edata) {
  39375. edata.DisposeModelRenderCache(this);
  39376. }
  39377. return true;
  39378. };
  39379. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  39380. get: function () {
  39381. return this._refCounter <= 0;
  39382. },
  39383. enumerable: true,
  39384. configurable: true
  39385. });
  39386. ModelRenderCache.prototype.addRef = function () {
  39387. return ++this._refCounter;
  39388. };
  39389. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  39390. get: function () {
  39391. return this._modelKey;
  39392. },
  39393. enumerable: true,
  39394. configurable: true
  39395. });
  39396. /**
  39397. * Render the model instances
  39398. * @param instanceInfo
  39399. * @param context
  39400. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  39401. */
  39402. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  39403. return true;
  39404. };
  39405. ModelRenderCache.prototype.addInstanceDataParts = function (data) {
  39406. var key = this._nextKey.toString();
  39407. if (!this._instancesData.add(key, data)) {
  39408. throw Error("Key: " + key + " is already allocated");
  39409. }
  39410. ++this._nextKey;
  39411. return key;
  39412. };
  39413. ModelRenderCache.prototype.removeInstanceData = function (key) {
  39414. this._instancesData.remove(key);
  39415. };
  39416. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  39417. for (var i = 0; i < this._partData.length; i++) {
  39418. if (this._partData[i]._partId === partId) {
  39419. return i;
  39420. }
  39421. }
  39422. return null;
  39423. };
  39424. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  39425. var i = this.getPartIndexFromId(partId);
  39426. if (i === null) {
  39427. return null;
  39428. }
  39429. var ci = this._partsClassInfo[i];
  39430. var categories = this._partData[i]._partUsedCategories;
  39431. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  39432. return res;
  39433. };
  39434. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  39435. var pd = this._partData[partIndex];
  39436. var offset = (pd._partDataStride / 4) * elementCount;
  39437. var pci = this._partsClassInfo[partIndex];
  39438. var self = this;
  39439. pci.fullContent.forEach(function (k, v) {
  39440. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  39441. switch (v.dataType) {
  39442. case 4 /* float */:
  39443. {
  39444. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  39445. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  39446. break;
  39447. }
  39448. case 0 /* Vector2 */:
  39449. {
  39450. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  39451. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  39452. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  39453. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  39454. break;
  39455. }
  39456. case 5 /* Color3 */:
  39457. case 1 /* Vector3 */:
  39458. {
  39459. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  39460. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  39461. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  39462. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  39463. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  39464. break;
  39465. }
  39466. case 6 /* Color4 */:
  39467. case 2 /* Vector4 */:
  39468. {
  39469. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  39470. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  39471. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  39472. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  39473. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  39474. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  39475. break;
  39476. }
  39477. default:
  39478. }
  39479. }
  39480. });
  39481. };
  39482. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  39483. // let i = this.getPartIndexFromId(partId);
  39484. // if (i === null) {
  39485. // return null;
  39486. // }
  39487. // let pci = this._partsClassInfo[i];
  39488. // pci.fullContent.forEach((k, v) => {
  39489. // if (uniforms.indexOf(v.attributeName) !== -1) {
  39490. // v.uniformLocation = effect.getUniform(v.attributeName);
  39491. // }
  39492. // });
  39493. //}
  39494. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  39495. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  39496. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  39497. return ModelRenderCache;
  39498. })();
  39499. BABYLON.ModelRenderCache = ModelRenderCache;
  39500. var ModelRenderCachePartData = (function () {
  39501. function ModelRenderCachePartData() {
  39502. }
  39503. return ModelRenderCachePartData;
  39504. })();
  39505. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  39506. })(BABYLON || (BABYLON = {}));
  39507. var BABYLON;
  39508. (function (BABYLON) {
  39509. var InstanceClassInfo = (function () {
  39510. function InstanceClassInfo(base) {
  39511. this._baseInfo = base;
  39512. this._nextOffset = new BABYLON.StringDictionary();
  39513. this._attributes = new Array();
  39514. }
  39515. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  39516. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  39517. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  39518. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  39519. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  39520. if (push) {
  39521. this._attributes.push(propInfo);
  39522. }
  39523. };
  39524. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  39525. var catInline = ";" + categories.join(";") + ";";
  39526. var res = new Array();
  39527. var curInfo = this;
  39528. while (curInfo) {
  39529. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  39530. var attrib = _a[_i];
  39531. // Only map if there's no category assigned to the instance data or if there's a category and it's in the given list
  39532. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  39533. var index = effect.getAttributeLocationByName(attrib.attributeName);
  39534. var iai = new BABYLON.InstancingAttributeInfo();
  39535. iai.index = index;
  39536. iai.attributeSize = attrib.size / 4; // attrib.size is in byte and we need to store in "component" (i.e float is 1, vec3 is 3)
  39537. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  39538. iai.attributeName = attrib.attributeName;
  39539. res.push(iai);
  39540. }
  39541. }
  39542. curInfo = curInfo._baseInfo;
  39543. }
  39544. return res;
  39545. };
  39546. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  39547. var res = new Array();
  39548. var curInfo = this;
  39549. while (curInfo) {
  39550. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  39551. var attrib = _a[_i];
  39552. // Only map if there's no category assigned to the instance data or if there's a category and it's in the given list
  39553. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  39554. res.push(attrib.attributeName);
  39555. }
  39556. }
  39557. curInfo = curInfo._baseInfo;
  39558. }
  39559. return res;
  39560. };
  39561. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  39562. var curOffset = 0;
  39563. var curBase = this._baseInfo;
  39564. while (curBase) {
  39565. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  39566. curBase = curBase._baseInfo;
  39567. }
  39568. return curOffset;
  39569. };
  39570. return InstanceClassInfo;
  39571. })();
  39572. BABYLON.InstanceClassInfo = InstanceClassInfo;
  39573. var InstancePropInfo = (function () {
  39574. function InstancePropInfo() {
  39575. this.instanceOffset = new BABYLON.StringDictionary();
  39576. }
  39577. InstancePropInfo.prototype.setSize = function (val) {
  39578. if (val instanceof BABYLON.Vector2) {
  39579. this.size = 8;
  39580. this.dataType = 0 /* Vector2 */;
  39581. return;
  39582. }
  39583. if (val instanceof BABYLON.Vector3) {
  39584. this.size = 12;
  39585. this.dataType = 1 /* Vector3 */;
  39586. return;
  39587. }
  39588. if (val instanceof BABYLON.Vector4) {
  39589. this.size = 16;
  39590. this.dataType = 2 /* Vector4 */;
  39591. return;
  39592. }
  39593. if (val instanceof BABYLON.Matrix) {
  39594. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  39595. }
  39596. if (typeof (val) === "number") {
  39597. this.size = 4;
  39598. this.dataType = 4 /* float */;
  39599. return;
  39600. }
  39601. if (val instanceof BABYLON.Color3) {
  39602. this.size = 12;
  39603. this.dataType = 5 /* Color3 */;
  39604. return;
  39605. }
  39606. if (val instanceof BABYLON.Color4) {
  39607. this.size = 16;
  39608. this.dataType = 6 /* Color4 */;
  39609. return;
  39610. }
  39611. if (val instanceof BABYLON.Size) {
  39612. this.size = 8;
  39613. this.dataType = 7 /* Size */;
  39614. return;
  39615. }
  39616. return;
  39617. };
  39618. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  39619. switch (this.dataType) {
  39620. case 0 /* Vector2 */:
  39621. {
  39622. var v = val;
  39623. array[offset + 0] = v.x;
  39624. array[offset + 1] = v.y;
  39625. break;
  39626. }
  39627. case 1 /* Vector3 */:
  39628. {
  39629. var v = val;
  39630. array[offset + 0] = v.x;
  39631. array[offset + 1] = v.y;
  39632. array[offset + 2] = v.z;
  39633. break;
  39634. }
  39635. case 2 /* Vector4 */:
  39636. {
  39637. var v = val;
  39638. array[offset + 0] = v.x;
  39639. array[offset + 1] = v.y;
  39640. array[offset + 2] = v.z;
  39641. array[offset + 3] = v.w;
  39642. break;
  39643. }
  39644. case 5 /* Color3 */:
  39645. {
  39646. var v = val;
  39647. array[offset + 0] = v.r;
  39648. array[offset + 1] = v.g;
  39649. array[offset + 2] = v.b;
  39650. break;
  39651. }
  39652. case 6 /* Color4 */:
  39653. {
  39654. var v = val;
  39655. array[offset + 0] = v.r;
  39656. array[offset + 1] = v.g;
  39657. array[offset + 2] = v.b;
  39658. array[offset + 3] = v.a;
  39659. break;
  39660. }
  39661. case 4 /* float */:
  39662. {
  39663. var v = val;
  39664. array[offset] = v;
  39665. break;
  39666. }
  39667. case 3 /* Matrix */:
  39668. {
  39669. var v = val;
  39670. for (var i = 0; i < 16; i++) {
  39671. array[offset + i] = v.m[i];
  39672. }
  39673. break;
  39674. }
  39675. case 7 /* Size */:
  39676. {
  39677. var s = val;
  39678. array[offset + 0] = s.width;
  39679. array[offset + 1] = s.height;
  39680. break;
  39681. }
  39682. }
  39683. };
  39684. return InstancePropInfo;
  39685. })();
  39686. BABYLON.InstancePropInfo = InstancePropInfo;
  39687. function instanceData(category, shaderAttributeName) {
  39688. return function (target, propName, descriptor) {
  39689. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  39690. var node = dic.getLevelOf(target);
  39691. var instanceDataName = propName;
  39692. shaderAttributeName = shaderAttributeName || instanceDataName;
  39693. var info = node.levelContent.get(instanceDataName);
  39694. if (info) {
  39695. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  39696. }
  39697. info = new InstancePropInfo();
  39698. info.attributeName = shaderAttributeName;
  39699. info.category = category || null;
  39700. if (info.category) {
  39701. info.delimitedCategory = ";" + info.category + ";";
  39702. }
  39703. node.levelContent.add(instanceDataName, info);
  39704. descriptor.get = function () {
  39705. return null;
  39706. };
  39707. descriptor.set = function (val) {
  39708. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  39709. // Quit if it's the case, otherwise we could overwrite data somewhere...
  39710. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  39711. return;
  39712. }
  39713. if (!info.size) {
  39714. info.setSize(val);
  39715. node.classContent.mapProperty(info, true);
  39716. }
  39717. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  39718. node.classContent.mapProperty(info, false);
  39719. }
  39720. var obj = this;
  39721. if (obj.dataBuffer && obj.dataElements) {
  39722. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  39723. info.writeData(obj.dataBuffer.buffer, offset, val);
  39724. }
  39725. };
  39726. };
  39727. }
  39728. BABYLON.instanceData = instanceData;
  39729. var InstanceDataBase = (function () {
  39730. function InstanceDataBase(partId, dataElementCount) {
  39731. this.id = partId;
  39732. this.curElement = 0;
  39733. this.dataElementCount = dataElementCount;
  39734. }
  39735. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  39736. get: function () {
  39737. return null;
  39738. },
  39739. enumerable: true,
  39740. configurable: true
  39741. });
  39742. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  39743. get: function () {
  39744. return null;
  39745. },
  39746. enumerable: true,
  39747. configurable: true
  39748. });
  39749. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  39750. get: function () {
  39751. return null;
  39752. },
  39753. enumerable: true,
  39754. configurable: true
  39755. });
  39756. InstanceDataBase.prototype.getClassTreeInfo = function () {
  39757. if (!this.typeInfo) {
  39758. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  39759. }
  39760. return this.typeInfo;
  39761. };
  39762. InstanceDataBase.prototype.allocElements = function () {
  39763. if (!this.dataBuffer) {
  39764. return;
  39765. }
  39766. var res = new Array(this.dataElementCount);
  39767. for (var i = 0; i < this.dataElementCount; i++) {
  39768. res[i] = this.dataBuffer.allocElement();
  39769. }
  39770. this.dataElements = res;
  39771. };
  39772. InstanceDataBase.prototype.freeElements = function () {
  39773. if (!this.dataElements) {
  39774. return;
  39775. }
  39776. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  39777. var ei = _a[_i];
  39778. this.dataBuffer.freeElement(ei);
  39779. }
  39780. this.dataElements = null;
  39781. };
  39782. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  39783. get: function () {
  39784. return this._dataElementCount;
  39785. },
  39786. set: function (value) {
  39787. if (value === this._dataElementCount) {
  39788. return;
  39789. }
  39790. this.freeElements();
  39791. this._dataElementCount = value;
  39792. this.allocElements();
  39793. },
  39794. enumerable: true,
  39795. configurable: true
  39796. });
  39797. __decorate([
  39798. instanceData()
  39799. ], InstanceDataBase.prototype, "zBias", null);
  39800. __decorate([
  39801. instanceData()
  39802. ], InstanceDataBase.prototype, "transformX", null);
  39803. __decorate([
  39804. instanceData()
  39805. ], InstanceDataBase.prototype, "transformY", null);
  39806. return InstanceDataBase;
  39807. })();
  39808. BABYLON.InstanceDataBase = InstanceDataBase;
  39809. var RenderablePrim2D = (function (_super) {
  39810. __extends(RenderablePrim2D, _super);
  39811. function RenderablePrim2D(settings) {
  39812. _super.call(this, settings);
  39813. this._isTransparent = false;
  39814. this._isAlphaTest = false;
  39815. this._transparentPrimitiveInfo = null;
  39816. }
  39817. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  39818. get: function () {
  39819. return this._isAlphaTest;
  39820. },
  39821. set: function (value) {
  39822. this._isAlphaTest = value;
  39823. },
  39824. enumerable: true,
  39825. configurable: true
  39826. });
  39827. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  39828. get: function () {
  39829. return this._isTransparent;
  39830. },
  39831. set: function (value) {
  39832. this._isTransparent = value;
  39833. },
  39834. enumerable: true,
  39835. configurable: true
  39836. });
  39837. /**
  39838. * Dispose the primitive and its resources, remove it from its parent
  39839. */
  39840. RenderablePrim2D.prototype.dispose = function () {
  39841. if (!_super.prototype.dispose.call(this)) {
  39842. return false;
  39843. }
  39844. if (this._transparentPrimitiveInfo) {
  39845. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  39846. this._transparentPrimitiveInfo = null;
  39847. }
  39848. if (this._modelRenderInstanceID) {
  39849. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  39850. this._modelRenderInstanceID = null;
  39851. }
  39852. if (this._modelRenderCache) {
  39853. this._modelRenderCache.dispose();
  39854. this._modelRenderCache = null;
  39855. }
  39856. if (this._instanceDataParts) {
  39857. this._instanceDataParts.forEach(function (p) {
  39858. p.freeElements();
  39859. });
  39860. this._instanceDataParts = null;
  39861. }
  39862. return true;
  39863. };
  39864. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  39865. _super.prototype._prepareRenderPre.call(this, context);
  39866. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  39867. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._modelRenderInstanceID) {
  39868. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  39869. this._modelRenderInstanceID = null;
  39870. }
  39871. // Need to create the model?
  39872. var setupModelRenderCache = false;
  39873. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  39874. setupModelRenderCache = this._createModelRenderCache();
  39875. }
  39876. var gii = null;
  39877. var newInstance = false;
  39878. // Need to create the instance data parts?
  39879. if (!this._modelRenderInstanceID) {
  39880. // Yes, flag it for later, more processing will have to be done
  39881. newInstance = true;
  39882. gii = this._createModelDataParts();
  39883. }
  39884. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  39885. if (setupModelRenderCache) {
  39886. this.setupModelRenderCache(this._modelRenderCache);
  39887. }
  39888. // At this stage we have everything correctly initialized, ModelRenderCache is setup, Model Instance data are good too, they have allocated elements in the Instanced DynamicFloatArray.
  39889. // The last thing to do is check if the instanced related data must be updated because a InstanceLevel property had changed or the primitive visibility changed.
  39890. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep)) {
  39891. if (this.isTransparent) {
  39892. }
  39893. this._updateInstanceDataParts(gii);
  39894. }
  39895. };
  39896. RenderablePrim2D.prototype._createModelRenderCache = function () {
  39897. var _this = this;
  39898. var setupModelRenderCache = false;
  39899. if (this._modelRenderCache) {
  39900. this._modelRenderCache.dispose();
  39901. }
  39902. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  39903. var mrc = _this.createModelRenderCache(key);
  39904. setupModelRenderCache = true;
  39905. return mrc;
  39906. });
  39907. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  39908. // if this is still false it means the MRC already exists, so we add a reference to it
  39909. if (!setupModelRenderCache) {
  39910. this._modelRenderCache.addRef();
  39911. }
  39912. return setupModelRenderCache;
  39913. };
  39914. RenderablePrim2D.prototype._createModelDataParts = function () {
  39915. var _this = this;
  39916. // Create the instance data parts of the primitive and store them
  39917. var parts = this.createInstanceDataParts();
  39918. this._instanceDataParts = parts;
  39919. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  39920. if (!this._modelRenderCache._partData) {
  39921. this._setupModelRenderCache(parts);
  39922. }
  39923. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  39924. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  39925. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  39926. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  39927. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  39928. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  39929. var part = _this._instanceDataParts[j];
  39930. res.partIndexFromId.add(part.id.toString(), j);
  39931. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  39932. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  39933. }
  39934. return res;
  39935. });
  39936. // Get the GroupInfoDataPart corresponding to the render category of the part
  39937. var gipd = null;
  39938. if (this.isTransparent) {
  39939. gipd = gii.transparentData;
  39940. }
  39941. else if (this.isAlphaTest) {
  39942. gipd = gii.alphaTestData;
  39943. }
  39944. else {
  39945. gipd = gii.opaqueData;
  39946. }
  39947. // For each instance data part of the primitive, allocate the instanced element it needs for render
  39948. for (var i = 0; i < parts.length; i++) {
  39949. var part = parts[i];
  39950. part.dataBuffer = gipd[i]._partData;
  39951. part.allocElements();
  39952. }
  39953. // Add the instance data parts in the ModelRenderCache they belong, track them by storing their ID in the primitive in case we need to change the model later on, so we'll have to release the allocated instance data parts because they won't fit anymore
  39954. this._modelRenderInstanceID = this._modelRenderCache.addInstanceDataParts(this._instanceDataParts);
  39955. return gii;
  39956. };
  39957. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  39958. var ctiArray = new Array();
  39959. this._modelRenderCache._partData = new Array();
  39960. for (var _i = 0; _i < parts.length; _i++) {
  39961. var dataPart = parts[_i];
  39962. var pd = new BABYLON.ModelRenderCachePartData();
  39963. this._modelRenderCache._partData.push(pd);
  39964. var cat = this.getUsedShaderCategories(dataPart);
  39965. var cti = dataPart.getClassTreeInfo();
  39966. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  39967. var curVisible = this.isVisible;
  39968. this.isVisible = true;
  39969. // We manually trigger refreshInstanceData for the only sake of evaluating each instance property size and offset in the instance data, this can only be made at runtime. Once it's done we have all the information to create the instance data buffer.
  39970. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  39971. var joinCat = ";" + cat.join(";") + ";";
  39972. pd._partJoinedUsedCategories = joinCat;
  39973. InstanceClassInfo._CurCategories = joinCat;
  39974. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  39975. this.refreshInstanceDataPart(dataPart);
  39976. this.afterRefreshForLayoutConstruction(dataPart, obj);
  39977. this.isVisible = curVisible;
  39978. var size = 0;
  39979. cti.fullContent.forEach(function (k, v) {
  39980. if (!v.category || cat.indexOf(v.category) !== -1) {
  39981. if (v.attributeName === "zBias") {
  39982. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  39983. }
  39984. if (!v.size) {
  39985. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  39986. }
  39987. else {
  39988. size += v.size;
  39989. }
  39990. }
  39991. });
  39992. pd._partDataStride = size;
  39993. pd._partUsedCategories = cat;
  39994. pd._partId = dataPart.id;
  39995. ctiArray.push(cti);
  39996. }
  39997. this._modelRenderCache._partsClassInfo = ctiArray;
  39998. };
  39999. RenderablePrim2D.prototype.onZOrderChanged = function () {
  40000. if (this.isTransparent && this._transparentPrimitiveInfo) {
  40001. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  40002. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  40003. // Flag the transparentData dirty has will have to sort it again
  40004. gii.transparentOrderDirty = true;
  40005. }
  40006. };
  40007. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  40008. // Fetch the GroupInstanceInfo if we don't already have it
  40009. if (!gii) {
  40010. gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  40011. }
  40012. // Handle changes related to ZOffset
  40013. if (this.isTransparent) {
  40014. // Handle visibility change, which is also triggered when the primitive just got created
  40015. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged)) {
  40016. if (this.isVisible) {
  40017. if (!this._transparentPrimitiveInfo) {
  40018. // Add the primitive to the list of transparent ones in the group that render is
  40019. this._transparentPrimitiveInfo = this.renderGroup._renderableData.addNewTransparentPrimitiveInfo(this, gii);
  40020. }
  40021. }
  40022. else {
  40023. if (this._transparentPrimitiveInfo) {
  40024. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  40025. this._transparentPrimitiveInfo = null;
  40026. }
  40027. }
  40028. gii.transparentOrderDirty = true;
  40029. }
  40030. }
  40031. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  40032. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  40033. var part = _a[_i];
  40034. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  40035. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged) && !part.dataElements) {
  40036. part.allocElements();
  40037. }
  40038. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  40039. // Will return false if the instance should not be rendered (not visible or other any reasons)
  40040. if (!this.refreshInstanceDataPart(part)) {
  40041. // Free the data element
  40042. if (part.dataElements) {
  40043. part.freeElements();
  40044. }
  40045. }
  40046. }
  40047. this._instanceDirtyFlags = 0;
  40048. // Make the appropriate data dirty
  40049. if (this.isTransparent) {
  40050. gii.transparentDirty = true;
  40051. }
  40052. else if (this.isAlphaTest) {
  40053. gii.alphaTestDirty = true;
  40054. }
  40055. else {
  40056. gii.opaqueDirty = true;
  40057. }
  40058. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  40059. };
  40060. RenderablePrim2D.prototype._getFirstIndexInDataBuffer = function () {
  40061. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  40062. var part = _a[_i];
  40063. if (part) {
  40064. return part.dataElements[0].offset / part.dataBuffer.stride;
  40065. }
  40066. }
  40067. return null;
  40068. };
  40069. RenderablePrim2D.prototype._getLastIndexInDataBuffer = function () {
  40070. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  40071. var part = _a[_i];
  40072. if (part) {
  40073. return part.dataElements[part.dataElements.length - 1].offset / part.dataBuffer.stride;
  40074. }
  40075. }
  40076. return null;
  40077. };
  40078. // This internal method is mainly used for transparency processing
  40079. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  40080. var length = this._instanceDataParts.length;
  40081. for (var i = 0; i < length; i++) {
  40082. var part = this._instanceDataParts[i];
  40083. if (part) {
  40084. var stride = part.dataBuffer.stride;
  40085. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  40086. // check if it's the last in the DFA
  40087. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  40088. return null;
  40089. }
  40090. // Return the Z of the next primitive that lies in the DFA
  40091. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  40092. }
  40093. }
  40094. return null;
  40095. };
  40096. // This internal method is mainly used for transparency processing
  40097. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  40098. var length = this._instanceDataParts.length;
  40099. for (var i = 0; i < length; i++) {
  40100. var part = this._instanceDataParts[i];
  40101. if (part) {
  40102. var stride = part.dataBuffer.stride;
  40103. var firstElementOffset = part.dataElements[0].offset;
  40104. // check if it's the first in the DFA
  40105. if (firstElementOffset === 0) {
  40106. return null;
  40107. }
  40108. // Return the Z of the previous primitive that lies in the DFA
  40109. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  40110. }
  40111. }
  40112. return null;
  40113. };
  40114. /**
  40115. * Transform a given point using the Primitive's origin setting.
  40116. * This method requires the Primitive's actualSize to be accurate
  40117. * @param p the point to transform
  40118. * @param originOffset an offset applied on the current origin before performing the transformation. Depending on which frame of reference your data is expressed you may have to apply a offset. (if you data is expressed from the bottom/left, no offset is required. If it's expressed from the center the a [-0.5;-0.5] offset has to be applied.
  40119. * @param res an allocated Vector2 that will receive the transformed content
  40120. */
  40121. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  40122. var actualSize = this.actualSize;
  40123. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  40124. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  40125. };
  40126. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  40127. this.transformPointWithOriginByRef(p, originOffset, res);
  40128. return res;
  40129. };
  40130. /**
  40131. * Get the info for a given effect based on the dataPart metadata
  40132. * @param dataPartId partId in part list to get the info
  40133. * @param vertexBufferAttributes vertex buffer attributes to manually add
  40134. * @param useInstanced specified if Instanced Array should be used, if null the engine caps will be used (so true if WebGL supports it, false otherwise), but you have the possibility to override the engine capability. However, if you manually set true but the engine does not support Instanced Array, this method will return null
  40135. */
  40136. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, useInstanced) {
  40137. if (useInstanced === void 0) { useInstanced = null; }
  40138. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  40139. if (!dataPart) {
  40140. return null;
  40141. }
  40142. var instancedArray = this.owner.supportInstancedArray;
  40143. if (useInstanced != null) {
  40144. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  40145. if (useInstanced && instancedArray === false) {
  40146. return null;
  40147. }
  40148. // Use the caller's setting
  40149. instancedArray = useInstanced;
  40150. }
  40151. var cti = dataPart.getClassTreeInfo();
  40152. var categories = this.getUsedShaderCategories(dataPart);
  40153. var att = cti.classContent.getShaderAttributes(categories);
  40154. var defines = "";
  40155. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  40156. if (instancedArray) {
  40157. defines += "#define Instanced\n";
  40158. }
  40159. return { attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes, uniforms: instancedArray ? [] : att, defines: defines };
  40160. };
  40161. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  40162. get: function () {
  40163. return this._modelRenderCache;
  40164. },
  40165. enumerable: true,
  40166. configurable: true
  40167. });
  40168. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  40169. return null;
  40170. };
  40171. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  40172. };
  40173. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  40174. return null;
  40175. };
  40176. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  40177. return [];
  40178. };
  40179. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  40180. };
  40181. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  40182. };
  40183. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  40184. if (!this.isVisible) {
  40185. return false;
  40186. }
  40187. part.isVisible = this.isVisible;
  40188. // Which means, if there's only one data element, we're update it from this method, otherwise it is the responsibility of the derived class to call updateInstanceDataPart as many times as needed, properly (look at Text2D's implementation for more information)
  40189. if (part.dataElementCount === 1) {
  40190. part.curElement = 0;
  40191. this.updateInstanceDataPart(part);
  40192. }
  40193. return true;
  40194. };
  40195. /**
  40196. * Update the instanceDataBase level properties of a part
  40197. * @param part the part to update
  40198. * @param positionOffset to use in multi part per primitive (e.g. the Text2D has N parts for N letter to display), this give the offset to apply (e.g. the position of the letter from the bottom/left corner of the text).
  40199. */
  40200. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  40201. if (positionOffset === void 0) { positionOffset = null; }
  40202. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform);
  40203. var size = this.renderGroup.viewportSize;
  40204. var zBias = this.actualZOffset;
  40205. var offX = 0;
  40206. var offY = 0;
  40207. // If there's an offset, apply the global transformation matrix on it to get a global offset
  40208. if (positionOffset) {
  40209. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  40210. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  40211. }
  40212. // Have to convert the coordinates to clip space which is ranged between [-1;1] on X and Y axis, with 0,0 being the left/bottom corner
  40213. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  40214. // So for X:
  40215. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  40216. // - tx.w = (value * 2 / width) - 1: w stores the translation in renderGroup coordinates so (value * 2 / width) to switch to a clip space translation value. - 1 is to offset the overall [0;2] to [-1;1].
  40217. var w = size.width;
  40218. var h = size.height;
  40219. var invZBias = 1 / zBias;
  40220. var tx = new BABYLON.Vector4(t.m[0] * 2 / w, t.m[4] * 2 / w, 0 /*t.m[8]*/, ((t.m[12] + offX) * 2 / w) - 1);
  40221. var ty = new BABYLON.Vector4(t.m[1] * 2 / h, t.m[5] * 2 / h, 0 /*t.m[9]*/, ((t.m[13] + offY) * 2 / h) - 1);
  40222. part.transformX = tx;
  40223. part.transformY = ty;
  40224. // Stores zBias and it's inverse value because that's needed to compute the clip space W coordinate (which is 1/Z, so 1/zBias)
  40225. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  40226. };
  40227. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  40228. __decorate([
  40229. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  40230. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  40231. __decorate([
  40232. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  40233. ], RenderablePrim2D.prototype, "isTransparent", null);
  40234. RenderablePrim2D = __decorate([
  40235. BABYLON.className("RenderablePrim2D")
  40236. ], RenderablePrim2D);
  40237. return RenderablePrim2D;
  40238. })(BABYLON.Prim2DBase);
  40239. BABYLON.RenderablePrim2D = RenderablePrim2D;
  40240. })(BABYLON || (BABYLON = {}));
  40241. var BABYLON;
  40242. (function (BABYLON) {
  40243. var Shape2D = (function (_super) {
  40244. __extends(Shape2D, _super);
  40245. function Shape2D(settings) {
  40246. _super.call(this, settings);
  40247. if (!settings) {
  40248. settings = {};
  40249. }
  40250. var borderBrush = null;
  40251. if (settings.border) {
  40252. if (typeof (settings.border) === "string") {
  40253. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  40254. }
  40255. else {
  40256. borderBrush = settings.border;
  40257. }
  40258. }
  40259. var fillBrush = null;
  40260. if (settings.fill) {
  40261. if (typeof (settings.fill) === "string") {
  40262. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  40263. }
  40264. else {
  40265. fillBrush = settings.fill;
  40266. }
  40267. }
  40268. this.border = borderBrush;
  40269. this.fill = fillBrush;
  40270. this.borderThickness = settings.borderThickness;
  40271. }
  40272. Object.defineProperty(Shape2D.prototype, "border", {
  40273. get: function () {
  40274. return this._border;
  40275. },
  40276. set: function (value) {
  40277. this._border = value;
  40278. this._updateTransparencyStatus();
  40279. },
  40280. enumerable: true,
  40281. configurable: true
  40282. });
  40283. Object.defineProperty(Shape2D.prototype, "fill", {
  40284. /**
  40285. * Get/set the brush to render the Fill part of the Primitive
  40286. */
  40287. get: function () {
  40288. return this._fill;
  40289. },
  40290. set: function (value) {
  40291. this._fill = value;
  40292. this._updateTransparencyStatus();
  40293. },
  40294. enumerable: true,
  40295. configurable: true
  40296. });
  40297. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  40298. get: function () {
  40299. return this._borderThickness;
  40300. },
  40301. set: function (value) {
  40302. this._borderThickness = value;
  40303. },
  40304. enumerable: true,
  40305. configurable: true
  40306. });
  40307. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  40308. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  40309. // Fill Part
  40310. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  40311. var fill = this.fill;
  40312. if (fill instanceof BABYLON.SolidColorBrush2D) {
  40313. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  40314. }
  40315. if (fill instanceof BABYLON.GradientColorBrush2D) {
  40316. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  40317. }
  40318. }
  40319. // Border Part
  40320. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  40321. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  40322. var border = this.border;
  40323. if (border instanceof BABYLON.SolidColorBrush2D) {
  40324. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  40325. }
  40326. if (border instanceof BABYLON.GradientColorBrush2D) {
  40327. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  40328. }
  40329. }
  40330. return cat;
  40331. };
  40332. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  40333. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  40334. return false;
  40335. }
  40336. // Fill Part
  40337. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  40338. var d = part;
  40339. if (this.fill) {
  40340. var fill = this.fill;
  40341. if (fill instanceof BABYLON.SolidColorBrush2D) {
  40342. d.fillSolidColor = fill.color;
  40343. }
  40344. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  40345. d.fillGradientColor1 = fill.color1;
  40346. d.fillGradientColor2 = fill.color2;
  40347. var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(fill.scale, fill.scale, fill.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), fill.rotation), new BABYLON.Vector3(fill.translation.x, fill.translation.y, 0));
  40348. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  40349. d.fillGradientTY = ty;
  40350. }
  40351. }
  40352. }
  40353. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  40354. var d = part;
  40355. if (this.border) {
  40356. d.borderThickness = this.borderThickness;
  40357. var border = this.border;
  40358. if (border instanceof BABYLON.SolidColorBrush2D) {
  40359. d.borderSolidColor = border.color;
  40360. }
  40361. else if (border instanceof BABYLON.GradientColorBrush2D) {
  40362. d.borderGradientColor1 = border.color1;
  40363. d.borderGradientColor2 = border.color2;
  40364. var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(border.scale, border.scale, border.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), border.rotation), new BABYLON.Vector3(border.translation.x, border.translation.y, 0));
  40365. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  40366. d.borderGradientTY = ty;
  40367. }
  40368. }
  40369. }
  40370. return true;
  40371. };
  40372. Shape2D.prototype._updateTransparencyStatus = function () {
  40373. this.isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent());
  40374. };
  40375. Shape2D.SHAPE2D_BORDERPARTID = 1;
  40376. Shape2D.SHAPE2D_FILLPARTID = 2;
  40377. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  40378. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  40379. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  40380. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  40381. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  40382. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  40383. __decorate([
  40384. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  40385. ], Shape2D.prototype, "border", null);
  40386. __decorate([
  40387. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  40388. ], Shape2D.prototype, "fill", null);
  40389. __decorate([
  40390. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  40391. ], Shape2D.prototype, "borderThickness", null);
  40392. Shape2D = __decorate([
  40393. BABYLON.className("Shape2D")
  40394. ], Shape2D);
  40395. return Shape2D;
  40396. })(BABYLON.RenderablePrim2D);
  40397. BABYLON.Shape2D = Shape2D;
  40398. var Shape2DInstanceData = (function (_super) {
  40399. __extends(Shape2DInstanceData, _super);
  40400. function Shape2DInstanceData() {
  40401. _super.apply(this, arguments);
  40402. }
  40403. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  40404. // FILL ATTRIBUTES
  40405. get: function () {
  40406. return null;
  40407. },
  40408. enumerable: true,
  40409. configurable: true
  40410. });
  40411. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  40412. get: function () {
  40413. return null;
  40414. },
  40415. enumerable: true,
  40416. configurable: true
  40417. });
  40418. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  40419. get: function () {
  40420. return null;
  40421. },
  40422. enumerable: true,
  40423. configurable: true
  40424. });
  40425. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  40426. get: function () {
  40427. return null;
  40428. },
  40429. enumerable: true,
  40430. configurable: true
  40431. });
  40432. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  40433. // BORDER ATTRIBUTES
  40434. get: function () {
  40435. return null;
  40436. },
  40437. enumerable: true,
  40438. configurable: true
  40439. });
  40440. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  40441. get: function () {
  40442. return null;
  40443. },
  40444. enumerable: true,
  40445. configurable: true
  40446. });
  40447. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  40448. get: function () {
  40449. return null;
  40450. },
  40451. enumerable: true,
  40452. configurable: true
  40453. });
  40454. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  40455. get: function () {
  40456. return null;
  40457. },
  40458. enumerable: true,
  40459. configurable: true
  40460. });
  40461. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  40462. get: function () {
  40463. return null;
  40464. },
  40465. enumerable: true,
  40466. configurable: true
  40467. });
  40468. __decorate([
  40469. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  40470. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  40471. __decorate([
  40472. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  40473. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  40474. __decorate([
  40475. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  40476. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  40477. __decorate([
  40478. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  40479. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  40480. __decorate([
  40481. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  40482. ], Shape2DInstanceData.prototype, "borderThickness", null);
  40483. __decorate([
  40484. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  40485. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  40486. __decorate([
  40487. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  40488. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  40489. __decorate([
  40490. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  40491. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  40492. __decorate([
  40493. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  40494. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  40495. return Shape2DInstanceData;
  40496. })(BABYLON.InstanceDataBase);
  40497. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  40498. })(BABYLON || (BABYLON = {}));
  40499. var BABYLON;
  40500. (function (BABYLON) {
  40501. var Group2D = (function (_super) {
  40502. __extends(Group2D, _super);
  40503. /**
  40504. * Create an Logical or Renderable Group.
  40505. * @param settings a combination of settings, possible ones are
  40506. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  40507. * - children: an array of direct children
  40508. * - id a text identifier, for information purpose
  40509. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  40510. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  40511. * - scale: the initial scale of the primitive. default is 1
  40512. * - origin: define the normalized origin point location, default [0.5;0.5]
  40513. * - size: the size of the group. Alternatively the width and height properties can be set. If null the size will be computed from its content, default is null.
  40514. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  40515. * - layoutEngine: either an instance of a layout engine based class (StackPanel.Vertical, StackPanel.Horizontal) or a string ('canvas' for Canvas layout, 'StackPanel' or 'HorizontalStackPanel' for horizontal Stack Panel layout, 'VerticalStackPanel' for vertical Stack Panel layout).
  40516. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  40517. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  40518. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  40519. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  40520. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  40521. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  40522. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  40523. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  40524. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  40525. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  40526. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  40527. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  40528. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  40529. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  40530. */
  40531. function Group2D(settings) {
  40532. if (settings == null) {
  40533. settings = {};
  40534. }
  40535. if (settings.origin == null) {
  40536. settings.origin = new BABYLON.Vector2(0, 0);
  40537. }
  40538. _super.call(this, settings);
  40539. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  40540. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  40541. if (this._trackedNode && this.owner) {
  40542. this.owner._registerTrackedNode(this);
  40543. }
  40544. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  40545. this.size = size;
  40546. this._viewportPosition = BABYLON.Vector2.Zero();
  40547. }
  40548. Group2D._createCachedCanvasGroup = function (owner) {
  40549. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true });
  40550. return g;
  40551. };
  40552. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  40553. this._bindCacheTarget();
  40554. if (vertexData) {
  40555. var uv = vertexData.uvs;
  40556. var nodeuv = this._renderableData._cacheNode.UVs;
  40557. for (var i = 0; i < 4; i++) {
  40558. uv[i * 2 + 0] = nodeuv[i].x;
  40559. uv[i * 2 + 1] = nodeuv[i].y;
  40560. }
  40561. }
  40562. if (material) {
  40563. material.diffuseTexture = this._renderableData._cacheTexture;
  40564. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  40565. }
  40566. this._renderableData._cacheTexture.hasAlpha = true;
  40567. this._unbindCacheTarget();
  40568. };
  40569. Object.defineProperty(Group2D.prototype, "cachedRect", {
  40570. /**
  40571. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  40572. * If the `noWorldSpaceNode` options was used at the creation of a WorldSpaceCanvas, the rendering of the canvas must be made by the caller, so typically you want to bind the cacheTexture property to some material/mesh and you must use the cachedRect.UVs property to get the UV coordinates to use for your quad that will display the Canvas.
  40573. */
  40574. get: function () {
  40575. if (!this._renderableData) {
  40576. return null;
  40577. }
  40578. return this._renderableData._cacheNode;
  40579. },
  40580. enumerable: true,
  40581. configurable: true
  40582. });
  40583. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  40584. /**
  40585. * Access the texture that maintains a cached version of the Group2D.
  40586. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  40587. */
  40588. get: function () {
  40589. if (!this._renderableData) {
  40590. return null;
  40591. }
  40592. return this._renderableData._cacheTexture;
  40593. },
  40594. enumerable: true,
  40595. configurable: true
  40596. });
  40597. /**
  40598. * Call this method to remove this Group and its children from the Canvas
  40599. */
  40600. Group2D.prototype.dispose = function () {
  40601. if (!_super.prototype.dispose.call(this)) {
  40602. return false;
  40603. }
  40604. if (this._trackedNode != null) {
  40605. this.owner._unregisterTrackedNode(this);
  40606. this._trackedNode = null;
  40607. }
  40608. if (this._renderableData) {
  40609. this._renderableData.dispose();
  40610. this._renderableData = null;
  40611. }
  40612. return true;
  40613. };
  40614. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  40615. /**
  40616. * @returns Returns true if the Group render content, false if it's a logical group only
  40617. */
  40618. get: function () {
  40619. return this._isRenderableGroup;
  40620. },
  40621. enumerable: true,
  40622. configurable: true
  40623. });
  40624. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  40625. /**
  40626. * @returns only meaningful for isRenderableGroup, will be true if the content of the Group is cached into a texture, false if it's rendered every time
  40627. */
  40628. get: function () {
  40629. return this._isCachedGroup;
  40630. },
  40631. enumerable: true,
  40632. configurable: true
  40633. });
  40634. Object.defineProperty(Group2D.prototype, "size", {
  40635. get: function () {
  40636. return this._size;
  40637. },
  40638. /**
  40639. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  40640. * BEWARE: if the Group is a RenderableGroup and its content is cache the texture will be resized each time the group is getting bigger. For performance reason the opposite won't be true: the texture won't shrink if the group does.
  40641. */
  40642. set: function (val) {
  40643. this._size = val;
  40644. },
  40645. enumerable: true,
  40646. configurable: true
  40647. });
  40648. Object.defineProperty(Group2D.prototype, "viewportSize", {
  40649. get: function () {
  40650. return this._viewportSize;
  40651. },
  40652. enumerable: true,
  40653. configurable: true
  40654. });
  40655. Object.defineProperty(Group2D.prototype, "actualSize", {
  40656. get: function () {
  40657. // The computed size will be floor on both width and height
  40658. var actualSize;
  40659. // Return the size if set by the user
  40660. if (this._size) {
  40661. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  40662. }
  40663. else {
  40664. var m = this.boundingInfo.max();
  40665. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  40666. }
  40667. // Compare the size with the one we previously had, if it differs we set the property dirty and trigger a GroupChanged to synchronize a displaySprite (if any)
  40668. if (!actualSize.equals(this._actualSize)) {
  40669. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  40670. this._actualSize = actualSize;
  40671. this.handleGroupChanged(Group2D.actualSizeProperty);
  40672. }
  40673. return actualSize;
  40674. },
  40675. enumerable: true,
  40676. configurable: true
  40677. });
  40678. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  40679. /**
  40680. * Get/set the Cache Behavior, used in case the Canvas Cache Strategy is set to CACHESTRATEGY_ALLGROUPS. Can be either GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP, GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE or GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY. See their documentation for more information.
  40681. * It is critical to understand than you HAVE TO play with this behavior in order to achieve a good performance/memory ratio. Caching all groups would certainly be the worst strategy of all.
  40682. */
  40683. get: function () {
  40684. return this._cacheBehavior;
  40685. },
  40686. enumerable: true,
  40687. configurable: true
  40688. });
  40689. Group2D.prototype._addPrimToDirtyList = function (prim) {
  40690. this._renderableData._primDirtyList.push(prim);
  40691. };
  40692. Group2D.prototype._renderCachedCanvas = function () {
  40693. this.updateCachedStates(true);
  40694. var context = new BABYLON.PrepareRender2DContext();
  40695. this._prepareGroupRender(context);
  40696. this._groupRender();
  40697. };
  40698. Object.defineProperty(Group2D.prototype, "trackedNode", {
  40699. /**
  40700. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  40701. */
  40702. get: function () {
  40703. return this._trackedNode;
  40704. },
  40705. set: function (val) {
  40706. if (val != null) {
  40707. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  40708. this.owner._registerTrackedNode(this);
  40709. }
  40710. this._trackedNode = val;
  40711. }
  40712. else {
  40713. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  40714. this.owner._unregisterTrackedNode(this);
  40715. }
  40716. this._trackedNode = null;
  40717. }
  40718. },
  40719. enumerable: true,
  40720. configurable: true
  40721. });
  40722. Group2D.prototype.levelIntersect = function (intersectInfo) {
  40723. // If we've made it so far it means the boundingInfo intersection test succeed, the Group2D is shaped the same, so we always return true
  40724. return true;
  40725. };
  40726. Group2D.prototype.updateLevelBoundingInfo = function () {
  40727. var size;
  40728. // If the size is set by the user, the boundingInfo is computed from this value
  40729. if (this.size) {
  40730. size = this.size;
  40731. }
  40732. else {
  40733. size = new BABYLON.Size(0, 0);
  40734. }
  40735. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  40736. };
  40737. // Method called only on renderable groups to prepare the rendering
  40738. Group2D.prototype._prepareGroupRender = function (context) {
  40739. var sortedDirtyList = null;
  40740. // Update the Global Transformation and visibility status of the changed primitives
  40741. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  40742. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  40743. this.updateCachedStatesOf(sortedDirtyList, true);
  40744. }
  40745. // Setup the size of the rendering viewport
  40746. // In non cache mode, we're rendering directly to the rendering canvas, in this case we have to detect if the canvas size changed since the previous iteration, if it's the case all primitives must be prepared again because their transformation must be recompute
  40747. if (!this._isCachedGroup) {
  40748. // Compute the WebGL viewport's location/size
  40749. var t = this._globalTransform.getTranslation();
  40750. var s = this.actualSize.clone();
  40751. var rs = this.owner._renderingSize;
  40752. s.height = Math.min(s.height, rs.height - t.y);
  40753. s.width = Math.min(s.width, rs.width - t.x);
  40754. var x = t.x;
  40755. var y = t.y;
  40756. // The viewport where we're rendering must be the size of the canvas if this one fit in the rendering screen or clipped to the screen dimensions if needed
  40757. this._viewportPosition.x = x;
  40758. this._viewportPosition.y = y;
  40759. var vw = s.width;
  40760. var vh = s.height;
  40761. if (!this._viewportSize) {
  40762. this._viewportSize = new BABYLON.Size(vw, vh);
  40763. }
  40764. else {
  40765. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  40766. context.forceRefreshPrimitive = true;
  40767. }
  40768. this._viewportSize.width = vw;
  40769. this._viewportSize.height = vh;
  40770. }
  40771. }
  40772. else {
  40773. var newSize = this.actualSize.clone();
  40774. if (!newSize.equals(this._viewportSize)) {
  40775. context.forceRefreshPrimitive = true;
  40776. }
  40777. this._viewportSize = newSize;
  40778. }
  40779. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  40780. // If the group is cached, set the dirty flag to true because of the incoming changes
  40781. this._cacheGroupDirty = this._isCachedGroup;
  40782. // If it's a force refresh, prepare all the children
  40783. if (context.forceRefreshPrimitive) {
  40784. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40785. var p = _a[_i];
  40786. p._prepareRender(context);
  40787. }
  40788. }
  40789. else {
  40790. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  40791. // the hierarchyDepth in order to prepare primitives from top to bottom
  40792. if (!sortedDirtyList) {
  40793. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  40794. }
  40795. sortedDirtyList.forEach(function (p) {
  40796. // We need to check if prepare is needed because even if the primitive is in the dirtyList, its parent primitive may also have been modified, then prepared, then recurse on its children primitives (this one for instance) if the changes where impacting them.
  40797. // For instance: a Rect's position change, the position of its children primitives will also change so a prepare will be call on them. If a child was in the dirtyList we will avoid a second prepare by making this check.
  40798. if (!p.isDisposed && p._needPrepare()) {
  40799. p._prepareRender(context);
  40800. }
  40801. });
  40802. // Everything is updated, clear the dirty list
  40803. this._renderableData._primDirtyList.forEach(function (p) { return p._resetPropertiesDirty(); });
  40804. this._renderableData._primDirtyList.splice(0);
  40805. }
  40806. }
  40807. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  40808. this._renderableData._childrenRenderableGroups.forEach(function (g) {
  40809. g._prepareGroupRender(context);
  40810. });
  40811. };
  40812. Group2D.prototype._groupRender = function () {
  40813. var _this = this;
  40814. var engine = this.owner.engine;
  40815. var failedCount = 0;
  40816. // First recurse to children render group to render them (in their cache or on screen)
  40817. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  40818. var childGroup = _a[_i];
  40819. childGroup._groupRender();
  40820. }
  40821. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  40822. if (!this.isCachedGroup || this._cacheGroupDirty) {
  40823. if (this.isCachedGroup) {
  40824. this._bindCacheTarget();
  40825. }
  40826. else {
  40827. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  40828. }
  40829. var curAlphaTest = engine.getAlphaTesting() === true;
  40830. var curDepthWrite = engine.getDepthWrite() === true;
  40831. // ===================================================================
  40832. // First pass, update the InstancedArray and render Opaque primitives
  40833. // Disable Alpha Testing, Enable Depth Write
  40834. engine.setAlphaTesting(false);
  40835. engine.setDepthWrite(true);
  40836. // For each different model of primitive to render
  40837. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  40838. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  40839. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  40840. var renderCount = _this._prepareContext(engine, context, v);
  40841. // If null is returned, there's no opaque data to render
  40842. if (renderCount === null) {
  40843. return;
  40844. }
  40845. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  40846. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  40847. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  40848. var renderFailed = !v.modelRenderCache.render(v, context);
  40849. // Update dirty flag/related
  40850. v.opaqueDirty = renderFailed;
  40851. failedCount += renderFailed ? 1 : 0;
  40852. }
  40853. });
  40854. // =======================================================================
  40855. // Second pass, update the InstancedArray and render AlphaTest primitives
  40856. // Enable Alpha Testing, Enable Depth Write
  40857. engine.setAlphaTesting(true);
  40858. engine.setDepthWrite(true);
  40859. // For each different model of primitive to render
  40860. context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  40861. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  40862. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  40863. var renderCount = _this._prepareContext(engine, context, v);
  40864. // If null is returned, there's no opaque data to render
  40865. if (renderCount === null) {
  40866. return;
  40867. }
  40868. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  40869. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  40870. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  40871. var renderFailed = !v.modelRenderCache.render(v, context);
  40872. // Update dirty flag/related
  40873. v.opaqueDirty = renderFailed;
  40874. failedCount += renderFailed ? 1 : 0;
  40875. }
  40876. });
  40877. // =======================================================================
  40878. // Third pass, transparent primitive rendering
  40879. // Enable Alpha Testing, Disable Depth Write
  40880. engine.setAlphaTesting(true);
  40881. engine.setDepthWrite(false);
  40882. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  40883. if (this._renderableData._transparentListChanged) {
  40884. this._updateTransparentData();
  40885. }
  40886. // From this point on we have up to date data to render, so let's go
  40887. failedCount += this._renderTransparentData();
  40888. // =======================================================================
  40889. // Unbind target/restore viewport setting, clear dirty flag, and quit
  40890. // The group's content is no longer dirty
  40891. this._cacheGroupDirty = failedCount !== 0;
  40892. if (this.isCachedGroup) {
  40893. this._unbindCacheTarget();
  40894. }
  40895. else {
  40896. if (curVP) {
  40897. engine.setViewport(curVP);
  40898. }
  40899. }
  40900. // Restore saved states
  40901. engine.setAlphaTesting(curAlphaTest);
  40902. engine.setDepthWrite(curDepthWrite);
  40903. }
  40904. };
  40905. Group2D.prototype._updateTransparentData = function () {
  40906. var rd = this._renderableData;
  40907. // If null, there was no change of ZOrder, we have nothing to do
  40908. if (rd._firstChangedPrim === null) {
  40909. return;
  40910. }
  40911. // Sort all the primitive from their depth, max (bottom) to min (top)
  40912. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  40913. var checkAndAddPrimInSegment = function (seg, tpiI) {
  40914. var tpi = rd._transparentPrimitives[tpiI];
  40915. // Fast rejection: if gii are different
  40916. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  40917. return false;
  40918. }
  40919. var tpiZ = tpi._primitive.actualZOffset;
  40920. // We've made it so far, the tpi can be part of the segment, add it
  40921. tpi._transparentSegment = seg;
  40922. // Check if we have to update endZ, a smaller value means one above the current one
  40923. if (tpiZ < seg.endZ) {
  40924. seg.endZ = tpiZ;
  40925. seg.endDataIndex = tpi._primitive._getLastIndexInDataBuffer() + 1; // Still exclusive
  40926. }
  40927. return true;
  40928. };
  40929. rd._transparentSegments.splice(0);
  40930. var prevSeg = null;
  40931. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  40932. var tpi = rd._transparentPrimitives[tpiI];
  40933. // Check if the Data in which the primitive is stored is not sorted properly
  40934. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  40935. tpi._groupInstanceInfo.sortTransparentData();
  40936. }
  40937. // Reset the segment, we have to create/rebuild it
  40938. tpi._transparentSegment = null;
  40939. // If there's a previous valid segment, check if this prim can be part of it
  40940. if (prevSeg) {
  40941. checkAndAddPrimInSegment(prevSeg, tpiI);
  40942. }
  40943. // If we couldn't insert in the adjacent segments, he have to create one
  40944. if (!tpi._transparentSegment) {
  40945. var ts = new BABYLON.TransparentSegment();
  40946. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  40947. var prim = tpi._primitive;
  40948. ts.startZ = prim.actualZOffset;
  40949. ts.startDataIndex = prim._getFirstIndexInDataBuffer();
  40950. ts.endDataIndex = prim._getLastIndexInDataBuffer() + 1; // Make it exclusive, more natural to use in a for loop
  40951. ts.endZ = ts.startZ;
  40952. tpi._transparentSegment = ts;
  40953. rd._transparentSegments.push(ts);
  40954. }
  40955. // Update prevSeg
  40956. prevSeg = tpi._transparentSegment;
  40957. }
  40958. rd._firstChangedPrim = null;
  40959. rd._transparentListChanged = false;
  40960. };
  40961. Group2D.prototype._renderTransparentData = function () {
  40962. var failedCount = 0;
  40963. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  40964. var rd = this._renderableData;
  40965. var length = rd._transparentSegments.length;
  40966. for (var i = 0; i < length; i++) {
  40967. var ts = rd._transparentSegments[i];
  40968. var gii = ts.groupInsanceInfo;
  40969. var mrc = gii.modelRenderCache;
  40970. context.useInstancing = false;
  40971. context.partDataStartIndex = ts.startDataIndex;
  40972. context.partDataEndIndex = ts.endDataIndex;
  40973. context.groupInfoPartData = gii.transparentData;
  40974. var renderFailed = !mrc.render(gii, context);
  40975. failedCount += renderFailed ? 1 : 0;
  40976. }
  40977. return failedCount;
  40978. };
  40979. Group2D.prototype._prepareContext = function (engine, context, gii) {
  40980. var gipd = null;
  40981. var setDirty;
  40982. var getDirty;
  40983. // Render Mode specifics
  40984. switch (context.renderMode) {
  40985. case BABYLON.Render2DContext.RenderModeOpaque:
  40986. {
  40987. if (!gii.hasOpaqueData) {
  40988. return null;
  40989. }
  40990. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  40991. getDirty = function () { return gii.opaqueDirty; };
  40992. context.groupInfoPartData = gii.opaqueData;
  40993. gipd = gii.opaqueData;
  40994. break;
  40995. }
  40996. case BABYLON.Render2DContext.RenderModeAlphaTest:
  40997. {
  40998. if (!gii.hasAlphaTestData) {
  40999. return null;
  41000. }
  41001. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  41002. getDirty = function () { return gii.alphaTestDirty; };
  41003. context.groupInfoPartData = gii.alphaTestData;
  41004. gipd = gii.alphaTestData;
  41005. break;
  41006. }
  41007. default:
  41008. throw new Error("_prepareContext is only for opaque or alphaTest");
  41009. }
  41010. var renderCount = 0;
  41011. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  41012. // Skip it if instanced arrays are not supported
  41013. if (this.owner.supportInstancedArray) {
  41014. // Flag for instancing
  41015. context.useInstancing = true;
  41016. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  41017. for (var i = 0; i < gipd.length; i++) {
  41018. var pid = gipd[i];
  41019. // If the instances of the model was changed, pack the data
  41020. var array = pid._partData;
  41021. var instanceData_1 = array.pack();
  41022. renderCount += array.usedElementCount;
  41023. // Compute the size the instance buffer should have
  41024. var neededSize = array.usedElementCount * array.stride * 4;
  41025. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  41026. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  41027. if (pid._partBuffer) {
  41028. engine.deleteInstancesBuffer(pid._partBuffer);
  41029. }
  41030. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  41031. pid._partBufferSize = neededSize;
  41032. setDirty(false);
  41033. // Update the WebGL buffer to match the new content of the instances data
  41034. engine.updateArrayBuffer(instanceData_1);
  41035. }
  41036. else if (getDirty()) {
  41037. // Update the WebGL buffer to match the new content of the instances data
  41038. engine.bindArrayBuffer(pid._partBuffer);
  41039. engine.updateArrayBuffer(instanceData_1);
  41040. }
  41041. }
  41042. setDirty(false);
  41043. }
  41044. else {
  41045. context.partDataStartIndex = 0;
  41046. // Find the first valid object to get the count
  41047. var i = 0;
  41048. while (!context.groupInfoPartData[i]) {
  41049. i++;
  41050. }
  41051. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  41052. }
  41053. return renderCount;
  41054. };
  41055. Group2D.prototype._bindCacheTarget = function () {
  41056. var curWidth;
  41057. var curHeight;
  41058. var rd = this._renderableData;
  41059. if (rd._cacheNode) {
  41060. var size = rd._cacheNode.contentSize;
  41061. var groupWidth = Math.ceil(this.actualSize.width);
  41062. var groupHeight = Math.ceil(this.actualSize.height);
  41063. if ((size.width < groupWidth) || (size.height < groupHeight)) {
  41064. curWidth = Math.floor(size.width * 1.07); // Grow 5% more to avoid frequent resizing for few pixels...
  41065. curHeight = Math.floor(size.height * 1.07);
  41066. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  41067. rd._cacheTexture.freeRect(rd._cacheNode);
  41068. rd._cacheNode = null;
  41069. }
  41070. }
  41071. if (!rd._cacheNode) {
  41072. // Check if we have to allocate a rendering zone in the global cache texture
  41073. var res = this.owner._allocateGroupCache(this, this.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null);
  41074. rd._cacheNode = res.node;
  41075. rd._cacheTexture = res.texture;
  41076. rd._cacheRenderSprite = res.sprite;
  41077. var size = rd._cacheNode.contentSize;
  41078. }
  41079. var n = rd._cacheNode;
  41080. rd._cacheTexture.bindTextureForPosSize(n.pos, this.actualSize, true);
  41081. };
  41082. Group2D.prototype._unbindCacheTarget = function () {
  41083. if (this._renderableData._cacheTexture) {
  41084. this._renderableData._cacheTexture.unbindTexture();
  41085. }
  41086. };
  41087. Group2D.prototype.handleGroupChanged = function (prop) {
  41088. // This method is only for cachedGroup
  41089. var rd = this._renderableData;
  41090. if (!this.isCachedGroup || !rd._cacheRenderSprite) {
  41091. return;
  41092. }
  41093. // For now we only support these property changes
  41094. // TODO: add more! :)
  41095. if (prop.id === BABYLON.Prim2DBase.actualPositionProperty.id) {
  41096. rd._cacheRenderSprite.actualPosition = this.actualPosition.clone();
  41097. }
  41098. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  41099. rd._cacheRenderSprite.rotation = this.rotation;
  41100. }
  41101. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  41102. rd._cacheRenderSprite.scale = this.scale;
  41103. }
  41104. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  41105. rd._cacheRenderSprite.origin = this.origin.clone();
  41106. }
  41107. else if (prop.id === Group2D.actualSizeProperty.id) {
  41108. rd._cacheRenderSprite.size = this.actualSize.clone();
  41109. }
  41110. };
  41111. Group2D.prototype.detectGroupStates = function () {
  41112. var isCanvas = this instanceof BABYLON.Canvas2D;
  41113. var canvasStrat = this.owner.cachingStrategy;
  41114. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  41115. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  41116. this._isRenderableGroup = isCanvas;
  41117. this._isCachedGroup = false;
  41118. }
  41119. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  41120. if (isCanvas) {
  41121. this._isRenderableGroup = true;
  41122. this._isCachedGroup = true;
  41123. }
  41124. else {
  41125. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  41126. this._isCachedGroup = false;
  41127. }
  41128. }
  41129. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  41130. if (isCanvas) {
  41131. this._isRenderableGroup = true;
  41132. this._isCachedGroup = false;
  41133. }
  41134. else {
  41135. if (this.hierarchyDepth === 1) {
  41136. this._isRenderableGroup = true;
  41137. this._isCachedGroup = true;
  41138. }
  41139. else {
  41140. this._isRenderableGroup = false;
  41141. this._isCachedGroup = false;
  41142. }
  41143. }
  41144. }
  41145. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  41146. var gcb = this.cacheBehavior;
  41147. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  41148. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  41149. this._isCachedGroup = false;
  41150. }
  41151. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  41152. this._isRenderableGroup = true;
  41153. this._isCachedGroup = true;
  41154. }
  41155. }
  41156. if (this._isRenderableGroup) {
  41157. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  41158. if (!this._renderableData) {
  41159. this._renderableData = new RenderableGroupData();
  41160. }
  41161. }
  41162. // If the group is tagged as renderable we add it to the renderable tree
  41163. if (this._isCachedGroup) {
  41164. var cur = this.parent;
  41165. while (cur) {
  41166. if (cur instanceof Group2D && cur._isRenderableGroup) {
  41167. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  41168. cur._renderableData._childrenRenderableGroups.push(this);
  41169. }
  41170. break;
  41171. }
  41172. cur = cur.parent;
  41173. }
  41174. }
  41175. };
  41176. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  41177. /**
  41178. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  41179. */
  41180. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  41181. /**
  41182. * When used, this group's content won't be cached, no matter which strategy used.
  41183. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  41184. */
  41185. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  41186. /**
  41187. * When used, the group's content will be cached in the nearest cached parent group/canvas
  41188. */
  41189. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  41190. __decorate([
  41191. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  41192. ], Group2D.prototype, "size", null);
  41193. __decorate([
  41194. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  41195. ], Group2D.prototype, "actualSize", null);
  41196. Group2D = __decorate([
  41197. BABYLON.className("Group2D")
  41198. ], Group2D);
  41199. return Group2D;
  41200. })(BABYLON.Prim2DBase);
  41201. BABYLON.Group2D = Group2D;
  41202. var RenderableGroupData = (function () {
  41203. function RenderableGroupData() {
  41204. this._primDirtyList = new Array();
  41205. this._childrenRenderableGroups = new Array();
  41206. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  41207. this._transparentPrimitives = new Array();
  41208. this._transparentSegments = new Array();
  41209. this._firstChangedPrim = null;
  41210. this._transparentListChanged = false;
  41211. this._cacheNode = null;
  41212. this._cacheTexture = null;
  41213. this._cacheRenderSprite = null;
  41214. }
  41215. RenderableGroupData.prototype.dispose = function () {
  41216. if (this._cacheRenderSprite) {
  41217. this._cacheRenderSprite.dispose();
  41218. this._cacheRenderSprite = null;
  41219. }
  41220. if (this._cacheTexture && this._cacheNode) {
  41221. this._cacheTexture.freeRect(this._cacheNode);
  41222. this._cacheTexture = null;
  41223. this._cacheNode = null;
  41224. }
  41225. if (this._primDirtyList) {
  41226. this._primDirtyList.splice(0);
  41227. this._primDirtyList = null;
  41228. }
  41229. if (this._renderGroupInstancesInfo) {
  41230. this._renderGroupInstancesInfo.forEach(function (k, v) {
  41231. v.dispose();
  41232. });
  41233. this._renderGroupInstancesInfo = null;
  41234. }
  41235. };
  41236. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  41237. var tpi = new TransparentPrimitiveInfo();
  41238. tpi._primitive = prim;
  41239. tpi._groupInstanceInfo = gii;
  41240. tpi._transparentSegment = null;
  41241. this._transparentPrimitives.push(tpi);
  41242. this._transparentListChanged = true;
  41243. this.updateSmallestZChangedPrim(tpi);
  41244. return tpi;
  41245. };
  41246. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  41247. var index = this._transparentPrimitives.indexOf(tpi);
  41248. if (index !== -1) {
  41249. this._transparentPrimitives.splice(index, 1);
  41250. this._transparentListChanged = true;
  41251. this.updateSmallestZChangedPrim(tpi);
  41252. }
  41253. };
  41254. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  41255. this._transparentListChanged = true;
  41256. this.updateSmallestZChangedPrim(tpi);
  41257. };
  41258. RenderableGroupData.prototype.updateSmallestZChangedPrim = function (tpi) {
  41259. if (tpi._primitive) {
  41260. var newZ = tpi._primitive.actualZOffset;
  41261. var curZ = this._firstChangedPrim ? this._firstChangedPrim._primitive.actualZOffset : Number.MIN_VALUE;
  41262. if (newZ > curZ) {
  41263. this._firstChangedPrim = tpi;
  41264. }
  41265. }
  41266. };
  41267. return RenderableGroupData;
  41268. })();
  41269. BABYLON.RenderableGroupData = RenderableGroupData;
  41270. var TransparentPrimitiveInfo = (function () {
  41271. function TransparentPrimitiveInfo() {
  41272. }
  41273. return TransparentPrimitiveInfo;
  41274. })();
  41275. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  41276. })(BABYLON || (BABYLON = {}));
  41277. var BABYLON;
  41278. (function (BABYLON) {
  41279. var Rectangle2DRenderCache = (function (_super) {
  41280. __extends(Rectangle2DRenderCache, _super);
  41281. function Rectangle2DRenderCache(engine, modelKey) {
  41282. _super.call(this, engine, modelKey);
  41283. this.effectsReady = false;
  41284. this.fillVB = null;
  41285. this.fillIB = null;
  41286. this.fillIndicesCount = 0;
  41287. this.instancingFillAttributes = null;
  41288. this.effectFill = null;
  41289. this.effectFillInstanced = null;
  41290. this.borderVB = null;
  41291. this.borderIB = null;
  41292. this.borderIndicesCount = 0;
  41293. this.instancingBorderAttributes = null;
  41294. this.effectBorder = null;
  41295. this.effectBorderInstanced = null;
  41296. }
  41297. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  41298. // Do nothing if the shader is still loading/preparing
  41299. if (!this.effectsReady) {
  41300. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  41301. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  41302. return false;
  41303. }
  41304. this.effectsReady = true;
  41305. }
  41306. var engine = instanceInfo.owner.owner.engine;
  41307. var depthFunction = 0;
  41308. if (this.effectFill && this.effectBorder) {
  41309. depthFunction = engine.getDepthFunction();
  41310. engine.setDepthFunctionToLessOrEqual();
  41311. }
  41312. var curAlphaMode = engine.getAlphaMode();
  41313. if (this.effectFill) {
  41314. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  41315. var pid = context.groupInfoPartData[partIndex];
  41316. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  41317. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41318. }
  41319. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  41320. engine.enableEffect(effect);
  41321. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  41322. if (context.useInstancing) {
  41323. if (!this.instancingFillAttributes) {
  41324. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  41325. }
  41326. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingFillAttributes);
  41327. engine.draw(true, 0, this.fillIndicesCount, pid._partData.usedElementCount);
  41328. engine.unbindInstanceAttributes();
  41329. }
  41330. else {
  41331. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  41332. this.setupUniforms(effect, partIndex, pid._partData, i);
  41333. engine.draw(true, 0, this.fillIndicesCount);
  41334. }
  41335. }
  41336. }
  41337. if (this.effectBorder) {
  41338. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  41339. var pid = context.groupInfoPartData[partIndex];
  41340. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  41341. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41342. }
  41343. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  41344. engine.enableEffect(effect);
  41345. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  41346. if (context.useInstancing) {
  41347. if (!this.instancingBorderAttributes) {
  41348. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  41349. }
  41350. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingBorderAttributes);
  41351. engine.draw(true, 0, this.borderIndicesCount, pid._partData.usedElementCount);
  41352. engine.unbindInstanceAttributes();
  41353. }
  41354. else {
  41355. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  41356. this.setupUniforms(effect, partIndex, pid._partData, i);
  41357. engine.draw(true, 0, this.borderIndicesCount);
  41358. }
  41359. }
  41360. }
  41361. engine.setAlphaMode(curAlphaMode);
  41362. if (this.effectFill && this.effectBorder) {
  41363. engine.setDepthFunction(depthFunction);
  41364. }
  41365. return true;
  41366. };
  41367. Rectangle2DRenderCache.prototype.dispose = function () {
  41368. if (!_super.prototype.dispose.call(this)) {
  41369. return false;
  41370. }
  41371. if (this.fillVB) {
  41372. this._engine._releaseBuffer(this.fillVB);
  41373. this.fillVB = null;
  41374. }
  41375. if (this.fillIB) {
  41376. this._engine._releaseBuffer(this.fillIB);
  41377. this.fillIB = null;
  41378. }
  41379. if (this.effectFill) {
  41380. this._engine._releaseEffect(this.effectFill);
  41381. this.effectFill = null;
  41382. }
  41383. if (this.effectFillInstanced) {
  41384. this._engine._releaseEffect(this.effectFillInstanced);
  41385. this.effectFillInstanced = null;
  41386. }
  41387. if (this.borderVB) {
  41388. this._engine._releaseBuffer(this.borderVB);
  41389. this.borderVB = null;
  41390. }
  41391. if (this.borderIB) {
  41392. this._engine._releaseBuffer(this.borderIB);
  41393. this.borderIB = null;
  41394. }
  41395. if (this.effectBorder) {
  41396. this._engine._releaseEffect(this.effectBorder);
  41397. this.effectBorder = null;
  41398. }
  41399. if (this.effectBorderInstanced) {
  41400. this._engine._releaseEffect(this.effectBorderInstanced);
  41401. this.effectBorderInstanced = null;
  41402. }
  41403. return true;
  41404. };
  41405. return Rectangle2DRenderCache;
  41406. })(BABYLON.ModelRenderCache);
  41407. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  41408. var Rectangle2DInstanceData = (function (_super) {
  41409. __extends(Rectangle2DInstanceData, _super);
  41410. function Rectangle2DInstanceData(partId) {
  41411. _super.call(this, partId, 1);
  41412. }
  41413. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  41414. get: function () {
  41415. return null;
  41416. },
  41417. enumerable: true,
  41418. configurable: true
  41419. });
  41420. __decorate([
  41421. BABYLON.instanceData()
  41422. ], Rectangle2DInstanceData.prototype, "properties", null);
  41423. return Rectangle2DInstanceData;
  41424. })(BABYLON.Shape2DInstanceData);
  41425. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  41426. var Rectangle2D = (function (_super) {
  41427. __extends(Rectangle2D, _super);
  41428. /**
  41429. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  41430. * @param settings a combination of settings, possible ones are
  41431. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  41432. * - children: an array of direct children
  41433. * - id a text identifier, for information purpose
  41434. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  41435. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  41436. * - scale: the initial scale of the primitive. default is 1
  41437. * - origin: define the normalized origin point location, default [0.5;0.5]
  41438. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  41439. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  41440. * - fill: the brush used to draw the fill content of the rectangle, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can also be a string value (see Canvas2D.GetBrushFromString)
  41441. * - border: the brush used to draw the border of the rectangle, you can set null to draw nothing (but you will have to set a fill brush), default is null. can also be a string value (see Canvas2D.GetBrushFromString)
  41442. * - borderThickness: the thickness of the drawn border, default is 1.
  41443. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  41444. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41445. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41446. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41447. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41448. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  41449. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  41450. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  41451. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  41452. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41453. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41454. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41455. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41456. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  41457. */
  41458. function Rectangle2D(settings) {
  41459. // Avoid checking every time if the object exists
  41460. if (settings == null) {
  41461. settings = {};
  41462. }
  41463. _super.call(this, settings);
  41464. if (settings.size != null) {
  41465. this.size = settings.size;
  41466. }
  41467. else if (settings.width || settings.height) {
  41468. var size = new BABYLON.Size(settings.width, settings.height);
  41469. this.size = size;
  41470. }
  41471. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  41472. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  41473. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  41474. //this.size = size;
  41475. this.roundRadius = roundRadius;
  41476. this.borderThickness = borderThickness;
  41477. }
  41478. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  41479. get: function () {
  41480. if (this._actualSize) {
  41481. return this._actualSize;
  41482. }
  41483. return this.size;
  41484. },
  41485. set: function (value) {
  41486. this._actualSize = value;
  41487. },
  41488. enumerable: true,
  41489. configurable: true
  41490. });
  41491. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  41492. get: function () {
  41493. return this._notRounded;
  41494. },
  41495. set: function (value) {
  41496. this._notRounded = value;
  41497. },
  41498. enumerable: true,
  41499. configurable: true
  41500. });
  41501. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  41502. get: function () {
  41503. return this._roundRadius;
  41504. },
  41505. set: function (value) {
  41506. this._roundRadius = value;
  41507. this.notRounded = value === 0;
  41508. this._positioningDirty();
  41509. },
  41510. enumerable: true,
  41511. configurable: true
  41512. });
  41513. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  41514. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  41515. if (this.notRounded) {
  41516. return true;
  41517. }
  41518. // If we got so far it means the bounding box at least passed, so we know it's inside the bounding rectangle, but it can be outside the roundedRectangle.
  41519. // The easiest way is to check if the point is inside on of the four corners area (a little square of roundRadius size at the four corners)
  41520. // If it's the case for one, check if the mouse is located in the quarter that we care about (the one who is visible) then finally make a distance check with the roundRadius radius to see if it's inside the circle quarter or outside.
  41521. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  41522. var size = this.size;
  41523. Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
  41524. Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
  41525. var rr = this.roundRadius;
  41526. var rrs = rr * rr;
  41527. // Check if the point is in the bottom/left quarter area
  41528. Rectangle2D._i1.x = rr;
  41529. Rectangle2D._i1.y = rr;
  41530. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  41531. // Compute the intersection point in the quarter local space
  41532. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  41533. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  41534. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  41535. return Rectangle2D._i2.lengthSquared() <= rrs;
  41536. }
  41537. // Check if the point is in the top/left quarter area
  41538. Rectangle2D._i1.x = rr;
  41539. Rectangle2D._i1.y = size.height - rr;
  41540. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  41541. // Compute the intersection point in the quarter local space
  41542. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  41543. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  41544. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  41545. return Rectangle2D._i2.lengthSquared() <= rrs;
  41546. }
  41547. // Check if the point is in the top/right quarter area
  41548. Rectangle2D._i1.x = size.width - rr;
  41549. Rectangle2D._i1.y = size.height - rr;
  41550. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  41551. // Compute the intersection point in the quarter local space
  41552. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  41553. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  41554. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  41555. return Rectangle2D._i2.lengthSquared() <= rrs;
  41556. }
  41557. // Check if the point is in the bottom/right quarter area
  41558. Rectangle2D._i1.x = size.width - rr;
  41559. Rectangle2D._i1.y = rr;
  41560. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  41561. // Compute the intersection point in the quarter local space
  41562. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  41563. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  41564. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  41565. return Rectangle2D._i2.lengthSquared() <= rrs;
  41566. }
  41567. // At any other locations the point is guarantied to be inside
  41568. return true;
  41569. };
  41570. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  41571. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  41572. };
  41573. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  41574. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  41575. return renderCache;
  41576. };
  41577. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  41578. var renderCache = modelRenderCache;
  41579. var engine = this.owner.engine;
  41580. // Need to create WebGL resources for fill part?
  41581. if (this.fill) {
  41582. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  41583. var vb = new Float32Array(vbSize);
  41584. for (var i = 0; i < vbSize; i++) {
  41585. vb[i] = i;
  41586. }
  41587. renderCache.fillVB = engine.createVertexBuffer(vb);
  41588. var triCount = vbSize - 1;
  41589. var ib = new Float32Array(triCount * 3);
  41590. for (var i = 0; i < triCount; i++) {
  41591. ib[i * 3 + 0] = 0;
  41592. ib[i * 3 + 2] = i + 1;
  41593. ib[i * 3 + 1] = i + 2;
  41594. }
  41595. ib[triCount * 3 - 2] = 1;
  41596. renderCache.fillIB = engine.createIndexBuffer(ib);
  41597. renderCache.fillIndicesCount = triCount * 3;
  41598. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  41599. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  41600. if (ei) {
  41601. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  41602. }
  41603. // Get the non instanced version
  41604. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  41605. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  41606. }
  41607. // Need to create WebGL resource for border part?
  41608. if (this.border) {
  41609. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  41610. var vb = new Float32Array(vbSize);
  41611. for (var i = 0; i < vbSize; i++) {
  41612. vb[i] = i;
  41613. }
  41614. renderCache.borderVB = engine.createVertexBuffer(vb);
  41615. var triCount = vbSize;
  41616. var rs = triCount / 2;
  41617. var ib = new Float32Array(triCount * 3);
  41618. for (var i = 0; i < rs; i++) {
  41619. var r0 = i;
  41620. var r1 = (i + 1) % rs;
  41621. ib[i * 6 + 0] = rs + r1;
  41622. ib[i * 6 + 1] = rs + r0;
  41623. ib[i * 6 + 2] = r0;
  41624. ib[i * 6 + 3] = r1;
  41625. ib[i * 6 + 4] = rs + r1;
  41626. ib[i * 6 + 5] = r0;
  41627. }
  41628. renderCache.borderIB = engine.createIndexBuffer(ib);
  41629. renderCache.borderIndicesCount = triCount * 3;
  41630. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  41631. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  41632. if (ei) {
  41633. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  41634. }
  41635. // Get the non instanced version
  41636. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  41637. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  41638. }
  41639. return renderCache;
  41640. };
  41641. // We override this method because if there's a roundRadius set, we will reduce the initial Content Area to make sure the computed area won't intersect with the shape contour. The formula is simple: we shrink the incoming size by the amount of the roundRadius
  41642. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  41643. // Fall back to default implementation if there's no round Radius
  41644. if (this._notRounded) {
  41645. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  41646. }
  41647. else {
  41648. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  41649. initialContentPosition.x = initialContentPosition.y = rr;
  41650. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  41651. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  41652. }
  41653. };
  41654. Rectangle2D.prototype.createInstanceDataParts = function () {
  41655. var res = new Array();
  41656. if (this.border) {
  41657. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  41658. }
  41659. if (this.fill) {
  41660. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  41661. }
  41662. return res;
  41663. };
  41664. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  41665. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  41666. return false;
  41667. }
  41668. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  41669. var d = part;
  41670. var size = this.actualSize;
  41671. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  41672. }
  41673. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  41674. var d = part;
  41675. var size = this.actualSize;
  41676. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  41677. }
  41678. return true;
  41679. };
  41680. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  41681. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  41682. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  41683. Rectangle2D.roundSubdivisions = 16;
  41684. __decorate([
  41685. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
  41686. ], Rectangle2D.prototype, "actualSize", null);
  41687. __decorate([
  41688. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  41689. ], Rectangle2D.prototype, "notRounded", null);
  41690. __decorate([
  41691. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  41692. ], Rectangle2D.prototype, "roundRadius", null);
  41693. Rectangle2D = __decorate([
  41694. BABYLON.className("Rectangle2D")
  41695. ], Rectangle2D);
  41696. return Rectangle2D;
  41697. })(BABYLON.Shape2D);
  41698. BABYLON.Rectangle2D = Rectangle2D;
  41699. })(BABYLON || (BABYLON = {}));
  41700. var BABYLON;
  41701. (function (BABYLON) {
  41702. var Ellipse2DRenderCache = (function (_super) {
  41703. __extends(Ellipse2DRenderCache, _super);
  41704. function Ellipse2DRenderCache(engine, modelKey) {
  41705. _super.call(this, engine, modelKey);
  41706. this.effectsReady = false;
  41707. this.fillVB = null;
  41708. this.fillIB = null;
  41709. this.fillIndicesCount = 0;
  41710. this.instancingFillAttributes = null;
  41711. this.effectFillInstanced = null;
  41712. this.effectFill = null;
  41713. this.borderVB = null;
  41714. this.borderIB = null;
  41715. this.borderIndicesCount = 0;
  41716. this.instancingBorderAttributes = null;
  41717. this.effectBorderInstanced = null;
  41718. this.effectBorder = null;
  41719. }
  41720. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  41721. // Do nothing if the shader is still loading/preparing
  41722. if (!this.effectsReady) {
  41723. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  41724. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  41725. return false;
  41726. }
  41727. this.effectsReady = true;
  41728. }
  41729. var engine = instanceInfo.owner.owner.engine;
  41730. var depthFunction = 0;
  41731. if (this.effectFill && this.effectBorder) {
  41732. depthFunction = engine.getDepthFunction();
  41733. engine.setDepthFunctionToLessOrEqual();
  41734. }
  41735. var curAlphaMode = engine.getAlphaMode();
  41736. if (this.effectFill) {
  41737. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  41738. var pid = context.groupInfoPartData[partIndex];
  41739. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  41740. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41741. }
  41742. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  41743. engine.enableEffect(effect);
  41744. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  41745. if (context.useInstancing) {
  41746. if (!this.instancingFillAttributes) {
  41747. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  41748. }
  41749. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingFillAttributes);
  41750. engine.draw(true, 0, this.fillIndicesCount, pid._partData.usedElementCount);
  41751. engine.unbindInstanceAttributes();
  41752. }
  41753. else {
  41754. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  41755. this.setupUniforms(effect, partIndex, pid._partData, i);
  41756. engine.draw(true, 0, this.fillIndicesCount);
  41757. }
  41758. }
  41759. }
  41760. if (this.effectBorder) {
  41761. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  41762. var pid = context.groupInfoPartData[partIndex];
  41763. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  41764. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41765. }
  41766. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  41767. engine.enableEffect(effect);
  41768. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  41769. if (context.useInstancing) {
  41770. if (!this.instancingBorderAttributes) {
  41771. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  41772. }
  41773. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingBorderAttributes);
  41774. engine.draw(true, 0, this.borderIndicesCount, pid._partData.usedElementCount);
  41775. engine.unbindInstanceAttributes();
  41776. }
  41777. else {
  41778. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  41779. this.setupUniforms(effect, partIndex, pid._partData, i);
  41780. engine.draw(true, 0, this.borderIndicesCount);
  41781. }
  41782. }
  41783. }
  41784. engine.setAlphaMode(curAlphaMode);
  41785. if (this.effectFill && this.effectBorder) {
  41786. engine.setDepthFunction(depthFunction);
  41787. }
  41788. return true;
  41789. };
  41790. Ellipse2DRenderCache.prototype.dispose = function () {
  41791. if (!_super.prototype.dispose.call(this)) {
  41792. return false;
  41793. }
  41794. if (this.fillVB) {
  41795. this._engine._releaseBuffer(this.fillVB);
  41796. this.fillVB = null;
  41797. }
  41798. if (this.fillIB) {
  41799. this._engine._releaseBuffer(this.fillIB);
  41800. this.fillIB = null;
  41801. }
  41802. if (this.effectFill) {
  41803. this._engine._releaseEffect(this.effectFill);
  41804. this.effectFill = null;
  41805. }
  41806. if (this.effectFillInstanced) {
  41807. this._engine._releaseEffect(this.effectFillInstanced);
  41808. this.effectFillInstanced = null;
  41809. }
  41810. if (this.borderVB) {
  41811. this._engine._releaseBuffer(this.borderVB);
  41812. this.borderVB = null;
  41813. }
  41814. if (this.borderIB) {
  41815. this._engine._releaseBuffer(this.borderIB);
  41816. this.borderIB = null;
  41817. }
  41818. if (this.effectBorder) {
  41819. this._engine._releaseEffect(this.effectBorder);
  41820. this.effectBorder = null;
  41821. }
  41822. if (this.effectBorderInstanced) {
  41823. this._engine._releaseEffect(this.effectBorderInstanced);
  41824. this.effectBorderInstanced = null;
  41825. }
  41826. return true;
  41827. };
  41828. return Ellipse2DRenderCache;
  41829. })(BABYLON.ModelRenderCache);
  41830. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  41831. var Ellipse2DInstanceData = (function (_super) {
  41832. __extends(Ellipse2DInstanceData, _super);
  41833. function Ellipse2DInstanceData(partId) {
  41834. _super.call(this, partId, 1);
  41835. }
  41836. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  41837. get: function () {
  41838. return null;
  41839. },
  41840. enumerable: true,
  41841. configurable: true
  41842. });
  41843. __decorate([
  41844. BABYLON.instanceData()
  41845. ], Ellipse2DInstanceData.prototype, "properties", null);
  41846. return Ellipse2DInstanceData;
  41847. })(BABYLON.Shape2DInstanceData);
  41848. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  41849. var Ellipse2D = (function (_super) {
  41850. __extends(Ellipse2D, _super);
  41851. /**
  41852. * Create an Ellipse 2D Shape primitive
  41853. * @param settings a combination of settings, possible ones are
  41854. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  41855. * - children: an array of direct children
  41856. * - id: a text identifier, for information purpose
  41857. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  41858. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  41859. * - scale: the initial scale of the primitive. default is 1
  41860. * - origin: define the normalized origin point location, default [0.5;0.5]
  41861. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  41862. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  41863. * - fill: the brush used to draw the fill content of the ellipse, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can also be a string value (see Canvas2D.GetBrushFromString)
  41864. * - border: the brush used to draw the border of the ellipse, you can set null to draw nothing (but you will have to set a fill brush), default is null. can be a string value (see Canvas2D.GetBrushFromString)
  41865. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41866. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41867. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41868. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41869. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  41870. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  41871. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  41872. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  41873. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41874. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41875. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41876. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41877. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  41878. */
  41879. function Ellipse2D(settings) {
  41880. // Avoid checking every time if the object exists
  41881. if (settings == null) {
  41882. settings = {};
  41883. }
  41884. _super.call(this, settings);
  41885. if (settings.size != null) {
  41886. this.size = settings.size;
  41887. }
  41888. else if (settings.width || settings.height) {
  41889. var size = new BABYLON.Size(settings.width, settings.height);
  41890. this.size = size;
  41891. }
  41892. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  41893. this.subdivisions = sub;
  41894. }
  41895. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  41896. get: function () {
  41897. if (this._actualSize) {
  41898. return this._actualSize;
  41899. }
  41900. return this.size;
  41901. },
  41902. set: function (value) {
  41903. this._actualSize = value;
  41904. },
  41905. enumerable: true,
  41906. configurable: true
  41907. });
  41908. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  41909. get: function () {
  41910. return this._subdivisions;
  41911. },
  41912. set: function (value) {
  41913. this._subdivisions = value;
  41914. },
  41915. enumerable: true,
  41916. configurable: true
  41917. });
  41918. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  41919. var w = this.size.width / 2;
  41920. var h = this.size.height / 2;
  41921. var x = intersectInfo._localPickPosition.x - w;
  41922. var y = intersectInfo._localPickPosition.y - h;
  41923. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  41924. };
  41925. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  41926. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  41927. };
  41928. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  41929. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  41930. return renderCache;
  41931. };
  41932. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  41933. var renderCache = modelRenderCache;
  41934. var engine = this.owner.engine;
  41935. // Need to create WebGL resources for fill part?
  41936. if (this.fill) {
  41937. var vbSize = this.subdivisions + 1;
  41938. var vb = new Float32Array(vbSize);
  41939. for (var i = 0; i < vbSize; i++) {
  41940. vb[i] = i;
  41941. }
  41942. renderCache.fillVB = engine.createVertexBuffer(vb);
  41943. var triCount = vbSize - 1;
  41944. var ib = new Float32Array(triCount * 3);
  41945. for (var i = 0; i < triCount; i++) {
  41946. ib[i * 3 + 0] = 0;
  41947. ib[i * 3 + 2] = i + 1;
  41948. ib[i * 3 + 1] = i + 2;
  41949. }
  41950. ib[triCount * 3 - 2] = 1;
  41951. renderCache.fillIB = engine.createIndexBuffer(ib);
  41952. renderCache.fillIndicesCount = triCount * 3;
  41953. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  41954. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  41955. if (ei) {
  41956. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  41957. }
  41958. // Get the non instanced version
  41959. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  41960. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  41961. }
  41962. // Need to create WebGL resource for border part?
  41963. if (this.border) {
  41964. var vbSize = this.subdivisions * 2;
  41965. var vb = new Float32Array(vbSize);
  41966. for (var i = 0; i < vbSize; i++) {
  41967. vb[i] = i;
  41968. }
  41969. renderCache.borderVB = engine.createVertexBuffer(vb);
  41970. var triCount = vbSize;
  41971. var rs = triCount / 2;
  41972. var ib = new Float32Array(triCount * 3);
  41973. for (var i = 0; i < rs; i++) {
  41974. var r0 = i;
  41975. var r1 = (i + 1) % rs;
  41976. ib[i * 6 + 0] = rs + r1;
  41977. ib[i * 6 + 1] = rs + r0;
  41978. ib[i * 6 + 2] = r0;
  41979. ib[i * 6 + 3] = r1;
  41980. ib[i * 6 + 4] = rs + r1;
  41981. ib[i * 6 + 5] = r0;
  41982. }
  41983. renderCache.borderIB = engine.createIndexBuffer(ib);
  41984. renderCache.borderIndicesCount = (triCount * 3);
  41985. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  41986. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  41987. if (ei) {
  41988. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  41989. }
  41990. // Get the non instanced version
  41991. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  41992. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  41993. }
  41994. return renderCache;
  41995. };
  41996. Ellipse2D.prototype.createInstanceDataParts = function () {
  41997. var res = new Array();
  41998. if (this.border) {
  41999. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  42000. }
  42001. if (this.fill) {
  42002. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  42003. }
  42004. return res;
  42005. };
  42006. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  42007. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  42008. return false;
  42009. }
  42010. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  42011. var d = part;
  42012. var size = this.actualSize;
  42013. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  42014. }
  42015. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  42016. var d = part;
  42017. var size = this.actualSize;
  42018. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  42019. }
  42020. return true;
  42021. };
  42022. __decorate([
  42023. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
  42024. ], Ellipse2D.prototype, "actualSize", null);
  42025. __decorate([
  42026. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  42027. ], Ellipse2D.prototype, "subdivisions", null);
  42028. Ellipse2D = __decorate([
  42029. BABYLON.className("Ellipse2D")
  42030. ], Ellipse2D);
  42031. return Ellipse2D;
  42032. })(BABYLON.Shape2D);
  42033. BABYLON.Ellipse2D = Ellipse2D;
  42034. })(BABYLON || (BABYLON = {}));
  42035. var BABYLON;
  42036. (function (BABYLON) {
  42037. var Sprite2DRenderCache = (function (_super) {
  42038. __extends(Sprite2DRenderCache, _super);
  42039. function Sprite2DRenderCache() {
  42040. _super.apply(this, arguments);
  42041. this.effectsReady = false;
  42042. this.vb = null;
  42043. this.ib = null;
  42044. this.instancingAttributes = null;
  42045. this.texture = null;
  42046. this.effect = null;
  42047. this.effectInstanced = null;
  42048. }
  42049. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  42050. // Do nothing if the shader is still loading/preparing
  42051. if (!this.effectsReady) {
  42052. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  42053. return false;
  42054. }
  42055. this.effectsReady = true;
  42056. }
  42057. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  42058. var engine = instanceInfo.owner.owner.engine;
  42059. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  42060. engine.enableEffect(effect);
  42061. effect.setTexture("diffuseSampler", this.texture);
  42062. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  42063. var cur = engine.getAlphaMode();
  42064. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  42065. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42066. }
  42067. var pid = context.groupInfoPartData[0];
  42068. if (context.useInstancing) {
  42069. if (!this.instancingAttributes) {
  42070. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  42071. }
  42072. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingAttributes);
  42073. engine.draw(true, 0, 6, pid._partData.usedElementCount);
  42074. engine.unbindInstanceAttributes();
  42075. }
  42076. else {
  42077. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42078. this.setupUniforms(effect, 0, pid._partData, i);
  42079. engine.draw(true, 0, 6);
  42080. }
  42081. }
  42082. engine.setAlphaMode(cur);
  42083. return true;
  42084. };
  42085. Sprite2DRenderCache.prototype.dispose = function () {
  42086. if (!_super.prototype.dispose.call(this)) {
  42087. return false;
  42088. }
  42089. if (this.vb) {
  42090. this._engine._releaseBuffer(this.vb);
  42091. this.vb = null;
  42092. }
  42093. if (this.ib) {
  42094. this._engine._releaseBuffer(this.ib);
  42095. this.ib = null;
  42096. }
  42097. if (this.texture) {
  42098. this.texture.dispose();
  42099. this.texture = null;
  42100. }
  42101. if (this.effect) {
  42102. this._engine._releaseEffect(this.effect);
  42103. this.effect = null;
  42104. }
  42105. if (this.effectInstanced) {
  42106. this._engine._releaseEffect(this.effectInstanced);
  42107. this.effectInstanced = null;
  42108. }
  42109. return true;
  42110. };
  42111. return Sprite2DRenderCache;
  42112. })(BABYLON.ModelRenderCache);
  42113. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  42114. var Sprite2DInstanceData = (function (_super) {
  42115. __extends(Sprite2DInstanceData, _super);
  42116. function Sprite2DInstanceData(partId) {
  42117. _super.call(this, partId, 1);
  42118. }
  42119. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  42120. get: function () {
  42121. return null;
  42122. },
  42123. enumerable: true,
  42124. configurable: true
  42125. });
  42126. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  42127. get: function () {
  42128. return null;
  42129. },
  42130. enumerable: true,
  42131. configurable: true
  42132. });
  42133. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  42134. get: function () {
  42135. return null;
  42136. },
  42137. enumerable: true,
  42138. configurable: true
  42139. });
  42140. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  42141. // 3 floats being:
  42142. // - x: frame number to display
  42143. // - y: invertY setting
  42144. // - z: alignToPixel setting
  42145. get: function () {
  42146. return null;
  42147. },
  42148. enumerable: true,
  42149. configurable: true
  42150. });
  42151. __decorate([
  42152. BABYLON.instanceData()
  42153. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  42154. __decorate([
  42155. BABYLON.instanceData()
  42156. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  42157. __decorate([
  42158. BABYLON.instanceData()
  42159. ], Sprite2DInstanceData.prototype, "textureSize", null);
  42160. __decorate([
  42161. BABYLON.instanceData()
  42162. ], Sprite2DInstanceData.prototype, "properties", null);
  42163. return Sprite2DInstanceData;
  42164. })(BABYLON.InstanceDataBase);
  42165. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  42166. var Sprite2D = (function (_super) {
  42167. __extends(Sprite2D, _super);
  42168. /**
  42169. * Create an 2D Sprite primitive
  42170. * @param texture the texture that stores the sprite to render
  42171. * @param settings a combination of settings, possible ones are
  42172. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  42173. * - children: an array of direct children
  42174. * - id a text identifier, for information purpose
  42175. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  42176. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  42177. * - scale: the initial scale of the primitive. default is 1
  42178. * - origin: define the normalized origin point location, default [0.5;0.5]
  42179. * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
  42180. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  42181. * - invertY: if true the texture Y will be inverted, default is false.
  42182. * - alignToPixel: if true the sprite's texels will be aligned to the rendering viewport pixels, ensuring the best rendering quality but slow animations won't be done as smooth as if you set false. If false a texel could lies between two pixels, being blended by the texture sampling mode you choose, the rendering result won't be as good, but very slow animation will be overall better looking. Default is true: content will be aligned.
  42183. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  42184. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42185. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42186. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42187. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42188. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  42189. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  42190. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  42191. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  42192. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42193. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42194. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42195. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42196. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  42197. */
  42198. function Sprite2D(texture, settings) {
  42199. if (!settings) {
  42200. settings = {};
  42201. }
  42202. _super.call(this, settings);
  42203. this.texture = texture;
  42204. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42205. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42206. this.size = settings.spriteSize || null;
  42207. this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
  42208. this.spriteFrame = 0;
  42209. this.invertY = (settings.invertY == null) ? false : settings.invertY;
  42210. this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  42211. this._isTransparent = true;
  42212. if (!this.size) {
  42213. var s = texture.getSize();
  42214. this.size = new BABYLON.Size(s.width, s.height);
  42215. }
  42216. }
  42217. Object.defineProperty(Sprite2D.prototype, "texture", {
  42218. get: function () {
  42219. return this._texture;
  42220. },
  42221. set: function (value) {
  42222. this._texture = value;
  42223. },
  42224. enumerable: true,
  42225. configurable: true
  42226. });
  42227. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  42228. get: function () {
  42229. if (this._actualSize) {
  42230. return this._actualSize;
  42231. }
  42232. return this.size;
  42233. },
  42234. set: function (value) {
  42235. this._actualSize = value;
  42236. },
  42237. enumerable: true,
  42238. configurable: true
  42239. });
  42240. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  42241. get: function () {
  42242. return this._location;
  42243. },
  42244. set: function (value) {
  42245. this._location = value;
  42246. },
  42247. enumerable: true,
  42248. configurable: true
  42249. });
  42250. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  42251. get: function () {
  42252. return this._spriteFrame;
  42253. },
  42254. set: function (value) {
  42255. this._spriteFrame = value;
  42256. },
  42257. enumerable: true,
  42258. configurable: true
  42259. });
  42260. Object.defineProperty(Sprite2D.prototype, "invertY", {
  42261. get: function () {
  42262. return this._invertY;
  42263. },
  42264. set: function (value) {
  42265. this._invertY = value;
  42266. },
  42267. enumerable: true,
  42268. configurable: true
  42269. });
  42270. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  42271. /**
  42272. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  42273. */
  42274. get: function () {
  42275. return this._alignToPixel;
  42276. },
  42277. set: function (value) {
  42278. this._alignToPixel = value;
  42279. },
  42280. enumerable: true,
  42281. configurable: true
  42282. });
  42283. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  42284. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  42285. };
  42286. /**
  42287. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  42288. */
  42289. Sprite2D.prototype.getAnimatables = function () {
  42290. var res = new Array();
  42291. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  42292. res.push(this.texture);
  42293. }
  42294. return res;
  42295. };
  42296. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  42297. // If we've made it so far it means the boundingInfo intersection test succeed, the Sprite2D is shaped the same, so we always return true
  42298. return true;
  42299. };
  42300. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  42301. var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
  42302. return sprite;
  42303. };
  42304. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  42305. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  42306. return renderCache;
  42307. };
  42308. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  42309. var renderCache = modelRenderCache;
  42310. var engine = this.owner.engine;
  42311. var vb = new Float32Array(4);
  42312. for (var i = 0; i < 4; i++) {
  42313. vb[i] = i;
  42314. }
  42315. renderCache.vb = engine.createVertexBuffer(vb);
  42316. var ib = new Float32Array(6);
  42317. ib[0] = 0;
  42318. ib[1] = 2;
  42319. ib[2] = 1;
  42320. ib[3] = 0;
  42321. ib[4] = 3;
  42322. ib[5] = 2;
  42323. renderCache.ib = engine.createIndexBuffer(ib);
  42324. renderCache.texture = this.texture;
  42325. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  42326. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], true);
  42327. if (ei) {
  42328. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  42329. }
  42330. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], false);
  42331. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  42332. return renderCache;
  42333. };
  42334. Sprite2D.prototype.createInstanceDataParts = function () {
  42335. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  42336. };
  42337. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  42338. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  42339. return false;
  42340. }
  42341. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  42342. var d = this._instanceDataParts[0];
  42343. var ts = this.texture.getBaseSize();
  42344. var sl = this.spriteLocation;
  42345. var ss = this.actualSize;
  42346. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  42347. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  42348. d.sizeUV = suv;
  42349. Sprite2D._prop.x = this.spriteFrame;
  42350. Sprite2D._prop.y = this.invertY ? 1 : 0;
  42351. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  42352. d.properties = Sprite2D._prop;
  42353. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  42354. }
  42355. return true;
  42356. };
  42357. Sprite2D.SPRITE2D_MAINPARTID = 1;
  42358. Sprite2D._prop = BABYLON.Vector3.Zero();
  42359. __decorate([
  42360. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  42361. ], Sprite2D.prototype, "texture", null);
  42362. __decorate([
  42363. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
  42364. ], Sprite2D.prototype, "actualSize", null);
  42365. __decorate([
  42366. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  42367. ], Sprite2D.prototype, "spriteLocation", null);
  42368. __decorate([
  42369. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  42370. ], Sprite2D.prototype, "spriteFrame", null);
  42371. __decorate([
  42372. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.invertYProperty = pi; })
  42373. ], Sprite2D.prototype, "invertY", null);
  42374. Sprite2D = __decorate([
  42375. BABYLON.className("Sprite2D")
  42376. ], Sprite2D);
  42377. return Sprite2D;
  42378. })(BABYLON.RenderablePrim2D);
  42379. BABYLON.Sprite2D = Sprite2D;
  42380. })(BABYLON || (BABYLON = {}));
  42381. var BABYLON;
  42382. (function (BABYLON) {
  42383. var Text2DRenderCache = (function (_super) {
  42384. __extends(Text2DRenderCache, _super);
  42385. function Text2DRenderCache() {
  42386. _super.apply(this, arguments);
  42387. this.effectsReady = false;
  42388. this.vb = null;
  42389. this.ib = null;
  42390. this.instancingAttributes = null;
  42391. this.fontTexture = null;
  42392. this.effect = null;
  42393. this.effectInstanced = null;
  42394. }
  42395. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  42396. // Do nothing if the shader is still loading/preparing
  42397. if (!this.effectsReady) {
  42398. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  42399. return false;
  42400. }
  42401. this.effectsReady = true;
  42402. }
  42403. var engine = instanceInfo.owner.owner.engine;
  42404. this.fontTexture.update();
  42405. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  42406. engine.enableEffect(effect);
  42407. effect.setTexture("diffuseSampler", this.fontTexture);
  42408. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  42409. var curAlphaMode = engine.getAlphaMode();
  42410. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  42411. var pid = context.groupInfoPartData[0];
  42412. if (context.useInstancing) {
  42413. if (!this.instancingAttributes) {
  42414. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  42415. }
  42416. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingAttributes);
  42417. engine.draw(true, 0, 6, pid._partData.usedElementCount);
  42418. engine.unbindInstanceAttributes();
  42419. }
  42420. else {
  42421. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42422. this.setupUniforms(effect, 0, pid._partData, i);
  42423. engine.draw(true, 0, 6);
  42424. }
  42425. }
  42426. engine.setAlphaMode(curAlphaMode);
  42427. return true;
  42428. };
  42429. Text2DRenderCache.prototype.dispose = function () {
  42430. if (!_super.prototype.dispose.call(this)) {
  42431. return false;
  42432. }
  42433. if (this.vb) {
  42434. this._engine._releaseBuffer(this.vb);
  42435. this.vb = null;
  42436. }
  42437. if (this.ib) {
  42438. this._engine._releaseBuffer(this.ib);
  42439. this.ib = null;
  42440. }
  42441. if (this.fontTexture) {
  42442. this.fontTexture.dispose();
  42443. this.fontTexture = null;
  42444. }
  42445. if (this.effect) {
  42446. this._engine._releaseEffect(this.effect);
  42447. this.effect = null;
  42448. }
  42449. if (this.effectInstanced) {
  42450. this._engine._releaseEffect(this.effectInstanced);
  42451. this.effectInstanced = null;
  42452. }
  42453. return true;
  42454. };
  42455. return Text2DRenderCache;
  42456. })(BABYLON.ModelRenderCache);
  42457. BABYLON.Text2DRenderCache = Text2DRenderCache;
  42458. var Text2DInstanceData = (function (_super) {
  42459. __extends(Text2DInstanceData, _super);
  42460. function Text2DInstanceData(partId, dataElementCount) {
  42461. _super.call(this, partId, dataElementCount);
  42462. }
  42463. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  42464. get: function () {
  42465. return null;
  42466. },
  42467. enumerable: true,
  42468. configurable: true
  42469. });
  42470. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  42471. get: function () {
  42472. return null;
  42473. },
  42474. enumerable: true,
  42475. configurable: true
  42476. });
  42477. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  42478. get: function () {
  42479. return null;
  42480. },
  42481. enumerable: true,
  42482. configurable: true
  42483. });
  42484. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  42485. get: function () {
  42486. return null;
  42487. },
  42488. enumerable: true,
  42489. configurable: true
  42490. });
  42491. __decorate([
  42492. BABYLON.instanceData()
  42493. ], Text2DInstanceData.prototype, "topLeftUV", null);
  42494. __decorate([
  42495. BABYLON.instanceData()
  42496. ], Text2DInstanceData.prototype, "sizeUV", null);
  42497. __decorate([
  42498. BABYLON.instanceData()
  42499. ], Text2DInstanceData.prototype, "textureSize", null);
  42500. __decorate([
  42501. BABYLON.instanceData()
  42502. ], Text2DInstanceData.prototype, "color", null);
  42503. return Text2DInstanceData;
  42504. })(BABYLON.InstanceDataBase);
  42505. BABYLON.Text2DInstanceData = Text2DInstanceData;
  42506. var Text2D = (function (_super) {
  42507. __extends(Text2D, _super);
  42508. /**
  42509. * Create a Text primitive
  42510. * @param text the text to display
  42511. * @param settings a combination of settings, possible ones are
  42512. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  42513. * - children: an array of direct children
  42514. * - id a text identifier, for information purpose
  42515. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  42516. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  42517. * - scale: the initial scale of the primitive. default is 1
  42518. * - origin: define the normalized origin point location, default [0.5;0.5]
  42519. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  42520. * - defaultColor: the color by default to apply on each letter of the text to display, default is plain white.
  42521. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  42522. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  42523. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  42524. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42525. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42526. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42527. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42528. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  42529. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  42530. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  42531. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  42532. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42533. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42534. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42535. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42536. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  42537. */
  42538. function Text2D(text, settings) {
  42539. if (!settings) {
  42540. settings = {};
  42541. }
  42542. _super.call(this, settings);
  42543. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  42544. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  42545. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  42546. this._textSize = null;
  42547. this.text = text;
  42548. this.size = (settings.size == null) ? null : settings.size;
  42549. this.isAlphaTest = true;
  42550. }
  42551. Object.defineProperty(Text2D.prototype, "fontName", {
  42552. get: function () {
  42553. return this._fontName;
  42554. },
  42555. set: function (value) {
  42556. if (this._fontName) {
  42557. throw new Error("Font Name change is not supported right now.");
  42558. }
  42559. this._fontName = value;
  42560. },
  42561. enumerable: true,
  42562. configurable: true
  42563. });
  42564. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  42565. get: function () {
  42566. return this._defaultFontColor;
  42567. },
  42568. set: function (value) {
  42569. this._defaultFontColor = value;
  42570. },
  42571. enumerable: true,
  42572. configurable: true
  42573. });
  42574. Object.defineProperty(Text2D.prototype, "text", {
  42575. get: function () {
  42576. return this._text;
  42577. },
  42578. set: function (value) {
  42579. this._text = value;
  42580. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  42581. this._size = null;
  42582. this._updateCharCount();
  42583. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  42584. var s = this.textSize;
  42585. },
  42586. enumerable: true,
  42587. configurable: true
  42588. });
  42589. Object.defineProperty(Text2D.prototype, "size", {
  42590. get: function () {
  42591. if (this._size != null) {
  42592. return this._size;
  42593. }
  42594. return this.textSize;
  42595. },
  42596. set: function (value) {
  42597. this._size = value;
  42598. },
  42599. enumerable: true,
  42600. configurable: true
  42601. });
  42602. Object.defineProperty(Text2D.prototype, "actualSize", {
  42603. /**
  42604. * Get the actual size of the Text2D primitive
  42605. */
  42606. get: function () {
  42607. if (this._actualSize) {
  42608. return this._actualSize;
  42609. }
  42610. return this.size;
  42611. },
  42612. enumerable: true,
  42613. configurable: true
  42614. });
  42615. Object.defineProperty(Text2D.prototype, "textSize", {
  42616. /**
  42617. * Get the area that bounds the text associated to the primitive
  42618. */
  42619. get: function () {
  42620. if (!this._textSize) {
  42621. if (this.owner) {
  42622. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  42623. if (!newSize.equals(this._textSize)) {
  42624. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  42625. this._positioningDirty();
  42626. }
  42627. this._textSize = newSize;
  42628. }
  42629. else {
  42630. return Text2D.nullSize;
  42631. }
  42632. }
  42633. return this._textSize;
  42634. },
  42635. enumerable: true,
  42636. configurable: true
  42637. });
  42638. Object.defineProperty(Text2D.prototype, "fontTexture", {
  42639. get: function () {
  42640. if (this._fontTexture) {
  42641. return this._fontTexture;
  42642. }
  42643. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName);
  42644. return this._fontTexture;
  42645. },
  42646. enumerable: true,
  42647. configurable: true
  42648. });
  42649. /**
  42650. * Dispose the primitive, remove it from its parent
  42651. */
  42652. Text2D.prototype.dispose = function () {
  42653. if (!_super.prototype.dispose.call(this)) {
  42654. return false;
  42655. }
  42656. if (this._fontTexture) {
  42657. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName);
  42658. this._fontTexture = null;
  42659. }
  42660. return true;
  42661. };
  42662. Text2D.prototype.updateLevelBoundingInfo = function () {
  42663. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  42664. };
  42665. Text2D.prototype.levelIntersect = function (intersectInfo) {
  42666. // For now I can't do something better that boundingInfo is a hit, detecting an intersection on a particular letter would be possible, but do we really need it? Not for now...
  42667. return true;
  42668. };
  42669. Text2D.prototype.createModelRenderCache = function (modelKey) {
  42670. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  42671. return renderCache;
  42672. };
  42673. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  42674. var renderCache = modelRenderCache;
  42675. var engine = this.owner.engine;
  42676. renderCache.fontTexture = this.fontTexture;
  42677. var vb = new Float32Array(4);
  42678. for (var i = 0; i < 4; i++) {
  42679. vb[i] = i;
  42680. }
  42681. renderCache.vb = engine.createVertexBuffer(vb);
  42682. var ib = new Float32Array(6);
  42683. ib[0] = 0;
  42684. ib[1] = 2;
  42685. ib[2] = 1;
  42686. ib[3] = 0;
  42687. ib[4] = 3;
  42688. ib[5] = 2;
  42689. renderCache.ib = engine.createIndexBuffer(ib);
  42690. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  42691. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], true);
  42692. if (ei) {
  42693. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  42694. }
  42695. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], false);
  42696. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  42697. return renderCache;
  42698. };
  42699. Text2D.prototype.createInstanceDataParts = function () {
  42700. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  42701. };
  42702. // Looks like a hack!? Yes! Because that's what it is!
  42703. // For the InstanceData layer to compute correctly we need to set all the properties involved, which won't be the case if there's no text
  42704. // This method is called before the layout construction for us to detect this case, set some text and return the initial one to restore it after (there can be some text without char to display, say "\t\n" for instance)
  42705. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  42706. if (!this._charCount) {
  42707. var curText = this._text;
  42708. this.text = "A";
  42709. return curText;
  42710. }
  42711. };
  42712. // if obj contains something, we restore the _text property
  42713. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  42714. if (obj !== undefined) {
  42715. this.text = obj;
  42716. }
  42717. };
  42718. Text2D.prototype.refreshInstanceDataPart = function (part) {
  42719. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  42720. return false;
  42721. }
  42722. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  42723. var d = part;
  42724. var texture = this.fontTexture;
  42725. var ts = texture.getSize();
  42726. var offset = BABYLON.Vector2.Zero();
  42727. var lh = this.fontTexture.lineHeight;
  42728. offset.y = ((this.textSize.height / lh) - 1) * lh; // Origin is bottom, not top, so the offset is starting with a y that is the top location of the text
  42729. var charxpos = 0;
  42730. d.dataElementCount = this._charCount;
  42731. d.curElement = 0;
  42732. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  42733. var char = _a[_i];
  42734. // Line feed
  42735. if (char === "\n") {
  42736. offset.x = 0;
  42737. offset.y -= texture.lineHeight;
  42738. }
  42739. // Tabulation ?
  42740. if (char === "\t") {
  42741. var nextPos = charxpos + this._tabulationSize;
  42742. nextPos = nextPos - (nextPos % this._tabulationSize);
  42743. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  42744. charxpos = nextPos;
  42745. continue;
  42746. }
  42747. if (char < " ") {
  42748. continue;
  42749. }
  42750. this.updateInstanceDataPart(d, offset);
  42751. var ci = texture.getChar(char);
  42752. offset.x += ci.charWidth;
  42753. d.topLeftUV = ci.topLeftUV;
  42754. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  42755. d.sizeUV = suv;
  42756. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  42757. d.color = this.defaultFontColor;
  42758. ++d.curElement;
  42759. }
  42760. }
  42761. return true;
  42762. };
  42763. Text2D.prototype._updateCharCount = function () {
  42764. var count = 0;
  42765. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  42766. var char = _a[_i];
  42767. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  42768. continue;
  42769. }
  42770. ++count;
  42771. }
  42772. this._charCount = count;
  42773. };
  42774. Text2D.TEXT2D_MAINPARTID = 1;
  42775. __decorate([
  42776. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  42777. ], Text2D.prototype, "fontName", null);
  42778. __decorate([
  42779. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  42780. ], Text2D.prototype, "defaultFontColor", null);
  42781. __decorate([
  42782. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  42783. ], Text2D.prototype, "text", null);
  42784. __decorate([
  42785. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  42786. ], Text2D.prototype, "size", null);
  42787. Text2D = __decorate([
  42788. BABYLON.className("Text2D")
  42789. ], Text2D);
  42790. return Text2D;
  42791. })(BABYLON.RenderablePrim2D);
  42792. BABYLON.Text2D = Text2D;
  42793. })(BABYLON || (BABYLON = {}));
  42794. var BABYLON;
  42795. (function (BABYLON) {
  42796. var Lines2DRenderCache = (function (_super) {
  42797. __extends(Lines2DRenderCache, _super);
  42798. function Lines2DRenderCache(engine, modelKey) {
  42799. _super.call(this, engine, modelKey);
  42800. this.effectsReady = false;
  42801. this.fillVB = null;
  42802. this.fillIB = null;
  42803. this.fillIndicesCount = 0;
  42804. this.instancingFillAttributes = null;
  42805. this.effectFill = null;
  42806. this.effectFillInstanced = null;
  42807. this.borderVB = null;
  42808. this.borderIB = null;
  42809. this.borderIndicesCount = 0;
  42810. this.instancingBorderAttributes = null;
  42811. this.effectBorder = null;
  42812. this.effectBorderInstanced = null;
  42813. }
  42814. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  42815. // Do nothing if the shader is still loading/preparing
  42816. if (!this.effectsReady) {
  42817. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  42818. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  42819. return false;
  42820. }
  42821. this.effectsReady = true;
  42822. }
  42823. var engine = instanceInfo.owner.owner.engine;
  42824. var depthFunction = 0;
  42825. if (this.effectFill && this.effectBorder) {
  42826. depthFunction = engine.getDepthFunction();
  42827. engine.setDepthFunctionToLessOrEqual();
  42828. }
  42829. var curAlphaMode = engine.getAlphaMode();
  42830. if (this.effectFill) {
  42831. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  42832. var pid = context.groupInfoPartData[partIndex];
  42833. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  42834. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42835. }
  42836. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  42837. engine.enableEffect(effect);
  42838. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  42839. if (context.useInstancing) {
  42840. if (!this.instancingFillAttributes) {
  42841. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  42842. }
  42843. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingFillAttributes);
  42844. engine.draw(true, 0, this.fillIndicesCount, pid._partData.usedElementCount);
  42845. engine.unbindInstanceAttributes();
  42846. }
  42847. else {
  42848. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42849. this.setupUniforms(effect, partIndex, pid._partData, i);
  42850. engine.draw(true, 0, this.fillIndicesCount);
  42851. }
  42852. }
  42853. }
  42854. if (this.effectBorder) {
  42855. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  42856. var pid = context.groupInfoPartData[partIndex];
  42857. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  42858. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42859. }
  42860. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  42861. engine.enableEffect(effect);
  42862. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  42863. if (context.useInstancing) {
  42864. if (!this.instancingBorderAttributes) {
  42865. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  42866. }
  42867. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingBorderAttributes);
  42868. engine.draw(true, 0, this.borderIndicesCount, pid._partData.usedElementCount);
  42869. engine.unbindInstanceAttributes();
  42870. }
  42871. else {
  42872. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42873. this.setupUniforms(effect, partIndex, pid._partData, i);
  42874. engine.draw(true, 0, this.borderIndicesCount);
  42875. }
  42876. }
  42877. }
  42878. engine.setAlphaMode(curAlphaMode);
  42879. if (this.effectFill && this.effectBorder) {
  42880. engine.setDepthFunction(depthFunction);
  42881. }
  42882. return true;
  42883. };
  42884. Lines2DRenderCache.prototype.dispose = function () {
  42885. if (!_super.prototype.dispose.call(this)) {
  42886. return false;
  42887. }
  42888. if (this.fillVB) {
  42889. this._engine._releaseBuffer(this.fillVB);
  42890. this.fillVB = null;
  42891. }
  42892. if (this.fillIB) {
  42893. this._engine._releaseBuffer(this.fillIB);
  42894. this.fillIB = null;
  42895. }
  42896. if (this.effectFill) {
  42897. this._engine._releaseEffect(this.effectFill);
  42898. this.effectFill = null;
  42899. }
  42900. if (this.effectFillInstanced) {
  42901. this._engine._releaseEffect(this.effectFillInstanced);
  42902. this.effectFillInstanced = null;
  42903. }
  42904. if (this.borderVB) {
  42905. this._engine._releaseBuffer(this.borderVB);
  42906. this.borderVB = null;
  42907. }
  42908. if (this.borderIB) {
  42909. this._engine._releaseBuffer(this.borderIB);
  42910. this.borderIB = null;
  42911. }
  42912. if (this.effectBorder) {
  42913. this._engine._releaseEffect(this.effectBorder);
  42914. this.effectBorder = null;
  42915. }
  42916. if (this.effectBorderInstanced) {
  42917. this._engine._releaseEffect(this.effectBorderInstanced);
  42918. this.effectBorderInstanced = null;
  42919. }
  42920. return true;
  42921. };
  42922. return Lines2DRenderCache;
  42923. })(BABYLON.ModelRenderCache);
  42924. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  42925. var Lines2DInstanceData = (function (_super) {
  42926. __extends(Lines2DInstanceData, _super);
  42927. function Lines2DInstanceData(partId) {
  42928. _super.call(this, partId, 1);
  42929. }
  42930. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  42931. get: function () {
  42932. return null;
  42933. },
  42934. enumerable: true,
  42935. configurable: true
  42936. });
  42937. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  42938. get: function () {
  42939. return null;
  42940. },
  42941. enumerable: true,
  42942. configurable: true
  42943. });
  42944. __decorate([
  42945. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  42946. ], Lines2DInstanceData.prototype, "boundingMin", null);
  42947. __decorate([
  42948. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  42949. ], Lines2DInstanceData.prototype, "boundingMax", null);
  42950. return Lines2DInstanceData;
  42951. })(BABYLON.Shape2DInstanceData);
  42952. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  42953. var Lines2D = (function (_super) {
  42954. __extends(Lines2D, _super);
  42955. /**
  42956. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  42957. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  42958. * @param settings a combination of settings, possible ones are
  42959. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  42960. * - children: an array of direct children
  42961. * - id a text identifier, for information purpose
  42962. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  42963. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  42964. * - scale: the initial scale of the primitive. default is 1
  42965. * - origin: define the normalized origin point location, default [0.5;0.5]
  42966. * - fillThickness: the thickness of the fill part of the line, can be null to draw nothing (but a border brush must be given), default is 1.
  42967. * - closed: if false the lines are said to be opened, the first point and the latest DON'T connect. if true the lines are said to be closed, the first and last point will be connected by a line. For instance you can define the 4 points of a rectangle, if you set closed to true a 4 edges rectangle will be drawn. If you set false, only three edges will be drawn, the edge formed by the first and last point won't exist. Default is false.
  42968. * - startCap: Draw a cap of the given type at the start of the first line, you can't define a Cap if the Lines2D is closed. Default is Lines2D.NoCap.
  42969. * - endCap: Draw a cap of the given type at the end of the last line, you can't define a Cap if the Lines2D is closed. Default is Lines2D.NoCap.
  42970. * - fill: the brush used to draw the fill content of the lines, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can be a string value (see Canvas2D.GetBrushFromString)
  42971. * - border: the brush used to draw the border of the lines, you can set null to draw nothing (but you will have to set a fill brush), default is null. can be a string value (see Canvas2D.GetBrushFromString)
  42972. * - borderThickness: the thickness of the drawn border, default is 1.
  42973. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  42974. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42975. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42976. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42977. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42978. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  42979. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  42980. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  42981. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  42982. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42983. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42984. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42985. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42986. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  42987. */
  42988. function Lines2D(points, settings) {
  42989. if (!settings) {
  42990. settings = {};
  42991. }
  42992. _super.call(this, settings);
  42993. this._fillVB = null;
  42994. this._fillIB = null;
  42995. this._borderVB = null;
  42996. this._borderIB = null;
  42997. this._size = BABYLON.Size.Zero();
  42998. this._boundingMin = null;
  42999. this._boundingMax = null;
  43000. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  43001. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  43002. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  43003. var closed = (settings.closed == null) ? false : settings.closed;
  43004. this.points = points;
  43005. this.fillThickness = fillThickness;
  43006. this.startCap = startCap;
  43007. this.endCap = endCap;
  43008. this.closed = closed;
  43009. }
  43010. Object.defineProperty(Lines2D, "NoCap", {
  43011. /**
  43012. * No Cap to apply on the extremity
  43013. */
  43014. get: function () { return Lines2D._noCap; },
  43015. enumerable: true,
  43016. configurable: true
  43017. });
  43018. Object.defineProperty(Lines2D, "RoundCap", {
  43019. /**
  43020. * A round cap, will use the line thickness as diameter
  43021. */
  43022. get: function () { return Lines2D._roundCap; },
  43023. enumerable: true,
  43024. configurable: true
  43025. });
  43026. Object.defineProperty(Lines2D, "TriangleCap", {
  43027. /**
  43028. * Creates a triangle at the extremity.
  43029. */
  43030. get: function () { return Lines2D._triangleCap; },
  43031. enumerable: true,
  43032. configurable: true
  43033. });
  43034. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  43035. /**
  43036. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  43037. */
  43038. get: function () { return Lines2D._squareAnchorCap; },
  43039. enumerable: true,
  43040. configurable: true
  43041. });
  43042. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  43043. /**
  43044. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  43045. */
  43046. get: function () { return Lines2D._roundAnchorCap; },
  43047. enumerable: true,
  43048. configurable: true
  43049. });
  43050. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  43051. /**
  43052. * Creates a diamond anchor at the extremity.
  43053. */
  43054. get: function () { return Lines2D._diamondAnchorCap; },
  43055. enumerable: true,
  43056. configurable: true
  43057. });
  43058. Object.defineProperty(Lines2D, "ArrowCap", {
  43059. /**
  43060. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  43061. */
  43062. get: function () { return Lines2D._arrowCap; },
  43063. enumerable: true,
  43064. configurable: true
  43065. });
  43066. Object.defineProperty(Lines2D.prototype, "points", {
  43067. get: function () {
  43068. return this._points;
  43069. },
  43070. set: function (value) {
  43071. this._points = value;
  43072. this._boundingBoxDirty();
  43073. },
  43074. enumerable: true,
  43075. configurable: true
  43076. });
  43077. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  43078. get: function () {
  43079. return this._fillThickness;
  43080. },
  43081. set: function (value) {
  43082. this._fillThickness = value;
  43083. },
  43084. enumerable: true,
  43085. configurable: true
  43086. });
  43087. Object.defineProperty(Lines2D.prototype, "closed", {
  43088. get: function () {
  43089. return this._closed;
  43090. },
  43091. set: function (value) {
  43092. this._closed = value;
  43093. },
  43094. enumerable: true,
  43095. configurable: true
  43096. });
  43097. Object.defineProperty(Lines2D.prototype, "startCap", {
  43098. get: function () {
  43099. return this._startCap;
  43100. },
  43101. set: function (value) {
  43102. this._startCap = value;
  43103. },
  43104. enumerable: true,
  43105. configurable: true
  43106. });
  43107. Object.defineProperty(Lines2D.prototype, "endCap", {
  43108. get: function () {
  43109. return this._endCap;
  43110. },
  43111. set: function (value) {
  43112. this._endCap = value;
  43113. },
  43114. enumerable: true,
  43115. configurable: true
  43116. });
  43117. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  43118. var _this = this;
  43119. if (this._contour == null) {
  43120. this._computeLines2D();
  43121. }
  43122. var pl = this.points.length;
  43123. var l = this.closed ? pl + 1 : pl;
  43124. var p = intersectInfo._localPickPosition;
  43125. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  43126. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  43127. for (var i = 1; i < l; i++) {
  43128. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  43129. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  43130. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  43131. return true;
  43132. }
  43133. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  43134. return true;
  43135. }
  43136. Lines2D._prevA.x = Lines2D._curA.x;
  43137. Lines2D._prevA.y = Lines2D._curA.y;
  43138. Lines2D._prevB.x = Lines2D._curB.x;
  43139. Lines2D._prevB.y = Lines2D._curB.y;
  43140. }
  43141. var capIntersect = function (tri, points) {
  43142. var l = tri.length;
  43143. for (var i = 0; i < l; i += 3) {
  43144. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  43145. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  43146. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  43147. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  43148. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  43149. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  43150. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  43151. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  43152. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  43153. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  43154. return true;
  43155. }
  43156. }
  43157. return false;
  43158. };
  43159. if (this._startCapTriIndices) {
  43160. if (capIntersect(this._startCapTriIndices, this._startCapContour)) {
  43161. return true;
  43162. }
  43163. if (capIntersect(this._endCapTriIndices, this._endCapContour)) {
  43164. return true;
  43165. }
  43166. }
  43167. return false;
  43168. };
  43169. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  43170. get: function () {
  43171. if (!this._boundingMin) {
  43172. this._computeLines2D();
  43173. }
  43174. return this._boundingMin;
  43175. },
  43176. enumerable: true,
  43177. configurable: true
  43178. });
  43179. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  43180. get: function () {
  43181. if (!this._boundingMax) {
  43182. this._computeLines2D();
  43183. }
  43184. return this._boundingMax;
  43185. },
  43186. enumerable: true,
  43187. configurable: true
  43188. });
  43189. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  43190. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  43191. // Remove the BORDER category, we don't use it in the VertexShader
  43192. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  43193. if (i !== -1) {
  43194. res.splice(i, 1);
  43195. }
  43196. return res;
  43197. };
  43198. Lines2D.prototype.updateLevelBoundingInfo = function () {
  43199. if (!this._boundingMin) {
  43200. this._computeLines2D();
  43201. }
  43202. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  43203. };
  43204. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  43205. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  43206. return renderCache;
  43207. };
  43208. ///////////////////////////////////////////////////////////////////////////////////
  43209. // Methods for Lines building
  43210. Lines2D.prototype._perp = function (v, res) {
  43211. res.x = v.y;
  43212. res.y = -v.x;
  43213. };
  43214. ;
  43215. Lines2D.prototype._direction = function (a, b, res) {
  43216. a.subtractToRef(b, res);
  43217. res.normalize();
  43218. };
  43219. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  43220. a.addToRef(b, tangent);
  43221. tangent.normalize();
  43222. miter.x = -tangent.y;
  43223. miter.y = tangent.x;
  43224. Lines2D._miterTps.x = -a.y;
  43225. Lines2D._miterTps.y = a.x;
  43226. return 1 / BABYLON.Vector2.Dot(miter, Lines2D._miterTps);
  43227. };
  43228. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  43229. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  43230. if (d === 0)
  43231. return false;
  43232. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  43233. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  43234. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  43235. return false;
  43236. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  43237. return false;
  43238. return true;
  43239. };
  43240. Lines2D.prototype._updateMinMax = function (array, offset) {
  43241. if (offset >= array.length) {
  43242. return;
  43243. }
  43244. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  43245. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  43246. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  43247. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  43248. };
  43249. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  43250. var borderMode = borderThickness != null && !isNaN(borderThickness);
  43251. var off = index * (borderMode ? 8 : 4);
  43252. // Mandatory because we'll be out of bound in case of closed line, for the very last point (which is a duplicate of the first that we don't store in the vb)
  43253. if (off >= array.length) {
  43254. return;
  43255. }
  43256. // Store start/end normal, we need it for the cap construction
  43257. if (index === 0) {
  43258. this._perp(n, Lines2D._startDir);
  43259. }
  43260. else if (index === max - 1) {
  43261. this._perp(n, Lines2D._endDir);
  43262. Lines2D._endDir.x *= -1;
  43263. Lines2D._endDir.y *= -1;
  43264. }
  43265. var swap = false;
  43266. array[off + 0] = p.x + n.x * halfThickness;
  43267. array[off + 1] = p.y + n.y * halfThickness;
  43268. array[off + 2] = p.x + n.x * -halfThickness;
  43269. array[off + 3] = p.y + n.y * -halfThickness;
  43270. this._updateMinMax(array, off);
  43271. this._updateMinMax(array, off + 2);
  43272. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  43273. // It should not be the case, they should be parallel, so if they cross, we switch the order of storage to ensure we'll have parallel lines
  43274. if (detectFlip !== undefined) {
  43275. // Flip if intersect
  43276. var flipOff = detectFlip * (borderMode ? 8 : 4);
  43277. if (this._intersect(array[off + 0], array[off + 1], array[flipOff + 0], array[flipOff + 1], array[off + 2], array[off + 3], array[flipOff + 2], array[flipOff + 3])) {
  43278. swap = true;
  43279. var tps = array[off + 0];
  43280. array[off + 0] = array[off + 2];
  43281. array[off + 2] = tps;
  43282. tps = array[off + 1];
  43283. array[off + 1] = array[off + 3];
  43284. array[off + 3] = tps;
  43285. }
  43286. }
  43287. if (borderMode) {
  43288. var t = halfThickness + borderThickness;
  43289. array[off + 4] = p.x + n.x * (swap ? -t : t);
  43290. array[off + 5] = p.y + n.y * (swap ? -t : t);
  43291. array[off + 6] = p.x + n.x * (swap ? t : -t);
  43292. array[off + 7] = p.y + n.y * (swap ? t : -t);
  43293. this._updateMinMax(array, off + 4);
  43294. this._updateMinMax(array, off + 6);
  43295. }
  43296. if (contour) {
  43297. off += borderMode ? 4 : 0;
  43298. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  43299. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  43300. }
  43301. };
  43302. Lines2D.prototype._getCapSize = function (type, border) {
  43303. if (border === void 0) { border = false; }
  43304. var sd = Lines2D._roundCapSubDiv;
  43305. // If no array given, we call this to get the size
  43306. var vbsize = 0, ibsize = 0;
  43307. switch (type) {
  43308. case Lines2D.NoCap:
  43309. {
  43310. // If the line is not close and we're computing border, we add the size to generate the edge border
  43311. if (!this.closed && border) {
  43312. vbsize = 4;
  43313. ibsize = 6;
  43314. }
  43315. else {
  43316. vbsize = ibsize = 0;
  43317. }
  43318. break;
  43319. }
  43320. case Lines2D.RoundCap:
  43321. {
  43322. if (border) {
  43323. vbsize = sd;
  43324. ibsize = (sd - 2) * 3;
  43325. }
  43326. else {
  43327. vbsize = (sd / 2) + 1;
  43328. ibsize = (sd / 2) * 3;
  43329. }
  43330. break;
  43331. }
  43332. case Lines2D.ArrowCap:
  43333. {
  43334. if (border) {
  43335. vbsize = 12;
  43336. ibsize = 24;
  43337. }
  43338. else {
  43339. vbsize = 3;
  43340. ibsize = 3;
  43341. }
  43342. break;
  43343. }
  43344. case Lines2D.TriangleCap:
  43345. {
  43346. if (border) {
  43347. vbsize = 6;
  43348. ibsize = 12;
  43349. }
  43350. else {
  43351. vbsize = 3;
  43352. ibsize = 3;
  43353. }
  43354. break;
  43355. }
  43356. case Lines2D.DiamondAnchorCap:
  43357. {
  43358. if (border) {
  43359. vbsize = 10;
  43360. ibsize = 24;
  43361. }
  43362. else {
  43363. vbsize = 5;
  43364. ibsize = 9;
  43365. }
  43366. break;
  43367. }
  43368. case Lines2D.SquareAnchorCap:
  43369. {
  43370. if (border) {
  43371. vbsize = 12;
  43372. ibsize = 30;
  43373. }
  43374. else {
  43375. vbsize = 4;
  43376. ibsize = 6;
  43377. }
  43378. break;
  43379. }
  43380. case Lines2D.RoundAnchorCap:
  43381. {
  43382. if (border) {
  43383. vbsize = sd * 2;
  43384. ibsize = (sd - 1) * 6;
  43385. }
  43386. else {
  43387. vbsize = sd + 1;
  43388. ibsize = (sd + 1) * 3;
  43389. }
  43390. break;
  43391. }
  43392. }
  43393. return { vbsize: vbsize * 2, ibsize: ibsize };
  43394. };
  43395. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  43396. var c = Math.cos(rotation);
  43397. var s = Math.sin(rotation);
  43398. Lines2D._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  43399. Lines2D._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  43400. var offset = baseOffset + (index * 2);
  43401. vb[offset + 0] = Lines2D._tpsV.x;
  43402. vb[offset + 1] = Lines2D._tpsV.y;
  43403. if (contour) {
  43404. contour.push(Lines2D._tpsV.x);
  43405. contour.push(Lines2D._tpsV.y);
  43406. }
  43407. this._updateMinMax(vb, offset);
  43408. return (baseOffset + index * 2) / 2;
  43409. };
  43410. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  43411. ib[baseOffset + index] = vertexIndex;
  43412. };
  43413. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  43414. // Compute the transformation from the direction of the cap to build relative to our default orientation [1;0] (our cap are by default pointing toward right, horizontal
  43415. var sd = Lines2D._roundCapSubDiv;
  43416. var dir = new BABYLON.Vector2(1, 0);
  43417. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  43418. var ht = thickness / 2;
  43419. var t = thickness;
  43420. var borderMode = borderThickness != null;
  43421. var bt = borderThickness;
  43422. switch (type) {
  43423. case Lines2D.NoCap:
  43424. if (borderMode && !this.closed) {
  43425. var vi = 0;
  43426. var ii = 0;
  43427. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  43428. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  43429. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  43430. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  43431. this._storeIndex(ib, ibi, ii++, v1);
  43432. this._storeIndex(ib, ibi, ii++, v2);
  43433. this._storeIndex(ib, ibi, ii++, v3);
  43434. this._storeIndex(ib, ibi, ii++, v1);
  43435. this._storeIndex(ib, ibi, ii++, v3);
  43436. this._storeIndex(ib, ibi, ii++, v4);
  43437. }
  43438. break;
  43439. case Lines2D.ArrowCap:
  43440. ht *= 2;
  43441. case Lines2D.TriangleCap:
  43442. {
  43443. if (borderMode) {
  43444. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  43445. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  43446. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  43447. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  43448. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  43449. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  43450. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  43451. var ii = 0;
  43452. this._storeIndex(ib, ibi, ii++, v1);
  43453. this._storeIndex(ib, ibi, ii++, v4);
  43454. this._storeIndex(ib, ibi, ii++, v5);
  43455. this._storeIndex(ib, ibi, ii++, v1);
  43456. this._storeIndex(ib, ibi, ii++, v5);
  43457. this._storeIndex(ib, ibi, ii++, v2);
  43458. this._storeIndex(ib, ibi, ii++, v6);
  43459. this._storeIndex(ib, ibi, ii++, v3);
  43460. this._storeIndex(ib, ibi, ii++, v2);
  43461. this._storeIndex(ib, ibi, ii++, v6);
  43462. this._storeIndex(ib, ibi, ii++, v2);
  43463. this._storeIndex(ib, ibi, ii++, v5);
  43464. if (type === Lines2D.ArrowCap) {
  43465. var rht = thickness / 2;
  43466. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  43467. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  43468. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  43469. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  43470. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  43471. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  43472. this._storeIndex(ib, ibi, ii++, v7);
  43473. this._storeIndex(ib, ibi, ii++, v8);
  43474. this._storeIndex(ib, ibi, ii++, v9);
  43475. this._storeIndex(ib, ibi, ii++, v7);
  43476. this._storeIndex(ib, ibi, ii++, v9);
  43477. this._storeIndex(ib, ibi, ii++, v4);
  43478. this._storeIndex(ib, ibi, ii++, v10);
  43479. this._storeIndex(ib, ibi, ii++, v12);
  43480. this._storeIndex(ib, ibi, ii++, v11);
  43481. this._storeIndex(ib, ibi, ii++, v10);
  43482. this._storeIndex(ib, ibi, ii++, v6);
  43483. this._storeIndex(ib, ibi, ii++, v12);
  43484. }
  43485. }
  43486. else {
  43487. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  43488. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  43489. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  43490. this._storeIndex(ib, ibi, 0, v1);
  43491. this._storeIndex(ib, ibi, 1, v2);
  43492. this._storeIndex(ib, ibi, 2, v3);
  43493. }
  43494. break;
  43495. }
  43496. case Lines2D.RoundCap:
  43497. {
  43498. if (borderMode) {
  43499. var curA = -Math.PI / 2;
  43500. var incA = Math.PI / (sd / 2 - 1);
  43501. var ii = 0;
  43502. for (var i = 0; i < (sd / 2); i++) {
  43503. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  43504. var v2 = this._storeVertex(vb, vbi, i * 2 + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * (ht + bt), Math.sin(curA) * (ht + bt)), contour);
  43505. if (i > 0) {
  43506. this._storeIndex(ib, ibi, ii++, v1 - 2);
  43507. this._storeIndex(ib, ibi, ii++, v2 - 2);
  43508. this._storeIndex(ib, ibi, ii++, v2);
  43509. this._storeIndex(ib, ibi, ii++, v1 - 2);
  43510. this._storeIndex(ib, ibi, ii++, v2);
  43511. this._storeIndex(ib, ibi, ii++, v1);
  43512. }
  43513. curA += incA;
  43514. }
  43515. }
  43516. else {
  43517. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  43518. var curA = -Math.PI / 2;
  43519. var incA = Math.PI / (sd / 2 - 1);
  43520. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  43521. curA += incA;
  43522. for (var i = 1; i < (sd / 2); i++) {
  43523. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  43524. this._storeIndex(ib, ibi, i * 3 + 0, c);
  43525. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  43526. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  43527. curA += incA;
  43528. }
  43529. }
  43530. break;
  43531. }
  43532. case Lines2D.SquareAnchorCap:
  43533. {
  43534. var vi = 0;
  43535. var c = borderMode ? null : contour;
  43536. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  43537. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  43538. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  43539. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  43540. if (borderMode) {
  43541. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  43542. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  43543. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  43544. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  43545. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  43546. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  43547. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  43548. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  43549. var ii = 0;
  43550. this._storeIndex(ib, ibi, ii++, v6);
  43551. this._storeIndex(ib, ibi, ii++, v1);
  43552. this._storeIndex(ib, ibi, ii++, v5);
  43553. this._storeIndex(ib, ibi, ii++, v6);
  43554. this._storeIndex(ib, ibi, ii++, v7);
  43555. this._storeIndex(ib, ibi, ii++, v1);
  43556. this._storeIndex(ib, ibi, ii++, v1);
  43557. this._storeIndex(ib, ibi, ii++, v7);
  43558. this._storeIndex(ib, ibi, ii++, v8);
  43559. this._storeIndex(ib, ibi, ii++, v1);
  43560. this._storeIndex(ib, ibi, ii++, v8);
  43561. this._storeIndex(ib, ibi, ii++, v2);
  43562. this._storeIndex(ib, ibi, ii++, v2);
  43563. this._storeIndex(ib, ibi, ii++, v8);
  43564. this._storeIndex(ib, ibi, ii++, v9);
  43565. this._storeIndex(ib, ibi, ii++, v2);
  43566. this._storeIndex(ib, ibi, ii++, v9);
  43567. this._storeIndex(ib, ibi, ii++, v3);
  43568. this._storeIndex(ib, ibi, ii++, v3);
  43569. this._storeIndex(ib, ibi, ii++, v9);
  43570. this._storeIndex(ib, ibi, ii++, v10);
  43571. this._storeIndex(ib, ibi, ii++, v3);
  43572. this._storeIndex(ib, ibi, ii++, v10);
  43573. this._storeIndex(ib, ibi, ii++, v4);
  43574. this._storeIndex(ib, ibi, ii++, v10);
  43575. this._storeIndex(ib, ibi, ii++, v11);
  43576. this._storeIndex(ib, ibi, ii++, v4);
  43577. this._storeIndex(ib, ibi, ii++, v11);
  43578. this._storeIndex(ib, ibi, ii++, v12);
  43579. this._storeIndex(ib, ibi, ii++, v4);
  43580. }
  43581. else {
  43582. this._storeIndex(ib, ibi, 0, v1);
  43583. this._storeIndex(ib, ibi, 1, v2);
  43584. this._storeIndex(ib, ibi, 2, v3);
  43585. this._storeIndex(ib, ibi, 3, v1);
  43586. this._storeIndex(ib, ibi, 4, v3);
  43587. this._storeIndex(ib, ibi, 5, v4);
  43588. }
  43589. break;
  43590. }
  43591. case Lines2D.RoundAnchorCap:
  43592. {
  43593. var cpos = Math.sqrt(t * t - ht * ht);
  43594. var center = new BABYLON.Vector2(cpos, 0);
  43595. var curA = BABYLON.Tools.ToRadians(-150);
  43596. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  43597. if (borderMode) {
  43598. var ii = 0;
  43599. for (var i = 0; i < sd; i++) {
  43600. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  43601. var v2 = this._storeVertex(vb, vbi, i * 2 + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * (t + bt), Math.sin(curA) * (t + bt)), contour);
  43602. if (i > 0) {
  43603. this._storeIndex(ib, ibi, ii++, v1 - 2);
  43604. this._storeIndex(ib, ibi, ii++, v2 - 2);
  43605. this._storeIndex(ib, ibi, ii++, v2);
  43606. this._storeIndex(ib, ibi, ii++, v1 - 2);
  43607. this._storeIndex(ib, ibi, ii++, v2);
  43608. this._storeIndex(ib, ibi, ii++, v1);
  43609. }
  43610. curA += incA;
  43611. }
  43612. }
  43613. else {
  43614. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  43615. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  43616. curA += incA;
  43617. for (var i = 1; i < sd; i++) {
  43618. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  43619. this._storeIndex(ib, ibi, i * 3 + 0, c);
  43620. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  43621. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  43622. curA += incA;
  43623. }
  43624. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  43625. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  43626. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  43627. }
  43628. break;
  43629. }
  43630. case Lines2D.DiamondAnchorCap:
  43631. {
  43632. var vi = 0;
  43633. var c = borderMode ? null : contour;
  43634. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  43635. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  43636. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  43637. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  43638. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  43639. if (borderMode) {
  43640. var f = Math.sqrt(bt * bt * 2);
  43641. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  43642. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  43643. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  43644. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  43645. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  43646. var ii = 0;
  43647. this._storeIndex(ib, ibi, ii++, v6);
  43648. this._storeIndex(ib, ibi, ii++, v7);
  43649. this._storeIndex(ib, ibi, ii++, v1);
  43650. this._storeIndex(ib, ibi, ii++, v1);
  43651. this._storeIndex(ib, ibi, ii++, v7);
  43652. this._storeIndex(ib, ibi, ii++, v2);
  43653. this._storeIndex(ib, ibi, ii++, v2);
  43654. this._storeIndex(ib, ibi, ii++, v7);
  43655. this._storeIndex(ib, ibi, ii++, v8);
  43656. this._storeIndex(ib, ibi, ii++, v2);
  43657. this._storeIndex(ib, ibi, ii++, v8);
  43658. this._storeIndex(ib, ibi, ii++, v3);
  43659. this._storeIndex(ib, ibi, ii++, v3);
  43660. this._storeIndex(ib, ibi, ii++, v8);
  43661. this._storeIndex(ib, ibi, ii++, v9);
  43662. this._storeIndex(ib, ibi, ii++, v3);
  43663. this._storeIndex(ib, ibi, ii++, v9);
  43664. this._storeIndex(ib, ibi, ii++, v4);
  43665. this._storeIndex(ib, ibi, ii++, v4);
  43666. this._storeIndex(ib, ibi, ii++, v9);
  43667. this._storeIndex(ib, ibi, ii++, v10);
  43668. this._storeIndex(ib, ibi, ii++, v4);
  43669. this._storeIndex(ib, ibi, ii++, v10);
  43670. this._storeIndex(ib, ibi, ii++, v5);
  43671. }
  43672. else {
  43673. this._storeIndex(ib, ibi, 0, v1);
  43674. this._storeIndex(ib, ibi, 1, v2);
  43675. this._storeIndex(ib, ibi, 2, v3);
  43676. this._storeIndex(ib, ibi, 3, v1);
  43677. this._storeIndex(ib, ibi, 4, v3);
  43678. this._storeIndex(ib, ibi, 5, v5);
  43679. this._storeIndex(ib, ibi, 6, v5);
  43680. this._storeIndex(ib, ibi, 7, v3);
  43681. this._storeIndex(ib, ibi, 8, v4);
  43682. }
  43683. break;
  43684. }
  43685. }
  43686. return null;
  43687. };
  43688. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  43689. var lineA = BABYLON.Vector2.Zero();
  43690. var lineB = BABYLON.Vector2.Zero();
  43691. var tangent = BABYLON.Vector2.Zero();
  43692. var miter = BABYLON.Vector2.Zero();
  43693. var curNormal = null;
  43694. if (this.closed) {
  43695. this.points.push(this.points[0]);
  43696. }
  43697. var total = this.points.length;
  43698. for (var i = 1; i < total; i++) {
  43699. var last = this.points[i - 1];
  43700. var cur = this.points[i];
  43701. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  43702. this._direction(cur, last, lineA);
  43703. if (!curNormal) {
  43704. curNormal = BABYLON.Vector2.Zero();
  43705. this._perp(lineA, curNormal);
  43706. }
  43707. if (i === 1) {
  43708. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  43709. }
  43710. if (!next) {
  43711. this._perp(lineA, curNormal);
  43712. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  43713. }
  43714. else {
  43715. this._direction(next, cur, lineB);
  43716. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  43717. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  43718. }
  43719. }
  43720. if (this.points.length > 2 && this.closed) {
  43721. var last2 = this.points[total - 2];
  43722. var cur2 = this.points[0];
  43723. var next2 = this.points[1];
  43724. this._direction(cur2, last2, lineA);
  43725. this._direction(next2, cur2, lineB);
  43726. this._perp(lineA, curNormal);
  43727. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  43728. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  43729. // Patch contour
  43730. if (contour) {
  43731. var off = (bt == null) ? 0 : 4;
  43732. contour[0].x = vb[off + 0];
  43733. contour[0].y = vb[off + 1];
  43734. contour[1].x = vb[off + 2];
  43735. contour[1].y = vb[off + 3];
  43736. }
  43737. }
  43738. // Remove the point we added at the beginning
  43739. if (this.closed) {
  43740. this.points.splice(total - 1);
  43741. }
  43742. };
  43743. // Methods for Lines building
  43744. ///////////////////////////////////////////////////////////////////////////////////
  43745. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43746. var renderCache = modelRenderCache;
  43747. var engine = this.owner.engine;
  43748. if (this._fillVB === null) {
  43749. this._computeLines2D();
  43750. }
  43751. // Need to create WebGL resources for fill part?
  43752. if (this.fill) {
  43753. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  43754. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  43755. renderCache.fillIndicesCount = this._fillIB.length;
  43756. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  43757. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], true);
  43758. if (ei) {
  43759. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43760. }
  43761. // Get the non instanced version
  43762. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], false);
  43763. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43764. }
  43765. // Need to create WebGL resources for border part?
  43766. if (this.border) {
  43767. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  43768. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  43769. renderCache.borderIndicesCount = this._borderIB.length;
  43770. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  43771. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], true);
  43772. if (ei) {
  43773. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  43774. }
  43775. // Get the non instanced version
  43776. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], false);
  43777. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  43778. }
  43779. this._fillVB = null;
  43780. this._fillIB = null;
  43781. this._borderVB = null;
  43782. this._borderIB = null;
  43783. return renderCache;
  43784. };
  43785. Lines2D.prototype._computeLines2D = function () {
  43786. // Init min/max because their being computed here
  43787. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  43788. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  43789. var contour = new Array();
  43790. var startCapContour = new Array();
  43791. var endCapContour = new Array();
  43792. // Need to create WebGL resources for fill part?
  43793. if (this.fill) {
  43794. var startCapInfo = this._getCapSize(this.startCap);
  43795. var endCapInfo = this._getCapSize(this.endCap);
  43796. var count = this.points.length;
  43797. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  43798. this._fillVB = new Float32Array(vbSize);
  43799. var vb = this._fillVB;
  43800. var ht = this.fillThickness / 2;
  43801. var total = this.points.length;
  43802. this._buildLine(vb, this.border ? null : contour, ht);
  43803. var max = total * 2;
  43804. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  43805. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  43806. var ib = this._fillIB;
  43807. for (var i = 0; i < triCount; i += 2) {
  43808. ib[i * 3 + 0] = i + 0;
  43809. ib[i * 3 + 1] = i + 1;
  43810. ib[i * 3 + 2] = (i + 2) % max;
  43811. ib[i * 3 + 3] = i + 1;
  43812. ib[i * 3 + 4] = (i + 3) % max;
  43813. ib[i * 3 + 5] = (i + 2) % max;
  43814. }
  43815. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D._startDir, this.border ? null : startCapContour);
  43816. this._buildCap(vb, (count * 2 * 2) + startCapInfo.vbsize, ib, (triCount * 3) + startCapInfo.ibsize, this.points[total - 1], this.fillThickness, null, this.endCap, Lines2D._endDir, this.border ? null : startCapContour);
  43817. }
  43818. // Need to create WebGL resources for border part?
  43819. if (this.border) {
  43820. var startCapInfo = this._getCapSize(this.startCap, true);
  43821. var endCapInfo = this._getCapSize(this.endCap, true);
  43822. var count = this.points.length;
  43823. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  43824. this._borderVB = new Float32Array(vbSize);
  43825. var vb = this._borderVB;
  43826. var ht = this.fillThickness / 2;
  43827. var bt = this.borderThickness;
  43828. var total = this.points.length;
  43829. this._buildLine(vb, contour, ht, bt);
  43830. var max = total * 2 * 2;
  43831. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  43832. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  43833. var ib = this._borderIB;
  43834. for (var i = 0; i < triCount; i += 4) {
  43835. ib[i * 3 + 0] = i + 0;
  43836. ib[i * 3 + 1] = i + 2;
  43837. ib[i * 3 + 2] = (i + 6) % max;
  43838. ib[i * 3 + 3] = i + 0;
  43839. ib[i * 3 + 4] = (i + 6) % max;
  43840. ib[i * 3 + 5] = (i + 4) % max;
  43841. ib[i * 3 + 6] = i + 3;
  43842. ib[i * 3 + 7] = i + 1;
  43843. ib[i * 3 + 8] = (i + 5) % max;
  43844. ib[i * 3 + 9] = i + 3;
  43845. ib[i * 3 + 10] = (i + 5) % max;
  43846. ib[i * 3 + 11] = (i + 7) % max;
  43847. }
  43848. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D._startDir, startCapContour);
  43849. this._buildCap(vb, (count * 2 * 2 * 2) + startCapInfo.vbsize, ib, (triCount * 3) + startCapInfo.ibsize, this.points[total - 1], this.fillThickness, this.borderThickness, this.endCap, Lines2D._endDir, endCapContour);
  43850. }
  43851. this._contour = contour;
  43852. if (startCapContour.length > 0) {
  43853. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  43854. this._startCapTriIndices = startCapTri;
  43855. this._startCapContour = startCapContour;
  43856. }
  43857. if (endCapContour.length > 0) {
  43858. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  43859. this._endCapContour = endCapContour;
  43860. this._endCapTriIndices = endCapTri;
  43861. }
  43862. var bs = this._boundingMax.subtract(this._boundingMin);
  43863. this._size.width = bs.x;
  43864. this._size.height = bs.y;
  43865. };
  43866. Object.defineProperty(Lines2D.prototype, "size", {
  43867. get: function () {
  43868. if (this._size == null) {
  43869. this._computeLines2D();
  43870. }
  43871. return this._size;
  43872. },
  43873. enumerable: true,
  43874. configurable: true
  43875. });
  43876. Lines2D.prototype.createInstanceDataParts = function () {
  43877. var res = new Array();
  43878. if (this.border) {
  43879. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  43880. }
  43881. if (this.fill) {
  43882. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  43883. }
  43884. return res;
  43885. };
  43886. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  43887. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43888. return false;
  43889. }
  43890. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  43891. var d = part;
  43892. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  43893. d.boundingMin = this.boundingMin;
  43894. d.boundingMax = this.boundingMax;
  43895. }
  43896. }
  43897. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  43898. var d = part;
  43899. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  43900. d.boundingMin = this.boundingMin;
  43901. d.boundingMax = this.boundingMax;
  43902. }
  43903. }
  43904. return true;
  43905. };
  43906. Lines2D._prevA = BABYLON.Vector2.Zero();
  43907. Lines2D._prevB = BABYLON.Vector2.Zero();
  43908. Lines2D._curA = BABYLON.Vector2.Zero();
  43909. Lines2D._curB = BABYLON.Vector2.Zero();
  43910. Lines2D._miterTps = BABYLON.Vector2.Zero();
  43911. Lines2D._startDir = BABYLON.Vector2.Zero();
  43912. Lines2D._endDir = BABYLON.Vector2.Zero();
  43913. Lines2D._tpsV = BABYLON.Vector2.Zero();
  43914. Lines2D._noCap = 0;
  43915. Lines2D._roundCap = 1;
  43916. Lines2D._triangleCap = 2;
  43917. Lines2D._squareAnchorCap = 3;
  43918. Lines2D._roundAnchorCap = 4;
  43919. Lines2D._diamondAnchorCap = 5;
  43920. Lines2D._arrowCap = 6;
  43921. Lines2D._roundCapSubDiv = 36;
  43922. __decorate([
  43923. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  43924. ], Lines2D.prototype, "points", null);
  43925. __decorate([
  43926. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  43927. ], Lines2D.prototype, "fillThickness", null);
  43928. __decorate([
  43929. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  43930. ], Lines2D.prototype, "closed", null);
  43931. __decorate([
  43932. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  43933. ], Lines2D.prototype, "startCap", null);
  43934. __decorate([
  43935. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  43936. ], Lines2D.prototype, "endCap", null);
  43937. Lines2D = __decorate([
  43938. BABYLON.className("Lines2D")
  43939. ], Lines2D);
  43940. return Lines2D;
  43941. })(BABYLON.Shape2D);
  43942. BABYLON.Lines2D = Lines2D;
  43943. })(BABYLON || (BABYLON = {}));
  43944. var BABYLON;
  43945. (function (BABYLON) {
  43946. // This class contains data that lifetime is bounding to the Babylon Engine object
  43947. var Canvas2DEngineBoundData = (function () {
  43948. function Canvas2DEngineBoundData() {
  43949. this._modelCache = new BABYLON.StringDictionary();
  43950. }
  43951. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  43952. return this._modelCache.getOrAddWithFactory(key, factory);
  43953. };
  43954. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  43955. if (!modelRenderCache.isDisposed) {
  43956. return false;
  43957. }
  43958. this._modelCache.remove(modelRenderCache.modelKey);
  43959. return true;
  43960. };
  43961. return Canvas2DEngineBoundData;
  43962. })();
  43963. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  43964. var Canvas2D = (function (_super) {
  43965. __extends(Canvas2D, _super);
  43966. function Canvas2D(scene, settings) {
  43967. var _this = this;
  43968. _super.call(this, settings);
  43969. /**
  43970. * If you set your own WorldSpaceNode to display the Canvas2D you have to provide your own implementation of this method which computes the local position in the Canvas based on the given 3D World one.
  43971. * Beware that you have to take under consideration the origin and the renderScaleFactor in your calculations! Good luck!
  43972. */
  43973. this.worldSpaceToNodeLocal = function (worldPos) {
  43974. var node = _this._worldSpaceNode;
  43975. if (!node) {
  43976. return;
  43977. }
  43978. var mtx = node.getWorldMatrix().clone();
  43979. mtx.invert();
  43980. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  43981. var rsf = _this._renderScaleFactor;
  43982. var res = new BABYLON.Vector2(v.x * rsf, v.y * rsf);
  43983. var size = _this.actualSize;
  43984. var o = _this.origin;
  43985. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  43986. res.y += size.width * 0.5;
  43987. return res;
  43988. };
  43989. this._notifDebugMode = false;
  43990. this._mapCounter = 0;
  43991. BABYLON.Prim2DBase._isCanvasInit = false;
  43992. if (!settings) {
  43993. settings = {};
  43994. }
  43995. var renderScaleFactor = (settings.renderScaleFactor == null) ? 1 : settings.renderScaleFactor;
  43996. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  43997. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  43998. this._background.zOrder = 1.0;
  43999. this._background.isPickable = false;
  44000. this._background.origin = BABYLON.Vector2.Zero();
  44001. this._background.levelVisible = false;
  44002. if (settings.backgroundRoundRadius != null) {
  44003. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  44004. }
  44005. if (settings.backgroundBorder != null) {
  44006. if (typeof (settings.backgroundBorder) === "string") {
  44007. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  44008. }
  44009. else {
  44010. this.backgroundBorder = settings.backgroundBorder;
  44011. }
  44012. }
  44013. if (settings.backgroundBorderThickNess != null) {
  44014. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  44015. }
  44016. if (settings.backgroundFill != null) {
  44017. if (typeof (settings.backgroundFill) === "string") {
  44018. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  44019. }
  44020. else {
  44021. this.backgroundFill = settings.backgroundFill;
  44022. }
  44023. }
  44024. this._background._patchHierarchy(this);
  44025. }
  44026. var engine = scene.getEngine();
  44027. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  44028. this._renderScaleFactor = renderScaleFactor;
  44029. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  44030. this._capturedPointers = new BABYLON.StringDictionary();
  44031. this._pickStartingPosition = BABYLON.Vector2.Zero();
  44032. this._hierarchyLevelMaxSiblingCount = 50;
  44033. this._hierarchyDepthOffset = 0;
  44034. this._siblingDepthOffset = 1 / this._hierarchyLevelMaxSiblingCount;
  44035. this._scene = scene;
  44036. this._engine = engine;
  44037. this._renderingSize = new BABYLON.Size(0, 0);
  44038. this._trackedGroups = new Array();
  44039. this._patchHierarchy(this);
  44040. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  44041. this._fitRenderingDevice = !settings.size;
  44042. if (!settings.size) {
  44043. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  44044. }
  44045. else {
  44046. settings.size.height *= renderScaleFactor;
  44047. settings.size.width *= renderScaleFactor;
  44048. }
  44049. // Register scene dispose to also dispose the canvas when it'll happens
  44050. scene.onDisposeObservable.add(function (d, s) {
  44051. _this.dispose();
  44052. });
  44053. if (this._isScreenSpace) {
  44054. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  44055. _this._engine.clear(null, false, true);
  44056. _this._render();
  44057. });
  44058. }
  44059. else {
  44060. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  44061. _this._render();
  44062. });
  44063. }
  44064. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  44065. // this._supprtInstancedArray = false; // TODO REMOVE!!!
  44066. this._setupInteraction(enableInteraction);
  44067. }
  44068. Canvas2D.prototype._canvasPreInit = function (settings) {
  44069. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  44070. this._cachingStrategy = cachingStrategy;
  44071. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  44072. };
  44073. Canvas2D.prototype._setupInteraction = function (enable) {
  44074. var _this = this;
  44075. // No change detection
  44076. if (enable === this._interactionEnabled) {
  44077. return;
  44078. }
  44079. // Set the new state
  44080. this._interactionEnabled = enable;
  44081. // ScreenSpace mode
  44082. if (this._isScreenSpace) {
  44083. // Disable interaction
  44084. if (!enable) {
  44085. if (this._scenePrePointerObserver) {
  44086. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  44087. this._scenePrePointerObserver = null;
  44088. }
  44089. return;
  44090. }
  44091. // Enable Interaction
  44092. // Register the observable
  44093. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  44094. var hs = 1 / _this.engine.getHardwareScalingLevel();
  44095. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  44096. _this._handlePointerEventForInteraction(e, localPos, s);
  44097. });
  44098. }
  44099. else {
  44100. var scene = this.scene;
  44101. if (enable) {
  44102. scene.constantlyUpdateMeshUnderPointer = true;
  44103. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  44104. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  44105. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  44106. _this._handlePointerEventForInteraction(e, localPos, s);
  44107. }
  44108. });
  44109. }
  44110. else {
  44111. if (this._scenePointerObserver) {
  44112. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  44113. this._scenePointerObserver = null;
  44114. }
  44115. }
  44116. }
  44117. };
  44118. /**
  44119. * Internal method, you should use the Prim2DBase version instead
  44120. */
  44121. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  44122. if (this.isPointerCaptured(pointerId)) {
  44123. return false;
  44124. }
  44125. // Try to capture the pointer on the HTML side
  44126. try {
  44127. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  44128. }
  44129. catch (e) {
  44130. }
  44131. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  44132. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  44133. this._capturedPointers.add(pointerId.toString(), primitive);
  44134. return true;
  44135. };
  44136. /**
  44137. * Internal method, you should use the Prim2DBase version instead
  44138. */
  44139. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  44140. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  44141. return false;
  44142. }
  44143. // Try to release the pointer on the HTML side
  44144. try {
  44145. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  44146. }
  44147. catch (e) {
  44148. }
  44149. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  44150. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  44151. this._capturedPointers.remove(pointerId.toString());
  44152. return true;
  44153. };
  44154. /**
  44155. * Determine if the given pointer is captured or not
  44156. * @param pointerId the Id of the pointer
  44157. * @return true if it's captured, false otherwise
  44158. */
  44159. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  44160. return this._capturedPointers.contains(pointerId.toString());
  44161. };
  44162. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  44163. // Avoid unnecessary lookup
  44164. if (this._capturedPointers.count === 0) {
  44165. return null;
  44166. }
  44167. return this._capturedPointers.get(pointerId.toString());
  44168. };
  44169. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  44170. // Dispose check
  44171. if (this.isDisposed) {
  44172. return;
  44173. }
  44174. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  44175. this._updatePointerInfo(eventData, localPosition);
  44176. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  44177. // Make sure the intersection list is up to date, we maintain this list either in response of a mouse event (here) or before rendering the canvas.
  44178. // Why before rendering the canvas? because some primitives may move and get away/under the mouse cursor (which is not moving). So we need to update at both location in order to always have an accurate list, which is needed for the hover state change.
  44179. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  44180. // Update the over status, same as above, it's could be done here or during rendering, but will be performed only once per render frame
  44181. this._updateOverStatus();
  44182. // Check if we have nothing to raise
  44183. if (!this._actualOverPrimitive && !capturedPrim) {
  44184. return;
  44185. }
  44186. // Update the relatedTarget info with the over primitive or the captured one (if any)
  44187. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  44188. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  44189. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  44190. // Analyze the pointer event type and fire proper events on the primitive
  44191. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  44192. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData.event);
  44193. }
  44194. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44195. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData.event);
  44196. }
  44197. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  44198. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData.event);
  44199. }
  44200. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  44201. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData.event);
  44202. }
  44203. };
  44204. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  44205. var pii = this._primPointerInfo;
  44206. if (!pii.canvasPointerPos) {
  44207. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  44208. }
  44209. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  44210. var engine = this._scene.getEngine();
  44211. if (this._isScreenSpace) {
  44212. var cameraViewport = camera.viewport;
  44213. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  44214. // Moving coordinates to local viewport world
  44215. var x = localPosition.x - viewport.x;
  44216. var y = localPosition.y - viewport.y;
  44217. pii.canvasPointerPos.x = x - this.actualPosition.x;
  44218. pii.canvasPointerPos.y = engine.getRenderHeight() - y - this.actualPosition.y;
  44219. }
  44220. else {
  44221. pii.canvasPointerPos.x = localPosition.x;
  44222. pii.canvasPointerPos.y = localPosition.y;
  44223. }
  44224. pii.mouseWheelDelta = 0;
  44225. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  44226. var event = eventData.event;
  44227. if (event.wheelDelta) {
  44228. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  44229. }
  44230. else if (event.detail) {
  44231. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  44232. }
  44233. }
  44234. else {
  44235. var pe = eventData.event;
  44236. pii.ctrlKey = pe.ctrlKey;
  44237. pii.altKey = pe.altKey;
  44238. pii.shiftKey = pe.shiftKey;
  44239. pii.metaKey = pe.metaKey;
  44240. pii.button = pe.button;
  44241. pii.buttons = pe.buttons;
  44242. pii.pointerId = pe.pointerId;
  44243. pii.width = pe.width;
  44244. pii.height = pe.height;
  44245. pii.presssure = pe.pressure;
  44246. pii.tilt.x = pe.tiltX;
  44247. pii.tilt.y = pe.tiltY;
  44248. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  44249. }
  44250. };
  44251. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  44252. if (this.scene.getRenderId() === this._intersectionRenderId) {
  44253. return;
  44254. }
  44255. // A little safe guard, it might happens than the event is triggered before the first render and nothing is computed, this simple check will make sure everything will be fine
  44256. if (!this._globalTransform) {
  44257. this.updateCachedStates(true);
  44258. }
  44259. var ii = Canvas2D._interInfo;
  44260. ii.pickPosition.x = mouseLocalPos.x;
  44261. ii.pickPosition.y = mouseLocalPos.y;
  44262. ii.findFirstOnly = false;
  44263. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  44264. if (!isCapture && !this.boundingInfo.doesIntersect(ii.pickPosition)) {
  44265. this._previousIntersectionList = this._actualIntersectionList;
  44266. this._actualIntersectionList = null;
  44267. this._previousOverPrimitive = this._actualOverPrimitive;
  44268. this._actualOverPrimitive = null;
  44269. return;
  44270. }
  44271. this.intersect(ii);
  44272. this._previousIntersectionList = this._actualIntersectionList;
  44273. this._actualIntersectionList = ii.intersectedPrimitives;
  44274. this._previousOverPrimitive = this._actualOverPrimitive;
  44275. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  44276. this._intersectionRenderId = this.scene.getRenderId();
  44277. };
  44278. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  44279. Canvas2D.prototype._updateOverStatus = function () {
  44280. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  44281. return;
  44282. }
  44283. // Detect a change of over
  44284. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  44285. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  44286. if (prevPrim !== actualPrim) {
  44287. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  44288. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  44289. // Notify the previous "over" prim that the pointer is no longer over it
  44290. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  44291. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  44292. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  44293. }
  44294. // Notify the new "over" prim that the pointer is over it
  44295. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  44296. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  44297. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  44298. }
  44299. }
  44300. this._hoverStatusRenderId = this.scene.getRenderId();
  44301. };
  44302. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  44303. if (this._primPointerInfo.isCaptured) {
  44304. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  44305. }
  44306. else {
  44307. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  44308. var pii = _a[_i];
  44309. if (pii.prim === prim) {
  44310. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  44311. return;
  44312. }
  44313. }
  44314. }
  44315. };
  44316. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  44317. if (!this._notifDebugMode) {
  44318. return;
  44319. }
  44320. var debug = "";
  44321. for (var i = 0; i < prim.hierarchyDepth; i++) {
  44322. debug += " ";
  44323. }
  44324. var pii = this._primPointerInfo;
  44325. debug += "[RID:" + this.scene.getRenderId() + "] [" + prim.hierarchyDepth + "] event:" + BABYLON.PrimitivePointerInfo.getEventTypeName(mask) + ", id: " + prim.id + " (" + BABYLON.Tools.getClassName(prim) + "), primPos: " + pii.primitivePointerPos.toString() + ", canvasPos: " + pii.canvasPointerPos.toString();
  44326. console.log(debug);
  44327. };
  44328. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  44329. var ppi = this._primPointerInfo;
  44330. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  44331. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  44332. this._notifParents(prim, mask);
  44333. }
  44334. var bubbleCancelled = false;
  44335. var cur = prim;
  44336. while (cur) {
  44337. // Only trigger the observers if the primitive is intersected (except for out)
  44338. if (!bubbleCancelled) {
  44339. this._updatePrimPointerPos(cur);
  44340. // Exec the observers
  44341. this._debugExecObserver(cur, mask);
  44342. cur._pointerEventObservable.notifyObservers(ppi, mask);
  44343. this._triggerActionManager(cur, ppi, mask, eventData);
  44344. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  44345. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  44346. if (ppi.cancelBubble) {
  44347. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  44348. return;
  44349. }
  44350. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  44351. bubbleCancelled = true;
  44352. }
  44353. }
  44354. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  44355. if (bubbleCancelled) {
  44356. this._updatePrimPointerPos(cur);
  44357. }
  44358. // Trigger a PointerEnter corresponding to the PointerOver
  44359. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  44360. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  44361. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  44362. }
  44363. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  44364. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  44365. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  44366. }
  44367. // Loop to the parent
  44368. cur = cur.parent;
  44369. }
  44370. };
  44371. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  44372. var _this = this;
  44373. // A little safe guard, it might happens than the event is triggered before the first render and nothing is computed, this simple check will make sure everything will be fine
  44374. if (!this._globalTransform) {
  44375. this.updateCachedStates(true);
  44376. }
  44377. // Process Trigger related to PointerDown
  44378. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  44379. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  44380. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  44381. this._pickStartingTime = new Date().getTime();
  44382. this._pickedDownPrim = null;
  44383. if (prim.actionManager) {
  44384. this._pickedDownPrim = prim;
  44385. if (prim.actionManager.hasPickTriggers) {
  44386. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  44387. switch (eventData.button) {
  44388. case 0:
  44389. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  44390. break;
  44391. case 1:
  44392. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  44393. break;
  44394. case 2:
  44395. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  44396. break;
  44397. }
  44398. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  44399. }
  44400. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  44401. window.setTimeout(function () {
  44402. var ppi = _this._primPointerInfo;
  44403. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  44404. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  44405. var ii = new BABYLON.IntersectInfo2D();
  44406. ii.pickPosition = ppi.canvasPointerPos.clone();
  44407. ii.findFirstOnly = false;
  44408. _this.intersect(ii);
  44409. if (ii.isPrimIntersected(prim) !== null) {
  44410. if (prim.actionManager) {
  44411. if (_this._pickStartingTime !== 0 && ((new Date().getTime() - _this._pickStartingTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(_this._pickStartingPosition.x - ii.pickPosition.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._pickStartingPosition.y - ii.pickPosition.y) < BABYLON.ActionManager.DragMovementThreshold)) {
  44412. _this._pickStartingTime = 0;
  44413. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  44414. }
  44415. }
  44416. }
  44417. }, BABYLON.ActionManager.LongPressDelay);
  44418. }
  44419. }
  44420. }
  44421. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  44422. this._pickStartingTime = 0;
  44423. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  44424. if (prim.actionManager) {
  44425. // OnPickUpTrigger
  44426. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  44427. // OnPickTrigger
  44428. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  44429. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  44430. }
  44431. }
  44432. // OnPickOutTrigger
  44433. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  44434. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  44435. }
  44436. }
  44437. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  44438. if (prim.actionManager) {
  44439. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  44440. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  44441. }
  44442. }
  44443. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  44444. if (prim.actionManager) {
  44445. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  44446. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  44447. }
  44448. }
  44449. };
  44450. Canvas2D.prototype._notifParents = function (prim, mask) {
  44451. var pii = this._primPointerInfo;
  44452. var curPrim = this;
  44453. while (curPrim) {
  44454. this._updatePrimPointerPos(curPrim);
  44455. // Fire the proper notification
  44456. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  44457. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  44458. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  44459. }
  44460. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  44461. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  44462. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  44463. }
  44464. curPrim = curPrim.parent;
  44465. }
  44466. };
  44467. /**
  44468. * Don't forget to call the dispose method when you're done with the Canvas instance.
  44469. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  44470. */
  44471. Canvas2D.prototype.dispose = function () {
  44472. if (!_super.prototype.dispose.call(this)) {
  44473. return false;
  44474. }
  44475. if (this.interactionEnabled) {
  44476. this._setupInteraction(false);
  44477. }
  44478. if (this._beforeRenderObserver) {
  44479. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  44480. this._beforeRenderObserver = null;
  44481. }
  44482. if (this._afterRenderObserver) {
  44483. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  44484. this._afterRenderObserver = null;
  44485. }
  44486. if (this._groupCacheMaps) {
  44487. this._groupCacheMaps.forEach(function (m) { return m.dispose(); });
  44488. this._groupCacheMaps = null;
  44489. }
  44490. };
  44491. Object.defineProperty(Canvas2D.prototype, "scene", {
  44492. /**
  44493. * Accessor to the Scene that owns the Canvas
  44494. * @returns The instance of the Scene object
  44495. */
  44496. get: function () {
  44497. return this._scene;
  44498. },
  44499. enumerable: true,
  44500. configurable: true
  44501. });
  44502. Object.defineProperty(Canvas2D.prototype, "engine", {
  44503. /**
  44504. * Accessor to the Engine that drives the Scene used by this Canvas
  44505. * @returns The instance of the Engine object
  44506. */
  44507. get: function () {
  44508. return this._engine;
  44509. },
  44510. enumerable: true,
  44511. configurable: true
  44512. });
  44513. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  44514. /**
  44515. * Accessor of the Caching Strategy used by this Canvas.
  44516. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  44517. * @returns the value corresponding to the used strategy.
  44518. */
  44519. get: function () {
  44520. return this._cachingStrategy;
  44521. },
  44522. enumerable: true,
  44523. configurable: true
  44524. });
  44525. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  44526. /**
  44527. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  44528. */
  44529. get: function () {
  44530. return this._worldSpaceNode;
  44531. },
  44532. set: function (val) {
  44533. this._worldSpaceNode = val;
  44534. },
  44535. enumerable: true,
  44536. configurable: true
  44537. });
  44538. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  44539. /**
  44540. * Check if the WebGL Instanced Array extension is supported or not
  44541. */
  44542. get: function () {
  44543. return this._supprtInstancedArray;
  44544. },
  44545. enumerable: true,
  44546. configurable: true
  44547. });
  44548. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  44549. /**
  44550. * Property that defines the fill object used to draw the background of the Canvas.
  44551. * Note that Canvas with a Caching Strategy of
  44552. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  44553. */
  44554. get: function () {
  44555. if (!this._background || !this._background.isVisible) {
  44556. return null;
  44557. }
  44558. return this._background.fill;
  44559. },
  44560. set: function (value) {
  44561. this.checkBackgroundAvailability();
  44562. if (value === this._background.fill) {
  44563. return;
  44564. }
  44565. this._background.fill = value;
  44566. this._background.levelVisible = true;
  44567. },
  44568. enumerable: true,
  44569. configurable: true
  44570. });
  44571. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  44572. /**
  44573. * Property that defines the border object used to draw the background of the Canvas.
  44574. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  44575. */
  44576. get: function () {
  44577. if (!this._background || !this._background.isVisible) {
  44578. return null;
  44579. }
  44580. return this._background.border;
  44581. },
  44582. set: function (value) {
  44583. this.checkBackgroundAvailability();
  44584. if (value === this._background.border) {
  44585. return;
  44586. }
  44587. this._background.border = value;
  44588. this._background.levelVisible = true;
  44589. },
  44590. enumerable: true,
  44591. configurable: true
  44592. });
  44593. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  44594. /**
  44595. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  44596. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  44597. */
  44598. get: function () {
  44599. if (!this._background || !this._background.isVisible) {
  44600. return null;
  44601. }
  44602. return this._background.borderThickness;
  44603. },
  44604. set: function (value) {
  44605. this.checkBackgroundAvailability();
  44606. if (value === this._background.borderThickness) {
  44607. return;
  44608. }
  44609. this._background.borderThickness = value;
  44610. },
  44611. enumerable: true,
  44612. configurable: true
  44613. });
  44614. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  44615. /**
  44616. * You can set the roundRadius of the background
  44617. * @returns The current roundRadius
  44618. */
  44619. get: function () {
  44620. if (!this._background || !this._background.isVisible) {
  44621. return null;
  44622. }
  44623. return this._background.roundRadius;
  44624. },
  44625. set: function (value) {
  44626. this.checkBackgroundAvailability();
  44627. if (value === this._background.roundRadius) {
  44628. return;
  44629. }
  44630. this._background.roundRadius = value;
  44631. this._background.levelVisible = true;
  44632. },
  44633. enumerable: true,
  44634. configurable: true
  44635. });
  44636. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  44637. /**
  44638. * Enable/Disable interaction for this Canvas
  44639. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  44640. */
  44641. get: function () {
  44642. return this._interactionEnabled;
  44643. },
  44644. set: function (enable) {
  44645. this._setupInteraction(enable);
  44646. },
  44647. enumerable: true,
  44648. configurable: true
  44649. });
  44650. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  44651. /**
  44652. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  44653. * @returns {}
  44654. */
  44655. get: function () {
  44656. return this.__engineData;
  44657. },
  44658. enumerable: true,
  44659. configurable: true
  44660. });
  44661. Canvas2D.prototype.checkBackgroundAvailability = function () {
  44662. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  44663. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  44664. }
  44665. };
  44666. Canvas2D.prototype.onPrimBecomesDirty = function () {
  44667. this._addPrimToDirtyList(this);
  44668. };
  44669. Canvas2D.prototype._updateTrackedNodes = function () {
  44670. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  44671. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  44672. var rh = this.engine.getRenderHeight();
  44673. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  44674. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  44675. var group = _a[_i];
  44676. if (group.isDisposed || !group.isVisible) {
  44677. continue;
  44678. }
  44679. var node = group.trackedNode;
  44680. var worldMtx = node.getWorldMatrix();
  44681. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  44682. group.x = Math.round(proj.x);
  44683. group.y = Math.round(rh - proj.y);
  44684. }
  44685. };
  44686. Canvas2D.prototype._updateCanvasState = function () {
  44687. // Check if the update has already been made for this render Frame
  44688. if (this.scene.getRenderId() === this._updateRenderId) {
  44689. return;
  44690. }
  44691. // Detect a change of rendering size
  44692. var renderingSizeChanged = false;
  44693. var newWidth = this.engine.getRenderWidth();
  44694. if (newWidth !== this._renderingSize.width) {
  44695. renderingSizeChanged = true;
  44696. }
  44697. this._renderingSize.width = newWidth;
  44698. var newHeight = this.engine.getRenderHeight();
  44699. if (newHeight !== this._renderingSize.height) {
  44700. renderingSizeChanged = true;
  44701. }
  44702. this._renderingSize.height = newHeight;
  44703. // If the canvas fit the rendering size and it changed, update
  44704. if (renderingSizeChanged && this._fitRenderingDevice) {
  44705. this.size = this._renderingSize;
  44706. if (this._background) {
  44707. this._background.size = this.size;
  44708. }
  44709. // Dirty the Layout at the Canvas level to recompute as the size changed
  44710. this._setLayoutDirty();
  44711. }
  44712. var context = new BABYLON.PrepareRender2DContext();
  44713. ++this._globalTransformProcessStep;
  44714. this.updateCachedStates(false);
  44715. this._prepareGroupRender(context);
  44716. this._updateRenderId = this.scene.getRenderId();
  44717. };
  44718. /**
  44719. * Method that renders the Canvas, you should not invoke
  44720. */
  44721. Canvas2D.prototype._render = function () {
  44722. this._updateTrackedNodes();
  44723. this._updateCanvasState();
  44724. if (this._primPointerInfo.canvasPointerPos) {
  44725. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  44726. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  44727. }
  44728. this.engine.setState(false);
  44729. this._groupRender();
  44730. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  44731. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  44732. this._cachedCanvasGroup._renderCachedCanvas();
  44733. }
  44734. };
  44735. /**
  44736. * Internal method that allocate a cache for the given group.
  44737. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  44738. * @param group The group to allocate the cache of.
  44739. * @return custom type with the PackedRect instance giving information about the cache location into the texture and also the MapTexture instance that stores the cache.
  44740. */
  44741. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize) {
  44742. // Determine size
  44743. var size = group.actualSize;
  44744. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  44745. if (minSize) {
  44746. size.width = Math.max(minSize.width, size.width);
  44747. size.height = Math.max(minSize.height, size.height);
  44748. }
  44749. if (!this._groupCacheMaps) {
  44750. this._groupCacheMaps = new Array();
  44751. }
  44752. // Try to find a spot in one of the cached texture
  44753. var res = null;
  44754. for (var _i = 0, _a = this._groupCacheMaps; _i < _a.length; _i++) {
  44755. var map = _a[_i];
  44756. var node = map.allocateRect(size);
  44757. if (node) {
  44758. res = { node: node, texture: map };
  44759. break;
  44760. }
  44761. }
  44762. // Couldn't find a map that could fit the rect, create a new map for it
  44763. if (!res) {
  44764. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  44765. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  44766. if (size.width > mapSize.width || size.height > mapSize.height) {
  44767. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  44768. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  44769. }
  44770. var id = "groupsMapChache" + this._mapCounter + "forCanvas" + this.id;
  44771. map = new BABYLON.MapTexture(id, this._scene, mapSize);
  44772. this._groupCacheMaps.push(map);
  44773. var node = map.allocateRect(size);
  44774. res = { node: node, texture: map };
  44775. }
  44776. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  44777. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  44778. if (group !== this || this._isScreenSpace) {
  44779. var node = res.node;
  44780. // Special case if the canvas is entirely cached: create a group that will have a single sprite it will be rendered specifically at the very end of the rendering process
  44781. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  44782. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  44783. var sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  44784. sprite.zOrder = 1;
  44785. sprite.origin = BABYLON.Vector2.Zero();
  44786. }
  44787. else {
  44788. var sprite = new BABYLON.Sprite2D(map, { parent: parent, id: "__cachedSpriteOfGroup__" + group.id, x: group.actualPosition.x, y: group.actualPosition.y, spriteSize: node.contentSize, spriteLocation: node.pos });
  44789. sprite.origin = group.origin.clone();
  44790. res.sprite = sprite;
  44791. }
  44792. }
  44793. return res;
  44794. };
  44795. /**
  44796. * Internal method used to register a Scene Node to track position for the given group
  44797. * Do not invoke this method, for internal purpose only.
  44798. * @param group the group to track its associated Scene Node
  44799. */
  44800. Canvas2D.prototype._registerTrackedNode = function (group) {
  44801. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  44802. return;
  44803. }
  44804. this._trackedGroups.push(group);
  44805. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  44806. };
  44807. /**
  44808. * Internal method used to unregister a tracked Scene Node
  44809. * Do not invoke this method, it's for internal purpose only.
  44810. * @param group the group to unregister its tracked Scene Node from.
  44811. */
  44812. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  44813. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  44814. return;
  44815. }
  44816. var i = this._trackedGroups.indexOf(group);
  44817. if (i !== -1) {
  44818. this._trackedGroups.splice(i, 1);
  44819. }
  44820. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  44821. };
  44822. /**
  44823. * Get a Solid Color Brush instance matching the given color.
  44824. * @param color The color to retrieve
  44825. * @return A shared instance of the SolidColorBrush2D class that use the given color
  44826. */
  44827. Canvas2D.GetSolidColorBrush = function (color) {
  44828. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  44829. };
  44830. /**
  44831. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  44832. * @param color The color to retrieve
  44833. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  44834. */
  44835. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  44836. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  44837. };
  44838. /**
  44839. * Get a Gradient Color Brush
  44840. * @param color1 starting color
  44841. * @param color2 engine color
  44842. * @param translation translation vector to apply. default is [0;0]
  44843. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  44844. * @param scale scaling factor to apply. default is 1.
  44845. */
  44846. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  44847. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  44848. if (rotation === void 0) { rotation = 0; }
  44849. if (scale === void 0) { scale = 1; }
  44850. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  44851. };
  44852. /**
  44853. * Create a solid or gradient brush from a string value.
  44854. * @param brushString should be either
  44855. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  44856. * - "gradient: #FF808080, #FFFFFFF[, [10:20], 180, 1]" for color1, color2, translation, rotation (degree), scale. The last three are optionals, but if specified must be is this order. "gradient:" can be omitted.
  44857. */
  44858. Canvas2D.GetBrushFromString = function (brushString) {
  44859. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  44860. brushString = brushString.trim();
  44861. var split = brushString.split(",");
  44862. // Solid, formatted as: "[solid:]#FF808080"
  44863. if (split.length === 1) {
  44864. var value = null;
  44865. if (brushString.indexOf("solid:") === 0) {
  44866. value = brushString.substr(6).trim();
  44867. }
  44868. else if (brushString.indexOf("#") === 0) {
  44869. value = brushString;
  44870. }
  44871. else {
  44872. return null;
  44873. }
  44874. return Canvas2D.GetSolidColorBrushFromHex(value);
  44875. }
  44876. else {
  44877. if (split[0].indexOf("gradient:") === 0) {
  44878. split[0] = split[0].substr(9).trim();
  44879. }
  44880. try {
  44881. var start = BABYLON.Color4.FromHexString(split[0].trim());
  44882. var end = BABYLON.Color4.FromHexString(split[1].trim());
  44883. var t = BABYLON.Vector2.Zero();
  44884. if (split.length > 2) {
  44885. var v = split[2].trim();
  44886. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  44887. return null;
  44888. }
  44889. var sep = v.indexOf(":");
  44890. var x = parseFloat(v.substr(1, sep));
  44891. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  44892. t = new BABYLON.Vector2(x, y);
  44893. }
  44894. var r = 0;
  44895. if (split.length > 3) {
  44896. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  44897. }
  44898. var s = 1;
  44899. if (split.length > 4) {
  44900. s = parseFloat(split[4].trim());
  44901. }
  44902. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  44903. }
  44904. catch (e) {
  44905. return null;
  44906. }
  44907. }
  44908. };
  44909. /**
  44910. * In this strategy only the direct children groups of the Canvas will be cached, their whole content (whatever the sub groups they have) into a single bitmap.
  44911. * This strategy doesn't allow primitives added directly as children of the Canvas.
  44912. * You typically want to use this strategy of a screenSpace fullscreen canvas: you don't want a bitmap cache taking the whole screen resolution but still want the main contents (say UI in the topLeft and rightBottom for instance) to be efficiently cached.
  44913. */
  44914. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  44915. /**
  44916. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  44917. * This strategy is typically used if the canvas has some groups that are frequently animated. Unchanged ones will have a steady cache and the others will be refreshed when they change, reducing the redraw operation count to their content only.
  44918. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  44919. * Note that in this mode the Canvas itself is not cached, it only contains the sprites of its direct children group to render, there's no point to cache the whole canvas, sprites will be rendered pretty efficiently, the memory cost would be too great for the value of it.
  44920. */
  44921. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  44922. /**
  44923. * In this strategy the whole canvas is cached into a single bitmap containing every primitives it owns, at the exception of the ones that are owned by a group having the DONTCACHEOVERRIDE behavior (these primitives will be directly drawn to the viewport at each render for screenSpace Canvas or be part of the Canvas cache bitmap for worldSpace Canvas).
  44924. */
  44925. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  44926. /**
  44927. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  44928. * Use this strategy if memory is a concern above rendering performances and/or if the canvas is frequently animated (hence reducing the benefits of caching).
  44929. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  44930. */
  44931. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  44932. Canvas2D.hierarchyLevelMaxSiblingCount = 50;
  44933. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  44934. Canvas2D._v = BABYLON.Vector3.Zero();
  44935. Canvas2D._m = BABYLON.Matrix.Identity();
  44936. /**
  44937. * Define the default size used for both the width and height of a MapTexture to allocate.
  44938. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  44939. */
  44940. Canvas2D._groupTextureCacheSize = 1024;
  44941. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  44942. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  44943. Canvas2D = __decorate([
  44944. BABYLON.className("Canvas2D")
  44945. ], Canvas2D);
  44946. return Canvas2D;
  44947. })(BABYLON.Group2D);
  44948. BABYLON.Canvas2D = Canvas2D;
  44949. var WorldSpaceCanvas2D = (function (_super) {
  44950. __extends(WorldSpaceCanvas2D, _super);
  44951. /**
  44952. * Create a new 2D WorldSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a world transformation information to place it in the world space.
  44953. * This kind of canvas can't have its Primitives directly drawn in the Viewport, they need to be cached in a bitmap at some point, as a consequence the DONT_CACHE strategy is unavailable. For now only CACHESTRATEGY_CANVAS is supported, but the remaining strategies will be soon.
  44954. * @param scene the Scene that owns the Canvas
  44955. * @param size the dimension of the Canvas in World Space
  44956. * @param settings a combination of settings, possible ones are
  44957. * - children: an array of direct children primitives
  44958. * - id: a text identifier, for information purpose only, default is null.
  44959. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  44960. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  44961. * - renderScaleFactor A scale factor applied to create the rendering texture that will be mapped in the Scene Rectangle. If you set 2 for instance the texture will be twice large in width and height. A greater value will allow to achieve a better rendering quality. Default value is 1.
  44962. * BE AWARE that the Canvas true dimension will be size*renderScaleFactor, then all coordinates and size will have to be express regarding this size.
  44963. * TIPS: if you want a renderScaleFactor independent reference of frame, create a child Group2D in the Canvas with position 0,0 and size set to null, then set its scale property to the same amount than the renderScaleFactor, put all your primitive inside using coordinates regarding the size property you pick for the Canvas and you'll be fine.
  44964. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  44965. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  44966. * - enableInteraction: if true the pointer events will be listened and rerouted to the appropriate primitives of the Canvas2D through the Prim2DBase.onPointerEventObservable observable property. Default is false (the opposite of ScreenSpace).
  44967. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  44968. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  44969. * - backgroundFill: the brush to use to create a background fill for the canvas. can be a string value (see Canvas2D.GetBrushFromString) or a IBrush2D instance.
  44970. * - backgroundBorder: the brush to use to create a background border for the canvas. can be a string value (see Canvas2D.GetBrushFromString) or a IBrush2D instance.
  44971. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  44972. * - customWorldSpaceNode: if specified the Canvas will be rendered in this given Node. But it's the responsibility of the caller to set the "worldSpaceToNodeLocal" property to compute the hit of the mouse ray into the node (in world coordinate system) as well as rendering the cached bitmap in the node itself. The properties cachedRect and cachedTexture of Group2D will give you what you need to do that.
  44973. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44974. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44975. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44976. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44977. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44978. */
  44979. function WorldSpaceCanvas2D(scene, size, settings) {
  44980. BABYLON.Prim2DBase._isCanvasInit = true;
  44981. var s = settings;
  44982. s.isScreenSpace = false;
  44983. s.size = size.clone();
  44984. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  44985. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  44986. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  44987. }
  44988. _super.call(this, scene, settings);
  44989. BABYLON.Prim2DBase._isCanvasInit = false;
  44990. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  44991. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  44992. //}
  44993. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  44994. var id = settings ? settings.id || null : null;
  44995. if (createWorldSpaceNode) {
  44996. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  44997. var vertexData = BABYLON.VertexData.CreatePlane({
  44998. width: size.width,
  44999. height: size.height,
  45000. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  45001. });
  45002. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  45003. this.applyCachedTexture(vertexData, mtl);
  45004. vertexData.applyToMesh(plane, false);
  45005. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  45006. mtl.disableLighting = true;
  45007. mtl.useAlphaFromDiffuseTexture = true;
  45008. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  45009. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  45010. plane.material = mtl;
  45011. this._worldSpaceNode = plane;
  45012. }
  45013. else {
  45014. this._worldSpaceNode = settings.customWorldSpaceNode;
  45015. this.applyCachedTexture(null, null);
  45016. }
  45017. }
  45018. WorldSpaceCanvas2D = __decorate([
  45019. BABYLON.className("WorldSpaceCanvas2D")
  45020. ], WorldSpaceCanvas2D);
  45021. return WorldSpaceCanvas2D;
  45022. })(Canvas2D);
  45023. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  45024. var ScreenSpaceCanvas2D = (function (_super) {
  45025. __extends(ScreenSpaceCanvas2D, _super);
  45026. /**
  45027. * Create a new 2D ScreenSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a position relative to the bottom/left corner of the screen.
  45028. * ScreenSpace Canvas will be drawn in the Viewport as a 2D Layer lying to the top of the 3D Scene. Typically used for traditional UI.
  45029. * All caching strategies will be available.
  45030. * PLEASE NOTE: the origin of a Screen Space Canvas is set to [0;0] (bottom/left) which is different than the default origin of a Primitive which is centered [0.5;0.5]
  45031. * @param scene the Scene that owns the Canvas
  45032. * @param settings a combination of settings, possible ones are
  45033. * - children: an array of direct children primitives
  45034. * - id: a text identifier, for information purpose only
  45035. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  45036. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  45037. * - position: the position of the canvas, relative from the bottom/left of the scene's viewport. Alternatively you can set the x and y properties directly. Default value is [0, 0]
  45038. * - width: the width of the Canvas. you can alternatively use the size setting.
  45039. * - height: the height of the Canvas. you can alternatively use the size setting.
  45040. * - size: the Size of the canvas. Alternatively the width and height properties can be set. If null two behaviors depend on the cachingStrategy: if it's CACHESTRATEGY_CACHECANVAS then it will always auto-fit the rendering device, in all the other modes it will fit the content of the Canvas
  45041. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  45042. * - enableInteraction: if true the pointer events will be listened and rerouted to the appropriate primitives of the Canvas2D through the Prim2DBase.onPointerEventObservable observable property. Default is true.
  45043. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  45044. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  45045. * - backgroundFill: the brush to use to create a background fill for the canvas. can be a string value (see BABYLON.Canvas2D.GetBrushFromString) or a IBrush2D instance.
  45046. * - backgroundBorder: the brush to use to create a background border for the canvas. can be a string value (see BABYLON.Canvas2D.GetBrushFromString) or a IBrush2D instance.
  45047. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  45048. * - customWorldSpaceNode: if specified the Canvas will be rendered in this given Node. But it's the responsibility of the caller to set the "worldSpaceToNodeLocal" property to compute the hit of the mouse ray into the node (in world coordinate system) as well as rendering the cached bitmap in the node itself. The properties cachedRect and cachedTexture of Group2D will give you what you need to do that.
  45049. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  45050. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  45051. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  45052. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  45053. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  45054. */
  45055. function ScreenSpaceCanvas2D(scene, settings) {
  45056. BABYLON.Prim2DBase._isCanvasInit = true;
  45057. _super.call(this, scene, settings);
  45058. }
  45059. ScreenSpaceCanvas2D = __decorate([
  45060. BABYLON.className("ScreenSpaceCanvas2D")
  45061. ], ScreenSpaceCanvas2D);
  45062. return ScreenSpaceCanvas2D;
  45063. })(Canvas2D);
  45064. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  45065. })(BABYLON || (BABYLON = {}));
  45066. var BABYLON;
  45067. (function (BABYLON) {
  45068. /**
  45069. * This is the class that is used to display a World Space Canvas into a 3D scene
  45070. */
  45071. var WorldSpaceCanvas2DNode = (function (_super) {
  45072. __extends(WorldSpaceCanvas2DNode, _super);
  45073. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  45074. _super.call(this, name, scene);
  45075. this._canvas = canvas;
  45076. }
  45077. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  45078. _super.prototype.dispose.call(this);
  45079. if (this._canvas) {
  45080. this._canvas.dispose();
  45081. this._canvas = null;
  45082. }
  45083. };
  45084. return WorldSpaceCanvas2DNode;
  45085. })(BABYLON.Mesh);
  45086. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  45087. })(BABYLON || (BABYLON = {}));
  45088. var BABYLON;
  45089. (function (BABYLON) {
  45090. var LayoutEngineBase = (function () {
  45091. function LayoutEngineBase() {
  45092. this.layoutDirtyOnPropertyChangedMask = 0;
  45093. }
  45094. LayoutEngineBase.prototype.updateLayout = function (prim) {
  45095. };
  45096. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  45097. get: function () {
  45098. return false;
  45099. },
  45100. enumerable: true,
  45101. configurable: true
  45102. });
  45103. LayoutEngineBase.prototype.isLocked = function () {
  45104. return this._isLocked;
  45105. };
  45106. LayoutEngineBase.prototype.lock = function () {
  45107. if (this._isLocked) {
  45108. return false;
  45109. }
  45110. this._isLocked = true;
  45111. return true;
  45112. };
  45113. LayoutEngineBase = __decorate([
  45114. BABYLON.className("LayoutEngineBase")
  45115. ], LayoutEngineBase);
  45116. return LayoutEngineBase;
  45117. })();
  45118. BABYLON.LayoutEngineBase = LayoutEngineBase;
  45119. var CanvasLayoutEngine = (function (_super) {
  45120. __extends(CanvasLayoutEngine, _super);
  45121. function CanvasLayoutEngine() {
  45122. _super.apply(this, arguments);
  45123. }
  45124. // A very simple (no) layout computing...
  45125. // The Canvas and its direct children gets the Canvas' size as Layout Area
  45126. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  45127. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  45128. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  45129. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  45130. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  45131. var child = _a[_i];
  45132. this._doUpdate(child);
  45133. }
  45134. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  45135. }
  45136. };
  45137. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  45138. // Canvas ?
  45139. if (prim instanceof BABYLON.Canvas2D) {
  45140. prim.layoutArea = prim.actualSize;
  45141. }
  45142. else if (prim.parent instanceof BABYLON.Canvas2D) {
  45143. prim.layoutArea = prim.owner.actualSize;
  45144. }
  45145. else {
  45146. prim.layoutArea = prim.parent.contentArea;
  45147. }
  45148. };
  45149. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  45150. get: function () {
  45151. return true;
  45152. },
  45153. enumerable: true,
  45154. configurable: true
  45155. });
  45156. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
  45157. CanvasLayoutEngine = __decorate([
  45158. BABYLON.className("CanvasLayoutEngine")
  45159. ], CanvasLayoutEngine);
  45160. return CanvasLayoutEngine;
  45161. })(LayoutEngineBase);
  45162. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  45163. var StackPanelLayoutEngine = (function (_super) {
  45164. __extends(StackPanelLayoutEngine, _super);
  45165. function StackPanelLayoutEngine() {
  45166. _super.call(this);
  45167. this._isHorizontal = true;
  45168. this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  45169. }
  45170. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  45171. get: function () {
  45172. if (!StackPanelLayoutEngine._horizontal) {
  45173. StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
  45174. StackPanelLayoutEngine._horizontal.isHorizontal = true;
  45175. StackPanelLayoutEngine._horizontal.lock();
  45176. }
  45177. return StackPanelLayoutEngine._horizontal;
  45178. },
  45179. enumerable: true,
  45180. configurable: true
  45181. });
  45182. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  45183. get: function () {
  45184. if (!StackPanelLayoutEngine._vertical) {
  45185. StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
  45186. StackPanelLayoutEngine._vertical.isHorizontal = false;
  45187. StackPanelLayoutEngine._vertical.lock();
  45188. }
  45189. return StackPanelLayoutEngine._vertical;
  45190. },
  45191. enumerable: true,
  45192. configurable: true
  45193. });
  45194. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  45195. get: function () {
  45196. return this._isHorizontal;
  45197. },
  45198. set: function (val) {
  45199. if (this.isLocked()) {
  45200. return;
  45201. }
  45202. this._isHorizontal = val;
  45203. },
  45204. enumerable: true,
  45205. configurable: true
  45206. });
  45207. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  45208. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  45209. var x = 0;
  45210. var y = 0;
  45211. var h = this.isHorizontal;
  45212. var max = 0;
  45213. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  45214. var child = _a[_i];
  45215. var layoutArea = child.layoutArea;
  45216. child.margin.computeArea(child.actualSize, layoutArea);
  45217. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  45218. }
  45219. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  45220. var child = _c[_b];
  45221. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  45222. var layoutArea = child.layoutArea;
  45223. if (h) {
  45224. x += layoutArea.width;
  45225. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  45226. }
  45227. else {
  45228. y += layoutArea.height;
  45229. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  45230. }
  45231. }
  45232. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  45233. }
  45234. };
  45235. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  45236. get: function () {
  45237. return false;
  45238. },
  45239. enumerable: true,
  45240. configurable: true
  45241. });
  45242. StackPanelLayoutEngine._horizontal = null;
  45243. StackPanelLayoutEngine._vertical = null;
  45244. StackPanelLayoutEngine = __decorate([
  45245. BABYLON.className("StackPanelLayoutEngine")
  45246. ], StackPanelLayoutEngine);
  45247. return StackPanelLayoutEngine;
  45248. })(LayoutEngineBase);
  45249. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  45250. })(BABYLON || (BABYLON = {}));
  45251. var BABYLON;
  45252. (function (BABYLON) {
  45253. var ShaderMaterial = (function (_super) {
  45254. __extends(ShaderMaterial, _super);
  45255. function ShaderMaterial(name, scene, shaderPath, options) {
  45256. _super.call(this, name, scene);
  45257. this._textures = {};
  45258. this._floats = {};
  45259. this._floatsArrays = {};
  45260. this._colors3 = {};
  45261. this._colors4 = {};
  45262. this._vectors2 = {};
  45263. this._vectors3 = {};
  45264. this._vectors4 = {};
  45265. this._matrices = {};
  45266. this._matrices3x3 = {};
  45267. this._matrices2x2 = {};
  45268. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  45269. this._shaderPath = shaderPath;
  45270. options.needAlphaBlending = options.needAlphaBlending || false;
  45271. options.needAlphaTesting = options.needAlphaTesting || false;
  45272. options.attributes = options.attributes || ["position", "normal", "uv"];
  45273. options.uniforms = options.uniforms || ["worldViewProjection"];
  45274. options.samplers = options.samplers || [];
  45275. options.defines = options.defines || [];
  45276. this._options = options;
  45277. }
  45278. ShaderMaterial.prototype.needAlphaBlending = function () {
  45279. return this._options.needAlphaBlending;
  45280. };
  45281. ShaderMaterial.prototype.needAlphaTesting = function () {
  45282. return this._options.needAlphaTesting;
  45283. };
  45284. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  45285. if (this._options.uniforms.indexOf(uniformName) === -1) {
  45286. this._options.uniforms.push(uniformName);
  45287. }
  45288. };
  45289. ShaderMaterial.prototype.setTexture = function (name, texture) {
  45290. if (this._options.samplers.indexOf(name) === -1) {
  45291. this._options.samplers.push(name);
  45292. }
  45293. this._textures[name] = texture;
  45294. return this;
  45295. };
  45296. ShaderMaterial.prototype.setFloat = function (name, value) {
  45297. this._checkUniform(name);
  45298. this._floats[name] = value;
  45299. return this;
  45300. };
  45301. ShaderMaterial.prototype.setFloats = function (name, value) {
  45302. this._checkUniform(name);
  45303. this._floatsArrays[name] = value;
  45304. return this;
  45305. };
  45306. ShaderMaterial.prototype.setColor3 = function (name, value) {
  45307. this._checkUniform(name);
  45308. this._colors3[name] = value;
  45309. return this;
  45310. };
  45311. ShaderMaterial.prototype.setColor4 = function (name, value) {
  45312. this._checkUniform(name);
  45313. this._colors4[name] = value;
  45314. return this;
  45315. };
  45316. ShaderMaterial.prototype.setVector2 = function (name, value) {
  45317. this._checkUniform(name);
  45318. this._vectors2[name] = value;
  45319. return this;
  45320. };
  45321. ShaderMaterial.prototype.setVector3 = function (name, value) {
  45322. this._checkUniform(name);
  45323. this._vectors3[name] = value;
  45324. return this;
  45325. };
  45326. ShaderMaterial.prototype.setVector4 = function (name, value) {
  45327. this._checkUniform(name);
  45328. this._vectors4[name] = value;
  45329. return this;
  45330. };
  45331. ShaderMaterial.prototype.setMatrix = function (name, value) {
  45332. this._checkUniform(name);
  45333. this._matrices[name] = value;
  45334. return this;
  45335. };
  45336. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  45337. this._checkUniform(name);
  45338. this._matrices3x3[name] = value;
  45339. return this;
  45340. };
  45341. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  45342. this._checkUniform(name);
  45343. this._matrices2x2[name] = value;
  45344. return this;
  45345. };
  45346. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  45347. var scene = this.getScene();
  45348. var engine = scene.getEngine();
  45349. if (!this.checkReadyOnEveryCall) {
  45350. if (this._renderId === scene.getRenderId()) {
  45351. return true;
  45352. }
  45353. }
  45354. // Instances
  45355. var defines = [];
  45356. var fallbacks = new BABYLON.EffectFallbacks();
  45357. if (useInstances) {
  45358. defines.push("#define INSTANCES");
  45359. }
  45360. for (var index = 0; index < this._options.defines.length; index++) {
  45361. defines.push(this._options.defines[index]);
  45362. }
  45363. // Bones
  45364. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  45365. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45366. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45367. fallbacks.addCPUSkinningFallback(0, mesh);
  45368. }
  45369. // Alpha test
  45370. if (engine.getAlphaTesting()) {
  45371. defines.push("#define ALPHATEST");
  45372. }
  45373. var previousEffect = this._effect;
  45374. var join = defines.join("\n");
  45375. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  45376. if (!this._effect.isReady()) {
  45377. return false;
  45378. }
  45379. if (previousEffect !== this._effect) {
  45380. scene.resetCachedMaterial();
  45381. }
  45382. this._renderId = scene.getRenderId();
  45383. return true;
  45384. };
  45385. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  45386. var scene = this.getScene();
  45387. if (this._options.uniforms.indexOf("world") !== -1) {
  45388. this._effect.setMatrix("world", world);
  45389. }
  45390. if (this._options.uniforms.indexOf("worldView") !== -1) {
  45391. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  45392. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  45393. }
  45394. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  45395. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  45396. }
  45397. };
  45398. ShaderMaterial.prototype.bind = function (world, mesh) {
  45399. // Std values
  45400. this.bindOnlyWorldMatrix(world);
  45401. if (this.getScene().getCachedMaterial() !== this) {
  45402. if (this._options.uniforms.indexOf("view") !== -1) {
  45403. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  45404. }
  45405. if (this._options.uniforms.indexOf("projection") !== -1) {
  45406. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  45407. }
  45408. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  45409. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  45410. }
  45411. // Bones
  45412. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  45413. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  45414. }
  45415. // Texture
  45416. for (var name in this._textures) {
  45417. this._effect.setTexture(name, this._textures[name]);
  45418. }
  45419. // Float
  45420. for (name in this._floats) {
  45421. this._effect.setFloat(name, this._floats[name]);
  45422. }
  45423. // Float s
  45424. for (name in this._floatsArrays) {
  45425. this._effect.setArray(name, this._floatsArrays[name]);
  45426. }
  45427. // Color3
  45428. for (name in this._colors3) {
  45429. this._effect.setColor3(name, this._colors3[name]);
  45430. }
  45431. // Color4
  45432. for (name in this._colors4) {
  45433. var color = this._colors4[name];
  45434. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  45435. }
  45436. // Vector2
  45437. for (name in this._vectors2) {
  45438. this._effect.setVector2(name, this._vectors2[name]);
  45439. }
  45440. // Vector3
  45441. for (name in this._vectors3) {
  45442. this._effect.setVector3(name, this._vectors3[name]);
  45443. }
  45444. // Vector4
  45445. for (name in this._vectors4) {
  45446. this._effect.setVector4(name, this._vectors4[name]);
  45447. }
  45448. // Matrix
  45449. for (name in this._matrices) {
  45450. this._effect.setMatrix(name, this._matrices[name]);
  45451. }
  45452. // Matrix 3x3
  45453. for (name in this._matrices3x3) {
  45454. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  45455. }
  45456. // Matrix 2x2
  45457. for (name in this._matrices2x2) {
  45458. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  45459. }
  45460. }
  45461. _super.prototype.bind.call(this, world, mesh);
  45462. };
  45463. ShaderMaterial.prototype.clone = function (name) {
  45464. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  45465. return newShaderMaterial;
  45466. };
  45467. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45468. if (forceDisposeTextures) {
  45469. for (var name in this._textures) {
  45470. this._textures[name].dispose();
  45471. }
  45472. }
  45473. this._textures = {};
  45474. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45475. };
  45476. ShaderMaterial.prototype.serialize = function () {
  45477. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45478. serializationObject.customType = "BABYLON.ShaderMaterial";
  45479. serializationObject.options = this._options;
  45480. serializationObject.shaderPath = this._shaderPath;
  45481. // Texture
  45482. serializationObject.textures = {};
  45483. for (var name in this._textures) {
  45484. serializationObject.textures[name] = this._textures[name].serialize();
  45485. }
  45486. // Float
  45487. serializationObject.floats = {};
  45488. for (name in this._floats) {
  45489. serializationObject.floats[name] = this._floats[name];
  45490. }
  45491. // Float s
  45492. serializationObject.floatArrays = {};
  45493. for (name in this._floatsArrays) {
  45494. serializationObject.floatArrays[name] = this._floatsArrays[name];
  45495. }
  45496. // Color3
  45497. serializationObject.colors3 = {};
  45498. for (name in this._colors3) {
  45499. serializationObject.colors3[name] = this._colors3[name].asArray();
  45500. }
  45501. // Color4
  45502. serializationObject.colors4 = {};
  45503. for (name in this._colors4) {
  45504. serializationObject.colors4[name] = this._colors4[name].asArray();
  45505. }
  45506. // Vector2
  45507. serializationObject.vectors2 = {};
  45508. for (name in this._vectors2) {
  45509. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  45510. }
  45511. // Vector3
  45512. serializationObject.vectors3 = {};
  45513. for (name in this._vectors3) {
  45514. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  45515. }
  45516. // Vector4
  45517. serializationObject.vectors4 = {};
  45518. for (name in this._vectors4) {
  45519. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  45520. }
  45521. // Matrix
  45522. serializationObject.matrices = {};
  45523. for (name in this._matrices) {
  45524. serializationObject.matrices[name] = this._matrices[name].asArray();
  45525. }
  45526. // Matrix 3x3
  45527. serializationObject.matrices3x3 = {};
  45528. for (name in this._matrices3x3) {
  45529. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  45530. }
  45531. // Matrix 2x2
  45532. serializationObject.matrices2x2 = {};
  45533. for (name in this._matrices2x2) {
  45534. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  45535. }
  45536. return serializationObject;
  45537. };
  45538. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  45539. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  45540. // Texture
  45541. for (var name in source.textures) {
  45542. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  45543. }
  45544. // Float
  45545. for (name in source.floats) {
  45546. material.setFloat(name, source.floats[name]);
  45547. }
  45548. // Float s
  45549. for (name in source.floatsArrays) {
  45550. material.setFloats(name, source.floatsArrays[name]);
  45551. }
  45552. // Color3
  45553. for (name in source.colors3) {
  45554. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  45555. }
  45556. // Color4
  45557. for (name in source.colors4) {
  45558. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  45559. }
  45560. // Vector2
  45561. for (name in source.vectors2) {
  45562. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  45563. }
  45564. // Vector3
  45565. for (name in source.vectors3) {
  45566. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  45567. }
  45568. // Vector4
  45569. for (name in source.vectors4) {
  45570. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  45571. }
  45572. // Matrix
  45573. for (name in source.matrices) {
  45574. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  45575. }
  45576. // Matrix 3x3
  45577. for (name in source.matrices3x3) {
  45578. material.setMatrix3x3(name, source.matrices3x3[name]);
  45579. }
  45580. // Matrix 2x2
  45581. for (name in source.matrices2x2) {
  45582. material.setMatrix2x2(name, source.matrices2x2[name]);
  45583. }
  45584. return material;
  45585. };
  45586. return ShaderMaterial;
  45587. })(BABYLON.Material);
  45588. BABYLON.ShaderMaterial = ShaderMaterial;
  45589. })(BABYLON || (BABYLON = {}));
  45590. var BABYLON;
  45591. (function (BABYLON) {
  45592. var Internals;
  45593. (function (Internals) {
  45594. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  45595. // All values and structures referenced from:
  45596. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  45597. var DDS_MAGIC = 0x20534444;
  45598. var DDSD_CAPS = 0x1, DDSD_HEIGHT = 0x2, DDSD_WIDTH = 0x4, DDSD_PITCH = 0x8, DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000, DDSD_LINEARSIZE = 0x80000, DDSD_DEPTH = 0x800000;
  45599. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  45600. var DDSCAPS2_CUBEMAP = 0x200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, DDSCAPS2_VOLUME = 0x200000;
  45601. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  45602. function FourCCToInt32(value) {
  45603. return value.charCodeAt(0) +
  45604. (value.charCodeAt(1) << 8) +
  45605. (value.charCodeAt(2) << 16) +
  45606. (value.charCodeAt(3) << 24);
  45607. }
  45608. function Int32ToFourCC(value) {
  45609. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  45610. }
  45611. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  45612. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  45613. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  45614. var headerLengthInt = 31; // The header length in 32 bit ints
  45615. // Offsets into the header array
  45616. var off_magic = 0;
  45617. var off_size = 1;
  45618. var off_flags = 2;
  45619. var off_height = 3;
  45620. var off_width = 4;
  45621. var off_mipmapCount = 7;
  45622. var off_pfFlags = 20;
  45623. var off_pfFourCC = 21;
  45624. var off_RGBbpp = 22;
  45625. var off_RMask = 23;
  45626. var off_GMask = 24;
  45627. var off_BMask = 25;
  45628. var off_AMask = 26;
  45629. var off_caps1 = 27;
  45630. var off_caps2 = 28;
  45631. ;
  45632. var DDSTools = (function () {
  45633. function DDSTools() {
  45634. }
  45635. DDSTools.GetDDSInfo = function (arrayBuffer) {
  45636. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  45637. var mipmapCount = 1;
  45638. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  45639. mipmapCount = Math.max(1, header[off_mipmapCount]);
  45640. }
  45641. return {
  45642. width: header[off_width],
  45643. height: header[off_height],
  45644. mipmapCount: mipmapCount,
  45645. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  45646. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  45647. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  45648. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  45649. };
  45650. };
  45651. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45652. var byteArray = new Uint8Array(dataLength);
  45653. var srcData = new Uint8Array(arrayBuffer);
  45654. var index = 0;
  45655. for (var y = height - 1; y >= 0; y--) {
  45656. for (var x = 0; x < width; x++) {
  45657. var srcPos = dataOffset + (x + y * width) * 4;
  45658. byteArray[index + 2] = srcData[srcPos];
  45659. byteArray[index + 1] = srcData[srcPos + 1];
  45660. byteArray[index] = srcData[srcPos + 2];
  45661. byteArray[index + 3] = srcData[srcPos + 3];
  45662. index += 4;
  45663. }
  45664. }
  45665. return byteArray;
  45666. };
  45667. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45668. var byteArray = new Uint8Array(dataLength);
  45669. var srcData = new Uint8Array(arrayBuffer);
  45670. var index = 0;
  45671. for (var y = height - 1; y >= 0; y--) {
  45672. for (var x = 0; x < width; x++) {
  45673. var srcPos = dataOffset + (x + y * width) * 3;
  45674. byteArray[index + 2] = srcData[srcPos];
  45675. byteArray[index + 1] = srcData[srcPos + 1];
  45676. byteArray[index] = srcData[srcPos + 2];
  45677. index += 3;
  45678. }
  45679. }
  45680. return byteArray;
  45681. };
  45682. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45683. var byteArray = new Uint8Array(dataLength);
  45684. var srcData = new Uint8Array(arrayBuffer);
  45685. var index = 0;
  45686. for (var y = height - 1; y >= 0; y--) {
  45687. for (var x = 0; x < width; x++) {
  45688. var srcPos = dataOffset + (x + y * width);
  45689. byteArray[index] = srcData[srcPos];
  45690. index++;
  45691. }
  45692. }
  45693. return byteArray;
  45694. };
  45695. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  45696. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  45697. if (header[off_magic] != DDS_MAGIC) {
  45698. BABYLON.Tools.Error("Invalid magic number in DDS header");
  45699. return;
  45700. }
  45701. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  45702. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  45703. return;
  45704. }
  45705. if (info.isFourCC) {
  45706. fourCC = header[off_pfFourCC];
  45707. switch (fourCC) {
  45708. case FOURCC_DXT1:
  45709. blockBytes = 8;
  45710. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  45711. break;
  45712. case FOURCC_DXT3:
  45713. blockBytes = 16;
  45714. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  45715. break;
  45716. case FOURCC_DXT5:
  45717. blockBytes = 16;
  45718. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  45719. break;
  45720. default:
  45721. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  45722. return;
  45723. }
  45724. }
  45725. mipmapCount = 1;
  45726. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  45727. mipmapCount = Math.max(1, header[off_mipmapCount]);
  45728. }
  45729. var bpp = header[off_RGBbpp];
  45730. for (var face = 0; face < faces; face++) {
  45731. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  45732. width = header[off_width];
  45733. height = header[off_height];
  45734. dataOffset = header[off_size] + 4;
  45735. for (i = 0; i < mipmapCount; ++i) {
  45736. if (info.isRGB) {
  45737. if (bpp === 24) {
  45738. dataLength = width * height * 3;
  45739. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45740. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  45741. }
  45742. else {
  45743. dataLength = width * height * 4;
  45744. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45745. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  45746. }
  45747. }
  45748. else if (info.isLuminance) {
  45749. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  45750. var unpaddedRowSize = width;
  45751. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  45752. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  45753. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45754. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  45755. }
  45756. else {
  45757. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  45758. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  45759. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  45760. }
  45761. dataOffset += dataLength;
  45762. width *= 0.5;
  45763. height *= 0.5;
  45764. width = Math.max(1.0, width);
  45765. height = Math.max(1.0, height);
  45766. }
  45767. }
  45768. };
  45769. return DDSTools;
  45770. })();
  45771. Internals.DDSTools = DDSTools;
  45772. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45773. })(BABYLON || (BABYLON = {}));
  45774. var BABYLON;
  45775. (function (BABYLON) {
  45776. var CannonJSPlugin = (function () {
  45777. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  45778. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  45779. if (iterations === void 0) { iterations = 10; }
  45780. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  45781. this.name = "CannonJSPlugin";
  45782. this._physicsMaterials = [];
  45783. this._fixedTimeStep = 1 / 60;
  45784. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  45785. this._currentCollisionGroup = 2;
  45786. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  45787. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  45788. this._tmpPosition = BABYLON.Vector3.Zero();
  45789. this._tmpQuaternion = new BABYLON.Quaternion();
  45790. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  45791. this._tmpDeltaRotation = new BABYLON.Quaternion();
  45792. this._tmpUnityRotation = new BABYLON.Quaternion();
  45793. if (!this.isSupported()) {
  45794. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  45795. return;
  45796. }
  45797. this.world = new CANNON.World();
  45798. this.world.broadphase = new CANNON.NaiveBroadphase();
  45799. this.world.solver.iterations = iterations;
  45800. }
  45801. CannonJSPlugin.prototype.setGravity = function (gravity) {
  45802. this.world.gravity.copy(gravity);
  45803. };
  45804. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  45805. this._fixedTimeStep = timeStep;
  45806. };
  45807. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  45808. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  45809. };
  45810. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  45811. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  45812. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  45813. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  45814. };
  45815. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  45816. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  45817. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  45818. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  45819. };
  45820. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  45821. //parent-child relationship. Does this impostor has a parent impostor?
  45822. if (impostor.parent) {
  45823. if (impostor.physicsBody) {
  45824. this.removePhysicsBody(impostor);
  45825. //TODO is that needed?
  45826. impostor.forceUpdate();
  45827. }
  45828. return;
  45829. }
  45830. //should a new body be created for this impostor?
  45831. if (impostor.isBodyInitRequired()) {
  45832. var shape = this._createShape(impostor);
  45833. //unregister events, if body is being changed
  45834. var oldBody = impostor.physicsBody;
  45835. if (oldBody) {
  45836. this.removePhysicsBody(impostor);
  45837. }
  45838. //create the body and material
  45839. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  45840. var bodyCreationObject = {
  45841. mass: impostor.getParam("mass"),
  45842. material: material
  45843. };
  45844. // A simple extend, in case native options were used.
  45845. var nativeOptions = impostor.getParam("nativeOptions");
  45846. for (var key in nativeOptions) {
  45847. if (nativeOptions.hasOwnProperty(key)) {
  45848. bodyCreationObject[key] = nativeOptions[key];
  45849. }
  45850. }
  45851. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  45852. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  45853. this.world.addEventListener("preStep", impostor.beforeStep);
  45854. this.world.addEventListener("postStep", impostor.afterStep);
  45855. impostor.physicsBody.addShape(shape);
  45856. this.world.add(impostor.physicsBody);
  45857. //try to keep the body moving in the right direction by taking old properties.
  45858. //Should be tested!
  45859. if (oldBody) {
  45860. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  45861. impostor.physicsBody[param].copy(oldBody[param]);
  45862. });
  45863. }
  45864. this._processChildMeshes(impostor);
  45865. }
  45866. //now update the body's transformation
  45867. this._updatePhysicsBodyTransformation(impostor);
  45868. };
  45869. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  45870. var _this = this;
  45871. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  45872. if (meshChildren.length) {
  45873. var processMesh = function (localPosition, mesh) {
  45874. var childImpostor = mesh.getPhysicsImpostor();
  45875. if (childImpostor) {
  45876. var parent = childImpostor.parent;
  45877. if (parent !== mainImpostor) {
  45878. var localPosition = mesh.position;
  45879. if (childImpostor.physicsBody) {
  45880. _this.removePhysicsBody(childImpostor);
  45881. childImpostor.physicsBody = null;
  45882. }
  45883. childImpostor.parent = mainImpostor;
  45884. childImpostor.resetUpdateFlags();
  45885. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  45886. //Add the mass of the children.
  45887. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  45888. }
  45889. }
  45890. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  45891. };
  45892. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  45893. }
  45894. };
  45895. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  45896. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  45897. this.world.removeEventListener("preStep", impostor.beforeStep);
  45898. this.world.removeEventListener("postStep", impostor.afterStep);
  45899. this.world.remove(impostor.physicsBody);
  45900. };
  45901. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  45902. var mainBody = impostorJoint.mainImpostor.physicsBody;
  45903. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  45904. if (!mainBody || !connectedBody) {
  45905. return;
  45906. }
  45907. var constraint;
  45908. var jointData = impostorJoint.joint.jointData;
  45909. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  45910. var constraintData = {
  45911. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  45912. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  45913. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  45914. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  45915. maxForce: jointData.nativeParams.maxForce,
  45916. collideConnected: !!jointData.collision
  45917. };
  45918. //Not needed, Cannon has a collideConnected flag
  45919. /*if (!jointData.collision) {
  45920. //add 1st body to a collision group of its own, if it is not in 1
  45921. if (mainBody.collisionFilterGroup === 1) {
  45922. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  45923. this._currentCollisionGroup <<= 1;
  45924. }
  45925. if (connectedBody.collisionFilterGroup === 1) {
  45926. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  45927. this._currentCollisionGroup <<= 1;
  45928. }
  45929. //add their mask to the collisionFilterMask of each other:
  45930. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  45931. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  45932. }*/
  45933. switch (impostorJoint.joint.type) {
  45934. case BABYLON.PhysicsJoint.HingeJoint:
  45935. case BABYLON.PhysicsJoint.Hinge2Joint:
  45936. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  45937. break;
  45938. case BABYLON.PhysicsJoint.DistanceJoint:
  45939. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  45940. break;
  45941. case BABYLON.PhysicsJoint.SpringJoint:
  45942. var springData = jointData;
  45943. constraint = new CANNON.Spring(mainBody, connectedBody, {
  45944. restLength: springData.length,
  45945. stiffness: springData.stiffness,
  45946. damping: springData.damping,
  45947. localAnchorA: constraintData.pivotA,
  45948. localAnchorB: constraintData.pivotB
  45949. });
  45950. break;
  45951. case BABYLON.PhysicsJoint.LockJoint:
  45952. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  45953. break;
  45954. case BABYLON.PhysicsJoint.PointToPointJoint:
  45955. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  45956. default:
  45957. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  45958. break;
  45959. }
  45960. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  45961. constraint.collideConnected = !!jointData.collision;
  45962. impostorJoint.joint.physicsJoint = constraint;
  45963. //don't add spring as constraint, as it is not one.
  45964. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  45965. this.world.addConstraint(constraint);
  45966. }
  45967. else {
  45968. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  45969. constraint.applyForce();
  45970. });
  45971. }
  45972. };
  45973. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  45974. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  45975. };
  45976. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  45977. var index;
  45978. var mat;
  45979. for (index = 0; index < this._physicsMaterials.length; index++) {
  45980. mat = this._physicsMaterials[index];
  45981. if (mat.friction === friction && mat.restitution === restitution) {
  45982. return mat;
  45983. }
  45984. }
  45985. var currentMat = new CANNON.Material(name);
  45986. currentMat.friction = friction;
  45987. currentMat.restitution = restitution;
  45988. this._physicsMaterials.push(currentMat);
  45989. return currentMat;
  45990. };
  45991. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  45992. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  45993. };
  45994. CannonJSPlugin.prototype._createShape = function (impostor) {
  45995. var object = impostor.object;
  45996. var returnValue;
  45997. var extendSize = impostor.getObjectExtendSize();
  45998. switch (impostor.type) {
  45999. case BABYLON.PhysicsEngine.SphereImpostor:
  46000. var radiusX = extendSize.x;
  46001. var radiusY = extendSize.y;
  46002. var radiusZ = extendSize.z;
  46003. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  46004. break;
  46005. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  46006. case BABYLON.PhysicsImpostor.CylinderImpostor:
  46007. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  46008. break;
  46009. case BABYLON.PhysicsImpostor.BoxImpostor:
  46010. var box = extendSize.scale(0.5);
  46011. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  46012. break;
  46013. case BABYLON.PhysicsImpostor.PlaneImpostor:
  46014. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  46015. returnValue = new CANNON.Plane();
  46016. break;
  46017. case BABYLON.PhysicsImpostor.MeshImpostor:
  46018. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  46019. var rawFaces = object.getIndices ? object.getIndices() : [];
  46020. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  46021. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  46022. break;
  46023. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  46024. returnValue = this._createHeightmap(object);
  46025. break;
  46026. case BABYLON.PhysicsImpostor.ParticleImpostor:
  46027. returnValue = new CANNON.Particle();
  46028. break;
  46029. }
  46030. return returnValue;
  46031. };
  46032. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  46033. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46034. var matrix = [];
  46035. //For now pointDepth will not be used and will be automatically calculated.
  46036. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  46037. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  46038. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  46039. var elementSize = dim * 2 / arraySize;
  46040. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  46041. for (var i = 0; i < pos.length; i = i + 3) {
  46042. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  46043. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  46044. var y = pos[i + 1] + minY;
  46045. if (!matrix[x]) {
  46046. matrix[x] = [];
  46047. }
  46048. if (!matrix[x][z]) {
  46049. matrix[x][z] = y;
  46050. }
  46051. matrix[x][z] = Math.max(y, matrix[x][z]);
  46052. }
  46053. for (var x = 0; x <= arraySize; ++x) {
  46054. if (!matrix[x]) {
  46055. var loc = 1;
  46056. while (!matrix[(x + loc) % arraySize]) {
  46057. loc++;
  46058. }
  46059. matrix[x] = matrix[(x + loc) % arraySize].slice();
  46060. }
  46061. for (var z = 0; z <= arraySize; ++z) {
  46062. if (!matrix[x][z]) {
  46063. var loc = 1;
  46064. var newValue;
  46065. while (newValue === undefined) {
  46066. newValue = matrix[x][(z + loc++) % arraySize];
  46067. }
  46068. matrix[x][z] = newValue;
  46069. }
  46070. }
  46071. }
  46072. var shape = new CANNON.Heightfield(matrix, {
  46073. elementSize: elementSize
  46074. });
  46075. //For future reference, needed for body transformation
  46076. shape.minY = minY;
  46077. return shape;
  46078. };
  46079. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  46080. var object = impostor.object;
  46081. //make sure it is updated...
  46082. object.computeWorldMatrix && object.computeWorldMatrix(true);
  46083. // The delta between the mesh position and the mesh bounding box center
  46084. var center = impostor.getObjectCenter();
  46085. var extendSize = impostor.getObjectExtendSize();
  46086. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  46087. this._tmpPosition.copyFrom(center);
  46088. var quaternion = object.rotationQuaternion;
  46089. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  46090. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  46091. //-90 DEG in X, precalculated
  46092. quaternion = quaternion.multiply(this._minus90X);
  46093. //Invert! (Precalculated, 90 deg in X)
  46094. //No need to clone. this will never change.
  46095. impostor.setDeltaRotation(this._plus90X);
  46096. }
  46097. //If it is a heightfield, if should be centered.
  46098. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  46099. var mesh = object;
  46100. //calculate the correct body position:
  46101. var rotationQuaternion = mesh.rotationQuaternion;
  46102. mesh.rotationQuaternion = this._tmpUnityRotation;
  46103. mesh.computeWorldMatrix(true);
  46104. //get original center with no rotation
  46105. var c = center.clone();
  46106. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  46107. //rotation is back
  46108. mesh.rotationQuaternion = rotationQuaternion;
  46109. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  46110. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  46111. mesh.setPivotMatrix(p);
  46112. mesh.computeWorldMatrix(true);
  46113. //calculate the translation
  46114. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  46115. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  46116. //add it inverted to the delta
  46117. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  46118. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  46119. mesh.setPivotMatrix(oldPivot);
  46120. mesh.computeWorldMatrix(true);
  46121. }
  46122. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  46123. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  46124. this._tmpPosition.copyFrom(object.position);
  46125. }
  46126. impostor.setDeltaPosition(this._tmpDeltaPosition);
  46127. //Now update the impostor object
  46128. impostor.physicsBody.position.copy(this._tmpPosition);
  46129. impostor.physicsBody.quaternion.copy(quaternion);
  46130. };
  46131. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  46132. impostor.object.position.copyFrom(impostor.physicsBody.position);
  46133. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  46134. };
  46135. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  46136. impostor.physicsBody.position.copy(newPosition);
  46137. impostor.physicsBody.quaternion.copy(newRotation);
  46138. };
  46139. CannonJSPlugin.prototype.isSupported = function () {
  46140. return window.CANNON !== undefined;
  46141. };
  46142. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  46143. impostor.physicsBody.velocity.copy(velocity);
  46144. };
  46145. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  46146. impostor.physicsBody.angularVelocity.copy(velocity);
  46147. };
  46148. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  46149. var v = impostor.physicsBody.velocity;
  46150. if (!v)
  46151. return null;
  46152. return new BABYLON.Vector3(v.x, v.y, v.z);
  46153. };
  46154. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  46155. var v = impostor.physicsBody.angularVelocity;
  46156. if (!v)
  46157. return null;
  46158. return new BABYLON.Vector3(v.x, v.y, v.z);
  46159. };
  46160. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  46161. impostor.physicsBody.mass = mass;
  46162. impostor.physicsBody.updateMassProperties();
  46163. };
  46164. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  46165. impostor.physicsBody.sleep();
  46166. };
  46167. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  46168. impostor.physicsBody.wakeUp();
  46169. };
  46170. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  46171. joint.physicsJoint.distance = maxDistance;
  46172. };
  46173. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  46174. if (!motorIndex) {
  46175. joint.physicsJoint.enableMotor();
  46176. }
  46177. };
  46178. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  46179. if (!motorIndex) {
  46180. joint.physicsJoint.disableMotor();
  46181. }
  46182. };
  46183. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  46184. if (!motorIndex) {
  46185. joint.physicsJoint.enableMotor();
  46186. joint.physicsJoint.setMotorSpeed(speed);
  46187. if (maxForce) {
  46188. this.setLimit(joint, maxForce);
  46189. }
  46190. }
  46191. };
  46192. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  46193. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  46194. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  46195. };
  46196. CannonJSPlugin.prototype.dispose = function () {
  46197. //nothing to do, actually.
  46198. };
  46199. return CannonJSPlugin;
  46200. })();
  46201. BABYLON.CannonJSPlugin = CannonJSPlugin;
  46202. })(BABYLON || (BABYLON = {}));
  46203. var BABYLON;
  46204. (function (BABYLON) {
  46205. var OimoJSPlugin = (function () {
  46206. function OimoJSPlugin(iterations) {
  46207. this.name = "OimoJSPlugin";
  46208. this._tmpImpostorsArray = [];
  46209. this._tmpPositionVector = BABYLON.Vector3.Zero();
  46210. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  46211. this.world.clear();
  46212. //making sure no stats are calculated
  46213. this.world.isNoStat = true;
  46214. }
  46215. OimoJSPlugin.prototype.setGravity = function (gravity) {
  46216. this.world.gravity.copy(gravity);
  46217. };
  46218. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  46219. this.world.timeStep = timeStep;
  46220. };
  46221. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  46222. var _this = this;
  46223. impostors.forEach(function (impostor) {
  46224. impostor.beforeStep();
  46225. });
  46226. this.world.step();
  46227. impostors.forEach(function (impostor) {
  46228. impostor.afterStep();
  46229. //update the ordered impostors array
  46230. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  46231. });
  46232. //check for collisions
  46233. var contact = this.world.contacts;
  46234. while (contact !== null) {
  46235. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  46236. contact = contact.next;
  46237. continue;
  46238. }
  46239. //is this body colliding with any other? get the impostor
  46240. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  46241. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  46242. if (!mainImpostor || !collidingImpostor) {
  46243. contact = contact.next;
  46244. continue;
  46245. }
  46246. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  46247. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  46248. contact = contact.next;
  46249. }
  46250. };
  46251. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  46252. var mass = impostor.physicsBody.massInfo.mass;
  46253. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  46254. };
  46255. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  46256. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  46257. this.applyImpulse(impostor, force, contactPoint);
  46258. };
  46259. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  46260. var _this = this;
  46261. //parent-child relationship. Does this impostor has a parent impostor?
  46262. if (impostor.parent) {
  46263. if (impostor.physicsBody) {
  46264. this.removePhysicsBody(impostor);
  46265. //TODO is that needed?
  46266. impostor.forceUpdate();
  46267. }
  46268. return;
  46269. }
  46270. if (impostor.isBodyInitRequired()) {
  46271. var bodyConfig = {
  46272. name: impostor.uniqueId,
  46273. //Oimo must have mass, also for static objects.
  46274. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  46275. size: [],
  46276. type: [],
  46277. pos: [],
  46278. rot: [],
  46279. move: impostor.getParam("mass") !== 0,
  46280. //Supporting older versions of Oimo
  46281. world: this.world
  46282. };
  46283. var impostors = [impostor];
  46284. function addToArray(parent) {
  46285. if (!parent.getChildMeshes)
  46286. return;
  46287. parent.getChildMeshes().forEach(function (m) {
  46288. if (m.physicsImpostor) {
  46289. impostors.push(m.physicsImpostor);
  46290. m.physicsImpostor._init();
  46291. }
  46292. });
  46293. }
  46294. addToArray(impostor.object);
  46295. function checkWithEpsilon(value) {
  46296. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  46297. }
  46298. impostors.forEach(function (i) {
  46299. //get the correct bounding box
  46300. var oldQuaternion = i.object.rotationQuaternion;
  46301. var rot = new OIMO.Euler().setFromQuaternion({
  46302. x: impostor.object.rotationQuaternion.x,
  46303. y: impostor.object.rotationQuaternion.y,
  46304. z: impostor.object.rotationQuaternion.z,
  46305. s: impostor.object.rotationQuaternion.w
  46306. });
  46307. var extendSize = i.getObjectExtendSize();
  46308. if (i === impostor) {
  46309. var center = impostor.getObjectCenter();
  46310. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  46311. //Can also use Array.prototype.push.apply
  46312. bodyConfig.pos.push(center.x);
  46313. bodyConfig.pos.push(center.y);
  46314. bodyConfig.pos.push(center.z);
  46315. //tmp solution
  46316. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  46317. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  46318. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  46319. }
  46320. else {
  46321. bodyConfig.pos.push(i.object.position.x);
  46322. bodyConfig.pos.push(i.object.position.y);
  46323. bodyConfig.pos.push(i.object.position.z);
  46324. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  46325. bodyConfig.rot.push(0);
  46326. bodyConfig.rot.push(0);
  46327. bodyConfig.rot.push(0);
  46328. }
  46329. // register mesh
  46330. switch (i.type) {
  46331. case BABYLON.PhysicsImpostor.ParticleImpostor:
  46332. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  46333. case BABYLON.PhysicsImpostor.SphereImpostor:
  46334. var radiusX = extendSize.x;
  46335. var radiusY = extendSize.y;
  46336. var radiusZ = extendSize.z;
  46337. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  46338. bodyConfig.type.push('sphere');
  46339. //due to the way oimo works with compounds, add 3 times
  46340. bodyConfig.size.push(size);
  46341. bodyConfig.size.push(size);
  46342. bodyConfig.size.push(size);
  46343. break;
  46344. case BABYLON.PhysicsImpostor.CylinderImpostor:
  46345. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  46346. var sizeY = checkWithEpsilon(extendSize.y);
  46347. bodyConfig.type.push('cylinder');
  46348. bodyConfig.size.push(sizeX);
  46349. bodyConfig.size.push(sizeY);
  46350. //due to the way oimo works with compounds, add one more value.
  46351. bodyConfig.size.push(sizeY);
  46352. break;
  46353. case BABYLON.PhysicsImpostor.PlaneImpostor:
  46354. case BABYLON.PhysicsImpostor.BoxImpostor:
  46355. default:
  46356. var sizeX = checkWithEpsilon(extendSize.x);
  46357. var sizeY = checkWithEpsilon(extendSize.y);
  46358. var sizeZ = checkWithEpsilon(extendSize.z);
  46359. bodyConfig.type.push('box');
  46360. bodyConfig.size.push(sizeX);
  46361. bodyConfig.size.push(sizeY);
  46362. bodyConfig.size.push(sizeZ);
  46363. break;
  46364. }
  46365. //actually not needed, but hey...
  46366. i.object.rotationQuaternion = oldQuaternion;
  46367. });
  46368. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  46369. }
  46370. else {
  46371. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  46372. }
  46373. impostor.setDeltaPosition(this._tmpPositionVector);
  46374. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  46375. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  46376. };
  46377. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  46378. //impostor.physicsBody.dispose();
  46379. //Same as : (older oimo versions)
  46380. this.world.removeRigidBody(impostor.physicsBody);
  46381. };
  46382. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  46383. var mainBody = impostorJoint.mainImpostor.physicsBody;
  46384. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  46385. if (!mainBody || !connectedBody) {
  46386. return;
  46387. }
  46388. var jointData = impostorJoint.joint.jointData;
  46389. var options = jointData.nativeParams || {};
  46390. var type;
  46391. var nativeJointData = {
  46392. body1: mainBody,
  46393. body2: connectedBody,
  46394. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  46395. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  46396. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  46397. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  46398. min: options.min,
  46399. max: options.max,
  46400. collision: options.collision || jointData.collision,
  46401. spring: options.spring,
  46402. //supporting older version of Oimo
  46403. world: this.world
  46404. };
  46405. switch (impostorJoint.joint.type) {
  46406. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  46407. type = "jointBall";
  46408. break;
  46409. case BABYLON.PhysicsJoint.SpringJoint:
  46410. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  46411. var springData = jointData;
  46412. nativeJointData.min = springData.length || nativeJointData.min;
  46413. //Max should also be set, just make sure it is at least min
  46414. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  46415. case BABYLON.PhysicsJoint.DistanceJoint:
  46416. type = "jointDistance";
  46417. nativeJointData.max = jointData.maxDistance;
  46418. break;
  46419. case BABYLON.PhysicsJoint.PrismaticJoint:
  46420. type = "jointPrisme";
  46421. break;
  46422. case BABYLON.PhysicsJoint.SliderJoint:
  46423. type = "jointSlide";
  46424. break;
  46425. case BABYLON.PhysicsJoint.WheelJoint:
  46426. type = "jointWheel";
  46427. break;
  46428. case BABYLON.PhysicsJoint.HingeJoint:
  46429. default:
  46430. type = "jointHinge";
  46431. break;
  46432. }
  46433. nativeJointData.type = type;
  46434. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  46435. };
  46436. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  46437. //Bug in Oimo prevents us from disposing a joint in the playground
  46438. //joint.joint.physicsJoint.dispose();
  46439. //So we will bruteforce it!
  46440. try {
  46441. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  46442. }
  46443. catch (e) {
  46444. BABYLON.Tools.Warn(e);
  46445. }
  46446. };
  46447. OimoJSPlugin.prototype.isSupported = function () {
  46448. return OIMO !== undefined;
  46449. };
  46450. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  46451. if (!impostor.physicsBody.sleeping) {
  46452. //TODO check that
  46453. if (impostor.physicsBody.shapes.next) {
  46454. var parentShape = this._getLastShape(impostor.physicsBody);
  46455. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  46456. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  46457. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  46458. }
  46459. else {
  46460. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  46461. }
  46462. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  46463. impostor.object.rotationQuaternion.normalize();
  46464. }
  46465. };
  46466. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  46467. var body = impostor.physicsBody;
  46468. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  46469. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  46470. body.syncShapes();
  46471. body.awake();
  46472. };
  46473. OimoJSPlugin.prototype._getLastShape = function (body) {
  46474. var lastShape = body.shapes;
  46475. while (lastShape.next) {
  46476. lastShape = lastShape.next;
  46477. }
  46478. return lastShape;
  46479. };
  46480. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  46481. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  46482. };
  46483. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  46484. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  46485. };
  46486. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  46487. var v = impostor.physicsBody.linearVelocity;
  46488. if (!v)
  46489. return null;
  46490. return new BABYLON.Vector3(v.x, v.y, v.z);
  46491. };
  46492. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  46493. var v = impostor.physicsBody.angularVelocity;
  46494. if (!v)
  46495. return null;
  46496. return new BABYLON.Vector3(v.x, v.y, v.z);
  46497. };
  46498. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  46499. var staticBody = mass === 0;
  46500. //this will actually set the body's density and not its mass.
  46501. //But this is how oimo treats the mass variable.
  46502. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  46503. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  46504. };
  46505. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  46506. impostor.physicsBody.sleep();
  46507. };
  46508. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  46509. impostor.physicsBody.awake();
  46510. };
  46511. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  46512. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  46513. if (minDistance !== void 0) {
  46514. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  46515. }
  46516. };
  46517. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  46518. //TODO separate rotational and transational motors.
  46519. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  46520. if (motor) {
  46521. motor.setMotor(speed, maxForce);
  46522. }
  46523. };
  46524. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  46525. //TODO separate rotational and transational motors.
  46526. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  46527. if (motor) {
  46528. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  46529. }
  46530. };
  46531. OimoJSPlugin.prototype.dispose = function () {
  46532. this.world.clear();
  46533. };
  46534. return OimoJSPlugin;
  46535. })();
  46536. BABYLON.OimoJSPlugin = OimoJSPlugin;
  46537. })(BABYLON || (BABYLON = {}));
  46538. var BABYLON;
  46539. (function (BABYLON) {
  46540. var DisplayPassPostProcess = (function (_super) {
  46541. __extends(DisplayPassPostProcess, _super);
  46542. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  46543. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  46544. }
  46545. return DisplayPassPostProcess;
  46546. })(BABYLON.PostProcess);
  46547. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  46548. })(BABYLON || (BABYLON = {}));
  46549. var BABYLON;
  46550. (function (BABYLON) {
  46551. var SimplificationSettings = (function () {
  46552. function SimplificationSettings(quality, distance, optimizeMesh) {
  46553. this.quality = quality;
  46554. this.distance = distance;
  46555. this.optimizeMesh = optimizeMesh;
  46556. }
  46557. return SimplificationSettings;
  46558. })();
  46559. BABYLON.SimplificationSettings = SimplificationSettings;
  46560. var SimplificationQueue = (function () {
  46561. function SimplificationQueue() {
  46562. this.running = false;
  46563. this._simplificationArray = [];
  46564. }
  46565. SimplificationQueue.prototype.addTask = function (task) {
  46566. this._simplificationArray.push(task);
  46567. };
  46568. SimplificationQueue.prototype.executeNext = function () {
  46569. var task = this._simplificationArray.pop();
  46570. if (task) {
  46571. this.running = true;
  46572. this.runSimplification(task);
  46573. }
  46574. else {
  46575. this.running = false;
  46576. }
  46577. };
  46578. SimplificationQueue.prototype.runSimplification = function (task) {
  46579. var _this = this;
  46580. if (task.parallelProcessing) {
  46581. //parallel simplifier
  46582. task.settings.forEach(function (setting) {
  46583. var simplifier = _this.getSimplifier(task);
  46584. simplifier.simplify(setting, function (newMesh) {
  46585. task.mesh.addLODLevel(setting.distance, newMesh);
  46586. newMesh.isVisible = true;
  46587. //check if it is the last
  46588. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  46589. //all done, run the success callback.
  46590. task.successCallback();
  46591. }
  46592. _this.executeNext();
  46593. });
  46594. });
  46595. }
  46596. else {
  46597. //single simplifier.
  46598. var simplifier = this.getSimplifier(task);
  46599. var runDecimation = function (setting, callback) {
  46600. simplifier.simplify(setting, function (newMesh) {
  46601. task.mesh.addLODLevel(setting.distance, newMesh);
  46602. newMesh.isVisible = true;
  46603. //run the next quality level
  46604. callback();
  46605. });
  46606. };
  46607. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  46608. runDecimation(task.settings[loop.index], function () {
  46609. loop.executeNext();
  46610. });
  46611. }, function () {
  46612. //execution ended, run the success callback.
  46613. if (task.successCallback) {
  46614. task.successCallback();
  46615. }
  46616. _this.executeNext();
  46617. });
  46618. }
  46619. };
  46620. SimplificationQueue.prototype.getSimplifier = function (task) {
  46621. switch (task.simplificationType) {
  46622. case SimplificationType.QUADRATIC:
  46623. default:
  46624. return new QuadraticErrorSimplification(task.mesh);
  46625. }
  46626. };
  46627. return SimplificationQueue;
  46628. })();
  46629. BABYLON.SimplificationQueue = SimplificationQueue;
  46630. /**
  46631. * The implemented types of simplification.
  46632. * At the moment only Quadratic Error Decimation is implemented.
  46633. */
  46634. (function (SimplificationType) {
  46635. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  46636. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  46637. var SimplificationType = BABYLON.SimplificationType;
  46638. var DecimationTriangle = (function () {
  46639. function DecimationTriangle(vertices) {
  46640. this.vertices = vertices;
  46641. this.error = new Array(4);
  46642. this.deleted = false;
  46643. this.isDirty = false;
  46644. this.deletePending = false;
  46645. this.borderFactor = 0;
  46646. }
  46647. return DecimationTriangle;
  46648. })();
  46649. BABYLON.DecimationTriangle = DecimationTriangle;
  46650. var DecimationVertex = (function () {
  46651. function DecimationVertex(position, id) {
  46652. this.position = position;
  46653. this.id = id;
  46654. this.isBorder = true;
  46655. this.q = new QuadraticMatrix();
  46656. this.triangleCount = 0;
  46657. this.triangleStart = 0;
  46658. this.originalOffsets = [];
  46659. }
  46660. DecimationVertex.prototype.updatePosition = function (newPosition) {
  46661. this.position.copyFrom(newPosition);
  46662. };
  46663. return DecimationVertex;
  46664. })();
  46665. BABYLON.DecimationVertex = DecimationVertex;
  46666. var QuadraticMatrix = (function () {
  46667. function QuadraticMatrix(data) {
  46668. this.data = new Array(10);
  46669. for (var i = 0; i < 10; ++i) {
  46670. if (data && data[i]) {
  46671. this.data[i] = data[i];
  46672. }
  46673. else {
  46674. this.data[i] = 0;
  46675. }
  46676. }
  46677. }
  46678. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  46679. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  46680. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  46681. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  46682. return det;
  46683. };
  46684. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  46685. for (var i = 0; i < 10; ++i) {
  46686. this.data[i] += matrix.data[i];
  46687. }
  46688. };
  46689. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  46690. for (var i = 0; i < 10; ++i) {
  46691. this.data[i] += data[i];
  46692. }
  46693. };
  46694. QuadraticMatrix.prototype.add = function (matrix) {
  46695. var m = new QuadraticMatrix();
  46696. for (var i = 0; i < 10; ++i) {
  46697. m.data[i] = this.data[i] + matrix.data[i];
  46698. }
  46699. return m;
  46700. };
  46701. QuadraticMatrix.FromData = function (a, b, c, d) {
  46702. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  46703. };
  46704. //returning an array to avoid garbage collection
  46705. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  46706. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  46707. };
  46708. return QuadraticMatrix;
  46709. })();
  46710. BABYLON.QuadraticMatrix = QuadraticMatrix;
  46711. var Reference = (function () {
  46712. function Reference(vertexId, triangleId) {
  46713. this.vertexId = vertexId;
  46714. this.triangleId = triangleId;
  46715. }
  46716. return Reference;
  46717. })();
  46718. BABYLON.Reference = Reference;
  46719. /**
  46720. * An implementation of the Quadratic Error simplification algorithm.
  46721. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  46722. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  46723. * @author RaananW
  46724. */
  46725. var QuadraticErrorSimplification = (function () {
  46726. function QuadraticErrorSimplification(_mesh) {
  46727. this._mesh = _mesh;
  46728. this.initialized = false;
  46729. this.syncIterations = 5000;
  46730. this.aggressiveness = 7;
  46731. this.decimationIterations = 100;
  46732. this.boundingBoxEpsilon = BABYLON.Epsilon;
  46733. }
  46734. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  46735. var _this = this;
  46736. this.initDecimatedMesh();
  46737. //iterating through the submeshes array, one after the other.
  46738. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  46739. _this.initWithMesh(loop.index, function () {
  46740. _this.runDecimation(settings, loop.index, function () {
  46741. loop.executeNext();
  46742. });
  46743. }, settings.optimizeMesh);
  46744. }, function () {
  46745. setTimeout(function () {
  46746. successCallback(_this._reconstructedMesh);
  46747. }, 0);
  46748. });
  46749. };
  46750. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  46751. var _this = this;
  46752. var gCount = 0;
  46753. triangle.vertices.forEach(function (vertex) {
  46754. var count = 0;
  46755. var vPos = vertex.position;
  46756. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  46757. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  46758. ++count;
  46759. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  46760. ++count;
  46761. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  46762. ++count;
  46763. if (count > 1) {
  46764. ++gCount;
  46765. }
  46766. ;
  46767. });
  46768. if (gCount > 1) {
  46769. console.log(triangle, gCount);
  46770. }
  46771. return gCount > 1;
  46772. };
  46773. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  46774. var _this = this;
  46775. var targetCount = ~~(this.triangles.length * settings.quality);
  46776. var deletedTriangles = 0;
  46777. var triangleCount = this.triangles.length;
  46778. var iterationFunction = function (iteration, callback) {
  46779. setTimeout(function () {
  46780. if (iteration % 5 === 0) {
  46781. _this.updateMesh(iteration === 0);
  46782. }
  46783. for (var i = 0; i < _this.triangles.length; ++i) {
  46784. _this.triangles[i].isDirty = false;
  46785. }
  46786. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  46787. var trianglesIterator = function (i) {
  46788. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  46789. var t = _this.triangles[tIdx];
  46790. if (!t)
  46791. return;
  46792. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  46793. return;
  46794. }
  46795. for (var j = 0; j < 3; ++j) {
  46796. if (t.error[j] < threshold) {
  46797. var deleted0 = [];
  46798. var deleted1 = [];
  46799. var v0 = t.vertices[j];
  46800. var v1 = t.vertices[(j + 1) % 3];
  46801. if (v0.isBorder || v1.isBorder)
  46802. continue;
  46803. var p = BABYLON.Vector3.Zero();
  46804. var n = BABYLON.Vector3.Zero();
  46805. var uv = BABYLON.Vector2.Zero();
  46806. var color = new BABYLON.Color4(0, 0, 0, 1);
  46807. _this.calculateError(v0, v1, p, n, uv, color);
  46808. var delTr = [];
  46809. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  46810. continue;
  46811. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  46812. continue;
  46813. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  46814. continue;
  46815. var uniqueArray = [];
  46816. delTr.forEach(function (deletedT) {
  46817. if (uniqueArray.indexOf(deletedT) === -1) {
  46818. deletedT.deletePending = true;
  46819. uniqueArray.push(deletedT);
  46820. }
  46821. });
  46822. if (uniqueArray.length % 2 !== 0) {
  46823. continue;
  46824. }
  46825. v0.q = v1.q.add(v0.q);
  46826. v0.updatePosition(p);
  46827. var tStart = _this.references.length;
  46828. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  46829. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  46830. var tCount = _this.references.length - tStart;
  46831. if (tCount <= v0.triangleCount) {
  46832. if (tCount) {
  46833. for (var c = 0; c < tCount; c++) {
  46834. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  46835. }
  46836. }
  46837. }
  46838. else {
  46839. v0.triangleStart = tStart;
  46840. }
  46841. v0.triangleCount = tCount;
  46842. break;
  46843. }
  46844. }
  46845. };
  46846. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  46847. }, 0);
  46848. };
  46849. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  46850. if (triangleCount - deletedTriangles <= targetCount)
  46851. loop.breakLoop();
  46852. else {
  46853. iterationFunction(loop.index, function () {
  46854. loop.executeNext();
  46855. });
  46856. }
  46857. }, function () {
  46858. setTimeout(function () {
  46859. //reconstruct this part of the mesh
  46860. _this.reconstructMesh(submeshIndex);
  46861. successCallback();
  46862. }, 0);
  46863. });
  46864. };
  46865. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  46866. var _this = this;
  46867. this.vertices = [];
  46868. this.triangles = [];
  46869. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46870. var indices = this._mesh.getIndices();
  46871. var submesh = this._mesh.subMeshes[submeshIndex];
  46872. var findInVertices = function (positionToSearch) {
  46873. if (optimizeMesh) {
  46874. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  46875. if (_this.vertices[ii].position.equals(positionToSearch)) {
  46876. return _this.vertices[ii];
  46877. }
  46878. }
  46879. }
  46880. return null;
  46881. };
  46882. var vertexReferences = [];
  46883. var vertexInit = function (i) {
  46884. var offset = i + submesh.verticesStart;
  46885. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  46886. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  46887. vertex.originalOffsets.push(offset);
  46888. if (vertex.id === _this.vertices.length) {
  46889. _this.vertices.push(vertex);
  46890. }
  46891. vertexReferences.push(vertex.id);
  46892. };
  46893. //var totalVertices = mesh.getTotalVertices();
  46894. var totalVertices = submesh.verticesCount;
  46895. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  46896. var indicesInit = function (i) {
  46897. var offset = (submesh.indexStart / 3) + i;
  46898. var pos = (offset * 3);
  46899. var i0 = indices[pos + 0];
  46900. var i1 = indices[pos + 1];
  46901. var i2 = indices[pos + 2];
  46902. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  46903. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  46904. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  46905. var triangle = new DecimationTriangle([v0, v1, v2]);
  46906. triangle.originalOffset = pos;
  46907. _this.triangles.push(triangle);
  46908. };
  46909. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  46910. _this.init(callback);
  46911. });
  46912. });
  46913. };
  46914. QuadraticErrorSimplification.prototype.init = function (callback) {
  46915. var _this = this;
  46916. var triangleInit1 = function (i) {
  46917. var t = _this.triangles[i];
  46918. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  46919. for (var j = 0; j < 3; j++) {
  46920. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  46921. }
  46922. };
  46923. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  46924. var triangleInit2 = function (i) {
  46925. var t = _this.triangles[i];
  46926. for (var j = 0; j < 3; ++j) {
  46927. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  46928. }
  46929. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  46930. };
  46931. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  46932. _this.initialized = true;
  46933. callback();
  46934. });
  46935. });
  46936. };
  46937. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  46938. var newTriangles = [];
  46939. var i;
  46940. for (i = 0; i < this.vertices.length; ++i) {
  46941. this.vertices[i].triangleCount = 0;
  46942. }
  46943. var t;
  46944. var j;
  46945. for (i = 0; i < this.triangles.length; ++i) {
  46946. if (!this.triangles[i].deleted) {
  46947. t = this.triangles[i];
  46948. for (j = 0; j < 3; ++j) {
  46949. t.vertices[j].triangleCount = 1;
  46950. }
  46951. newTriangles.push(t);
  46952. }
  46953. }
  46954. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  46955. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  46956. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  46957. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  46958. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46959. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46960. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46961. var vertexCount = 0;
  46962. for (i = 0; i < this.vertices.length; ++i) {
  46963. var vertex = this.vertices[i];
  46964. vertex.id = vertexCount;
  46965. if (vertex.triangleCount) {
  46966. vertex.originalOffsets.forEach(function (originalOffset) {
  46967. newPositionData.push(vertex.position.x);
  46968. newPositionData.push(vertex.position.y);
  46969. newPositionData.push(vertex.position.z);
  46970. newNormalData.push(normalData[originalOffset * 3]);
  46971. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  46972. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  46973. if (uvs && uvs.length) {
  46974. newUVsData.push(uvs[(originalOffset * 2)]);
  46975. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  46976. }
  46977. else if (colorsData && colorsData.length) {
  46978. newColorsData.push(colorsData[(originalOffset * 4)]);
  46979. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  46980. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  46981. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  46982. }
  46983. ++vertexCount;
  46984. });
  46985. }
  46986. }
  46987. var startingIndex = this._reconstructedMesh.getTotalIndices();
  46988. var startingVertex = this._reconstructedMesh.getTotalVertices();
  46989. var submeshesArray = this._reconstructedMesh.subMeshes;
  46990. this._reconstructedMesh.subMeshes = [];
  46991. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  46992. var originalIndices = this._mesh.getIndices();
  46993. for (i = 0; i < newTriangles.length; ++i) {
  46994. t = newTriangles[i]; //now get the new referencing point for each vertex
  46995. [0, 1, 2].forEach(function (idx) {
  46996. var id = originalIndices[t.originalOffset + idx];
  46997. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  46998. if (offset < 0)
  46999. offset = 0;
  47000. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  47001. });
  47002. }
  47003. //overwriting the old vertex buffers and indices.
  47004. this._reconstructedMesh.setIndices(newIndicesArray);
  47005. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  47006. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  47007. if (newUVsData.length > 0)
  47008. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  47009. if (newColorsData.length > 0)
  47010. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  47011. //create submesh
  47012. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  47013. if (submeshIndex > 0) {
  47014. this._reconstructedMesh.subMeshes = [];
  47015. submeshesArray.forEach(function (submesh) {
  47016. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  47017. });
  47018. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  47019. }
  47020. };
  47021. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  47022. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  47023. this._reconstructedMesh.material = this._mesh.material;
  47024. this._reconstructedMesh.parent = this._mesh.parent;
  47025. this._reconstructedMesh.isVisible = false;
  47026. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  47027. };
  47028. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  47029. for (var i = 0; i < vertex1.triangleCount; ++i) {
  47030. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  47031. if (t.deleted)
  47032. continue;
  47033. var s = this.references[vertex1.triangleStart + i].vertexId;
  47034. var v1 = t.vertices[(s + 1) % 3];
  47035. var v2 = t.vertices[(s + 2) % 3];
  47036. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  47037. deletedArray[i] = true;
  47038. delTr.push(t);
  47039. continue;
  47040. }
  47041. var d1 = v1.position.subtract(point);
  47042. d1 = d1.normalize();
  47043. var d2 = v2.position.subtract(point);
  47044. d2 = d2.normalize();
  47045. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  47046. return true;
  47047. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  47048. deletedArray[i] = false;
  47049. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  47050. return true;
  47051. }
  47052. return false;
  47053. };
  47054. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  47055. var newDeleted = deletedTriangles;
  47056. for (var i = 0; i < vertex.triangleCount; ++i) {
  47057. var ref = this.references[vertex.triangleStart + i];
  47058. var t = this.triangles[ref.triangleId];
  47059. if (t.deleted)
  47060. continue;
  47061. if (deletedArray[i] && t.deletePending) {
  47062. t.deleted = true;
  47063. newDeleted++;
  47064. continue;
  47065. }
  47066. t.vertices[ref.vertexId] = origVertex;
  47067. t.isDirty = true;
  47068. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  47069. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  47070. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  47071. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  47072. this.references.push(ref);
  47073. }
  47074. return newDeleted;
  47075. };
  47076. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  47077. for (var i = 0; i < this.vertices.length; ++i) {
  47078. var vCount = [];
  47079. var vId = [];
  47080. var v = this.vertices[i];
  47081. var j;
  47082. for (j = 0; j < v.triangleCount; ++j) {
  47083. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  47084. for (var ii = 0; ii < 3; ii++) {
  47085. var ofs = 0;
  47086. var vv = triangle.vertices[ii];
  47087. while (ofs < vCount.length) {
  47088. if (vId[ofs] === vv.id)
  47089. break;
  47090. ++ofs;
  47091. }
  47092. if (ofs === vCount.length) {
  47093. vCount.push(1);
  47094. vId.push(vv.id);
  47095. }
  47096. else {
  47097. vCount[ofs]++;
  47098. }
  47099. }
  47100. }
  47101. for (j = 0; j < vCount.length; ++j) {
  47102. if (vCount[j] === 1) {
  47103. this.vertices[vId[j]].isBorder = true;
  47104. }
  47105. else {
  47106. this.vertices[vId[j]].isBorder = false;
  47107. }
  47108. }
  47109. }
  47110. };
  47111. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  47112. if (identifyBorders === void 0) { identifyBorders = false; }
  47113. var i;
  47114. if (!identifyBorders) {
  47115. var newTrianglesVector = [];
  47116. for (i = 0; i < this.triangles.length; ++i) {
  47117. if (!this.triangles[i].deleted) {
  47118. newTrianglesVector.push(this.triangles[i]);
  47119. }
  47120. }
  47121. this.triangles = newTrianglesVector;
  47122. }
  47123. for (i = 0; i < this.vertices.length; ++i) {
  47124. this.vertices[i].triangleCount = 0;
  47125. this.vertices[i].triangleStart = 0;
  47126. }
  47127. var t;
  47128. var j;
  47129. var v;
  47130. for (i = 0; i < this.triangles.length; ++i) {
  47131. t = this.triangles[i];
  47132. for (j = 0; j < 3; ++j) {
  47133. v = t.vertices[j];
  47134. v.triangleCount++;
  47135. }
  47136. }
  47137. var tStart = 0;
  47138. for (i = 0; i < this.vertices.length; ++i) {
  47139. this.vertices[i].triangleStart = tStart;
  47140. tStart += this.vertices[i].triangleCount;
  47141. this.vertices[i].triangleCount = 0;
  47142. }
  47143. var newReferences = new Array(this.triangles.length * 3);
  47144. for (i = 0; i < this.triangles.length; ++i) {
  47145. t = this.triangles[i];
  47146. for (j = 0; j < 3; ++j) {
  47147. v = t.vertices[j];
  47148. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  47149. v.triangleCount++;
  47150. }
  47151. }
  47152. this.references = newReferences;
  47153. if (identifyBorders) {
  47154. this.identifyBorder();
  47155. }
  47156. };
  47157. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  47158. var x = point.x;
  47159. var y = point.y;
  47160. var z = point.z;
  47161. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y
  47162. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  47163. };
  47164. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  47165. var q = vertex1.q.add(vertex2.q);
  47166. var border = vertex1.isBorder && vertex2.isBorder;
  47167. var error = 0;
  47168. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  47169. if (qDet !== 0 && !border) {
  47170. if (!pointResult) {
  47171. pointResult = BABYLON.Vector3.Zero();
  47172. }
  47173. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  47174. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  47175. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  47176. error = this.vertexError(q, pointResult);
  47177. }
  47178. else {
  47179. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  47180. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  47181. var error1 = this.vertexError(q, vertex1.position);
  47182. var error2 = this.vertexError(q, vertex2.position);
  47183. var error3 = this.vertexError(q, p3);
  47184. error = Math.min(error1, error2, error3);
  47185. if (error === error1) {
  47186. if (pointResult) {
  47187. pointResult.copyFrom(vertex1.position);
  47188. }
  47189. }
  47190. else if (error === error2) {
  47191. if (pointResult) {
  47192. pointResult.copyFrom(vertex2.position);
  47193. }
  47194. }
  47195. else {
  47196. if (pointResult) {
  47197. pointResult.copyFrom(p3);
  47198. }
  47199. }
  47200. }
  47201. return error;
  47202. };
  47203. return QuadraticErrorSimplification;
  47204. })();
  47205. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  47206. })(BABYLON || (BABYLON = {}));
  47207. var BABYLON;
  47208. (function (BABYLON) {
  47209. var serializedGeometries = [];
  47210. var serializeGeometry = function (geometry, serializationGeometries) {
  47211. if (serializedGeometries[geometry.id]) {
  47212. return;
  47213. }
  47214. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  47215. serializationGeometries.boxes.push(geometry.serialize());
  47216. }
  47217. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  47218. serializationGeometries.spheres.push(geometry.serialize());
  47219. }
  47220. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  47221. serializationGeometries.cylinders.push(geometry.serialize());
  47222. }
  47223. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  47224. serializationGeometries.toruses.push(geometry.serialize());
  47225. }
  47226. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  47227. serializationGeometries.grounds.push(geometry.serialize());
  47228. }
  47229. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  47230. serializationGeometries.planes.push(geometry.serialize());
  47231. }
  47232. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  47233. serializationGeometries.torusKnots.push(geometry.serialize());
  47234. }
  47235. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  47236. throw new Error("Unknown primitive type");
  47237. }
  47238. else {
  47239. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  47240. }
  47241. serializedGeometries[geometry.id] = true;
  47242. };
  47243. var serializeMesh = function (mesh, serializationScene) {
  47244. var serializationObject = {};
  47245. serializationObject.name = mesh.name;
  47246. serializationObject.id = mesh.id;
  47247. if (BABYLON.Tags.HasTags(mesh)) {
  47248. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  47249. }
  47250. serializationObject.position = mesh.position.asArray();
  47251. if (mesh.rotationQuaternion) {
  47252. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  47253. }
  47254. else if (mesh.rotation) {
  47255. serializationObject.rotation = mesh.rotation.asArray();
  47256. }
  47257. serializationObject.scaling = mesh.scaling.asArray();
  47258. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  47259. serializationObject.isEnabled = mesh.isEnabled();
  47260. serializationObject.isVisible = mesh.isVisible;
  47261. serializationObject.infiniteDistance = mesh.infiniteDistance;
  47262. serializationObject.pickable = mesh.isPickable;
  47263. serializationObject.receiveShadows = mesh.receiveShadows;
  47264. serializationObject.billboardMode = mesh.billboardMode;
  47265. serializationObject.visibility = mesh.visibility;
  47266. serializationObject.checkCollisions = mesh.checkCollisions;
  47267. // Parent
  47268. if (mesh.parent) {
  47269. serializationObject.parentId = mesh.parent.id;
  47270. }
  47271. // Geometry
  47272. var geometry = mesh._geometry;
  47273. if (geometry) {
  47274. var geometryId = geometry.id;
  47275. serializationObject.geometryId = geometryId;
  47276. if (!mesh.getScene().getGeometryByID(geometryId)) {
  47277. // geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
  47278. serializeGeometry(geometry, serializationScene.geometries);
  47279. }
  47280. // SubMeshes
  47281. serializationObject.subMeshes = [];
  47282. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  47283. var subMesh = mesh.subMeshes[subIndex];
  47284. serializationObject.subMeshes.push({
  47285. materialIndex: subMesh.materialIndex,
  47286. verticesStart: subMesh.verticesStart,
  47287. verticesCount: subMesh.verticesCount,
  47288. indexStart: subMesh.indexStart,
  47289. indexCount: subMesh.indexCount
  47290. });
  47291. }
  47292. }
  47293. // Material
  47294. if (mesh.material) {
  47295. serializationObject.materialId = mesh.material.id;
  47296. }
  47297. else {
  47298. mesh.material = null;
  47299. }
  47300. // Skeleton
  47301. if (mesh.skeleton) {
  47302. serializationObject.skeletonId = mesh.skeleton.id;
  47303. }
  47304. // Physics
  47305. //TODO implement correct serialization for physics impostors.
  47306. if (mesh.getPhysicsImpostor()) {
  47307. serializationObject.physicsMass = mesh.getPhysicsMass();
  47308. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  47309. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  47310. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  47311. }
  47312. // Instances
  47313. serializationObject.instances = [];
  47314. for (var index = 0; index < mesh.instances.length; index++) {
  47315. var instance = mesh.instances[index];
  47316. var serializationInstance = {
  47317. name: instance.name,
  47318. position: instance.position.asArray(),
  47319. scaling: instance.scaling.asArray()
  47320. };
  47321. if (instance.rotationQuaternion) {
  47322. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  47323. }
  47324. else if (instance.rotation) {
  47325. serializationInstance.rotation = instance.rotation.asArray();
  47326. }
  47327. serializationObject.instances.push(serializationInstance);
  47328. // Animations
  47329. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  47330. serializationInstance.ranges = instance.serializeAnimationRanges();
  47331. }
  47332. // Animations
  47333. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  47334. serializationObject.ranges = mesh.serializeAnimationRanges();
  47335. // Layer mask
  47336. serializationObject.layerMask = mesh.layerMask;
  47337. // Action Manager
  47338. if (mesh.actionManager) {
  47339. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  47340. }
  47341. return serializationObject;
  47342. };
  47343. var finalizeSingleMesh = function (mesh, serializationObject) {
  47344. //only works if the mesh is already loaded
  47345. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  47346. //serialize material
  47347. if (mesh.material) {
  47348. if (mesh.material instanceof BABYLON.StandardMaterial) {
  47349. serializationObject.materials = serializationObject.materials || [];
  47350. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  47351. serializationObject.materials.push(mesh.material.serialize());
  47352. }
  47353. }
  47354. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  47355. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  47356. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  47357. serializationObject.multiMaterials.push(mesh.material.serialize());
  47358. }
  47359. }
  47360. }
  47361. //serialize geometry
  47362. var geometry = mesh._geometry;
  47363. if (geometry) {
  47364. if (!serializationObject.geometries) {
  47365. serializationObject.geometries = {};
  47366. serializationObject.geometries.boxes = [];
  47367. serializationObject.geometries.spheres = [];
  47368. serializationObject.geometries.cylinders = [];
  47369. serializationObject.geometries.toruses = [];
  47370. serializationObject.geometries.grounds = [];
  47371. serializationObject.geometries.planes = [];
  47372. serializationObject.geometries.torusKnots = [];
  47373. serializationObject.geometries.vertexData = [];
  47374. }
  47375. serializeGeometry(geometry, serializationObject.geometries);
  47376. }
  47377. // Skeletons
  47378. if (mesh.skeleton) {
  47379. serializationObject.skeletons = serializationObject.skeletons || [];
  47380. serializationObject.skeletons.push(mesh.skeleton.serialize());
  47381. }
  47382. //serialize the actual mesh
  47383. serializationObject.meshes = serializationObject.meshes || [];
  47384. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  47385. }
  47386. };
  47387. var SceneSerializer = (function () {
  47388. function SceneSerializer() {
  47389. }
  47390. SceneSerializer.ClearCache = function () {
  47391. serializedGeometries = [];
  47392. };
  47393. SceneSerializer.Serialize = function (scene) {
  47394. var serializationObject = {};
  47395. // Scene
  47396. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  47397. serializationObject.autoClear = scene.autoClear;
  47398. serializationObject.clearColor = scene.clearColor.asArray();
  47399. serializationObject.ambientColor = scene.ambientColor.asArray();
  47400. serializationObject.gravity = scene.gravity.asArray();
  47401. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  47402. serializationObject.workerCollisions = scene.workerCollisions;
  47403. // Fog
  47404. if (scene.fogMode && scene.fogMode !== 0) {
  47405. serializationObject.fogMode = scene.fogMode;
  47406. serializationObject.fogColor = scene.fogColor.asArray();
  47407. serializationObject.fogStart = scene.fogStart;
  47408. serializationObject.fogEnd = scene.fogEnd;
  47409. serializationObject.fogDensity = scene.fogDensity;
  47410. }
  47411. //Physics
  47412. if (scene.isPhysicsEnabled()) {
  47413. serializationObject.physicsEnabled = true;
  47414. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  47415. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  47416. }
  47417. // Lights
  47418. serializationObject.lights = [];
  47419. var index;
  47420. var light;
  47421. for (index = 0; index < scene.lights.length; index++) {
  47422. light = scene.lights[index];
  47423. serializationObject.lights.push(light.serialize());
  47424. }
  47425. // Cameras
  47426. serializationObject.cameras = [];
  47427. for (index = 0; index < scene.cameras.length; index++) {
  47428. var camera = scene.cameras[index];
  47429. serializationObject.cameras.push(camera.serialize());
  47430. }
  47431. if (scene.activeCamera) {
  47432. serializationObject.activeCameraID = scene.activeCamera.id;
  47433. }
  47434. // Animations
  47435. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  47436. // Materials
  47437. serializationObject.materials = [];
  47438. serializationObject.multiMaterials = [];
  47439. var material;
  47440. for (index = 0; index < scene.materials.length; index++) {
  47441. material = scene.materials[index];
  47442. serializationObject.materials.push(material.serialize());
  47443. }
  47444. // MultiMaterials
  47445. serializationObject.multiMaterials = [];
  47446. for (index = 0; index < scene.multiMaterials.length; index++) {
  47447. var multiMaterial = scene.multiMaterials[index];
  47448. serializationObject.multiMaterials.push(multiMaterial.serialize());
  47449. }
  47450. // Skeletons
  47451. serializationObject.skeletons = [];
  47452. for (index = 0; index < scene.skeletons.length; index++) {
  47453. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  47454. }
  47455. // Geometries
  47456. serializationObject.geometries = {};
  47457. serializationObject.geometries.boxes = [];
  47458. serializationObject.geometries.spheres = [];
  47459. serializationObject.geometries.cylinders = [];
  47460. serializationObject.geometries.toruses = [];
  47461. serializationObject.geometries.grounds = [];
  47462. serializationObject.geometries.planes = [];
  47463. serializationObject.geometries.torusKnots = [];
  47464. serializationObject.geometries.vertexData = [];
  47465. serializedGeometries = [];
  47466. var geometries = scene.getGeometries();
  47467. for (index = 0; index < geometries.length; index++) {
  47468. var geometry = geometries[index];
  47469. if (geometry.isReady()) {
  47470. serializeGeometry(geometry, serializationObject.geometries);
  47471. }
  47472. }
  47473. // Meshes
  47474. serializationObject.meshes = [];
  47475. for (index = 0; index < scene.meshes.length; index++) {
  47476. var abstractMesh = scene.meshes[index];
  47477. if (abstractMesh instanceof BABYLON.Mesh) {
  47478. var mesh = abstractMesh;
  47479. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  47480. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  47481. }
  47482. }
  47483. }
  47484. // Particles Systems
  47485. serializationObject.particleSystems = [];
  47486. for (index = 0; index < scene.particleSystems.length; index++) {
  47487. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  47488. }
  47489. // Lens flares
  47490. serializationObject.lensFlareSystems = [];
  47491. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  47492. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  47493. }
  47494. // Shadows
  47495. serializationObject.shadowGenerators = [];
  47496. for (index = 0; index < scene.lights.length; index++) {
  47497. light = scene.lights[index];
  47498. if (light.getShadowGenerator()) {
  47499. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  47500. }
  47501. }
  47502. // Action Manager
  47503. if (scene.actionManager) {
  47504. serializationObject.actions = scene.actionManager.serialize("scene");
  47505. }
  47506. return serializationObject;
  47507. };
  47508. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  47509. if (withParents === void 0) { withParents = false; }
  47510. if (withChildren === void 0) { withChildren = false; }
  47511. var serializationObject = {};
  47512. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  47513. if (withParents || withChildren) {
  47514. //deliberate for loop! not for each, appended should be processed as well.
  47515. for (var i = 0; i < toSerialize.length; ++i) {
  47516. if (withChildren) {
  47517. toSerialize[i].getDescendants().forEach(function (node) {
  47518. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  47519. toSerialize.push(node);
  47520. }
  47521. });
  47522. }
  47523. //make sure the array doesn't contain the object already
  47524. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  47525. toSerialize.push(toSerialize[i].parent);
  47526. }
  47527. }
  47528. }
  47529. toSerialize.forEach(function (mesh) {
  47530. finalizeSingleMesh(mesh, serializationObject);
  47531. });
  47532. return serializationObject;
  47533. };
  47534. return SceneSerializer;
  47535. })();
  47536. BABYLON.SceneSerializer = SceneSerializer;
  47537. })(BABYLON || (BABYLON = {}));
  47538. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  47539. // Huge respect for a such great lib.
  47540. // Earcut license:
  47541. // Copyright (c) 2016, Mapbox
  47542. //
  47543. // Permission to use, copy, modify, and/or distribute this software for any purpose
  47544. // with or without fee is hereby granted, provided that the above copyright notice
  47545. // and this permission notice appear in all copies.
  47546. //
  47547. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  47548. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  47549. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  47550. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  47551. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  47552. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  47553. // THIS SOFTWARE.
  47554. var Earcut;
  47555. (function (Earcut) {
  47556. /**
  47557. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  47558. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  47559. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  47560. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  47561. */
  47562. function earcut(data, holeIndices, dim) {
  47563. dim = dim || 2;
  47564. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  47565. if (!outerNode)
  47566. return triangles;
  47567. var minX, minY, maxX, maxY, x, y, size;
  47568. if (hasHoles)
  47569. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  47570. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  47571. if (data.length > 80 * dim) {
  47572. minX = maxX = data[0];
  47573. minY = maxY = data[1];
  47574. for (var i = dim; i < outerLen; i += dim) {
  47575. x = data[i];
  47576. y = data[i + 1];
  47577. if (x < minX)
  47578. minX = x;
  47579. if (y < minY)
  47580. minY = y;
  47581. if (x > maxX)
  47582. maxX = x;
  47583. if (y > maxY)
  47584. maxY = y;
  47585. }
  47586. // minX, minY and size are later used to transform coords into integers for z-order calculation
  47587. size = Math.max(maxX - minX, maxY - minY);
  47588. }
  47589. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  47590. return triangles;
  47591. }
  47592. Earcut.earcut = earcut;
  47593. // create a circular doubly linked list from polygon points in the specified winding order
  47594. function linkedList(data, start, end, dim, clockwise) {
  47595. var i, last;
  47596. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  47597. for (i = start; i < end; i += dim)
  47598. last = insertNode(i, data[i], data[i + 1], last);
  47599. }
  47600. else {
  47601. for (i = end - dim; i >= start; i -= dim)
  47602. last = insertNode(i, data[i], data[i + 1], last);
  47603. }
  47604. if (last && equals(last, last.next)) {
  47605. removeNode(last);
  47606. last = last.next;
  47607. }
  47608. return last;
  47609. }
  47610. // eliminate colinear or duplicate points
  47611. function filterPoints(start, end) {
  47612. if (!start)
  47613. return start;
  47614. if (!end)
  47615. end = start;
  47616. var p = start, again;
  47617. do {
  47618. again = false;
  47619. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  47620. removeNode(p);
  47621. p = end = p.prev;
  47622. if (p === p.next)
  47623. return null;
  47624. again = true;
  47625. }
  47626. else {
  47627. p = p.next;
  47628. }
  47629. } while (again || p !== end);
  47630. return end;
  47631. }
  47632. // main ear slicing loop which triangulates a polygon (given as a linked list)
  47633. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  47634. if (!ear)
  47635. return;
  47636. // interlink polygon nodes in z-order
  47637. if (!pass && size)
  47638. indexCurve(ear, minX, minY, size);
  47639. var stop = ear, prev, next;
  47640. // iterate through ears, slicing them one by one
  47641. while (ear.prev !== ear.next) {
  47642. prev = ear.prev;
  47643. next = ear.next;
  47644. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  47645. // cut off the triangle
  47646. triangles.push(prev.i / dim);
  47647. triangles.push(ear.i / dim);
  47648. triangles.push(next.i / dim);
  47649. removeNode(ear);
  47650. // skipping the next vertice leads to less sliver triangles
  47651. ear = next.next;
  47652. stop = next.next;
  47653. continue;
  47654. }
  47655. ear = next;
  47656. // if we looped through the whole remaining polygon and can't find any more ears
  47657. if (ear === stop) {
  47658. // try filtering points and slicing again
  47659. if (!pass) {
  47660. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  47661. }
  47662. else if (pass === 1) {
  47663. ear = cureLocalIntersections(ear, triangles, dim);
  47664. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  47665. }
  47666. else if (pass === 2) {
  47667. splitEarcut(ear, triangles, dim, minX, minY, size);
  47668. }
  47669. break;
  47670. }
  47671. }
  47672. }
  47673. // check whether a polygon node forms a valid ear with adjacent nodes
  47674. function isEar(ear) {
  47675. var a = ear.prev, b = ear, c = ear.next;
  47676. if (area(a, b, c) >= 0)
  47677. return false; // reflex, can't be an ear
  47678. // now make sure we don't have other points inside the potential ear
  47679. var p = ear.next.next;
  47680. while (p !== ear.prev) {
  47681. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47682. area(p.prev, p, p.next) >= 0)
  47683. return false;
  47684. p = p.next;
  47685. }
  47686. return true;
  47687. }
  47688. function isEarHashed(ear, minX, minY, size) {
  47689. var a = ear.prev, b = ear, c = ear.next;
  47690. if (area(a, b, c) >= 0)
  47691. return false; // reflex, can't be an ear
  47692. // triangle bbox; min & max are calculated like this for speed
  47693. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  47694. // z-order range for the current triangle bbox;
  47695. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  47696. // first look for points inside the triangle in increasing z-order
  47697. var p = ear.nextZ;
  47698. while (p && p.z <= maxZ) {
  47699. if (p !== ear.prev &&
  47700. p !== ear.next &&
  47701. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47702. area(p.prev, p, p.next) >= 0)
  47703. return false;
  47704. p = p.nextZ;
  47705. }
  47706. // then look for points in decreasing z-order
  47707. p = ear.prevZ;
  47708. while (p && p.z >= minZ) {
  47709. if (p !== ear.prev &&
  47710. p !== ear.next &&
  47711. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47712. area(p.prev, p, p.next) >= 0)
  47713. return false;
  47714. p = p.prevZ;
  47715. }
  47716. return true;
  47717. }
  47718. // go through all polygon nodes and cure small local self-intersections
  47719. function cureLocalIntersections(start, triangles, dim) {
  47720. var p = start;
  47721. do {
  47722. var a = p.prev, b = p.next.next;
  47723. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  47724. triangles.push(a.i / dim);
  47725. triangles.push(p.i / dim);
  47726. triangles.push(b.i / dim);
  47727. // remove two nodes involved
  47728. removeNode(p);
  47729. removeNode(p.next);
  47730. p = start = b;
  47731. }
  47732. p = p.next;
  47733. } while (p !== start);
  47734. return p;
  47735. }
  47736. // try splitting polygon into two and triangulate them independently
  47737. function splitEarcut(start, triangles, dim, minX, minY, size) {
  47738. // look for a valid diagonal that divides the polygon into two
  47739. var a = start;
  47740. do {
  47741. var b = a.next.next;
  47742. while (b !== a.prev) {
  47743. if (a.i !== b.i && isValidDiagonal(a, b)) {
  47744. // split the polygon in two by the diagonal
  47745. var c = splitPolygon(a, b);
  47746. // filter colinear points around the cuts
  47747. a = filterPoints(a, a.next);
  47748. c = filterPoints(c, c.next);
  47749. // run earcut on each half
  47750. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  47751. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  47752. return;
  47753. }
  47754. b = b.next;
  47755. }
  47756. a = a.next;
  47757. } while (a !== start);
  47758. }
  47759. // link every hole into the outer loop, producing a single-ring polygon without holes
  47760. function eliminateHoles(data, holeIndices, outerNode, dim) {
  47761. var queue = [], i, len, start, end, list;
  47762. for (i = 0, len = holeIndices.length; i < len; i++) {
  47763. start = holeIndices[i] * dim;
  47764. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  47765. list = linkedList(data, start, end, dim, false);
  47766. if (list === list.next)
  47767. list.steiner = true;
  47768. queue.push(getLeftmost(list));
  47769. }
  47770. queue.sort(compareX);
  47771. // process holes from left to right
  47772. for (i = 0; i < queue.length; i++) {
  47773. eliminateHole(queue[i], outerNode);
  47774. outerNode = filterPoints(outerNode, outerNode.next);
  47775. }
  47776. return outerNode;
  47777. }
  47778. function compareX(a, b) {
  47779. return a.x - b.x;
  47780. }
  47781. // find a bridge between vertices that connects hole with an outer ring and and link it
  47782. function eliminateHole(hole, outerNode) {
  47783. outerNode = findHoleBridge(hole, outerNode);
  47784. if (outerNode) {
  47785. var b = splitPolygon(outerNode, hole);
  47786. filterPoints(b, b.next);
  47787. }
  47788. }
  47789. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  47790. function findHoleBridge(hole, outerNode) {
  47791. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  47792. // find a segment intersected by a ray from the hole's leftmost point to the left;
  47793. // segment's endpoint with lesser x will be potential connection point
  47794. do {
  47795. if (hy <= p.y && hy >= p.next.y) {
  47796. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  47797. if (x <= hx && x > qx) {
  47798. qx = x;
  47799. if (x === hx) {
  47800. if (hy === p.y)
  47801. return p;
  47802. if (hy === p.next.y)
  47803. return p.next;
  47804. }
  47805. m = p.x < p.next.x ? p : p.next;
  47806. }
  47807. }
  47808. p = p.next;
  47809. } while (p !== outerNode);
  47810. if (!m)
  47811. return null;
  47812. if (hx === qx)
  47813. return m.prev; // hole touches outer segment; pick lower endpoint
  47814. // look for points inside the triangle of hole point, segment intersection and endpoint;
  47815. // if there are no points found, we have a valid connection;
  47816. // otherwise choose the point of the minimum angle with the ray as connection point
  47817. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  47818. p = m.next;
  47819. while (p !== stop) {
  47820. if (hx >= p.x &&
  47821. p.x >= mx &&
  47822. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  47823. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  47824. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  47825. m = p;
  47826. tanMin = tan;
  47827. }
  47828. }
  47829. p = p.next;
  47830. }
  47831. return m;
  47832. }
  47833. // interlink polygon nodes in z-order
  47834. function indexCurve(start, minX, minY, size) {
  47835. var p = start;
  47836. do {
  47837. if (p.z === null)
  47838. p.z = zOrder(p.x, p.y, minX, minY, size);
  47839. p.prevZ = p.prev;
  47840. p.nextZ = p.next;
  47841. p = p.next;
  47842. } while (p !== start);
  47843. p.prevZ.nextZ = null;
  47844. p.prevZ = null;
  47845. sortLinked(p);
  47846. }
  47847. // Simon Tatham's linked list merge sort algorithm
  47848. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  47849. function sortLinked(list) {
  47850. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  47851. do {
  47852. p = list;
  47853. list = null;
  47854. tail = null;
  47855. numMerges = 0;
  47856. while (p) {
  47857. numMerges++;
  47858. q = p;
  47859. pSize = 0;
  47860. for (i = 0; i < inSize; i++) {
  47861. pSize++;
  47862. q = q.nextZ;
  47863. if (!q)
  47864. break;
  47865. }
  47866. qSize = inSize;
  47867. while (pSize > 0 || (qSize > 0 && q)) {
  47868. if (pSize === 0) {
  47869. e = q;
  47870. q = q.nextZ;
  47871. qSize--;
  47872. }
  47873. else if (qSize === 0 || !q) {
  47874. e = p;
  47875. p = p.nextZ;
  47876. pSize--;
  47877. }
  47878. else if (p.z <= q.z) {
  47879. e = p;
  47880. p = p.nextZ;
  47881. pSize--;
  47882. }
  47883. else {
  47884. e = q;
  47885. q = q.nextZ;
  47886. qSize--;
  47887. }
  47888. if (tail)
  47889. tail.nextZ = e;
  47890. else
  47891. list = e;
  47892. e.prevZ = tail;
  47893. tail = e;
  47894. }
  47895. p = q;
  47896. }
  47897. tail.nextZ = null;
  47898. inSize *= 2;
  47899. } while (numMerges > 1);
  47900. return list;
  47901. }
  47902. // z-order of a point given coords and size of the data bounding box
  47903. function zOrder(x, y, minX, minY, size) {
  47904. // coords are transformed into non-negative 15-bit integer range
  47905. x = 32767 * (x - minX) / size;
  47906. y = 32767 * (y - minY) / size;
  47907. x = (x | (x << 8)) & 0x00FF00FF;
  47908. x = (x | (x << 4)) & 0x0F0F0F0F;
  47909. x = (x | (x << 2)) & 0x33333333;
  47910. x = (x | (x << 1)) & 0x55555555;
  47911. y = (y | (y << 8)) & 0x00FF00FF;
  47912. y = (y | (y << 4)) & 0x0F0F0F0F;
  47913. y = (y | (y << 2)) & 0x33333333;
  47914. y = (y | (y << 1)) & 0x55555555;
  47915. return x | (y << 1);
  47916. }
  47917. // find the leftmost node of a polygon ring
  47918. function getLeftmost(start) {
  47919. var p = start, leftmost = start;
  47920. do {
  47921. if (p.x < leftmost.x)
  47922. leftmost = p;
  47923. p = p.next;
  47924. } while (p !== start);
  47925. return leftmost;
  47926. }
  47927. // check if a point lies within a convex triangle
  47928. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  47929. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  47930. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  47931. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  47932. }
  47933. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  47934. function isValidDiagonal(a, b) {
  47935. return a.next.i !== b.i &&
  47936. a.prev.i !== b.i &&
  47937. !intersectsPolygon(a, b) &&
  47938. locallyInside(a, b) &&
  47939. locallyInside(b, a) &&
  47940. middleInside(a, b);
  47941. }
  47942. // signed area of a triangle
  47943. function area(p, q, r) {
  47944. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  47945. }
  47946. // check if two points are equal
  47947. function equals(p1, p2) {
  47948. return p1.x === p2.x && p1.y === p2.y;
  47949. }
  47950. // check if two segments intersect
  47951. function intersects(p1, q1, p2, q2) {
  47952. if ((equals(p1, q1) && equals(p2, q2)) ||
  47953. (equals(p1, q2) && equals(p2, q1)))
  47954. return true;
  47955. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  47956. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  47957. }
  47958. // check if a polygon diagonal intersects any polygon segments
  47959. function intersectsPolygon(a, b) {
  47960. var p = a;
  47961. do {
  47962. if (p.i !== a.i &&
  47963. p.next.i !== a.i &&
  47964. p.i !== b.i &&
  47965. p.next.i !== b.i &&
  47966. intersects(p, p.next, a, b))
  47967. return true;
  47968. p = p.next;
  47969. } while (p !== a);
  47970. return false;
  47971. }
  47972. // check if a polygon diagonal is locally inside the polygon
  47973. function locallyInside(a, b) {
  47974. return area(a.prev, a, a.next) < 0
  47975. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  47976. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  47977. }
  47978. // check if the middle point of a polygon diagonal is inside the polygon
  47979. function middleInside(a, b) {
  47980. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  47981. do {
  47982. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  47983. inside = !inside;
  47984. p = p.next;
  47985. } while (p !== a);
  47986. return inside;
  47987. }
  47988. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  47989. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  47990. function splitPolygon(a, b) {
  47991. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  47992. a.next = b;
  47993. b.prev = a;
  47994. a2.next = an;
  47995. an.prev = a2;
  47996. b2.next = a2;
  47997. a2.prev = b2;
  47998. bp.next = b2;
  47999. b2.prev = bp;
  48000. return b2;
  48001. }
  48002. // create a node and optionally link it with previous one (in a circular doubly linked list)
  48003. function insertNode(i, x, y, last) {
  48004. var p = new Node(i, x, y);
  48005. if (!last) {
  48006. p.prev = p;
  48007. p.next = p;
  48008. }
  48009. else {
  48010. p.next = last.next;
  48011. p.prev = last;
  48012. last.next.prev = p;
  48013. last.next = p;
  48014. }
  48015. return p;
  48016. }
  48017. function removeNode(p) {
  48018. p.next.prev = p.prev;
  48019. p.prev.next = p.next;
  48020. if (p.prevZ)
  48021. p.prevZ.nextZ = p.nextZ;
  48022. if (p.nextZ)
  48023. p.nextZ.prevZ = p.prevZ;
  48024. }
  48025. function Node(i, x, y) {
  48026. // vertice index in coordinates array
  48027. this.i = i;
  48028. // vertex coordinates
  48029. this.x = x;
  48030. this.y = y;
  48031. // previous and next vertice nodes in a polygon ring
  48032. this.prev = null;
  48033. this.next = null;
  48034. // z-order curve value
  48035. this.z = null;
  48036. // previous and next nodes in z-order
  48037. this.prevZ = null;
  48038. this.nextZ = null;
  48039. // indicates whether this is a steiner point
  48040. this.steiner = false;
  48041. }
  48042. /**
  48043. * return a percentage difference between the polygon area and its triangulation area;
  48044. * used to verify correctness of triangulation
  48045. */
  48046. function deviation(data, holeIndices, dim, triangles) {
  48047. var hasHoles = holeIndices && holeIndices.length;
  48048. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  48049. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  48050. if (hasHoles) {
  48051. for (var i = 0, len = holeIndices.length; i < len; i++) {
  48052. var start = holeIndices[i] * dim;
  48053. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  48054. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  48055. }
  48056. }
  48057. var trianglesArea = 0;
  48058. for (i = 0; i < triangles.length; i += 3) {
  48059. var a = triangles[i] * dim;
  48060. var b = triangles[i + 1] * dim;
  48061. var c = triangles[i + 2] * dim;
  48062. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  48063. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  48064. }
  48065. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  48066. }
  48067. Earcut.deviation = deviation;
  48068. ;
  48069. function signedArea(data, start, end, dim) {
  48070. var sum = 0;
  48071. for (var i = start, j = end - dim; i < end; i += dim) {
  48072. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  48073. j = i;
  48074. }
  48075. return sum;
  48076. }
  48077. /**
  48078. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  48079. */
  48080. function flatten(data) {
  48081. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  48082. for (var i = 0; i < data.length; i++) {
  48083. for (var j = 0; j < data[i].length; j++) {
  48084. for (var d = 0; d < dim; d++)
  48085. result.vertices.push(data[i][j][d]);
  48086. }
  48087. if (i > 0) {
  48088. holeIndex += data[i - 1].length;
  48089. result.holes.push(holeIndex);
  48090. }
  48091. }
  48092. return result;
  48093. }
  48094. Earcut.flatten = flatten;
  48095. ;
  48096. })(Earcut || (Earcut = {}));
  48097. var BABYLON;
  48098. (function (BABYLON) {
  48099. // Unique ID when we import meshes from Babylon to CSG
  48100. var currentCSGMeshId = 0;
  48101. // # class Vertex
  48102. // Represents a vertex of a polygon. Use your own vertex class instead of this
  48103. // one to provide additional features like texture coordinates and vertex
  48104. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  48105. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  48106. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  48107. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  48108. // is not used anywhere else.
  48109. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  48110. var Vertex = (function () {
  48111. function Vertex(pos, normal, uv) {
  48112. this.pos = pos;
  48113. this.normal = normal;
  48114. this.uv = uv;
  48115. }
  48116. Vertex.prototype.clone = function () {
  48117. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  48118. };
  48119. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  48120. // orientation of a polygon is flipped.
  48121. Vertex.prototype.flip = function () {
  48122. this.normal = this.normal.scale(-1);
  48123. };
  48124. // Create a new vertex between this vertex and `other` by linearly
  48125. // interpolating all properties using a parameter of `t`. Subclasses should
  48126. // override this to interpolate additional properties.
  48127. Vertex.prototype.interpolate = function (other, t) {
  48128. return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t));
  48129. };
  48130. return Vertex;
  48131. })();
  48132. // # class Plane
  48133. // Represents a plane in 3D space.
  48134. var Plane = (function () {
  48135. function Plane(normal, w) {
  48136. this.normal = normal;
  48137. this.w = w;
  48138. }
  48139. Plane.FromPoints = function (a, b, c) {
  48140. var v0 = c.subtract(a);
  48141. var v1 = b.subtract(a);
  48142. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  48143. return null;
  48144. }
  48145. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  48146. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  48147. };
  48148. Plane.prototype.clone = function () {
  48149. return new Plane(this.normal.clone(), this.w);
  48150. };
  48151. Plane.prototype.flip = function () {
  48152. this.normal.scaleInPlace(-1);
  48153. this.w = -this.w;
  48154. };
  48155. // Split `polygon` by this plane if needed, then put the polygon or polygon
  48156. // fragments in the appropriate lists. Coplanar polygons go into either
  48157. // `coplanarFront` or `coplanarBack` depending on their orientation with
  48158. // respect to this plane. Polygons in front or in back of this plane go into
  48159. // either `front` or `back`.
  48160. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  48161. var COPLANAR = 0;
  48162. var FRONT = 1;
  48163. var BACK = 2;
  48164. var SPANNING = 3;
  48165. // Classify each point as well as the entire polygon into one of the above
  48166. // four classes.
  48167. var polygonType = 0;
  48168. var types = [];
  48169. var i;
  48170. var t;
  48171. for (i = 0; i < polygon.vertices.length; i++) {
  48172. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  48173. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  48174. polygonType |= type;
  48175. types.push(type);
  48176. }
  48177. // Put the polygon in the correct list, splitting it when necessary.
  48178. switch (polygonType) {
  48179. case COPLANAR:
  48180. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  48181. break;
  48182. case FRONT:
  48183. front.push(polygon);
  48184. break;
  48185. case BACK:
  48186. back.push(polygon);
  48187. break;
  48188. case SPANNING:
  48189. var f = [], b = [];
  48190. for (i = 0; i < polygon.vertices.length; i++) {
  48191. var j = (i + 1) % polygon.vertices.length;
  48192. var ti = types[i], tj = types[j];
  48193. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  48194. if (ti !== BACK)
  48195. f.push(vi);
  48196. if (ti !== FRONT)
  48197. b.push(ti !== BACK ? vi.clone() : vi);
  48198. if ((ti | tj) === SPANNING) {
  48199. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  48200. var v = vi.interpolate(vj, t);
  48201. f.push(v);
  48202. b.push(v.clone());
  48203. }
  48204. }
  48205. var poly;
  48206. if (f.length >= 3) {
  48207. poly = new Polygon(f, polygon.shared);
  48208. if (poly.plane)
  48209. front.push(poly);
  48210. }
  48211. if (b.length >= 3) {
  48212. poly = new Polygon(b, polygon.shared);
  48213. if (poly.plane)
  48214. back.push(poly);
  48215. }
  48216. break;
  48217. }
  48218. };
  48219. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  48220. // point is on the plane.
  48221. Plane.EPSILON = 1e-5;
  48222. return Plane;
  48223. })();
  48224. // # class Polygon
  48225. // Represents a convex polygon. The vertices used to initialize a polygon must
  48226. // be coplanar and form a convex loop.
  48227. //
  48228. // Each convex polygon has a `shared` property, which is shared between all
  48229. // polygons that are clones of each other or were split from the same polygon.
  48230. // This can be used to define per-polygon properties (such as surface color).
  48231. var Polygon = (function () {
  48232. function Polygon(vertices, shared) {
  48233. this.vertices = vertices;
  48234. this.shared = shared;
  48235. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  48236. }
  48237. Polygon.prototype.clone = function () {
  48238. var vertices = this.vertices.map(function (v) { return v.clone(); });
  48239. return new Polygon(vertices, this.shared);
  48240. };
  48241. Polygon.prototype.flip = function () {
  48242. this.vertices.reverse().map(function (v) { v.flip(); });
  48243. this.plane.flip();
  48244. };
  48245. return Polygon;
  48246. })();
  48247. // # class Node
  48248. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  48249. // by picking a polygon to split along. That polygon (and all other coplanar
  48250. // polygons) are added directly to that node and the other polygons are added to
  48251. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  48252. // no distinction between internal and leaf nodes.
  48253. var Node = (function () {
  48254. function Node(polygons) {
  48255. this.plane = null;
  48256. this.front = null;
  48257. this.back = null;
  48258. this.polygons = [];
  48259. if (polygons) {
  48260. this.build(polygons);
  48261. }
  48262. }
  48263. Node.prototype.clone = function () {
  48264. var node = new Node();
  48265. node.plane = this.plane && this.plane.clone();
  48266. node.front = this.front && this.front.clone();
  48267. node.back = this.back && this.back.clone();
  48268. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  48269. return node;
  48270. };
  48271. // Convert solid space to empty space and empty space to solid space.
  48272. Node.prototype.invert = function () {
  48273. for (var i = 0; i < this.polygons.length; i++) {
  48274. this.polygons[i].flip();
  48275. }
  48276. if (this.plane) {
  48277. this.plane.flip();
  48278. }
  48279. if (this.front) {
  48280. this.front.invert();
  48281. }
  48282. if (this.back) {
  48283. this.back.invert();
  48284. }
  48285. var temp = this.front;
  48286. this.front = this.back;
  48287. this.back = temp;
  48288. };
  48289. // Recursively remove all polygons in `polygons` that are inside this BSP
  48290. // tree.
  48291. Node.prototype.clipPolygons = function (polygons) {
  48292. if (!this.plane)
  48293. return polygons.slice();
  48294. var front = [], back = [];
  48295. for (var i = 0; i < polygons.length; i++) {
  48296. this.plane.splitPolygon(polygons[i], front, back, front, back);
  48297. }
  48298. if (this.front) {
  48299. front = this.front.clipPolygons(front);
  48300. }
  48301. if (this.back) {
  48302. back = this.back.clipPolygons(back);
  48303. }
  48304. else {
  48305. back = [];
  48306. }
  48307. return front.concat(back);
  48308. };
  48309. // Remove all polygons in this BSP tree that are inside the other BSP tree
  48310. // `bsp`.
  48311. Node.prototype.clipTo = function (bsp) {
  48312. this.polygons = bsp.clipPolygons(this.polygons);
  48313. if (this.front)
  48314. this.front.clipTo(bsp);
  48315. if (this.back)
  48316. this.back.clipTo(bsp);
  48317. };
  48318. // Return a list of all polygons in this BSP tree.
  48319. Node.prototype.allPolygons = function () {
  48320. var polygons = this.polygons.slice();
  48321. if (this.front)
  48322. polygons = polygons.concat(this.front.allPolygons());
  48323. if (this.back)
  48324. polygons = polygons.concat(this.back.allPolygons());
  48325. return polygons;
  48326. };
  48327. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  48328. // new polygons are filtered down to the bottom of the tree and become new
  48329. // nodes there. Each set of polygons is partitioned using the first polygon
  48330. // (no heuristic is used to pick a good split).
  48331. Node.prototype.build = function (polygons) {
  48332. if (!polygons.length)
  48333. return;
  48334. if (!this.plane)
  48335. this.plane = polygons[0].plane.clone();
  48336. var front = [], back = [];
  48337. for (var i = 0; i < polygons.length; i++) {
  48338. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  48339. }
  48340. if (front.length) {
  48341. if (!this.front)
  48342. this.front = new Node();
  48343. this.front.build(front);
  48344. }
  48345. if (back.length) {
  48346. if (!this.back)
  48347. this.back = new Node();
  48348. this.back.build(back);
  48349. }
  48350. };
  48351. return Node;
  48352. })();
  48353. var CSG = (function () {
  48354. function CSG() {
  48355. this.polygons = new Array();
  48356. }
  48357. // Convert BABYLON.Mesh to BABYLON.CSG
  48358. CSG.FromMesh = function (mesh) {
  48359. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  48360. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  48361. if (mesh instanceof BABYLON.Mesh) {
  48362. mesh.computeWorldMatrix(true);
  48363. matrix = mesh.getWorldMatrix();
  48364. meshPosition = mesh.position.clone();
  48365. meshRotation = mesh.rotation.clone();
  48366. if (mesh.rotationQuaternion) {
  48367. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  48368. }
  48369. meshScaling = mesh.scaling.clone();
  48370. }
  48371. else {
  48372. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  48373. }
  48374. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48375. var subMeshes = mesh.subMeshes;
  48376. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  48377. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  48378. vertices = [];
  48379. for (var j = 0; j < 3; j++) {
  48380. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  48381. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  48382. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  48383. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  48384. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  48385. vertex = new Vertex(position, normal, uv);
  48386. vertices.push(vertex);
  48387. }
  48388. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  48389. // To handle the case of degenerated triangle
  48390. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  48391. if (polygon.plane)
  48392. polygons.push(polygon);
  48393. }
  48394. }
  48395. var csg = CSG.FromPolygons(polygons);
  48396. csg.matrix = matrix;
  48397. csg.position = meshPosition;
  48398. csg.rotation = meshRotation;
  48399. csg.scaling = meshScaling;
  48400. csg.rotationQuaternion = meshRotationQuaternion;
  48401. currentCSGMeshId++;
  48402. return csg;
  48403. };
  48404. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  48405. CSG.FromPolygons = function (polygons) {
  48406. var csg = new CSG();
  48407. csg.polygons = polygons;
  48408. return csg;
  48409. };
  48410. CSG.prototype.clone = function () {
  48411. var csg = new CSG();
  48412. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  48413. csg.copyTransformAttributes(this);
  48414. return csg;
  48415. };
  48416. CSG.prototype.toPolygons = function () {
  48417. return this.polygons;
  48418. };
  48419. CSG.prototype.union = function (csg) {
  48420. var a = new Node(this.clone().polygons);
  48421. var b = new Node(csg.clone().polygons);
  48422. a.clipTo(b);
  48423. b.clipTo(a);
  48424. b.invert();
  48425. b.clipTo(a);
  48426. b.invert();
  48427. a.build(b.allPolygons());
  48428. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48429. };
  48430. CSG.prototype.unionInPlace = function (csg) {
  48431. var a = new Node(this.polygons);
  48432. var b = new Node(csg.polygons);
  48433. a.clipTo(b);
  48434. b.clipTo(a);
  48435. b.invert();
  48436. b.clipTo(a);
  48437. b.invert();
  48438. a.build(b.allPolygons());
  48439. this.polygons = a.allPolygons();
  48440. };
  48441. CSG.prototype.subtract = function (csg) {
  48442. var a = new Node(this.clone().polygons);
  48443. var b = new Node(csg.clone().polygons);
  48444. a.invert();
  48445. a.clipTo(b);
  48446. b.clipTo(a);
  48447. b.invert();
  48448. b.clipTo(a);
  48449. b.invert();
  48450. a.build(b.allPolygons());
  48451. a.invert();
  48452. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48453. };
  48454. CSG.prototype.subtractInPlace = function (csg) {
  48455. var a = new Node(this.polygons);
  48456. var b = new Node(csg.polygons);
  48457. a.invert();
  48458. a.clipTo(b);
  48459. b.clipTo(a);
  48460. b.invert();
  48461. b.clipTo(a);
  48462. b.invert();
  48463. a.build(b.allPolygons());
  48464. a.invert();
  48465. this.polygons = a.allPolygons();
  48466. };
  48467. CSG.prototype.intersect = function (csg) {
  48468. var a = new Node(this.clone().polygons);
  48469. var b = new Node(csg.clone().polygons);
  48470. a.invert();
  48471. b.clipTo(a);
  48472. b.invert();
  48473. a.clipTo(b);
  48474. b.clipTo(a);
  48475. a.build(b.allPolygons());
  48476. a.invert();
  48477. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48478. };
  48479. CSG.prototype.intersectInPlace = function (csg) {
  48480. var a = new Node(this.polygons);
  48481. var b = new Node(csg.polygons);
  48482. a.invert();
  48483. b.clipTo(a);
  48484. b.invert();
  48485. a.clipTo(b);
  48486. b.clipTo(a);
  48487. a.build(b.allPolygons());
  48488. a.invert();
  48489. this.polygons = a.allPolygons();
  48490. };
  48491. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  48492. // not modified.
  48493. CSG.prototype.inverse = function () {
  48494. var csg = this.clone();
  48495. csg.inverseInPlace();
  48496. return csg;
  48497. };
  48498. CSG.prototype.inverseInPlace = function () {
  48499. this.polygons.map(function (p) { p.flip(); });
  48500. };
  48501. // This is used to keep meshes transformations so they can be restored
  48502. // when we build back a Babylon Mesh
  48503. // NB : All CSG operations are performed in world coordinates
  48504. CSG.prototype.copyTransformAttributes = function (csg) {
  48505. this.matrix = csg.matrix;
  48506. this.position = csg.position;
  48507. this.rotation = csg.rotation;
  48508. this.scaling = csg.scaling;
  48509. this.rotationQuaternion = csg.rotationQuaternion;
  48510. return this;
  48511. };
  48512. // Build Raw mesh from CSG
  48513. // Coordinates here are in world space
  48514. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  48515. var matrix = this.matrix.clone();
  48516. matrix.invert();
  48517. var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;
  48518. if (keepSubMeshes) {
  48519. // Sort Polygons, since subMeshes are indices range
  48520. polygons.sort(function (a, b) {
  48521. if (a.shared.meshId === b.shared.meshId) {
  48522. return a.shared.subMeshId - b.shared.subMeshId;
  48523. }
  48524. else {
  48525. return a.shared.meshId - b.shared.meshId;
  48526. }
  48527. });
  48528. }
  48529. for (var i = 0, il = polygons.length; i < il; i++) {
  48530. polygon = polygons[i];
  48531. // Building SubMeshes
  48532. if (!subMesh_dict[polygon.shared.meshId]) {
  48533. subMesh_dict[polygon.shared.meshId] = {};
  48534. }
  48535. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  48536. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  48537. indexStart: +Infinity,
  48538. indexEnd: -Infinity,
  48539. materialIndex: polygon.shared.materialIndex
  48540. };
  48541. }
  48542. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  48543. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  48544. polygonIndices[0] = 0;
  48545. polygonIndices[1] = j - 1;
  48546. polygonIndices[2] = j;
  48547. for (var k = 0; k < 3; k++) {
  48548. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  48549. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  48550. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  48551. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  48552. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  48553. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  48554. // Check if 2 points can be merged
  48555. if (!(typeof vertex_idx !== 'undefined' &&
  48556. normals[vertex_idx * 3] === localNormal.x &&
  48557. normals[vertex_idx * 3 + 1] === localNormal.y &&
  48558. normals[vertex_idx * 3 + 2] === localNormal.z &&
  48559. uvs[vertex_idx * 2] === uv.x &&
  48560. uvs[vertex_idx * 2 + 1] === uv.y)) {
  48561. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  48562. uvs.push(uv.x, uv.y);
  48563. normals.push(normal.x, normal.y, normal.z);
  48564. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  48565. }
  48566. indices.push(vertex_idx);
  48567. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  48568. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  48569. currentIndex++;
  48570. }
  48571. }
  48572. }
  48573. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  48574. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  48575. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  48576. mesh.setIndices(indices);
  48577. if (keepSubMeshes) {
  48578. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  48579. var materialIndexOffset = 0, materialMaxIndex;
  48580. mesh.subMeshes = new Array();
  48581. for (var m in subMesh_dict) {
  48582. materialMaxIndex = -1;
  48583. for (var sm in subMesh_dict[m]) {
  48584. subMesh_obj = subMesh_dict[m][sm];
  48585. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  48586. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  48587. }
  48588. materialIndexOffset += ++materialMaxIndex;
  48589. }
  48590. }
  48591. return mesh;
  48592. };
  48593. // Build Mesh from CSG taking material and transforms into account
  48594. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  48595. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  48596. mesh.material = material;
  48597. mesh.position.copyFrom(this.position);
  48598. mesh.rotation.copyFrom(this.rotation);
  48599. if (this.rotationQuaternion) {
  48600. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  48601. }
  48602. mesh.scaling.copyFrom(this.scaling);
  48603. mesh.computeWorldMatrix(true);
  48604. return mesh;
  48605. };
  48606. return CSG;
  48607. })();
  48608. BABYLON.CSG = CSG;
  48609. })(BABYLON || (BABYLON = {}));
  48610. var BABYLON;
  48611. (function (BABYLON) {
  48612. var VRDistortionCorrectionPostProcess = (function (_super) {
  48613. __extends(VRDistortionCorrectionPostProcess, _super);
  48614. //ANY
  48615. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  48616. var _this = this;
  48617. _super.call(this, name, "vrDistortionCorrection", [
  48618. 'LensCenter',
  48619. 'Scale',
  48620. 'ScaleIn',
  48621. 'HmdWarpParam'
  48622. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  48623. this._isRightEye = isRightEye;
  48624. this._distortionFactors = vrMetrics.distortionK;
  48625. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  48626. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  48627. this.onSizeChangedObservable.add(function () {
  48628. _this.aspectRatio = _this.width * .5 / _this.height;
  48629. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  48630. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  48631. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  48632. });
  48633. this.onApplyObservable.add(function (effect) {
  48634. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  48635. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  48636. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  48637. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  48638. });
  48639. }
  48640. return VRDistortionCorrectionPostProcess;
  48641. })(BABYLON.PostProcess);
  48642. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  48643. })(BABYLON || (BABYLON = {}));
  48644. // Mainly based on these 2 articles :
  48645. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  48646. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  48647. var BABYLON;
  48648. (function (BABYLON) {
  48649. (function (JoystickAxis) {
  48650. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  48651. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  48652. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  48653. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  48654. var JoystickAxis = BABYLON.JoystickAxis;
  48655. var VirtualJoystick = (function () {
  48656. function VirtualJoystick(leftJoystick) {
  48657. var _this = this;
  48658. if (leftJoystick) {
  48659. this._leftJoystick = true;
  48660. }
  48661. else {
  48662. this._leftJoystick = false;
  48663. }
  48664. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  48665. VirtualJoystick._globalJoystickIndex++;
  48666. // By default left & right arrow keys are moving the X
  48667. // and up & down keys are moving the Y
  48668. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  48669. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  48670. this.reverseLeftRight = false;
  48671. this.reverseUpDown = false;
  48672. // collections of pointers
  48673. this._touches = new BABYLON.StringDictionary();
  48674. this.deltaPosition = BABYLON.Vector3.Zero();
  48675. this._joystickSensibility = 25;
  48676. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  48677. this._rotationSpeed = 25;
  48678. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  48679. this._rotateOnAxisRelativeToMesh = false;
  48680. this._onResize = function (evt) {
  48681. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  48682. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  48683. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  48684. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  48685. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  48686. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  48687. };
  48688. // injecting a canvas element on top of the canvas 3D game
  48689. if (!VirtualJoystick.vjCanvas) {
  48690. window.addEventListener("resize", this._onResize, false);
  48691. VirtualJoystick.vjCanvas = document.createElement("canvas");
  48692. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  48693. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  48694. VirtualJoystick.vjCanvas.width = window.innerWidth;
  48695. VirtualJoystick.vjCanvas.height = window.innerHeight;
  48696. VirtualJoystick.vjCanvas.style.width = "100%";
  48697. VirtualJoystick.vjCanvas.style.height = "100%";
  48698. VirtualJoystick.vjCanvas.style.position = "absolute";
  48699. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  48700. VirtualJoystick.vjCanvas.style.top = "0px";
  48701. VirtualJoystick.vjCanvas.style.left = "0px";
  48702. VirtualJoystick.vjCanvas.style.zIndex = "5";
  48703. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  48704. // Support for jQuery PEP polyfill
  48705. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  48706. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  48707. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  48708. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  48709. document.body.appendChild(VirtualJoystick.vjCanvas);
  48710. }
  48711. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  48712. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  48713. this.pressed = false;
  48714. // default joystick color
  48715. this._joystickColor = "cyan";
  48716. this._joystickPointerID = -1;
  48717. // current joystick position
  48718. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  48719. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  48720. // origin joystick position
  48721. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  48722. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  48723. this._onPointerDownHandlerRef = function (evt) {
  48724. _this._onPointerDown(evt);
  48725. };
  48726. this._onPointerMoveHandlerRef = function (evt) {
  48727. _this._onPointerMove(evt);
  48728. };
  48729. this._onPointerOutHandlerRef = function (evt) {
  48730. _this._onPointerUp(evt);
  48731. };
  48732. this._onPointerUpHandlerRef = function (evt) {
  48733. _this._onPointerUp(evt);
  48734. };
  48735. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  48736. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  48737. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  48738. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  48739. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  48740. evt.preventDefault(); // Disables system menu
  48741. }, false);
  48742. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  48743. }
  48744. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  48745. this._joystickSensibility = newJoystickSensibility;
  48746. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  48747. };
  48748. VirtualJoystick.prototype._onPointerDown = function (e) {
  48749. var positionOnScreenCondition;
  48750. e.preventDefault();
  48751. if (this._leftJoystick === true) {
  48752. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  48753. }
  48754. else {
  48755. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  48756. }
  48757. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  48758. // First contact will be dedicated to the virtual joystick
  48759. this._joystickPointerID = e.pointerId;
  48760. this._joystickPointerStartPos.x = e.clientX;
  48761. this._joystickPointerStartPos.y = e.clientY;
  48762. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  48763. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  48764. this._deltaJoystickVector.x = 0;
  48765. this._deltaJoystickVector.y = 0;
  48766. this.pressed = true;
  48767. this._touches.add(e.pointerId.toString(), e);
  48768. }
  48769. else {
  48770. // You can only trigger the action buttons with a joystick declared
  48771. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  48772. this._action();
  48773. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  48774. }
  48775. }
  48776. };
  48777. VirtualJoystick.prototype._onPointerMove = function (e) {
  48778. // If the current pointer is the one associated to the joystick (first touch contact)
  48779. if (this._joystickPointerID == e.pointerId) {
  48780. this._joystickPointerPos.x = e.clientX;
  48781. this._joystickPointerPos.y = e.clientY;
  48782. this._deltaJoystickVector = this._joystickPointerPos.clone();
  48783. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  48784. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  48785. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  48786. switch (this._axisTargetedByLeftAndRight) {
  48787. case JoystickAxis.X:
  48788. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  48789. break;
  48790. case JoystickAxis.Y:
  48791. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  48792. break;
  48793. case JoystickAxis.Z:
  48794. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  48795. break;
  48796. }
  48797. var directionUpDown = this.reverseUpDown ? 1 : -1;
  48798. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  48799. switch (this._axisTargetedByUpAndDown) {
  48800. case JoystickAxis.X:
  48801. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  48802. break;
  48803. case JoystickAxis.Y:
  48804. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  48805. break;
  48806. case JoystickAxis.Z:
  48807. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  48808. break;
  48809. }
  48810. }
  48811. else {
  48812. var data = this._touches.get(e.pointerId.toString());
  48813. if (data) {
  48814. data.x = e.clientX;
  48815. data.y = e.clientY;
  48816. }
  48817. }
  48818. };
  48819. VirtualJoystick.prototype._onPointerUp = function (e) {
  48820. if (this._joystickPointerID == e.pointerId) {
  48821. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  48822. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  48823. this._joystickPointerID = -1;
  48824. this.pressed = false;
  48825. }
  48826. else {
  48827. var touch = this._touches.get(e.pointerId.toString());
  48828. if (touch) {
  48829. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  48830. }
  48831. }
  48832. this._deltaJoystickVector.x = 0;
  48833. this._deltaJoystickVector.y = 0;
  48834. this._touches.remove(e.pointerId.toString());
  48835. };
  48836. /**
  48837. * Change the color of the virtual joystick
  48838. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  48839. */
  48840. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  48841. this._joystickColor = newColor;
  48842. };
  48843. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  48844. this._action = action;
  48845. };
  48846. // Define which axis you'd like to control for left & right
  48847. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  48848. switch (axis) {
  48849. case JoystickAxis.X:
  48850. case JoystickAxis.Y:
  48851. case JoystickAxis.Z:
  48852. this._axisTargetedByLeftAndRight = axis;
  48853. break;
  48854. default:
  48855. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  48856. break;
  48857. }
  48858. };
  48859. // Define which axis you'd like to control for up & down
  48860. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  48861. switch (axis) {
  48862. case JoystickAxis.X:
  48863. case JoystickAxis.Y:
  48864. case JoystickAxis.Z:
  48865. this._axisTargetedByUpAndDown = axis;
  48866. break;
  48867. default:
  48868. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  48869. break;
  48870. }
  48871. };
  48872. VirtualJoystick.prototype._clearCanvas = function () {
  48873. if (this._leftJoystick) {
  48874. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  48875. }
  48876. else {
  48877. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  48878. }
  48879. };
  48880. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  48881. var _this = this;
  48882. if (this.pressed) {
  48883. this._touches.forEach(function (touch) {
  48884. if (touch.pointerId === _this._joystickPointerID) {
  48885. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  48886. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  48887. VirtualJoystick.vjCanvasContext.beginPath();
  48888. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  48889. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48890. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  48891. VirtualJoystick.vjCanvasContext.stroke();
  48892. VirtualJoystick.vjCanvasContext.closePath();
  48893. VirtualJoystick.vjCanvasContext.beginPath();
  48894. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48895. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  48896. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  48897. VirtualJoystick.vjCanvasContext.stroke();
  48898. VirtualJoystick.vjCanvasContext.closePath();
  48899. VirtualJoystick.vjCanvasContext.beginPath();
  48900. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48901. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  48902. VirtualJoystick.vjCanvasContext.stroke();
  48903. VirtualJoystick.vjCanvasContext.closePath();
  48904. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  48905. }
  48906. else {
  48907. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  48908. VirtualJoystick.vjCanvasContext.beginPath();
  48909. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  48910. VirtualJoystick.vjCanvasContext.beginPath();
  48911. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  48912. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  48913. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  48914. VirtualJoystick.vjCanvasContext.stroke();
  48915. VirtualJoystick.vjCanvasContext.closePath();
  48916. touch.prevX = touch.x;
  48917. touch.prevY = touch.y;
  48918. }
  48919. ;
  48920. });
  48921. }
  48922. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  48923. };
  48924. VirtualJoystick.prototype.releaseCanvas = function () {
  48925. if (VirtualJoystick.vjCanvas) {
  48926. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  48927. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  48928. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  48929. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  48930. window.removeEventListener("resize", this._onResize);
  48931. document.body.removeChild(VirtualJoystick.vjCanvas);
  48932. VirtualJoystick.vjCanvas = null;
  48933. }
  48934. };
  48935. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  48936. VirtualJoystick._globalJoystickIndex = 0;
  48937. return VirtualJoystick;
  48938. })();
  48939. BABYLON.VirtualJoystick = VirtualJoystick;
  48940. })(BABYLON || (BABYLON = {}));
  48941. var BABYLON;
  48942. (function (BABYLON) {
  48943. // We're mainly based on the logic defined into the FreeCamera code
  48944. var VirtualJoysticksCamera = (function (_super) {
  48945. __extends(VirtualJoysticksCamera, _super);
  48946. function VirtualJoysticksCamera(name, position, scene) {
  48947. _super.call(this, name, position, scene);
  48948. this.inputs.addVirtualJoystick();
  48949. }
  48950. return VirtualJoysticksCamera;
  48951. })(BABYLON.FreeCamera);
  48952. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  48953. })(BABYLON || (BABYLON = {}));
  48954. var BABYLON;
  48955. (function (BABYLON) {
  48956. var FreeCameraVirtualJoystickInput = (function () {
  48957. function FreeCameraVirtualJoystickInput() {
  48958. }
  48959. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  48960. return this._leftjoystick;
  48961. };
  48962. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  48963. return this._rightjoystick;
  48964. };
  48965. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  48966. if (this._leftjoystick) {
  48967. var camera = this.camera;
  48968. var speed = camera._computeLocalCameraSpeed() * 50;
  48969. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  48970. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  48971. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  48972. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  48973. if (!this._leftjoystick.pressed) {
  48974. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  48975. }
  48976. if (!this._rightjoystick.pressed) {
  48977. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  48978. }
  48979. }
  48980. };
  48981. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  48982. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  48983. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  48984. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  48985. this._leftjoystick.setJoystickSensibility(0.15);
  48986. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  48987. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  48988. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  48989. this._rightjoystick.reverseUpDown = true;
  48990. this._rightjoystick.setJoystickSensibility(0.05);
  48991. this._rightjoystick.setJoystickColor("yellow");
  48992. };
  48993. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  48994. this._leftjoystick.releaseCanvas();
  48995. this._rightjoystick.releaseCanvas();
  48996. };
  48997. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  48998. return "FreeCameraVirtualJoystickInput";
  48999. };
  49000. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  49001. return "virtualJoystick";
  49002. };
  49003. return FreeCameraVirtualJoystickInput;
  49004. })();
  49005. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  49006. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  49007. })(BABYLON || (BABYLON = {}));
  49008. var BABYLON;
  49009. (function (BABYLON) {
  49010. var AnaglyphPostProcess = (function (_super) {
  49011. __extends(AnaglyphPostProcess, _super);
  49012. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  49013. var _this = this;
  49014. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  49015. this._passedProcess = rigCameras[0]._rigPostProcess;
  49016. this.onApplyObservable.add(function (effect) {
  49017. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  49018. });
  49019. }
  49020. return AnaglyphPostProcess;
  49021. })(BABYLON.PostProcess);
  49022. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  49023. })(BABYLON || (BABYLON = {}));
  49024. var BABYLON;
  49025. (function (BABYLON) {
  49026. var OutlineRenderer = (function () {
  49027. function OutlineRenderer(scene) {
  49028. this._scene = scene;
  49029. }
  49030. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  49031. var _this = this;
  49032. if (useOverlay === void 0) { useOverlay = false; }
  49033. var scene = this._scene;
  49034. var engine = this._scene.getEngine();
  49035. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  49036. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  49037. return;
  49038. }
  49039. var mesh = subMesh.getRenderingMesh();
  49040. var material = subMesh.getMaterial();
  49041. engine.enableEffect(this._effect);
  49042. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  49043. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  49044. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  49045. // Bones
  49046. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49047. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  49048. }
  49049. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  49050. // Alpha test
  49051. if (material && material.needAlphaTesting()) {
  49052. var alphaTexture = material.getAlphaTestTexture();
  49053. this._effect.setTexture("diffuseSampler", alphaTexture);
  49054. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  49055. }
  49056. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  49057. };
  49058. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  49059. var defines = [];
  49060. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  49061. var mesh = subMesh.getMesh();
  49062. var material = subMesh.getMaterial();
  49063. // Alpha test
  49064. if (material && material.needAlphaTesting()) {
  49065. defines.push("#define ALPHATEST");
  49066. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49067. attribs.push(BABYLON.VertexBuffer.UVKind);
  49068. defines.push("#define UV1");
  49069. }
  49070. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  49071. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  49072. defines.push("#define UV2");
  49073. }
  49074. }
  49075. // Bones
  49076. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49077. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  49078. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  49079. if (mesh.numBoneInfluencers > 4) {
  49080. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  49081. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  49082. }
  49083. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49084. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49085. }
  49086. else {
  49087. defines.push("#define NUM_BONE_INFLUENCERS 0");
  49088. }
  49089. // Instances
  49090. if (useInstances) {
  49091. defines.push("#define INSTANCES");
  49092. attribs.push("world0");
  49093. attribs.push("world1");
  49094. attribs.push("world2");
  49095. attribs.push("world3");
  49096. }
  49097. // Get correct effect
  49098. var join = defines.join("\n");
  49099. if (this._cachedDefines !== join) {
  49100. this._cachedDefines = join;
  49101. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  49102. }
  49103. return this._effect.isReady();
  49104. };
  49105. return OutlineRenderer;
  49106. })();
  49107. BABYLON.OutlineRenderer = OutlineRenderer;
  49108. })(BABYLON || (BABYLON = {}));
  49109. var BABYLON;
  49110. (function (BABYLON) {
  49111. var MeshAssetTask = (function () {
  49112. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  49113. this.name = name;
  49114. this.meshesNames = meshesNames;
  49115. this.rootUrl = rootUrl;
  49116. this.sceneFilename = sceneFilename;
  49117. this.isCompleted = false;
  49118. }
  49119. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49120. var _this = this;
  49121. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  49122. _this.loadedMeshes = meshes;
  49123. _this.loadedParticleSystems = particleSystems;
  49124. _this.loadedSkeletons = skeletons;
  49125. _this.isCompleted = true;
  49126. if (_this.onSuccess) {
  49127. _this.onSuccess(_this);
  49128. }
  49129. onSuccess();
  49130. }, null, function () {
  49131. if (_this.onError) {
  49132. _this.onError(_this);
  49133. }
  49134. onError();
  49135. });
  49136. };
  49137. return MeshAssetTask;
  49138. })();
  49139. BABYLON.MeshAssetTask = MeshAssetTask;
  49140. var TextFileAssetTask = (function () {
  49141. function TextFileAssetTask(name, url) {
  49142. this.name = name;
  49143. this.url = url;
  49144. this.isCompleted = false;
  49145. }
  49146. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49147. var _this = this;
  49148. BABYLON.Tools.LoadFile(this.url, function (data) {
  49149. _this.text = data;
  49150. _this.isCompleted = true;
  49151. if (_this.onSuccess) {
  49152. _this.onSuccess(_this);
  49153. }
  49154. onSuccess();
  49155. }, null, scene.database, false, function () {
  49156. if (_this.onError) {
  49157. _this.onError(_this);
  49158. }
  49159. onError();
  49160. });
  49161. };
  49162. return TextFileAssetTask;
  49163. })();
  49164. BABYLON.TextFileAssetTask = TextFileAssetTask;
  49165. var BinaryFileAssetTask = (function () {
  49166. function BinaryFileAssetTask(name, url) {
  49167. this.name = name;
  49168. this.url = url;
  49169. this.isCompleted = false;
  49170. }
  49171. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49172. var _this = this;
  49173. BABYLON.Tools.LoadFile(this.url, function (data) {
  49174. _this.data = data;
  49175. _this.isCompleted = true;
  49176. if (_this.onSuccess) {
  49177. _this.onSuccess(_this);
  49178. }
  49179. onSuccess();
  49180. }, null, scene.database, true, function () {
  49181. if (_this.onError) {
  49182. _this.onError(_this);
  49183. }
  49184. onError();
  49185. });
  49186. };
  49187. return BinaryFileAssetTask;
  49188. })();
  49189. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  49190. var ImageAssetTask = (function () {
  49191. function ImageAssetTask(name, url) {
  49192. this.name = name;
  49193. this.url = url;
  49194. this.isCompleted = false;
  49195. }
  49196. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49197. var _this = this;
  49198. var img = new Image();
  49199. img.onload = function () {
  49200. _this.image = img;
  49201. _this.isCompleted = true;
  49202. if (_this.onSuccess) {
  49203. _this.onSuccess(_this);
  49204. }
  49205. onSuccess();
  49206. };
  49207. img.onerror = function () {
  49208. if (_this.onError) {
  49209. _this.onError(_this);
  49210. }
  49211. onError();
  49212. };
  49213. img.src = this.url;
  49214. };
  49215. return ImageAssetTask;
  49216. })();
  49217. BABYLON.ImageAssetTask = ImageAssetTask;
  49218. var TextureAssetTask = (function () {
  49219. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  49220. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49221. this.name = name;
  49222. this.url = url;
  49223. this.noMipmap = noMipmap;
  49224. this.invertY = invertY;
  49225. this.samplingMode = samplingMode;
  49226. this.isCompleted = false;
  49227. }
  49228. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49229. var _this = this;
  49230. var onload = function () {
  49231. _this.isCompleted = true;
  49232. if (_this.onSuccess) {
  49233. _this.onSuccess(_this);
  49234. }
  49235. onSuccess();
  49236. };
  49237. var onerror = function () {
  49238. if (_this.onError) {
  49239. _this.onError(_this);
  49240. }
  49241. onError();
  49242. };
  49243. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  49244. };
  49245. return TextureAssetTask;
  49246. })();
  49247. BABYLON.TextureAssetTask = TextureAssetTask;
  49248. var AssetsManager = (function () {
  49249. function AssetsManager(scene) {
  49250. this._tasks = new Array();
  49251. this._waitingTasksCount = 0;
  49252. this.useDefaultLoadingScreen = true;
  49253. this._scene = scene;
  49254. }
  49255. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  49256. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  49257. this._tasks.push(task);
  49258. return task;
  49259. };
  49260. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  49261. var task = new TextFileAssetTask(taskName, url);
  49262. this._tasks.push(task);
  49263. return task;
  49264. };
  49265. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  49266. var task = new BinaryFileAssetTask(taskName, url);
  49267. this._tasks.push(task);
  49268. return task;
  49269. };
  49270. AssetsManager.prototype.addImageTask = function (taskName, url) {
  49271. var task = new ImageAssetTask(taskName, url);
  49272. this._tasks.push(task);
  49273. return task;
  49274. };
  49275. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  49276. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49277. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  49278. this._tasks.push(task);
  49279. return task;
  49280. };
  49281. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  49282. this._waitingTasksCount--;
  49283. if (this._waitingTasksCount === 0) {
  49284. if (this.onFinish) {
  49285. this.onFinish(this._tasks);
  49286. }
  49287. this._scene.getEngine().hideLoadingUI();
  49288. }
  49289. };
  49290. AssetsManager.prototype._runTask = function (task) {
  49291. var _this = this;
  49292. task.run(this._scene, function () {
  49293. if (_this.onTaskSuccess) {
  49294. _this.onTaskSuccess(task);
  49295. }
  49296. _this._decreaseWaitingTasksCount();
  49297. }, function () {
  49298. if (_this.onTaskError) {
  49299. _this.onTaskError(task);
  49300. }
  49301. _this._decreaseWaitingTasksCount();
  49302. });
  49303. };
  49304. AssetsManager.prototype.reset = function () {
  49305. this._tasks = new Array();
  49306. return this;
  49307. };
  49308. AssetsManager.prototype.load = function () {
  49309. this._waitingTasksCount = this._tasks.length;
  49310. if (this._waitingTasksCount === 0) {
  49311. if (this.onFinish) {
  49312. this.onFinish(this._tasks);
  49313. }
  49314. return this;
  49315. }
  49316. if (this.useDefaultLoadingScreen) {
  49317. this._scene.getEngine().displayLoadingUI();
  49318. }
  49319. for (var index = 0; index < this._tasks.length; index++) {
  49320. var task = this._tasks[index];
  49321. this._runTask(task);
  49322. }
  49323. return this;
  49324. };
  49325. return AssetsManager;
  49326. })();
  49327. BABYLON.AssetsManager = AssetsManager;
  49328. })(BABYLON || (BABYLON = {}));
  49329. var BABYLON;
  49330. (function (BABYLON) {
  49331. var VRCameraMetrics = (function () {
  49332. function VRCameraMetrics() {
  49333. this.compensateDistortion = true;
  49334. }
  49335. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  49336. get: function () {
  49337. return this.hResolution / (2 * this.vResolution);
  49338. },
  49339. enumerable: true,
  49340. configurable: true
  49341. });
  49342. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  49343. get: function () {
  49344. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  49345. },
  49346. enumerable: true,
  49347. configurable: true
  49348. });
  49349. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  49350. get: function () {
  49351. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  49352. var h = (4 * meters) / this.hScreenSize;
  49353. return BABYLON.Matrix.Translation(h, 0, 0);
  49354. },
  49355. enumerable: true,
  49356. configurable: true
  49357. });
  49358. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  49359. get: function () {
  49360. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  49361. var h = (4 * meters) / this.hScreenSize;
  49362. return BABYLON.Matrix.Translation(-h, 0, 0);
  49363. },
  49364. enumerable: true,
  49365. configurable: true
  49366. });
  49367. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  49368. get: function () {
  49369. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  49370. },
  49371. enumerable: true,
  49372. configurable: true
  49373. });
  49374. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  49375. get: function () {
  49376. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  49377. },
  49378. enumerable: true,
  49379. configurable: true
  49380. });
  49381. VRCameraMetrics.GetDefault = function () {
  49382. var result = new VRCameraMetrics();
  49383. result.hResolution = 1280;
  49384. result.vResolution = 800;
  49385. result.hScreenSize = 0.149759993;
  49386. result.vScreenSize = 0.0935999975;
  49387. result.vScreenCenter = 0.0467999987,
  49388. result.eyeToScreenDistance = 0.0410000011;
  49389. result.lensSeparationDistance = 0.0635000020;
  49390. result.interpupillaryDistance = 0.0640000030;
  49391. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  49392. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  49393. result.postProcessScaleFactor = 1.714605507808412;
  49394. result.lensCenterOffset = 0.151976421;
  49395. return result;
  49396. };
  49397. return VRCameraMetrics;
  49398. })();
  49399. BABYLON.VRCameraMetrics = VRCameraMetrics;
  49400. })(BABYLON || (BABYLON = {}));
  49401. var BABYLON;
  49402. (function (BABYLON) {
  49403. var VRDeviceOrientationFreeCamera = (function (_super) {
  49404. __extends(VRDeviceOrientationFreeCamera, _super);
  49405. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  49406. if (compensateDistortion === void 0) { compensateDistortion = true; }
  49407. _super.call(this, name, position, scene);
  49408. this.rotationQuaternion = new BABYLON.Quaternion();
  49409. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  49410. metrics.compensateDistortion = compensateDistortion;
  49411. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  49412. this.inputs.addDeviceOrientation();
  49413. }
  49414. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  49415. return "VRDeviceOrientationFreeCamera";
  49416. };
  49417. return VRDeviceOrientationFreeCamera;
  49418. })(BABYLON.FreeCamera);
  49419. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  49420. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  49421. __extends(VRDeviceOrientationArcRotateCamera, _super);
  49422. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  49423. if (compensateDistortion === void 0) { compensateDistortion = true; }
  49424. _super.call(this, name, alpha, beta, radius, target, scene);
  49425. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  49426. metrics.compensateDistortion = compensateDistortion;
  49427. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  49428. this.inputs.addVRDeviceOrientation();
  49429. }
  49430. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  49431. return "VRDeviceOrientationArcRotateCamera";
  49432. };
  49433. return VRDeviceOrientationArcRotateCamera;
  49434. })(BABYLON.ArcRotateCamera);
  49435. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  49436. })(BABYLON || (BABYLON = {}));
  49437. var BABYLON;
  49438. (function (BABYLON) {
  49439. var WebVRFreeCamera = (function (_super) {
  49440. __extends(WebVRFreeCamera, _super);
  49441. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  49442. if (compensateDistortion === void 0) { compensateDistortion = true; }
  49443. _super.call(this, name, position, scene);
  49444. this._hmdDevice = null;
  49445. this._sensorDevice = null;
  49446. this._cacheState = null;
  49447. this._vrEnabled = false;
  49448. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  49449. metrics.compensateDistortion = compensateDistortion;
  49450. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  49451. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  49452. this.rotationQuaternion = new BABYLON.Quaternion();
  49453. }
  49454. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  49455. var size = devices.length;
  49456. var i = 0;
  49457. // Reset devices.
  49458. this._sensorDevice = null;
  49459. this._hmdDevice = null;
  49460. // Search for a HmdDevice.
  49461. while (i < size && this._hmdDevice === null) {
  49462. if (devices[i] instanceof HMDVRDevice) {
  49463. this._hmdDevice = devices[i];
  49464. }
  49465. i++;
  49466. }
  49467. i = 0;
  49468. while (i < size && this._sensorDevice === null) {
  49469. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  49470. this._sensorDevice = devices[i];
  49471. }
  49472. i++;
  49473. }
  49474. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  49475. };
  49476. WebVRFreeCamera.prototype._checkInputs = function () {
  49477. if (this._vrEnabled) {
  49478. this._cacheState = this._sensorDevice.getState();
  49479. this.rotationQuaternion.copyFrom(this._cacheState.orientation);
  49480. //Flip in XY plane
  49481. this.rotationQuaternion.z *= -1;
  49482. this.rotationQuaternion.w *= -1;
  49483. }
  49484. _super.prototype._checkInputs.call(this);
  49485. };
  49486. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  49487. _super.prototype.attachControl.call(this, element, noPreventDefault);
  49488. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  49489. if (navigator.getVRDevices) {
  49490. navigator.getVRDevices().then(this._getWebVRDevices);
  49491. }
  49492. else if (navigator.mozGetVRDevices) {
  49493. navigator.mozGetVRDevices(this._getWebVRDevices);
  49494. }
  49495. };
  49496. WebVRFreeCamera.prototype.detachControl = function (element) {
  49497. _super.prototype.detachControl.call(this, element);
  49498. this._vrEnabled = false;
  49499. };
  49500. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  49501. if (!this._hmdDevice)
  49502. return;
  49503. this.getEngine().switchFullscreen(requestPointerlock, { vrDisplay: this._hmdDevice });
  49504. };
  49505. WebVRFreeCamera.prototype.getTypeName = function () {
  49506. return "WebVRFreeCamera";
  49507. };
  49508. return WebVRFreeCamera;
  49509. })(BABYLON.FreeCamera);
  49510. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  49511. })(BABYLON || (BABYLON = {}));
  49512. var BABYLON;
  49513. (function (BABYLON) {
  49514. // Standard optimizations
  49515. var SceneOptimization = (function () {
  49516. function SceneOptimization(priority) {
  49517. if (priority === void 0) { priority = 0; }
  49518. this.priority = priority;
  49519. this.apply = function (scene) {
  49520. return true; // Return true if everything that can be done was applied
  49521. };
  49522. }
  49523. return SceneOptimization;
  49524. })();
  49525. BABYLON.SceneOptimization = SceneOptimization;
  49526. var TextureOptimization = (function (_super) {
  49527. __extends(TextureOptimization, _super);
  49528. function TextureOptimization(priority, maximumSize) {
  49529. var _this = this;
  49530. if (priority === void 0) { priority = 0; }
  49531. if (maximumSize === void 0) { maximumSize = 1024; }
  49532. _super.call(this, priority);
  49533. this.priority = priority;
  49534. this.maximumSize = maximumSize;
  49535. this.apply = function (scene) {
  49536. var allDone = true;
  49537. for (var index = 0; index < scene.textures.length; index++) {
  49538. var texture = scene.textures[index];
  49539. if (!texture.canRescale) {
  49540. continue;
  49541. }
  49542. var currentSize = texture.getSize();
  49543. var maxDimension = Math.max(currentSize.width, currentSize.height);
  49544. if (maxDimension > _this.maximumSize) {
  49545. texture.scale(0.5);
  49546. allDone = false;
  49547. }
  49548. }
  49549. return allDone;
  49550. };
  49551. }
  49552. return TextureOptimization;
  49553. })(SceneOptimization);
  49554. BABYLON.TextureOptimization = TextureOptimization;
  49555. var HardwareScalingOptimization = (function (_super) {
  49556. __extends(HardwareScalingOptimization, _super);
  49557. function HardwareScalingOptimization(priority, maximumScale) {
  49558. var _this = this;
  49559. if (priority === void 0) { priority = 0; }
  49560. if (maximumScale === void 0) { maximumScale = 2; }
  49561. _super.call(this, priority);
  49562. this.priority = priority;
  49563. this.maximumScale = maximumScale;
  49564. this._currentScale = 1;
  49565. this.apply = function (scene) {
  49566. _this._currentScale++;
  49567. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  49568. return _this._currentScale >= _this.maximumScale;
  49569. };
  49570. }
  49571. return HardwareScalingOptimization;
  49572. })(SceneOptimization);
  49573. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  49574. var ShadowsOptimization = (function (_super) {
  49575. __extends(ShadowsOptimization, _super);
  49576. function ShadowsOptimization() {
  49577. _super.apply(this, arguments);
  49578. this.apply = function (scene) {
  49579. scene.shadowsEnabled = false;
  49580. return true;
  49581. };
  49582. }
  49583. return ShadowsOptimization;
  49584. })(SceneOptimization);
  49585. BABYLON.ShadowsOptimization = ShadowsOptimization;
  49586. var PostProcessesOptimization = (function (_super) {
  49587. __extends(PostProcessesOptimization, _super);
  49588. function PostProcessesOptimization() {
  49589. _super.apply(this, arguments);
  49590. this.apply = function (scene) {
  49591. scene.postProcessesEnabled = false;
  49592. return true;
  49593. };
  49594. }
  49595. return PostProcessesOptimization;
  49596. })(SceneOptimization);
  49597. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  49598. var LensFlaresOptimization = (function (_super) {
  49599. __extends(LensFlaresOptimization, _super);
  49600. function LensFlaresOptimization() {
  49601. _super.apply(this, arguments);
  49602. this.apply = function (scene) {
  49603. scene.lensFlaresEnabled = false;
  49604. return true;
  49605. };
  49606. }
  49607. return LensFlaresOptimization;
  49608. })(SceneOptimization);
  49609. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  49610. var ParticlesOptimization = (function (_super) {
  49611. __extends(ParticlesOptimization, _super);
  49612. function ParticlesOptimization() {
  49613. _super.apply(this, arguments);
  49614. this.apply = function (scene) {
  49615. scene.particlesEnabled = false;
  49616. return true;
  49617. };
  49618. }
  49619. return ParticlesOptimization;
  49620. })(SceneOptimization);
  49621. BABYLON.ParticlesOptimization = ParticlesOptimization;
  49622. var RenderTargetsOptimization = (function (_super) {
  49623. __extends(RenderTargetsOptimization, _super);
  49624. function RenderTargetsOptimization() {
  49625. _super.apply(this, arguments);
  49626. this.apply = function (scene) {
  49627. scene.renderTargetsEnabled = false;
  49628. return true;
  49629. };
  49630. }
  49631. return RenderTargetsOptimization;
  49632. })(SceneOptimization);
  49633. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  49634. var MergeMeshesOptimization = (function (_super) {
  49635. __extends(MergeMeshesOptimization, _super);
  49636. function MergeMeshesOptimization() {
  49637. var _this = this;
  49638. _super.apply(this, arguments);
  49639. this._canBeMerged = function (abstractMesh) {
  49640. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  49641. return false;
  49642. }
  49643. var mesh = abstractMesh;
  49644. if (!mesh.isVisible || !mesh.isEnabled()) {
  49645. return false;
  49646. }
  49647. if (mesh.instances.length > 0) {
  49648. return false;
  49649. }
  49650. if (mesh.skeleton || mesh.hasLODLevels) {
  49651. return false;
  49652. }
  49653. if (mesh.parent) {
  49654. return false;
  49655. }
  49656. return true;
  49657. };
  49658. this.apply = function (scene, updateSelectionTree) {
  49659. var globalPool = scene.meshes.slice(0);
  49660. var globalLength = globalPool.length;
  49661. for (var index = 0; index < globalLength; index++) {
  49662. var currentPool = new Array();
  49663. var current = globalPool[index];
  49664. // Checks
  49665. if (!_this._canBeMerged(current)) {
  49666. continue;
  49667. }
  49668. currentPool.push(current);
  49669. // Find compatible meshes
  49670. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  49671. var otherMesh = globalPool[subIndex];
  49672. if (!_this._canBeMerged(otherMesh)) {
  49673. continue;
  49674. }
  49675. if (otherMesh.material !== current.material) {
  49676. continue;
  49677. }
  49678. if (otherMesh.checkCollisions !== current.checkCollisions) {
  49679. continue;
  49680. }
  49681. currentPool.push(otherMesh);
  49682. globalLength--;
  49683. globalPool.splice(subIndex, 1);
  49684. subIndex--;
  49685. }
  49686. if (currentPool.length < 2) {
  49687. continue;
  49688. }
  49689. // Merge meshes
  49690. BABYLON.Mesh.MergeMeshes(currentPool);
  49691. }
  49692. if (updateSelectionTree != undefined) {
  49693. if (updateSelectionTree) {
  49694. scene.createOrUpdateSelectionOctree();
  49695. }
  49696. }
  49697. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  49698. scene.createOrUpdateSelectionOctree();
  49699. }
  49700. return true;
  49701. };
  49702. }
  49703. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  49704. get: function () {
  49705. return MergeMeshesOptimization._UpdateSelectionTree;
  49706. },
  49707. set: function (value) {
  49708. MergeMeshesOptimization._UpdateSelectionTree = value;
  49709. },
  49710. enumerable: true,
  49711. configurable: true
  49712. });
  49713. MergeMeshesOptimization._UpdateSelectionTree = false;
  49714. return MergeMeshesOptimization;
  49715. })(SceneOptimization);
  49716. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  49717. // Options
  49718. var SceneOptimizerOptions = (function () {
  49719. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  49720. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  49721. if (trackerDuration === void 0) { trackerDuration = 2000; }
  49722. this.targetFrameRate = targetFrameRate;
  49723. this.trackerDuration = trackerDuration;
  49724. this.optimizations = new Array();
  49725. }
  49726. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  49727. var result = new SceneOptimizerOptions(targetFrameRate);
  49728. var priority = 0;
  49729. result.optimizations.push(new MergeMeshesOptimization(priority));
  49730. result.optimizations.push(new ShadowsOptimization(priority));
  49731. result.optimizations.push(new LensFlaresOptimization(priority));
  49732. // Next priority
  49733. priority++;
  49734. result.optimizations.push(new PostProcessesOptimization(priority));
  49735. result.optimizations.push(new ParticlesOptimization(priority));
  49736. // Next priority
  49737. priority++;
  49738. result.optimizations.push(new TextureOptimization(priority, 1024));
  49739. return result;
  49740. };
  49741. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  49742. var result = new SceneOptimizerOptions(targetFrameRate);
  49743. var priority = 0;
  49744. result.optimizations.push(new MergeMeshesOptimization(priority));
  49745. result.optimizations.push(new ShadowsOptimization(priority));
  49746. result.optimizations.push(new LensFlaresOptimization(priority));
  49747. // Next priority
  49748. priority++;
  49749. result.optimizations.push(new PostProcessesOptimization(priority));
  49750. result.optimizations.push(new ParticlesOptimization(priority));
  49751. // Next priority
  49752. priority++;
  49753. result.optimizations.push(new TextureOptimization(priority, 512));
  49754. // Next priority
  49755. priority++;
  49756. result.optimizations.push(new RenderTargetsOptimization(priority));
  49757. // Next priority
  49758. priority++;
  49759. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  49760. return result;
  49761. };
  49762. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  49763. var result = new SceneOptimizerOptions(targetFrameRate);
  49764. var priority = 0;
  49765. result.optimizations.push(new MergeMeshesOptimization(priority));
  49766. result.optimizations.push(new ShadowsOptimization(priority));
  49767. result.optimizations.push(new LensFlaresOptimization(priority));
  49768. // Next priority
  49769. priority++;
  49770. result.optimizations.push(new PostProcessesOptimization(priority));
  49771. result.optimizations.push(new ParticlesOptimization(priority));
  49772. // Next priority
  49773. priority++;
  49774. result.optimizations.push(new TextureOptimization(priority, 256));
  49775. // Next priority
  49776. priority++;
  49777. result.optimizations.push(new RenderTargetsOptimization(priority));
  49778. // Next priority
  49779. priority++;
  49780. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  49781. return result;
  49782. };
  49783. return SceneOptimizerOptions;
  49784. })();
  49785. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  49786. // Scene optimizer tool
  49787. var SceneOptimizer = (function () {
  49788. function SceneOptimizer() {
  49789. }
  49790. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  49791. // TODO: add an epsilon
  49792. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  49793. if (onSuccess) {
  49794. onSuccess();
  49795. }
  49796. return;
  49797. }
  49798. // Apply current level of optimizations
  49799. var allDone = true;
  49800. var noOptimizationApplied = true;
  49801. for (var index = 0; index < options.optimizations.length; index++) {
  49802. var optimization = options.optimizations[index];
  49803. if (optimization.priority === currentPriorityLevel) {
  49804. noOptimizationApplied = false;
  49805. allDone = allDone && optimization.apply(scene);
  49806. }
  49807. }
  49808. // If no optimization was applied, this is a failure :(
  49809. if (noOptimizationApplied) {
  49810. if (onFailure) {
  49811. onFailure();
  49812. }
  49813. return;
  49814. }
  49815. // If all optimizations were done, move to next level
  49816. if (allDone) {
  49817. currentPriorityLevel++;
  49818. }
  49819. // Let's the system running for a specific amount of time before checking FPS
  49820. scene.executeWhenReady(function () {
  49821. setTimeout(function () {
  49822. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  49823. }, options.trackerDuration);
  49824. });
  49825. };
  49826. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  49827. if (!options) {
  49828. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  49829. }
  49830. // Let's the system running for a specific amount of time before checking FPS
  49831. scene.executeWhenReady(function () {
  49832. setTimeout(function () {
  49833. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  49834. }, options.trackerDuration);
  49835. });
  49836. };
  49837. return SceneOptimizer;
  49838. })();
  49839. BABYLON.SceneOptimizer = SceneOptimizer;
  49840. })(BABYLON || (BABYLON = {}));
  49841. var BABYLON;
  49842. (function (BABYLON) {
  49843. var Internals;
  49844. (function (Internals) {
  49845. var MeshLODLevel = (function () {
  49846. function MeshLODLevel(distance, mesh) {
  49847. this.distance = distance;
  49848. this.mesh = mesh;
  49849. }
  49850. return MeshLODLevel;
  49851. })();
  49852. Internals.MeshLODLevel = MeshLODLevel;
  49853. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49854. })(BABYLON || (BABYLON = {}));
  49855. var BABYLON;
  49856. (function (BABYLON) {
  49857. var RawTexture = (function (_super) {
  49858. __extends(RawTexture, _super);
  49859. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  49860. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49861. if (invertY === void 0) { invertY = false; }
  49862. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49863. _super.call(this, null, scene, !generateMipMaps, invertY);
  49864. this.format = format;
  49865. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  49866. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49867. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49868. }
  49869. RawTexture.prototype.update = function (data) {
  49870. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  49871. };
  49872. // Statics
  49873. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49874. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49875. if (invertY === void 0) { invertY = false; }
  49876. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49877. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  49878. };
  49879. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49880. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49881. if (invertY === void 0) { invertY = false; }
  49882. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49883. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  49884. };
  49885. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49886. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49887. if (invertY === void 0) { invertY = false; }
  49888. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49889. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  49890. };
  49891. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49892. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49893. if (invertY === void 0) { invertY = false; }
  49894. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49895. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  49896. };
  49897. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49898. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49899. if (invertY === void 0) { invertY = false; }
  49900. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49901. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  49902. };
  49903. return RawTexture;
  49904. })(BABYLON.Texture);
  49905. BABYLON.RawTexture = RawTexture;
  49906. })(BABYLON || (BABYLON = {}));
  49907. var BABYLON;
  49908. (function (BABYLON) {
  49909. var IndexedVector2 = (function (_super) {
  49910. __extends(IndexedVector2, _super);
  49911. function IndexedVector2(original, index) {
  49912. _super.call(this, original.x, original.y);
  49913. this.index = index;
  49914. }
  49915. return IndexedVector2;
  49916. })(BABYLON.Vector2);
  49917. var PolygonPoints = (function () {
  49918. function PolygonPoints() {
  49919. this.elements = new Array();
  49920. }
  49921. PolygonPoints.prototype.add = function (originalPoints) {
  49922. var _this = this;
  49923. var result = new Array();
  49924. originalPoints.forEach(function (point) {
  49925. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  49926. var newPoint = new IndexedVector2(point, _this.elements.length);
  49927. result.push(newPoint);
  49928. _this.elements.push(newPoint);
  49929. }
  49930. });
  49931. return result;
  49932. };
  49933. PolygonPoints.prototype.computeBounds = function () {
  49934. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  49935. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  49936. this.elements.forEach(function (point) {
  49937. // x
  49938. if (point.x < lmin.x) {
  49939. lmin.x = point.x;
  49940. }
  49941. else if (point.x > lmax.x) {
  49942. lmax.x = point.x;
  49943. }
  49944. // y
  49945. if (point.y < lmin.y) {
  49946. lmin.y = point.y;
  49947. }
  49948. else if (point.y > lmax.y) {
  49949. lmax.y = point.y;
  49950. }
  49951. });
  49952. return {
  49953. min: lmin,
  49954. max: lmax,
  49955. width: lmax.x - lmin.x,
  49956. height: lmax.y - lmin.y
  49957. };
  49958. };
  49959. return PolygonPoints;
  49960. })();
  49961. var Polygon = (function () {
  49962. function Polygon() {
  49963. }
  49964. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  49965. return [
  49966. new BABYLON.Vector2(xmin, ymin),
  49967. new BABYLON.Vector2(xmax, ymin),
  49968. new BABYLON.Vector2(xmax, ymax),
  49969. new BABYLON.Vector2(xmin, ymax)
  49970. ];
  49971. };
  49972. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  49973. if (cx === void 0) { cx = 0; }
  49974. if (cy === void 0) { cy = 0; }
  49975. if (numberOfSides === void 0) { numberOfSides = 32; }
  49976. var result = new Array();
  49977. var angle = 0;
  49978. var increment = (Math.PI * 2) / numberOfSides;
  49979. for (var i = 0; i < numberOfSides; i++) {
  49980. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  49981. angle -= increment;
  49982. }
  49983. return result;
  49984. };
  49985. Polygon.Parse = function (input) {
  49986. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  49987. var i, result = [];
  49988. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  49989. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  49990. }
  49991. return result;
  49992. };
  49993. Polygon.StartingAt = function (x, y) {
  49994. return BABYLON.Path2.StartingAt(x, y);
  49995. };
  49996. return Polygon;
  49997. })();
  49998. BABYLON.Polygon = Polygon;
  49999. var PolygonMeshBuilder = (function () {
  50000. function PolygonMeshBuilder(name, contours, scene) {
  50001. this._points = new PolygonPoints();
  50002. this._outlinepoints = new PolygonPoints();
  50003. this._holes = [];
  50004. this._epoints = new Array();
  50005. this._eholes = new Array();
  50006. this._name = name;
  50007. this._scene = scene;
  50008. var points;
  50009. if (contours instanceof BABYLON.Path2) {
  50010. points = contours.getPoints();
  50011. }
  50012. else {
  50013. points = contours;
  50014. }
  50015. this._addToepoint(points);
  50016. this._points.add(points);
  50017. this._outlinepoints.add(points);
  50018. }
  50019. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  50020. for (var _i = 0; _i < points.length; _i++) {
  50021. var p = points[_i];
  50022. this._epoints.push(p.x, p.y);
  50023. }
  50024. };
  50025. PolygonMeshBuilder.prototype.addHole = function (hole) {
  50026. this._points.add(hole);
  50027. var holepoints = new PolygonPoints();
  50028. holepoints.add(hole);
  50029. this._holes.push(holepoints);
  50030. this._eholes.push(this._epoints.length / 2);
  50031. this._addToepoint(hole);
  50032. return this;
  50033. };
  50034. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  50035. var _this = this;
  50036. if (updatable === void 0) { updatable = false; }
  50037. var result = new BABYLON.Mesh(this._name, this._scene);
  50038. var normals = [];
  50039. var positions = [];
  50040. var uvs = [];
  50041. var bounds = this._points.computeBounds();
  50042. this._points.elements.forEach(function (p) {
  50043. normals.push(0, 1.0, 0);
  50044. positions.push(p.x, 0, p.y);
  50045. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  50046. });
  50047. var indices = [];
  50048. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  50049. for (var i = 0; i < res.length; i++) {
  50050. indices.push(res[i]);
  50051. }
  50052. if (depth > 0) {
  50053. var positionscount = (positions.length / 3); //get the current pointcount
  50054. this._points.elements.forEach(function (p) {
  50055. normals.push(0, -1.0, 0);
  50056. positions.push(p.x, -depth, p.y);
  50057. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  50058. });
  50059. var totalCount = indices.length;
  50060. for (var i = 0; i < totalCount; i += 3) {
  50061. var i0 = indices[i + 0];
  50062. var i1 = indices[i + 1];
  50063. var i2 = indices[i + 2];
  50064. indices.push(i2 + positionscount);
  50065. indices.push(i1 + positionscount);
  50066. indices.push(i0 + positionscount);
  50067. }
  50068. //Add the sides
  50069. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  50070. this._holes.forEach(function (hole) {
  50071. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  50072. });
  50073. }
  50074. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  50075. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  50076. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  50077. result.setIndices(indices);
  50078. return result;
  50079. };
  50080. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  50081. var StartIndex = positions.length / 3;
  50082. var ulength = 0;
  50083. for (var i = 0; i < points.elements.length; i++) {
  50084. var p = points.elements[i];
  50085. var p1;
  50086. if ((i + 1) > points.elements.length - 1) {
  50087. p1 = points.elements[0];
  50088. }
  50089. else {
  50090. p1 = points.elements[i + 1];
  50091. }
  50092. positions.push(p.x, 0, p.y);
  50093. positions.push(p.x, -depth, p.y);
  50094. positions.push(p1.x, 0, p1.y);
  50095. positions.push(p1.x, -depth, p1.y);
  50096. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  50097. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  50098. var v3 = v2.subtract(v1);
  50099. var v4 = new BABYLON.Vector3(0, 1, 0);
  50100. var vn = BABYLON.Vector3.Cross(v3, v4);
  50101. vn = vn.normalize();
  50102. uvs.push(ulength / bounds.width, 0);
  50103. uvs.push(ulength / bounds.width, 1);
  50104. ulength += v3.length();
  50105. uvs.push((ulength / bounds.width), 0);
  50106. uvs.push((ulength / bounds.width), 1);
  50107. if (!flip) {
  50108. normals.push(-vn.x, -vn.y, -vn.z);
  50109. normals.push(-vn.x, -vn.y, -vn.z);
  50110. normals.push(-vn.x, -vn.y, -vn.z);
  50111. normals.push(-vn.x, -vn.y, -vn.z);
  50112. indices.push(StartIndex);
  50113. indices.push(StartIndex + 1);
  50114. indices.push(StartIndex + 2);
  50115. indices.push(StartIndex + 1);
  50116. indices.push(StartIndex + 3);
  50117. indices.push(StartIndex + 2);
  50118. }
  50119. else {
  50120. normals.push(vn.x, vn.y, vn.z);
  50121. normals.push(vn.x, vn.y, vn.z);
  50122. normals.push(vn.x, vn.y, vn.z);
  50123. normals.push(vn.x, vn.y, vn.z);
  50124. indices.push(StartIndex);
  50125. indices.push(StartIndex + 2);
  50126. indices.push(StartIndex + 1);
  50127. indices.push(StartIndex + 1);
  50128. indices.push(StartIndex + 2);
  50129. indices.push(StartIndex + 3);
  50130. }
  50131. StartIndex += 4;
  50132. }
  50133. ;
  50134. };
  50135. return PolygonMeshBuilder;
  50136. })();
  50137. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  50138. })(BABYLON || (BABYLON = {}));
  50139. var BABYLON;
  50140. (function (BABYLON) {
  50141. var Octree = (function () {
  50142. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  50143. if (maxDepth === void 0) { maxDepth = 2; }
  50144. this.maxDepth = maxDepth;
  50145. this.dynamicContent = new Array();
  50146. this._maxBlockCapacity = maxBlockCapacity || 64;
  50147. this._selectionContent = new BABYLON.SmartArray(1024);
  50148. this._creationFunc = creationFunc;
  50149. }
  50150. // Methods
  50151. Octree.prototype.update = function (worldMin, worldMax, entries) {
  50152. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  50153. };
  50154. Octree.prototype.addMesh = function (entry) {
  50155. for (var index = 0; index < this.blocks.length; index++) {
  50156. var block = this.blocks[index];
  50157. block.addEntry(entry);
  50158. }
  50159. };
  50160. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  50161. this._selectionContent.reset();
  50162. for (var index = 0; index < this.blocks.length; index++) {
  50163. var block = this.blocks[index];
  50164. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  50165. }
  50166. if (allowDuplicate) {
  50167. this._selectionContent.concat(this.dynamicContent);
  50168. }
  50169. else {
  50170. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50171. }
  50172. return this._selectionContent;
  50173. };
  50174. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  50175. this._selectionContent.reset();
  50176. for (var index = 0; index < this.blocks.length; index++) {
  50177. var block = this.blocks[index];
  50178. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  50179. }
  50180. if (allowDuplicate) {
  50181. this._selectionContent.concat(this.dynamicContent);
  50182. }
  50183. else {
  50184. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50185. }
  50186. return this._selectionContent;
  50187. };
  50188. Octree.prototype.intersectsRay = function (ray) {
  50189. this._selectionContent.reset();
  50190. for (var index = 0; index < this.blocks.length; index++) {
  50191. var block = this.blocks[index];
  50192. block.intersectsRay(ray, this._selectionContent);
  50193. }
  50194. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50195. return this._selectionContent;
  50196. };
  50197. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  50198. target.blocks = new Array();
  50199. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  50200. // Segmenting space
  50201. for (var x = 0; x < 2; x++) {
  50202. for (var y = 0; y < 2; y++) {
  50203. for (var z = 0; z < 2; z++) {
  50204. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  50205. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  50206. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  50207. block.addEntries(entries);
  50208. target.blocks.push(block);
  50209. }
  50210. }
  50211. }
  50212. };
  50213. Octree.CreationFuncForMeshes = function (entry, block) {
  50214. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  50215. block.entries.push(entry);
  50216. }
  50217. };
  50218. Octree.CreationFuncForSubMeshes = function (entry, block) {
  50219. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  50220. block.entries.push(entry);
  50221. }
  50222. };
  50223. return Octree;
  50224. })();
  50225. BABYLON.Octree = Octree;
  50226. })(BABYLON || (BABYLON = {}));
  50227. var BABYLON;
  50228. (function (BABYLON) {
  50229. var OctreeBlock = (function () {
  50230. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  50231. this.entries = new Array();
  50232. this._boundingVectors = new Array();
  50233. this._capacity = capacity;
  50234. this._depth = depth;
  50235. this._maxDepth = maxDepth;
  50236. this._creationFunc = creationFunc;
  50237. this._minPoint = minPoint;
  50238. this._maxPoint = maxPoint;
  50239. this._boundingVectors.push(minPoint.clone());
  50240. this._boundingVectors.push(maxPoint.clone());
  50241. this._boundingVectors.push(minPoint.clone());
  50242. this._boundingVectors[2].x = maxPoint.x;
  50243. this._boundingVectors.push(minPoint.clone());
  50244. this._boundingVectors[3].y = maxPoint.y;
  50245. this._boundingVectors.push(minPoint.clone());
  50246. this._boundingVectors[4].z = maxPoint.z;
  50247. this._boundingVectors.push(maxPoint.clone());
  50248. this._boundingVectors[5].z = minPoint.z;
  50249. this._boundingVectors.push(maxPoint.clone());
  50250. this._boundingVectors[6].x = minPoint.x;
  50251. this._boundingVectors.push(maxPoint.clone());
  50252. this._boundingVectors[7].y = minPoint.y;
  50253. }
  50254. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  50255. // Property
  50256. get: function () {
  50257. return this._capacity;
  50258. },
  50259. enumerable: true,
  50260. configurable: true
  50261. });
  50262. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  50263. get: function () {
  50264. return this._minPoint;
  50265. },
  50266. enumerable: true,
  50267. configurable: true
  50268. });
  50269. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  50270. get: function () {
  50271. return this._maxPoint;
  50272. },
  50273. enumerable: true,
  50274. configurable: true
  50275. });
  50276. // Methods
  50277. OctreeBlock.prototype.addEntry = function (entry) {
  50278. if (this.blocks) {
  50279. for (var index = 0; index < this.blocks.length; index++) {
  50280. var block = this.blocks[index];
  50281. block.addEntry(entry);
  50282. }
  50283. return;
  50284. }
  50285. this._creationFunc(entry, this);
  50286. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  50287. this.createInnerBlocks();
  50288. }
  50289. };
  50290. OctreeBlock.prototype.addEntries = function (entries) {
  50291. for (var index = 0; index < entries.length; index++) {
  50292. var mesh = entries[index];
  50293. this.addEntry(mesh);
  50294. }
  50295. };
  50296. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  50297. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  50298. if (this.blocks) {
  50299. for (var index = 0; index < this.blocks.length; index++) {
  50300. var block = this.blocks[index];
  50301. block.select(frustumPlanes, selection, allowDuplicate);
  50302. }
  50303. return;
  50304. }
  50305. if (allowDuplicate) {
  50306. selection.concat(this.entries);
  50307. }
  50308. else {
  50309. selection.concatWithNoDuplicate(this.entries);
  50310. }
  50311. }
  50312. };
  50313. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  50314. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  50315. if (this.blocks) {
  50316. for (var index = 0; index < this.blocks.length; index++) {
  50317. var block = this.blocks[index];
  50318. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  50319. }
  50320. return;
  50321. }
  50322. if (allowDuplicate) {
  50323. selection.concat(this.entries);
  50324. }
  50325. else {
  50326. selection.concatWithNoDuplicate(this.entries);
  50327. }
  50328. }
  50329. };
  50330. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  50331. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  50332. if (this.blocks) {
  50333. for (var index = 0; index < this.blocks.length; index++) {
  50334. var block = this.blocks[index];
  50335. block.intersectsRay(ray, selection);
  50336. }
  50337. return;
  50338. }
  50339. selection.concatWithNoDuplicate(this.entries);
  50340. }
  50341. };
  50342. OctreeBlock.prototype.createInnerBlocks = function () {
  50343. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  50344. };
  50345. return OctreeBlock;
  50346. })();
  50347. BABYLON.OctreeBlock = OctreeBlock;
  50348. })(BABYLON || (BABYLON = {}));
  50349. var BABYLON;
  50350. (function (BABYLON) {
  50351. var BlurPostProcess = (function (_super) {
  50352. __extends(BlurPostProcess, _super);
  50353. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  50354. var _this = this;
  50355. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50356. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  50357. this.direction = direction;
  50358. this.blurWidth = blurWidth;
  50359. this.onApplyObservable.add(function (effect) {
  50360. effect.setFloat2("screenSize", _this.width, _this.height);
  50361. effect.setVector2("direction", _this.direction);
  50362. effect.setFloat("blurWidth", _this.blurWidth);
  50363. });
  50364. }
  50365. return BlurPostProcess;
  50366. })(BABYLON.PostProcess);
  50367. BABYLON.BlurPostProcess = BlurPostProcess;
  50368. })(BABYLON || (BABYLON = {}));
  50369. var BABYLON;
  50370. (function (BABYLON) {
  50371. var RefractionPostProcess = (function (_super) {
  50372. __extends(RefractionPostProcess, _super);
  50373. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  50374. var _this = this;
  50375. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  50376. this.color = color;
  50377. this.depth = depth;
  50378. this.colorLevel = colorLevel;
  50379. this.onActivateObservable.add(function (cam) {
  50380. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  50381. });
  50382. this.onApplyObservable.add(function (effect) {
  50383. effect.setColor3("baseColor", _this.color);
  50384. effect.setFloat("depth", _this.depth);
  50385. effect.setFloat("colorLevel", _this.colorLevel);
  50386. effect.setTexture("refractionSampler", _this._refRexture);
  50387. });
  50388. }
  50389. // Methods
  50390. RefractionPostProcess.prototype.dispose = function (camera) {
  50391. if (this._refRexture) {
  50392. this._refRexture.dispose();
  50393. }
  50394. _super.prototype.dispose.call(this, camera);
  50395. };
  50396. return RefractionPostProcess;
  50397. })(BABYLON.PostProcess);
  50398. BABYLON.RefractionPostProcess = RefractionPostProcess;
  50399. })(BABYLON || (BABYLON = {}));
  50400. var BABYLON;
  50401. (function (BABYLON) {
  50402. var BlackAndWhitePostProcess = (function (_super) {
  50403. __extends(BlackAndWhitePostProcess, _super);
  50404. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  50405. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  50406. }
  50407. return BlackAndWhitePostProcess;
  50408. })(BABYLON.PostProcess);
  50409. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  50410. })(BABYLON || (BABYLON = {}));
  50411. var BABYLON;
  50412. (function (BABYLON) {
  50413. var ConvolutionPostProcess = (function (_super) {
  50414. __extends(ConvolutionPostProcess, _super);
  50415. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  50416. var _this = this;
  50417. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  50418. this.kernel = kernel;
  50419. this.onApply = function (effect) {
  50420. effect.setFloat2("screenSize", _this.width, _this.height);
  50421. effect.setArray("kernel", _this.kernel);
  50422. };
  50423. }
  50424. // Statics
  50425. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  50426. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  50427. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  50428. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  50429. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  50430. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  50431. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  50432. return ConvolutionPostProcess;
  50433. })(BABYLON.PostProcess);
  50434. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  50435. })(BABYLON || (BABYLON = {}));
  50436. var BABYLON;
  50437. (function (BABYLON) {
  50438. var FilterPostProcess = (function (_super) {
  50439. __extends(FilterPostProcess, _super);
  50440. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  50441. var _this = this;
  50442. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  50443. this.kernelMatrix = kernelMatrix;
  50444. this.onApply = function (effect) {
  50445. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  50446. };
  50447. }
  50448. return FilterPostProcess;
  50449. })(BABYLON.PostProcess);
  50450. BABYLON.FilterPostProcess = FilterPostProcess;
  50451. })(BABYLON || (BABYLON = {}));
  50452. var BABYLON;
  50453. (function (BABYLON) {
  50454. var FxaaPostProcess = (function (_super) {
  50455. __extends(FxaaPostProcess, _super);
  50456. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  50457. var _this = this;
  50458. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  50459. this.onSizeChangedObservable.add(function () {
  50460. _this.texelWidth = 1.0 / _this.width;
  50461. _this.texelHeight = 1.0 / _this.height;
  50462. });
  50463. this.onApplyObservable.add(function (effect) {
  50464. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  50465. });
  50466. }
  50467. return FxaaPostProcess;
  50468. })(BABYLON.PostProcess);
  50469. BABYLON.FxaaPostProcess = FxaaPostProcess;
  50470. })(BABYLON || (BABYLON = {}));
  50471. var BABYLON;
  50472. (function (BABYLON) {
  50473. var StereoscopicInterlacePostProcess = (function (_super) {
  50474. __extends(StereoscopicInterlacePostProcess, _super);
  50475. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  50476. var _this = this;
  50477. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  50478. this._passedProcess = rigCameras[0]._rigPostProcess;
  50479. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  50480. this.onSizeChangedObservable.add(function () {
  50481. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  50482. });
  50483. this.onApplyObservable.add(function (effect) {
  50484. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  50485. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  50486. });
  50487. }
  50488. return StereoscopicInterlacePostProcess;
  50489. })(BABYLON.PostProcess);
  50490. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  50491. })(BABYLON || (BABYLON = {}));
  50492. var BABYLON;
  50493. (function (BABYLON) {
  50494. var LensFlare = (function () {
  50495. function LensFlare(size, position, color, imgUrl, system) {
  50496. this.size = size;
  50497. this.position = position;
  50498. this.dispose = function () {
  50499. if (this.texture) {
  50500. this.texture.dispose();
  50501. }
  50502. // Remove from scene
  50503. var index = this._system.lensFlares.indexOf(this);
  50504. this._system.lensFlares.splice(index, 1);
  50505. };
  50506. this.color = color || new BABYLON.Color3(1, 1, 1);
  50507. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  50508. this._system = system;
  50509. system.lensFlares.push(this);
  50510. }
  50511. return LensFlare;
  50512. })();
  50513. BABYLON.LensFlare = LensFlare;
  50514. })(BABYLON || (BABYLON = {}));
  50515. var BABYLON;
  50516. (function (BABYLON) {
  50517. var LensFlareSystem = (function () {
  50518. function LensFlareSystem(name, emitter, scene) {
  50519. this.name = name;
  50520. this.lensFlares = new Array();
  50521. this.borderLimit = 300;
  50522. this.layerMask = 0x0FFFFFFF;
  50523. this._vertexBuffers = {};
  50524. this._isEnabled = true;
  50525. this._scene = scene;
  50526. this._emitter = emitter;
  50527. this.id = name;
  50528. scene.lensFlareSystems.push(this);
  50529. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  50530. var engine = scene.getEngine();
  50531. // VBO
  50532. var vertices = [];
  50533. vertices.push(1, 1);
  50534. vertices.push(-1, 1);
  50535. vertices.push(-1, -1);
  50536. vertices.push(1, -1);
  50537. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  50538. // Indices
  50539. var indices = [];
  50540. indices.push(0);
  50541. indices.push(1);
  50542. indices.push(2);
  50543. indices.push(0);
  50544. indices.push(2);
  50545. indices.push(3);
  50546. this._indexBuffer = engine.createIndexBuffer(indices);
  50547. // Effects
  50548. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  50549. }
  50550. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  50551. get: function () {
  50552. return this._isEnabled;
  50553. },
  50554. set: function (value) {
  50555. this._isEnabled = value;
  50556. },
  50557. enumerable: true,
  50558. configurable: true
  50559. });
  50560. LensFlareSystem.prototype.getScene = function () {
  50561. return this._scene;
  50562. };
  50563. LensFlareSystem.prototype.getEmitter = function () {
  50564. return this._emitter;
  50565. };
  50566. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  50567. this._emitter = newEmitter;
  50568. };
  50569. LensFlareSystem.prototype.getEmitterPosition = function () {
  50570. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  50571. };
  50572. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  50573. var position = this.getEmitterPosition();
  50574. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  50575. this._positionX = position.x;
  50576. this._positionY = position.y;
  50577. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  50578. if (position.z > 0) {
  50579. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  50580. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  50581. return true;
  50582. }
  50583. }
  50584. return false;
  50585. };
  50586. LensFlareSystem.prototype._isVisible = function () {
  50587. if (!this._isEnabled) {
  50588. return false;
  50589. }
  50590. var emitterPosition = this.getEmitterPosition();
  50591. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  50592. var distance = direction.length();
  50593. direction.normalize();
  50594. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  50595. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  50596. return !pickInfo.hit || pickInfo.distance > distance;
  50597. };
  50598. LensFlareSystem.prototype.render = function () {
  50599. if (!this._effect.isReady())
  50600. return false;
  50601. var engine = this._scene.getEngine();
  50602. var viewport = this._scene.activeCamera.viewport;
  50603. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  50604. // Position
  50605. if (!this.computeEffectivePosition(globalViewport)) {
  50606. return false;
  50607. }
  50608. // Visibility
  50609. if (!this._isVisible()) {
  50610. return false;
  50611. }
  50612. // Intensity
  50613. var awayX;
  50614. var awayY;
  50615. if (this._positionX < this.borderLimit + globalViewport.x) {
  50616. awayX = this.borderLimit + globalViewport.x - this._positionX;
  50617. }
  50618. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  50619. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  50620. }
  50621. else {
  50622. awayX = 0;
  50623. }
  50624. if (this._positionY < this.borderLimit + globalViewport.y) {
  50625. awayY = this.borderLimit + globalViewport.y - this._positionY;
  50626. }
  50627. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  50628. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  50629. }
  50630. else {
  50631. awayY = 0;
  50632. }
  50633. var away = (awayX > awayY) ? awayX : awayY;
  50634. if (away > this.borderLimit) {
  50635. away = this.borderLimit;
  50636. }
  50637. var intensity = 1.0 - (away / this.borderLimit);
  50638. if (intensity < 0) {
  50639. return false;
  50640. }
  50641. if (intensity > 1.0) {
  50642. intensity = 1.0;
  50643. }
  50644. // Position
  50645. var centerX = globalViewport.x + globalViewport.width / 2;
  50646. var centerY = globalViewport.y + globalViewport.height / 2;
  50647. var distX = centerX - this._positionX;
  50648. var distY = centerY - this._positionY;
  50649. // Effects
  50650. engine.enableEffect(this._effect);
  50651. engine.setState(false);
  50652. engine.setDepthBuffer(false);
  50653. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  50654. // VBOs
  50655. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50656. // Flares
  50657. for (var index = 0; index < this.lensFlares.length; index++) {
  50658. var flare = this.lensFlares[index];
  50659. var x = centerX - (distX * flare.position);
  50660. var y = centerY - (distY * flare.position);
  50661. var cw = flare.size;
  50662. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  50663. var cx = 2 * (x / globalViewport.width) - 1.0;
  50664. var cy = 1.0 - 2 * (y / globalViewport.height);
  50665. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  50666. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  50667. // Texture
  50668. this._effect.setTexture("textureSampler", flare.texture);
  50669. // Color
  50670. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  50671. // Draw order
  50672. engine.draw(true, 0, 6);
  50673. }
  50674. engine.setDepthBuffer(true);
  50675. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50676. return true;
  50677. };
  50678. LensFlareSystem.prototype.dispose = function () {
  50679. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  50680. if (vertexBuffer) {
  50681. vertexBuffer.dispose();
  50682. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  50683. }
  50684. if (this._indexBuffer) {
  50685. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50686. this._indexBuffer = null;
  50687. }
  50688. while (this.lensFlares.length) {
  50689. this.lensFlares[0].dispose();
  50690. }
  50691. // Remove from scene
  50692. var index = this._scene.lensFlareSystems.indexOf(this);
  50693. this._scene.lensFlareSystems.splice(index, 1);
  50694. };
  50695. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  50696. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  50697. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  50698. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  50699. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  50700. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  50701. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  50702. var parsedFlare = parsedLensFlareSystem.flares[index];
  50703. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  50704. }
  50705. return lensFlareSystem;
  50706. };
  50707. LensFlareSystem.prototype.serialize = function () {
  50708. var serializationObject = {};
  50709. serializationObject.id = this.id;
  50710. serializationObject.name = this.name;
  50711. serializationObject.emitterId = this.getEmitter().id;
  50712. serializationObject.borderLimit = this.borderLimit;
  50713. serializationObject.flares = [];
  50714. for (var index = 0; index < this.lensFlares.length; index++) {
  50715. var flare = this.lensFlares[index];
  50716. serializationObject.flares.push({
  50717. size: flare.size,
  50718. position: flare.position,
  50719. color: flare.color.asArray(),
  50720. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  50721. });
  50722. }
  50723. return serializationObject;
  50724. };
  50725. return LensFlareSystem;
  50726. })();
  50727. BABYLON.LensFlareSystem = LensFlareSystem;
  50728. })(BABYLON || (BABYLON = {}));
  50729. var BABYLON;
  50730. (function (BABYLON) {
  50731. // We're mainly based on the logic defined into the FreeCamera code
  50732. var DeviceOrientationCamera = (function (_super) {
  50733. __extends(DeviceOrientationCamera, _super);
  50734. //-- end properties for backward compatibility for inputs
  50735. function DeviceOrientationCamera(name, position, scene) {
  50736. _super.call(this, name, position, scene);
  50737. this.inputs.addDeviceOrientation();
  50738. }
  50739. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  50740. //-- Begin properties for backward compatibility for inputs
  50741. get: function () {
  50742. return 0;
  50743. },
  50744. set: function (value) {
  50745. },
  50746. enumerable: true,
  50747. configurable: true
  50748. });
  50749. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  50750. get: function () {
  50751. return 0;
  50752. },
  50753. set: function (value) {
  50754. },
  50755. enumerable: true,
  50756. configurable: true
  50757. });
  50758. DeviceOrientationCamera.prototype.getTypeName = function () {
  50759. return "DeviceOrientationCamera";
  50760. };
  50761. return DeviceOrientationCamera;
  50762. })(BABYLON.FreeCamera);
  50763. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  50764. })(BABYLON || (BABYLON = {}));
  50765. var BABYLON;
  50766. (function (BABYLON) {
  50767. // We're mainly based on the logic defined into the FreeCamera code
  50768. var UniversalCamera = (function (_super) {
  50769. __extends(UniversalCamera, _super);
  50770. //-- end properties for backward compatibility for inputs
  50771. function UniversalCamera(name, position, scene) {
  50772. _super.call(this, name, position, scene);
  50773. this.inputs.addGamepad();
  50774. }
  50775. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  50776. //-- Begin properties for backward compatibility for inputs
  50777. get: function () {
  50778. var gamepad = this.inputs.attached["gamepad"];
  50779. if (gamepad)
  50780. return gamepad.gamepadAngularSensibility;
  50781. },
  50782. set: function (value) {
  50783. var gamepad = this.inputs.attached["gamepad"];
  50784. if (gamepad)
  50785. gamepad.gamepadAngularSensibility = value;
  50786. },
  50787. enumerable: true,
  50788. configurable: true
  50789. });
  50790. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  50791. get: function () {
  50792. var gamepad = this.inputs.attached["gamepad"];
  50793. if (gamepad)
  50794. return gamepad.gamepadMoveSensibility;
  50795. },
  50796. set: function (value) {
  50797. var gamepad = this.inputs.attached["gamepad"];
  50798. if (gamepad)
  50799. gamepad.gamepadMoveSensibility = value;
  50800. },
  50801. enumerable: true,
  50802. configurable: true
  50803. });
  50804. UniversalCamera.prototype.getTypeName = function () {
  50805. return "UniversalCamera";
  50806. };
  50807. return UniversalCamera;
  50808. })(BABYLON.TouchCamera);
  50809. BABYLON.UniversalCamera = UniversalCamera;
  50810. })(BABYLON || (BABYLON = {}));
  50811. var BABYLON;
  50812. (function (BABYLON) {
  50813. var Gamepads = (function () {
  50814. function Gamepads(ongamedpadconnected) {
  50815. var _this = this;
  50816. this.babylonGamepads = [];
  50817. this.oneGamepadConnected = false;
  50818. this.isMonitoring = false;
  50819. this.gamepadEventSupported = 'GamepadEvent' in window;
  50820. this.gamepadSupportAvailable = (navigator.getGamepads ||
  50821. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  50822. this._callbackGamepadConnected = ongamedpadconnected;
  50823. if (this.gamepadSupportAvailable) {
  50824. // Checking if the gamepad connected event is supported (like in Firefox)
  50825. if (this.gamepadEventSupported) {
  50826. this._onGamepadConnectedEvent = function (evt) {
  50827. _this._onGamepadConnected(evt);
  50828. };
  50829. this._onGamepadDisonnectedEvent = function (evt) {
  50830. _this._onGamepadDisconnected(evt);
  50831. };
  50832. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  50833. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  50834. }
  50835. else {
  50836. this._startMonitoringGamepads();
  50837. }
  50838. }
  50839. }
  50840. Gamepads.prototype.dispose = function () {
  50841. if (Gamepads.gamepadDOMInfo) {
  50842. document.body.removeChild(Gamepads.gamepadDOMInfo);
  50843. }
  50844. if (this._onGamepadConnectedEvent) {
  50845. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  50846. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  50847. this._onGamepadConnectedEvent = null;
  50848. this._onGamepadDisonnectedEvent = null;
  50849. }
  50850. };
  50851. Gamepads.prototype._onGamepadConnected = function (evt) {
  50852. var newGamepad = this._addNewGamepad(evt.gamepad);
  50853. if (this._callbackGamepadConnected)
  50854. this._callbackGamepadConnected(newGamepad);
  50855. this._startMonitoringGamepads();
  50856. };
  50857. Gamepads.prototype._addNewGamepad = function (gamepad) {
  50858. if (!this.oneGamepadConnected) {
  50859. this.oneGamepadConnected = true;
  50860. if (Gamepads.gamepadDOMInfo) {
  50861. document.body.removeChild(Gamepads.gamepadDOMInfo);
  50862. Gamepads.gamepadDOMInfo = null;
  50863. }
  50864. }
  50865. var newGamepad;
  50866. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  50867. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  50868. }
  50869. else {
  50870. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  50871. }
  50872. this.babylonGamepads.push(newGamepad);
  50873. return newGamepad;
  50874. };
  50875. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  50876. // Remove the gamepad from the list of gamepads to monitor.
  50877. for (var i in this.babylonGamepads) {
  50878. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  50879. this.babylonGamepads.splice(+i, 1);
  50880. break;
  50881. }
  50882. }
  50883. // If no gamepads are left, stop the polling loop.
  50884. if (this.babylonGamepads.length == 0) {
  50885. this._stopMonitoringGamepads();
  50886. }
  50887. };
  50888. Gamepads.prototype._startMonitoringGamepads = function () {
  50889. if (!this.isMonitoring) {
  50890. this.isMonitoring = true;
  50891. this._checkGamepadsStatus();
  50892. }
  50893. };
  50894. Gamepads.prototype._stopMonitoringGamepads = function () {
  50895. this.isMonitoring = false;
  50896. };
  50897. Gamepads.prototype._checkGamepadsStatus = function () {
  50898. var _this = this;
  50899. // updating gamepad objects
  50900. this._updateGamepadObjects();
  50901. for (var i in this.babylonGamepads) {
  50902. this.babylonGamepads[i].update();
  50903. }
  50904. if (this.isMonitoring) {
  50905. if (window.requestAnimationFrame) {
  50906. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50907. }
  50908. else if (window.mozRequestAnimationFrame) {
  50909. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50910. }
  50911. else if (window.webkitRequestAnimationFrame) {
  50912. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50913. }
  50914. }
  50915. };
  50916. // This function is called only on Chrome, which does not yet support
  50917. // connection/disconnection events, but requires you to monitor
  50918. // an array for changes.
  50919. Gamepads.prototype._updateGamepadObjects = function () {
  50920. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  50921. for (var i = 0; i < gamepads.length; i++) {
  50922. if (gamepads[i]) {
  50923. if (!(gamepads[i].index in this.babylonGamepads)) {
  50924. var newGamepad = this._addNewGamepad(gamepads[i]);
  50925. if (this._callbackGamepadConnected) {
  50926. this._callbackGamepadConnected(newGamepad);
  50927. }
  50928. }
  50929. else {
  50930. this.babylonGamepads[i].browserGamepad = gamepads[i];
  50931. }
  50932. }
  50933. }
  50934. };
  50935. return Gamepads;
  50936. })();
  50937. BABYLON.Gamepads = Gamepads;
  50938. var StickValues = (function () {
  50939. function StickValues(x, y) {
  50940. this.x = x;
  50941. this.y = y;
  50942. }
  50943. return StickValues;
  50944. })();
  50945. BABYLON.StickValues = StickValues;
  50946. var Gamepad = (function () {
  50947. function Gamepad(id, index, browserGamepad) {
  50948. this.id = id;
  50949. this.index = index;
  50950. this.browserGamepad = browserGamepad;
  50951. if (this.browserGamepad.axes.length >= 2) {
  50952. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  50953. }
  50954. if (this.browserGamepad.axes.length >= 4) {
  50955. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  50956. }
  50957. }
  50958. Gamepad.prototype.onleftstickchanged = function (callback) {
  50959. this._onleftstickchanged = callback;
  50960. };
  50961. Gamepad.prototype.onrightstickchanged = function (callback) {
  50962. this._onrightstickchanged = callback;
  50963. };
  50964. Object.defineProperty(Gamepad.prototype, "leftStick", {
  50965. get: function () {
  50966. return this._leftStick;
  50967. },
  50968. set: function (newValues) {
  50969. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  50970. this._onleftstickchanged(newValues);
  50971. }
  50972. this._leftStick = newValues;
  50973. },
  50974. enumerable: true,
  50975. configurable: true
  50976. });
  50977. Object.defineProperty(Gamepad.prototype, "rightStick", {
  50978. get: function () {
  50979. return this._rightStick;
  50980. },
  50981. set: function (newValues) {
  50982. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  50983. this._onrightstickchanged(newValues);
  50984. }
  50985. this._rightStick = newValues;
  50986. },
  50987. enumerable: true,
  50988. configurable: true
  50989. });
  50990. Gamepad.prototype.update = function () {
  50991. if (this._leftStick) {
  50992. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  50993. }
  50994. if (this._rightStick) {
  50995. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  50996. }
  50997. };
  50998. return Gamepad;
  50999. })();
  51000. BABYLON.Gamepad = Gamepad;
  51001. var GenericPad = (function (_super) {
  51002. __extends(GenericPad, _super);
  51003. function GenericPad(id, index, gamepad) {
  51004. _super.call(this, id, index, gamepad);
  51005. this.id = id;
  51006. this.index = index;
  51007. this.gamepad = gamepad;
  51008. this._buttons = new Array(gamepad.buttons.length);
  51009. }
  51010. GenericPad.prototype.onbuttondown = function (callback) {
  51011. this._onbuttondown = callback;
  51012. };
  51013. GenericPad.prototype.onbuttonup = function (callback) {
  51014. this._onbuttonup = callback;
  51015. };
  51016. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  51017. if (newValue !== currentValue) {
  51018. if (this._onbuttondown && newValue === 1) {
  51019. this._onbuttondown(buttonIndex);
  51020. }
  51021. if (this._onbuttonup && newValue === 0) {
  51022. this._onbuttonup(buttonIndex);
  51023. }
  51024. }
  51025. return newValue;
  51026. };
  51027. GenericPad.prototype.update = function () {
  51028. _super.prototype.update.call(this);
  51029. for (var index = 0; index < this._buttons.length; index++) {
  51030. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  51031. }
  51032. };
  51033. return GenericPad;
  51034. })(Gamepad);
  51035. BABYLON.GenericPad = GenericPad;
  51036. (function (Xbox360Button) {
  51037. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  51038. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  51039. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  51040. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  51041. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  51042. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  51043. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  51044. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  51045. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  51046. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  51047. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  51048. var Xbox360Button = BABYLON.Xbox360Button;
  51049. (function (Xbox360Dpad) {
  51050. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  51051. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  51052. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  51053. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  51054. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  51055. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  51056. var Xbox360Pad = (function (_super) {
  51057. __extends(Xbox360Pad, _super);
  51058. function Xbox360Pad() {
  51059. _super.apply(this, arguments);
  51060. this._leftTrigger = 0;
  51061. this._rightTrigger = 0;
  51062. this._buttonA = 0;
  51063. this._buttonB = 0;
  51064. this._buttonX = 0;
  51065. this._buttonY = 0;
  51066. this._buttonBack = 0;
  51067. this._buttonStart = 0;
  51068. this._buttonLB = 0;
  51069. this._buttonRB = 0;
  51070. this._buttonLeftStick = 0;
  51071. this._buttonRightStick = 0;
  51072. this._dPadUp = 0;
  51073. this._dPadDown = 0;
  51074. this._dPadLeft = 0;
  51075. this._dPadRight = 0;
  51076. }
  51077. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  51078. this._onlefttriggerchanged = callback;
  51079. };
  51080. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  51081. this._onrighttriggerchanged = callback;
  51082. };
  51083. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  51084. get: function () {
  51085. return this._leftTrigger;
  51086. },
  51087. set: function (newValue) {
  51088. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  51089. this._onlefttriggerchanged(newValue);
  51090. }
  51091. this._leftTrigger = newValue;
  51092. },
  51093. enumerable: true,
  51094. configurable: true
  51095. });
  51096. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  51097. get: function () {
  51098. return this._rightTrigger;
  51099. },
  51100. set: function (newValue) {
  51101. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  51102. this._onrighttriggerchanged(newValue);
  51103. }
  51104. this._rightTrigger = newValue;
  51105. },
  51106. enumerable: true,
  51107. configurable: true
  51108. });
  51109. Xbox360Pad.prototype.onbuttondown = function (callback) {
  51110. this._onbuttondown = callback;
  51111. };
  51112. Xbox360Pad.prototype.onbuttonup = function (callback) {
  51113. this._onbuttonup = callback;
  51114. };
  51115. Xbox360Pad.prototype.ondpaddown = function (callback) {
  51116. this._ondpaddown = callback;
  51117. };
  51118. Xbox360Pad.prototype.ondpadup = function (callback) {
  51119. this._ondpadup = callback;
  51120. };
  51121. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  51122. if (newValue !== currentValue) {
  51123. if (this._onbuttondown && newValue === 1) {
  51124. this._onbuttondown(buttonType);
  51125. }
  51126. if (this._onbuttonup && newValue === 0) {
  51127. this._onbuttonup(buttonType);
  51128. }
  51129. }
  51130. return newValue;
  51131. };
  51132. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  51133. if (newValue !== currentValue) {
  51134. if (this._ondpaddown && newValue === 1) {
  51135. this._ondpaddown(buttonType);
  51136. }
  51137. if (this._ondpadup && newValue === 0) {
  51138. this._ondpadup(buttonType);
  51139. }
  51140. }
  51141. return newValue;
  51142. };
  51143. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  51144. get: function () {
  51145. return this._buttonA;
  51146. },
  51147. set: function (value) {
  51148. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  51149. },
  51150. enumerable: true,
  51151. configurable: true
  51152. });
  51153. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  51154. get: function () {
  51155. return this._buttonB;
  51156. },
  51157. set: function (value) {
  51158. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  51159. },
  51160. enumerable: true,
  51161. configurable: true
  51162. });
  51163. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  51164. get: function () {
  51165. return this._buttonX;
  51166. },
  51167. set: function (value) {
  51168. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  51169. },
  51170. enumerable: true,
  51171. configurable: true
  51172. });
  51173. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  51174. get: function () {
  51175. return this._buttonY;
  51176. },
  51177. set: function (value) {
  51178. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  51179. },
  51180. enumerable: true,
  51181. configurable: true
  51182. });
  51183. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  51184. get: function () {
  51185. return this._buttonStart;
  51186. },
  51187. set: function (value) {
  51188. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  51189. },
  51190. enumerable: true,
  51191. configurable: true
  51192. });
  51193. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  51194. get: function () {
  51195. return this._buttonBack;
  51196. },
  51197. set: function (value) {
  51198. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  51199. },
  51200. enumerable: true,
  51201. configurable: true
  51202. });
  51203. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  51204. get: function () {
  51205. return this._buttonLB;
  51206. },
  51207. set: function (value) {
  51208. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  51209. },
  51210. enumerable: true,
  51211. configurable: true
  51212. });
  51213. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  51214. get: function () {
  51215. return this._buttonRB;
  51216. },
  51217. set: function (value) {
  51218. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  51219. },
  51220. enumerable: true,
  51221. configurable: true
  51222. });
  51223. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  51224. get: function () {
  51225. return this._buttonLeftStick;
  51226. },
  51227. set: function (value) {
  51228. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  51229. },
  51230. enumerable: true,
  51231. configurable: true
  51232. });
  51233. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  51234. get: function () {
  51235. return this._buttonRightStick;
  51236. },
  51237. set: function (value) {
  51238. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  51239. },
  51240. enumerable: true,
  51241. configurable: true
  51242. });
  51243. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  51244. get: function () {
  51245. return this._dPadUp;
  51246. },
  51247. set: function (value) {
  51248. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  51249. },
  51250. enumerable: true,
  51251. configurable: true
  51252. });
  51253. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  51254. get: function () {
  51255. return this._dPadDown;
  51256. },
  51257. set: function (value) {
  51258. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  51259. },
  51260. enumerable: true,
  51261. configurable: true
  51262. });
  51263. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  51264. get: function () {
  51265. return this._dPadLeft;
  51266. },
  51267. set: function (value) {
  51268. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  51269. },
  51270. enumerable: true,
  51271. configurable: true
  51272. });
  51273. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  51274. get: function () {
  51275. return this._dPadRight;
  51276. },
  51277. set: function (value) {
  51278. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  51279. },
  51280. enumerable: true,
  51281. configurable: true
  51282. });
  51283. Xbox360Pad.prototype.update = function () {
  51284. _super.prototype.update.call(this);
  51285. this.buttonA = this.browserGamepad.buttons[0].value;
  51286. this.buttonB = this.browserGamepad.buttons[1].value;
  51287. this.buttonX = this.browserGamepad.buttons[2].value;
  51288. this.buttonY = this.browserGamepad.buttons[3].value;
  51289. this.buttonLB = this.browserGamepad.buttons[4].value;
  51290. this.buttonRB = this.browserGamepad.buttons[5].value;
  51291. this.leftTrigger = this.browserGamepad.buttons[6].value;
  51292. this.rightTrigger = this.browserGamepad.buttons[7].value;
  51293. this.buttonBack = this.browserGamepad.buttons[8].value;
  51294. this.buttonStart = this.browserGamepad.buttons[9].value;
  51295. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  51296. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  51297. this.dPadUp = this.browserGamepad.buttons[12].value;
  51298. this.dPadDown = this.browserGamepad.buttons[13].value;
  51299. this.dPadLeft = this.browserGamepad.buttons[14].value;
  51300. this.dPadRight = this.browserGamepad.buttons[15].value;
  51301. };
  51302. return Xbox360Pad;
  51303. })(Gamepad);
  51304. BABYLON.Xbox360Pad = Xbox360Pad;
  51305. })(BABYLON || (BABYLON = {}));
  51306. var BABYLON;
  51307. (function (BABYLON) {
  51308. // We're mainly based on the logic defined into the FreeCamera code
  51309. var GamepadCamera = (function (_super) {
  51310. __extends(GamepadCamera, _super);
  51311. //-- end properties for backward compatibility for inputs
  51312. function GamepadCamera(name, position, scene) {
  51313. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  51314. _super.call(this, name, position, scene);
  51315. }
  51316. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  51317. //-- Begin properties for backward compatibility for inputs
  51318. get: function () {
  51319. var gamepad = this.inputs.attached["gamepad"];
  51320. if (gamepad)
  51321. return gamepad.gamepadAngularSensibility;
  51322. },
  51323. set: function (value) {
  51324. var gamepad = this.inputs.attached["gamepad"];
  51325. if (gamepad)
  51326. gamepad.gamepadAngularSensibility = value;
  51327. },
  51328. enumerable: true,
  51329. configurable: true
  51330. });
  51331. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  51332. get: function () {
  51333. var gamepad = this.inputs.attached["gamepad"];
  51334. if (gamepad)
  51335. return gamepad.gamepadMoveSensibility;
  51336. },
  51337. set: function (value) {
  51338. var gamepad = this.inputs.attached["gamepad"];
  51339. if (gamepad)
  51340. gamepad.gamepadMoveSensibility = value;
  51341. },
  51342. enumerable: true,
  51343. configurable: true
  51344. });
  51345. GamepadCamera.prototype.getTypeName = function () {
  51346. return "GamepadCamera";
  51347. };
  51348. return GamepadCamera;
  51349. })(BABYLON.UniversalCamera);
  51350. BABYLON.GamepadCamera = GamepadCamera;
  51351. })(BABYLON || (BABYLON = {}));
  51352. var BABYLON;
  51353. (function (BABYLON) {
  51354. var Analyser = (function () {
  51355. function Analyser(scene) {
  51356. this.SMOOTHING = 0.75;
  51357. this.FFT_SIZE = 512;
  51358. this.BARGRAPHAMPLITUDE = 256;
  51359. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  51360. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  51361. this._scene = scene;
  51362. this._audioEngine = BABYLON.Engine.audioEngine;
  51363. if (this._audioEngine.canUseWebAudio) {
  51364. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  51365. this._webAudioAnalyser.minDecibels = -140;
  51366. this._webAudioAnalyser.maxDecibels = 0;
  51367. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51368. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51369. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  51370. }
  51371. }
  51372. Analyser.prototype.getFrequencyBinCount = function () {
  51373. if (this._audioEngine.canUseWebAudio) {
  51374. return this._webAudioAnalyser.frequencyBinCount;
  51375. }
  51376. else {
  51377. return 0;
  51378. }
  51379. };
  51380. Analyser.prototype.getByteFrequencyData = function () {
  51381. if (this._audioEngine.canUseWebAudio) {
  51382. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51383. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51384. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  51385. }
  51386. return this._byteFreqs;
  51387. };
  51388. Analyser.prototype.getByteTimeDomainData = function () {
  51389. if (this._audioEngine.canUseWebAudio) {
  51390. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51391. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51392. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  51393. }
  51394. return this._byteTime;
  51395. };
  51396. Analyser.prototype.getFloatFrequencyData = function () {
  51397. if (this._audioEngine.canUseWebAudio) {
  51398. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51399. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51400. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  51401. }
  51402. return this._floatFreqs;
  51403. };
  51404. Analyser.prototype.drawDebugCanvas = function () {
  51405. var _this = this;
  51406. if (this._audioEngine.canUseWebAudio) {
  51407. if (!this._debugCanvas) {
  51408. this._debugCanvas = document.createElement("canvas");
  51409. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  51410. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  51411. this._debugCanvas.style.position = "absolute";
  51412. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  51413. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  51414. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  51415. document.body.appendChild(this._debugCanvas);
  51416. this._registerFunc = function () {
  51417. _this.drawDebugCanvas();
  51418. };
  51419. this._scene.registerBeforeRender(this._registerFunc);
  51420. }
  51421. if (this._registerFunc) {
  51422. var workingArray = this.getByteFrequencyData();
  51423. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  51424. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  51425. // Draw the frequency domain chart.
  51426. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  51427. var value = workingArray[i];
  51428. var percent = value / this.BARGRAPHAMPLITUDE;
  51429. var height = this.DEBUGCANVASSIZE.height * percent;
  51430. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  51431. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  51432. var hue = i / this.getFrequencyBinCount() * 360;
  51433. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  51434. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  51435. }
  51436. }
  51437. }
  51438. };
  51439. Analyser.prototype.stopDebugCanvas = function () {
  51440. if (this._debugCanvas) {
  51441. this._scene.unregisterBeforeRender(this._registerFunc);
  51442. this._registerFunc = null;
  51443. document.body.removeChild(this._debugCanvas);
  51444. this._debugCanvas = null;
  51445. this._debugCanvasContext = null;
  51446. }
  51447. };
  51448. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  51449. if (this._audioEngine.canUseWebAudio) {
  51450. inputAudioNode.connect(this._webAudioAnalyser);
  51451. this._webAudioAnalyser.connect(outputAudioNode);
  51452. }
  51453. };
  51454. Analyser.prototype.dispose = function () {
  51455. if (this._audioEngine.canUseWebAudio) {
  51456. this._webAudioAnalyser.disconnect();
  51457. }
  51458. };
  51459. return Analyser;
  51460. })();
  51461. BABYLON.Analyser = Analyser;
  51462. })(BABYLON || (BABYLON = {}));
  51463. var BABYLON;
  51464. (function (BABYLON) {
  51465. var DepthRenderer = (function () {
  51466. function DepthRenderer(scene, type) {
  51467. var _this = this;
  51468. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  51469. this._viewMatrix = BABYLON.Matrix.Zero();
  51470. this._projectionMatrix = BABYLON.Matrix.Zero();
  51471. this._transformMatrix = BABYLON.Matrix.Zero();
  51472. this._worldViewProjection = BABYLON.Matrix.Zero();
  51473. this._scene = scene;
  51474. var engine = scene.getEngine();
  51475. // Render target
  51476. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  51477. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51478. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51479. this._depthMap.refreshRate = 1;
  51480. this._depthMap.renderParticles = false;
  51481. this._depthMap.renderList = null;
  51482. // set default depth value to 1.0 (far away)
  51483. this._depthMap.onClearObservable.add(function (engine) {
  51484. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  51485. });
  51486. // Custom render function
  51487. var renderSubMesh = function (subMesh) {
  51488. var mesh = subMesh.getRenderingMesh();
  51489. var scene = _this._scene;
  51490. var engine = scene.getEngine();
  51491. // Culling
  51492. engine.setState(subMesh.getMaterial().backFaceCulling);
  51493. // Managing instances
  51494. var batch = mesh._getInstancesRenderList(subMesh._id);
  51495. if (batch.mustReturn) {
  51496. return;
  51497. }
  51498. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  51499. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  51500. engine.enableEffect(_this._effect);
  51501. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  51502. var material = subMesh.getMaterial();
  51503. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  51504. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  51505. // Alpha test
  51506. if (material && material.needAlphaTesting()) {
  51507. var alphaTexture = material.getAlphaTestTexture();
  51508. _this._effect.setTexture("diffuseSampler", alphaTexture);
  51509. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  51510. }
  51511. // Bones
  51512. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51513. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  51514. }
  51515. // Draw
  51516. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51517. }
  51518. };
  51519. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  51520. var index;
  51521. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51522. renderSubMesh(opaqueSubMeshes.data[index]);
  51523. }
  51524. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51525. renderSubMesh(alphaTestSubMeshes.data[index]);
  51526. }
  51527. };
  51528. }
  51529. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  51530. var material = subMesh.getMaterial();
  51531. if (material.disableDepthWrite) {
  51532. return false;
  51533. }
  51534. var defines = [];
  51535. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51536. var mesh = subMesh.getMesh();
  51537. var scene = mesh.getScene();
  51538. // Alpha test
  51539. if (material && material.needAlphaTesting()) {
  51540. defines.push("#define ALPHATEST");
  51541. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51542. attribs.push(BABYLON.VertexBuffer.UVKind);
  51543. defines.push("#define UV1");
  51544. }
  51545. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51546. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51547. defines.push("#define UV2");
  51548. }
  51549. }
  51550. // Bones
  51551. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51552. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51553. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51554. if (mesh.numBoneInfluencers > 4) {
  51555. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51556. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51557. }
  51558. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51559. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51560. }
  51561. else {
  51562. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51563. }
  51564. // Instances
  51565. if (useInstances) {
  51566. defines.push("#define INSTANCES");
  51567. attribs.push("world0");
  51568. attribs.push("world1");
  51569. attribs.push("world2");
  51570. attribs.push("world3");
  51571. }
  51572. // Get correct effect
  51573. var join = defines.join("\n");
  51574. if (this._cachedDefines !== join) {
  51575. this._cachedDefines = join;
  51576. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  51577. }
  51578. return this._effect.isReady();
  51579. };
  51580. DepthRenderer.prototype.getDepthMap = function () {
  51581. return this._depthMap;
  51582. };
  51583. // Methods
  51584. DepthRenderer.prototype.dispose = function () {
  51585. this._depthMap.dispose();
  51586. };
  51587. return DepthRenderer;
  51588. })();
  51589. BABYLON.DepthRenderer = DepthRenderer;
  51590. })(BABYLON || (BABYLON = {}));
  51591. var BABYLON;
  51592. (function (BABYLON) {
  51593. var SSAORenderingPipeline = (function (_super) {
  51594. __extends(SSAORenderingPipeline, _super);
  51595. /**
  51596. * @constructor
  51597. * @param {string} name - The rendering pipeline name
  51598. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51599. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  51600. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51601. */
  51602. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  51603. var _this = this;
  51604. _super.call(this, scene.getEngine(), name);
  51605. // Members
  51606. /**
  51607. * The PassPostProcess id in the pipeline that contains the original scene color
  51608. * @type {string}
  51609. */
  51610. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  51611. /**
  51612. * The SSAO PostProcess id in the pipeline
  51613. * @type {string}
  51614. */
  51615. this.SSAORenderEffect = "SSAORenderEffect";
  51616. /**
  51617. * The horizontal blur PostProcess id in the pipeline
  51618. * @type {string}
  51619. */
  51620. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  51621. /**
  51622. * The vertical blur PostProcess id in the pipeline
  51623. * @type {string}
  51624. */
  51625. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  51626. /**
  51627. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  51628. * @type {string}
  51629. */
  51630. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  51631. /**
  51632. * The output strength of the SSAO post-process. Default value is 1.0.
  51633. * @type {number}
  51634. */
  51635. this.totalStrength = 1.0;
  51636. /**
  51637. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  51638. * @type {number}
  51639. */
  51640. this.radius = 0.0001;
  51641. /**
  51642. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  51643. * Must not be equal to fallOff and superior to fallOff.
  51644. * Default value is 0.975
  51645. * @type {number}
  51646. */
  51647. this.area = 0.0075;
  51648. /**
  51649. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  51650. * Must not be equal to area and inferior to area.
  51651. * Default value is 0.0
  51652. * @type {number}
  51653. */
  51654. this.fallOff = 0.000001;
  51655. /**
  51656. * The base color of the SSAO post-process
  51657. * The final result is "base + ssao" between [0, 1]
  51658. * @type {number}
  51659. */
  51660. this.base = 0.5;
  51661. this._firstUpdate = true;
  51662. this._scene = scene;
  51663. // Set up assets
  51664. this._createRandomTexture();
  51665. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  51666. var ssaoRatio = ratio.ssaoRatio || ratio;
  51667. var combineRatio = ratio.combineRatio || ratio;
  51668. this._ratio = {
  51669. ssaoRatio: ssaoRatio,
  51670. combineRatio: combineRatio
  51671. };
  51672. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  51673. this._createSSAOPostProcess(ssaoRatio);
  51674. this._createBlurPostProcess(ssaoRatio);
  51675. this._createSSAOCombinePostProcess(combineRatio);
  51676. // Set up pipeline
  51677. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  51678. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  51679. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  51680. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  51681. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  51682. // Finish
  51683. scene.postProcessRenderPipelineManager.addPipeline(this);
  51684. if (cameras)
  51685. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  51686. }
  51687. // Public Methods
  51688. /**
  51689. * Returns the horizontal blur PostProcess
  51690. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  51691. */
  51692. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  51693. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  51694. return null;
  51695. };
  51696. /**
  51697. * Returns the vertical blur PostProcess
  51698. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  51699. */
  51700. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  51701. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  51702. return null;
  51703. };
  51704. /**
  51705. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  51706. */
  51707. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  51708. if (disableDepthRender === void 0) { disableDepthRender = false; }
  51709. for (var i = 0; i < this._scene.cameras.length; i++) {
  51710. var camera = this._scene.cameras[i];
  51711. this._originalColorPostProcess.dispose(camera);
  51712. this._ssaoPostProcess.dispose(camera);
  51713. this._blurHPostProcess.dispose(camera);
  51714. this._blurVPostProcess.dispose(camera);
  51715. this._ssaoCombinePostProcess.dispose(camera);
  51716. }
  51717. this._randomTexture.dispose();
  51718. if (disableDepthRender)
  51719. this._scene.disableDepthRenderer();
  51720. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  51721. };
  51722. // Private Methods
  51723. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  51724. var _this = this;
  51725. /*
  51726. var samplerOffsets = [
  51727. -8.0, -6.0, -4.0, -2.0,
  51728. 0.0,
  51729. 2.0, 4.0, 6.0, 8.0
  51730. ];
  51731. */
  51732. var samples = 16;
  51733. var samplerOffsets = [];
  51734. for (var i = -8; i < 8; i++) {
  51735. samplerOffsets.push(i * 2);
  51736. }
  51737. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  51738. this._blurHPostProcess.onApply = function (effect) {
  51739. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  51740. effect.setTexture("depthSampler", _this._depthTexture);
  51741. if (_this._firstUpdate) {
  51742. effect.setArray("samplerOffsets", samplerOffsets);
  51743. }
  51744. };
  51745. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  51746. this._blurVPostProcess.onApply = function (effect) {
  51747. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  51748. effect.setTexture("depthSampler", _this._depthTexture);
  51749. if (_this._firstUpdate) {
  51750. effect.setArray("samplerOffsets", samplerOffsets);
  51751. _this._firstUpdate = false;
  51752. }
  51753. };
  51754. };
  51755. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  51756. var _this = this;
  51757. var numSamples = 16;
  51758. var sampleSphere = [
  51759. 0.5381, 0.1856, -0.4319,
  51760. 0.1379, 0.2486, 0.4430,
  51761. 0.3371, 0.5679, -0.0057,
  51762. -0.6999, -0.0451, -0.0019,
  51763. 0.0689, -0.1598, -0.8547,
  51764. 0.0560, 0.0069, -0.1843,
  51765. -0.0146, 0.1402, 0.0762,
  51766. 0.0100, -0.1924, -0.0344,
  51767. -0.3577, -0.5301, -0.4358,
  51768. -0.3169, 0.1063, 0.0158,
  51769. 0.0103, -0.5869, 0.0046,
  51770. -0.0897, -0.4940, 0.3287,
  51771. 0.7119, -0.0154, -0.0918,
  51772. -0.0533, 0.0596, -0.5411,
  51773. 0.0352, -0.0631, 0.5460,
  51774. -0.4776, 0.2847, -0.0271
  51775. ];
  51776. var samplesFactor = 1.0 / numSamples;
  51777. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  51778. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  51779. "area", "fallOff", "base", "range", "viewport"
  51780. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  51781. var viewport = new BABYLON.Vector2(0, 0);
  51782. this._ssaoPostProcess.onApply = function (effect) {
  51783. if (_this._firstUpdate) {
  51784. effect.setArray3("sampleSphere", sampleSphere);
  51785. effect.setFloat("samplesFactor", samplesFactor);
  51786. effect.setFloat("randTextureTiles", 4.0);
  51787. }
  51788. effect.setFloat("totalStrength", _this.totalStrength);
  51789. effect.setFloat("radius", _this.radius);
  51790. effect.setFloat("area", _this.area);
  51791. effect.setFloat("fallOff", _this.fallOff);
  51792. effect.setFloat("base", _this.base);
  51793. effect.setTexture("textureSampler", _this._depthTexture);
  51794. effect.setTexture("randomSampler", _this._randomTexture);
  51795. };
  51796. };
  51797. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  51798. var _this = this;
  51799. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  51800. this._ssaoCombinePostProcess.onApply = function (effect) {
  51801. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  51802. };
  51803. };
  51804. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  51805. var size = 512;
  51806. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  51807. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51808. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51809. var context = this._randomTexture.getContext();
  51810. var rand = function (min, max) {
  51811. return Math.random() * (max - min) + min;
  51812. };
  51813. var randVector = BABYLON.Vector3.Zero();
  51814. for (var x = 0; x < size; x++) {
  51815. for (var y = 0; y < size; y++) {
  51816. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  51817. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  51818. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  51819. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  51820. context.fillRect(x, y, 1, 1);
  51821. }
  51822. }
  51823. this._randomTexture.update(false);
  51824. };
  51825. __decorate([
  51826. BABYLON.serialize()
  51827. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  51828. __decorate([
  51829. BABYLON.serialize()
  51830. ], SSAORenderingPipeline.prototype, "radius", void 0);
  51831. __decorate([
  51832. BABYLON.serialize()
  51833. ], SSAORenderingPipeline.prototype, "area", void 0);
  51834. __decorate([
  51835. BABYLON.serialize()
  51836. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  51837. __decorate([
  51838. BABYLON.serialize()
  51839. ], SSAORenderingPipeline.prototype, "base", void 0);
  51840. __decorate([
  51841. BABYLON.serialize()
  51842. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  51843. return SSAORenderingPipeline;
  51844. })(BABYLON.PostProcessRenderPipeline);
  51845. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  51846. })(BABYLON || (BABYLON = {}));
  51847. var BABYLON;
  51848. (function (BABYLON) {
  51849. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  51850. var VolumetricLightScatteringPostProcess = (function (_super) {
  51851. __extends(VolumetricLightScatteringPostProcess, _super);
  51852. /**
  51853. * @constructor
  51854. * @param {string} name - The post-process name
  51855. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  51856. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  51857. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  51858. * @param {number} samples - The post-process quality, default 100
  51859. * @param {number} samplingMode - The post-process filtering mode
  51860. * @param {BABYLON.Engine} engine - The babylon engine
  51861. * @param {boolean} reusable - If the post-process is reusable
  51862. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  51863. */
  51864. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  51865. var _this = this;
  51866. if (samples === void 0) { samples = 100; }
  51867. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51868. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  51869. this._screenCoordinates = BABYLON.Vector2.Zero();
  51870. /**
  51871. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  51872. * @type {Vector3}
  51873. */
  51874. this.customMeshPosition = BABYLON.Vector3.Zero();
  51875. /**
  51876. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  51877. * @type {boolean}
  51878. */
  51879. this.useCustomMeshPosition = false;
  51880. /**
  51881. * If the post-process should inverse the light scattering direction
  51882. * @type {boolean}
  51883. */
  51884. this.invert = true;
  51885. /**
  51886. * Array containing the excluded meshes not rendered in the internal pass
  51887. */
  51888. this.excludedMeshes = new Array();
  51889. /**
  51890. * Controls the overall intensity of the post-process
  51891. * @type {number}
  51892. */
  51893. this.exposure = 0.3;
  51894. /**
  51895. * Dissipates each sample's contribution in range [0, 1]
  51896. * @type {number}
  51897. */
  51898. this.decay = 0.96815;
  51899. /**
  51900. * Controls the overall intensity of each sample
  51901. * @type {number}
  51902. */
  51903. this.weight = 0.58767;
  51904. /**
  51905. * Controls the density of each sample
  51906. * @type {number}
  51907. */
  51908. this.density = 0.926;
  51909. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  51910. var engine = scene.getEngine();
  51911. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  51912. // Configure mesh
  51913. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  51914. // Configure
  51915. this._createPass(scene, ratio.passRatio || ratio);
  51916. this.onActivate = function (camera) {
  51917. if (!_this.isSupported) {
  51918. _this.dispose(camera);
  51919. }
  51920. _this.onActivate = null;
  51921. };
  51922. this.onApplyObservable.add(function (effect) {
  51923. _this._updateMeshScreenCoordinates(scene);
  51924. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  51925. effect.setFloat("exposure", _this.exposure);
  51926. effect.setFloat("decay", _this.decay);
  51927. effect.setFloat("weight", _this.weight);
  51928. effect.setFloat("density", _this.density);
  51929. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  51930. });
  51931. }
  51932. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  51933. get: function () {
  51934. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  51935. return false;
  51936. },
  51937. set: function (useDiffuseColor) {
  51938. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  51939. },
  51940. enumerable: true,
  51941. configurable: true
  51942. });
  51943. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  51944. var mesh = subMesh.getMesh();
  51945. // Render this.mesh as default
  51946. if (mesh === this.mesh) {
  51947. return mesh.material.isReady(mesh);
  51948. }
  51949. var defines = [];
  51950. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51951. var material = subMesh.getMaterial();
  51952. var needUV = false;
  51953. // Alpha test
  51954. if (material) {
  51955. if (material.needAlphaTesting()) {
  51956. defines.push("#define ALPHATEST");
  51957. }
  51958. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51959. attribs.push(BABYLON.VertexBuffer.UVKind);
  51960. defines.push("#define UV1");
  51961. }
  51962. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51963. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51964. defines.push("#define UV2");
  51965. }
  51966. }
  51967. // Bones
  51968. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51969. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51970. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51971. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51972. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51973. }
  51974. else {
  51975. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51976. }
  51977. // Instances
  51978. if (useInstances) {
  51979. defines.push("#define INSTANCES");
  51980. attribs.push("world0");
  51981. attribs.push("world1");
  51982. attribs.push("world2");
  51983. attribs.push("world3");
  51984. }
  51985. // Get correct effect
  51986. var join = defines.join("\n");
  51987. if (this._cachedDefines !== join) {
  51988. this._cachedDefines = join;
  51989. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  51990. }
  51991. return this._volumetricLightScatteringPass.isReady();
  51992. };
  51993. /**
  51994. * Sets the new light position for light scattering effect
  51995. * @param {BABYLON.Vector3} The new custom light position
  51996. */
  51997. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  51998. this.customMeshPosition = position;
  51999. };
  52000. /**
  52001. * Returns the light position for light scattering effect
  52002. * @return {BABYLON.Vector3} The custom light position
  52003. */
  52004. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  52005. return this.customMeshPosition;
  52006. };
  52007. /**
  52008. * Disposes the internal assets and detaches the post-process from the camera
  52009. */
  52010. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  52011. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  52012. if (rttIndex !== -1) {
  52013. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  52014. }
  52015. this._volumetricLightScatteringRTT.dispose();
  52016. _super.prototype.dispose.call(this, camera);
  52017. };
  52018. /**
  52019. * Returns the render target texture used by the post-process
  52020. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  52021. */
  52022. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  52023. return this._volumetricLightScatteringRTT;
  52024. };
  52025. // Private methods
  52026. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  52027. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  52028. return true;
  52029. }
  52030. return false;
  52031. };
  52032. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  52033. var _this = this;
  52034. var engine = scene.getEngine();
  52035. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52036. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52037. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52038. this._volumetricLightScatteringRTT.renderList = null;
  52039. this._volumetricLightScatteringRTT.renderParticles = false;
  52040. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  52041. // Custom render function for submeshes
  52042. var renderSubMesh = function (subMesh) {
  52043. var mesh = subMesh.getRenderingMesh();
  52044. if (_this._meshExcluded(mesh)) {
  52045. return;
  52046. }
  52047. var scene = mesh.getScene();
  52048. var engine = scene.getEngine();
  52049. // Culling
  52050. engine.setState(subMesh.getMaterial().backFaceCulling);
  52051. // Managing instances
  52052. var batch = mesh._getInstancesRenderList(subMesh._id);
  52053. if (batch.mustReturn) {
  52054. return;
  52055. }
  52056. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  52057. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52058. var effect = _this._volumetricLightScatteringPass;
  52059. if (mesh === _this.mesh) {
  52060. effect = subMesh.getMaterial().getEffect();
  52061. }
  52062. engine.enableEffect(effect);
  52063. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  52064. if (mesh === _this.mesh) {
  52065. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  52066. }
  52067. else {
  52068. var material = subMesh.getMaterial();
  52069. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  52070. // Alpha test
  52071. if (material && material.needAlphaTesting()) {
  52072. var alphaTexture = material.getAlphaTestTexture();
  52073. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  52074. if (alphaTexture) {
  52075. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52076. }
  52077. }
  52078. // Bones
  52079. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52080. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52081. }
  52082. }
  52083. // Draw
  52084. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  52085. }
  52086. };
  52087. // Render target texture callbacks
  52088. var savedSceneClearColor;
  52089. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  52090. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  52091. savedSceneClearColor = scene.clearColor;
  52092. scene.clearColor = sceneClearColor;
  52093. });
  52094. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  52095. scene.clearColor = savedSceneClearColor;
  52096. });
  52097. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  52098. var engine = scene.getEngine();
  52099. var index;
  52100. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52101. renderSubMesh(opaqueSubMeshes.data[index]);
  52102. }
  52103. engine.setAlphaTesting(true);
  52104. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52105. renderSubMesh(alphaTestSubMeshes.data[index]);
  52106. }
  52107. engine.setAlphaTesting(false);
  52108. if (transparentSubMeshes.length) {
  52109. // Sort sub meshes
  52110. for (index = 0; index < transparentSubMeshes.length; index++) {
  52111. var submesh = transparentSubMeshes.data[index];
  52112. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  52113. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  52114. }
  52115. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  52116. sortedArray.sort(function (a, b) {
  52117. // Alpha index first
  52118. if (a._alphaIndex > b._alphaIndex) {
  52119. return 1;
  52120. }
  52121. if (a._alphaIndex < b._alphaIndex) {
  52122. return -1;
  52123. }
  52124. // Then distance to camera
  52125. if (a._distanceToCamera < b._distanceToCamera) {
  52126. return 1;
  52127. }
  52128. if (a._distanceToCamera > b._distanceToCamera) {
  52129. return -1;
  52130. }
  52131. return 0;
  52132. });
  52133. // Render sub meshes
  52134. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52135. for (index = 0; index < sortedArray.length; index++) {
  52136. renderSubMesh(sortedArray[index]);
  52137. }
  52138. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52139. }
  52140. };
  52141. };
  52142. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  52143. var transform = scene.getTransformMatrix();
  52144. var meshPosition;
  52145. if (this.useCustomMeshPosition) {
  52146. meshPosition = this.customMeshPosition;
  52147. }
  52148. else if (this.attachedNode) {
  52149. meshPosition = this.attachedNode.position;
  52150. }
  52151. else {
  52152. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  52153. }
  52154. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  52155. this._screenCoordinates.x = pos.x / this._viewPort.width;
  52156. this._screenCoordinates.y = pos.y / this._viewPort.height;
  52157. if (this.invert)
  52158. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  52159. };
  52160. // Static methods
  52161. /**
  52162. * Creates a default mesh for the Volumeric Light Scattering post-process
  52163. * @param {string} The mesh name
  52164. * @param {BABYLON.Scene} The scene where to create the mesh
  52165. * @return {BABYLON.Mesh} the default mesh
  52166. */
  52167. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  52168. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  52169. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  52170. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  52171. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  52172. mesh.material = material;
  52173. return mesh;
  52174. };
  52175. __decorate([
  52176. BABYLON.serializeAsVector3()
  52177. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  52178. __decorate([
  52179. BABYLON.serialize()
  52180. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  52181. __decorate([
  52182. BABYLON.serialize()
  52183. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  52184. __decorate([
  52185. BABYLON.serializeAsMeshReference()
  52186. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  52187. __decorate([
  52188. BABYLON.serialize()
  52189. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  52190. __decorate([
  52191. BABYLON.serialize()
  52192. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  52193. __decorate([
  52194. BABYLON.serialize()
  52195. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  52196. __decorate([
  52197. BABYLON.serialize()
  52198. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  52199. __decorate([
  52200. BABYLON.serialize()
  52201. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  52202. return VolumetricLightScatteringPostProcess;
  52203. })(BABYLON.PostProcess);
  52204. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  52205. })(BABYLON || (BABYLON = {}));
  52206. // BABYLON.JS Chromatic Aberration GLSL Shader
  52207. // Author: Olivier Guyot
  52208. // Separates very slightly R, G and B colors on the edges of the screen
  52209. // Inspired by Francois Tarlier & Martins Upitis
  52210. var BABYLON;
  52211. (function (BABYLON) {
  52212. var LensRenderingPipeline = (function (_super) {
  52213. __extends(LensRenderingPipeline, _super);
  52214. /**
  52215. * @constructor
  52216. *
  52217. * Effect parameters are as follow:
  52218. * {
  52219. * chromatic_aberration: number; // from 0 to x (1 for realism)
  52220. * edge_blur: number; // from 0 to x (1 for realism)
  52221. * distortion: number; // from 0 to x (1 for realism)
  52222. * grain_amount: number; // from 0 to 1
  52223. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  52224. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  52225. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  52226. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  52227. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  52228. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  52229. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  52230. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  52231. * }
  52232. * Note: if an effect parameter is unset, effect is disabled
  52233. *
  52234. * @param {string} name - The rendering pipeline name
  52235. * @param {object} parameters - An object containing all parameters (see above)
  52236. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52237. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  52238. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52239. */
  52240. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  52241. var _this = this;
  52242. if (ratio === void 0) { ratio = 1.0; }
  52243. _super.call(this, scene.getEngine(), name);
  52244. // Lens effects can be of the following:
  52245. // - chromatic aberration (slight shift of RGB colors)
  52246. // - blur on the edge of the lens
  52247. // - lens distortion
  52248. // - depth-of-field blur & highlights enhancing
  52249. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  52250. // - grain effect (noise or custom texture)
  52251. // Two additional texture samplers are needed:
  52252. // - depth map (for depth-of-field)
  52253. // - grain texture
  52254. /**
  52255. * The chromatic aberration PostProcess id in the pipeline
  52256. * @type {string}
  52257. */
  52258. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  52259. /**
  52260. * The highlights enhancing PostProcess id in the pipeline
  52261. * @type {string}
  52262. */
  52263. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  52264. /**
  52265. * The depth-of-field PostProcess id in the pipeline
  52266. * @type {string}
  52267. */
  52268. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  52269. this._scene = scene;
  52270. // Fetch texture samplers
  52271. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52272. if (parameters.grain_texture) {
  52273. this._grainTexture = parameters.grain_texture;
  52274. }
  52275. else {
  52276. this._createGrainTexture();
  52277. }
  52278. // save parameters
  52279. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  52280. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  52281. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  52282. this._distortion = parameters.distortion ? parameters.distortion : 0;
  52283. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  52284. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  52285. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  52286. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  52287. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  52288. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  52289. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  52290. // Create effects
  52291. this._createChromaticAberrationPostProcess(ratio);
  52292. this._createHighlightsPostProcess(ratio);
  52293. this._createDepthOfFieldPostProcess(ratio / 4);
  52294. // Set up pipeline
  52295. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  52296. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  52297. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  52298. if (this._highlightsGain === -1) {
  52299. this._disableEffect(this.HighlightsEnhancingEffect, null);
  52300. }
  52301. // Finish
  52302. scene.postProcessRenderPipelineManager.addPipeline(this);
  52303. if (cameras) {
  52304. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52305. }
  52306. }
  52307. // public methods (self explanatory)
  52308. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  52309. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  52310. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  52311. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  52312. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  52313. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  52314. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  52315. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  52316. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  52317. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  52318. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  52319. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  52320. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  52321. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  52322. };
  52323. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  52324. this._highlightsPostProcess.updateEffect();
  52325. };
  52326. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  52327. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  52328. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  52329. this._highlightsGain = amount;
  52330. };
  52331. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  52332. if (this._highlightsGain === -1) {
  52333. this._highlightsGain = 1.0;
  52334. }
  52335. this._highlightsThreshold = amount;
  52336. };
  52337. LensRenderingPipeline.prototype.disableHighlights = function () {
  52338. this._highlightsGain = -1;
  52339. };
  52340. /**
  52341. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  52342. */
  52343. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52344. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52345. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52346. this._chromaticAberrationPostProcess = undefined;
  52347. this._highlightsPostProcess = undefined;
  52348. this._depthOfFieldPostProcess = undefined;
  52349. this._grainTexture.dispose();
  52350. if (disableDepthRender)
  52351. this._scene.disableDepthRenderer();
  52352. };
  52353. // colors shifting and distortion
  52354. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  52355. var _this = this;
  52356. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  52357. [], // samplers
  52358. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52359. this._chromaticAberrationPostProcess.onApply = function (effect) {
  52360. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  52361. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52362. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52363. };
  52364. };
  52365. // highlights enhancing
  52366. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  52367. var _this = this;
  52368. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  52369. [], // samplers
  52370. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  52371. this._highlightsPostProcess.onApply = function (effect) {
  52372. effect.setFloat('gain', _this._highlightsGain);
  52373. effect.setFloat('threshold', _this._highlightsThreshold);
  52374. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  52375. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52376. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52377. };
  52378. };
  52379. // colors shifting and distortion
  52380. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  52381. var _this = this;
  52382. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  52383. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  52384. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  52385. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52386. this._depthOfFieldPostProcess.onApply = function (effect) {
  52387. effect.setTexture("depthSampler", _this._depthTexture);
  52388. effect.setTexture("grainSampler", _this._grainTexture);
  52389. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  52390. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  52391. effect.setFloat('grain_amount', _this._grainAmount);
  52392. effect.setBool('blur_noise', _this._blurNoise);
  52393. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52394. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52395. effect.setFloat('distortion', _this._distortion);
  52396. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  52397. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  52398. effect.setFloat('aperture', _this._dofAperture);
  52399. effect.setFloat('darken', _this._dofDarken);
  52400. effect.setFloat('edge_blur', _this._edgeBlur);
  52401. effect.setBool('highlights', (_this._highlightsGain !== -1));
  52402. effect.setFloat('near', _this._scene.activeCamera.minZ);
  52403. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  52404. };
  52405. };
  52406. // creates a black and white random noise texture, 512x512
  52407. LensRenderingPipeline.prototype._createGrainTexture = function () {
  52408. var size = 512;
  52409. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52410. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52411. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52412. var context = this._grainTexture.getContext();
  52413. var rand = function (min, max) {
  52414. return Math.random() * (max - min) + min;
  52415. };
  52416. var value;
  52417. for (var x = 0; x < size; x++) {
  52418. for (var y = 0; y < size; y++) {
  52419. value = Math.floor(rand(0.42, 0.58) * 255);
  52420. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  52421. context.fillRect(x, y, 1, 1);
  52422. }
  52423. }
  52424. this._grainTexture.update(false);
  52425. };
  52426. return LensRenderingPipeline;
  52427. })(BABYLON.PostProcessRenderPipeline);
  52428. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  52429. })(BABYLON || (BABYLON = {}));
  52430. //
  52431. // This post-process allows the modification of rendered colors by using
  52432. // a 'look-up table' (LUT). This effect is also called Color Grading.
  52433. //
  52434. // The object needs to be provided an url to a texture containing the color
  52435. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  52436. // Use an image editing software to tweak the LUT to match your needs.
  52437. //
  52438. // For an example of a color LUT, see here:
  52439. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  52440. // For explanations on color grading, see here:
  52441. // http://udn.epicgames.com/Three/ColorGrading.html
  52442. //
  52443. var BABYLON;
  52444. (function (BABYLON) {
  52445. var ColorCorrectionPostProcess = (function (_super) {
  52446. __extends(ColorCorrectionPostProcess, _super);
  52447. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  52448. var _this = this;
  52449. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  52450. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52451. this._colorTableTexture.anisotropicFilteringLevel = 1;
  52452. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52453. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52454. this.onApply = function (effect) {
  52455. effect.setTexture("colorTable", _this._colorTableTexture);
  52456. };
  52457. }
  52458. return ColorCorrectionPostProcess;
  52459. })(BABYLON.PostProcess);
  52460. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  52461. })(BABYLON || (BABYLON = {}));
  52462. var BABYLON;
  52463. (function (BABYLON) {
  52464. var AnaglyphFreeCamera = (function (_super) {
  52465. __extends(AnaglyphFreeCamera, _super);
  52466. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  52467. _super.call(this, name, position, scene);
  52468. this.interaxialDistance = interaxialDistance;
  52469. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52470. }
  52471. AnaglyphFreeCamera.prototype.getTypeName = function () {
  52472. return "AnaglyphFreeCamera";
  52473. };
  52474. return AnaglyphFreeCamera;
  52475. })(BABYLON.FreeCamera);
  52476. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  52477. var AnaglyphArcRotateCamera = (function (_super) {
  52478. __extends(AnaglyphArcRotateCamera, _super);
  52479. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  52480. _super.call(this, name, alpha, beta, radius, target, scene);
  52481. this.interaxialDistance = interaxialDistance;
  52482. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52483. }
  52484. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  52485. return "AnaglyphArcRotateCamera";
  52486. };
  52487. return AnaglyphArcRotateCamera;
  52488. })(BABYLON.ArcRotateCamera);
  52489. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  52490. var AnaglyphGamepadCamera = (function (_super) {
  52491. __extends(AnaglyphGamepadCamera, _super);
  52492. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  52493. _super.call(this, name, position, scene);
  52494. this.interaxialDistance = interaxialDistance;
  52495. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52496. }
  52497. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  52498. return "AnaglyphGamepadCamera";
  52499. };
  52500. return AnaglyphGamepadCamera;
  52501. })(BABYLON.GamepadCamera);
  52502. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  52503. var AnaglyphUniversalCamera = (function (_super) {
  52504. __extends(AnaglyphUniversalCamera, _super);
  52505. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  52506. _super.call(this, name, position, scene);
  52507. this.interaxialDistance = interaxialDistance;
  52508. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52509. }
  52510. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  52511. return "AnaglyphUniversalCamera";
  52512. };
  52513. return AnaglyphUniversalCamera;
  52514. })(BABYLON.UniversalCamera);
  52515. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  52516. var StereoscopicFreeCamera = (function (_super) {
  52517. __extends(StereoscopicFreeCamera, _super);
  52518. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  52519. _super.call(this, name, position, scene);
  52520. this.interaxialDistance = interaxialDistance;
  52521. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  52522. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  52523. }
  52524. StereoscopicFreeCamera.prototype.getTypeName = function () {
  52525. return "StereoscopicFreeCamera";
  52526. };
  52527. return StereoscopicFreeCamera;
  52528. })(BABYLON.FreeCamera);
  52529. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  52530. var StereoscopicArcRotateCamera = (function (_super) {
  52531. __extends(StereoscopicArcRotateCamera, _super);
  52532. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  52533. _super.call(this, name, alpha, beta, radius, target, scene);
  52534. this.interaxialDistance = interaxialDistance;
  52535. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  52536. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  52537. }
  52538. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  52539. return "StereoscopicArcRotateCamera";
  52540. };
  52541. return StereoscopicArcRotateCamera;
  52542. })(BABYLON.ArcRotateCamera);
  52543. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  52544. var StereoscopicGamepadCamera = (function (_super) {
  52545. __extends(StereoscopicGamepadCamera, _super);
  52546. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  52547. _super.call(this, name, position, scene);
  52548. this.interaxialDistance = interaxialDistance;
  52549. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  52550. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  52551. }
  52552. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  52553. return "StereoscopicGamepadCamera";
  52554. };
  52555. return StereoscopicGamepadCamera;
  52556. })(BABYLON.GamepadCamera);
  52557. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  52558. var StereoscopicUniversalCamera = (function (_super) {
  52559. __extends(StereoscopicUniversalCamera, _super);
  52560. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  52561. _super.call(this, name, position, scene);
  52562. this.interaxialDistance = interaxialDistance;
  52563. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  52564. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  52565. }
  52566. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  52567. return "StereoscopicUniversalCamera";
  52568. };
  52569. return StereoscopicUniversalCamera;
  52570. })(BABYLON.UniversalCamera);
  52571. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  52572. })(BABYLON || (BABYLON = {}));
  52573. var BABYLON;
  52574. (function (BABYLON) {
  52575. var HDRRenderingPipeline = (function (_super) {
  52576. __extends(HDRRenderingPipeline, _super);
  52577. /**
  52578. * @constructor
  52579. * @param {string} name - The rendering pipeline name
  52580. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52581. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  52582. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  52583. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52584. */
  52585. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  52586. var _this = this;
  52587. if (originalPostProcess === void 0) { originalPostProcess = null; }
  52588. _super.call(this, scene.getEngine(), name);
  52589. /**
  52590. * Public members
  52591. */
  52592. // Gaussian Blur
  52593. /**
  52594. * Gaussian blur coefficient
  52595. * @type {number}
  52596. */
  52597. this.gaussCoeff = 0.3;
  52598. /**
  52599. * Gaussian blur mean
  52600. * @type {number}
  52601. */
  52602. this.gaussMean = 1.0;
  52603. /**
  52604. * Gaussian blur standard deviation
  52605. * @type {number}
  52606. */
  52607. this.gaussStandDev = 0.8;
  52608. /**
  52609. * Gaussian blur multiplier. Multiplies the blur effect
  52610. * @type {number}
  52611. */
  52612. this.gaussMultiplier = 4.0;
  52613. // HDR
  52614. /**
  52615. * Exposure, controls the overall intensity of the pipeline
  52616. * @type {number}
  52617. */
  52618. this.exposure = 1.0;
  52619. /**
  52620. * Minimum luminance that the post-process can output. Luminance is >= 0
  52621. * @type {number}
  52622. */
  52623. this.minimumLuminance = 1.0;
  52624. /**
  52625. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  52626. * @type {number}
  52627. */
  52628. this.maximumLuminance = 1e20;
  52629. /**
  52630. * Increase rate for luminance: eye adaptation speed to dark
  52631. * @type {number}
  52632. */
  52633. this.luminanceIncreaserate = 0.5;
  52634. /**
  52635. * Decrease rate for luminance: eye adaptation speed to bright
  52636. * @type {number}
  52637. */
  52638. this.luminanceDecreaseRate = 0.5;
  52639. // Bright pass
  52640. /**
  52641. * Minimum luminance needed to compute HDR
  52642. * @type {number}
  52643. */
  52644. this.brightThreshold = 0.8;
  52645. this._needUpdate = true;
  52646. this._scene = scene;
  52647. // Bright pass
  52648. this._createBrightPassPostProcess(scene, ratio);
  52649. // Down sample X4
  52650. this._createDownSampleX4PostProcess(scene, ratio);
  52651. // Create gaussian blur post-processes
  52652. this._createGaussianBlurPostProcess(scene, ratio);
  52653. // Texture adder
  52654. this._createTextureAdderPostProcess(scene, ratio);
  52655. // Luminance generator
  52656. this._createLuminanceGeneratorPostProcess(scene);
  52657. // HDR
  52658. this._createHDRPostProcess(scene, ratio);
  52659. // Pass postprocess
  52660. if (originalPostProcess === null) {
  52661. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  52662. }
  52663. else {
  52664. this._originalPostProcess = originalPostProcess;
  52665. }
  52666. // Configure pipeline
  52667. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  52668. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  52669. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  52670. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  52671. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  52672. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  52673. var addDownSamplerPostProcess = function (id) {
  52674. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  52675. };
  52676. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  52677. addDownSamplerPostProcess(i);
  52678. }
  52679. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  52680. // Finish
  52681. scene.postProcessRenderPipelineManager.addPipeline(this);
  52682. if (cameras !== null) {
  52683. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52684. }
  52685. this.update();
  52686. }
  52687. /**
  52688. * Tells the pipeline to update its post-processes
  52689. */
  52690. HDRRenderingPipeline.prototype.update = function () {
  52691. this._needUpdate = true;
  52692. };
  52693. /**
  52694. * Returns the current calculated luminance
  52695. */
  52696. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  52697. return this._hdrCurrentLuminance;
  52698. };
  52699. /**
  52700. * Returns the currently drawn luminance
  52701. */
  52702. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  52703. return this._hdrOutputLuminance;
  52704. };
  52705. /**
  52706. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  52707. */
  52708. HDRRenderingPipeline.prototype.dispose = function () {
  52709. this._originalPostProcess = undefined;
  52710. this._brightPassPostProcess = undefined;
  52711. this._downSampleX4PostProcess = undefined;
  52712. this._guassianBlurHPostProcess = undefined;
  52713. this._guassianBlurVPostProcess = undefined;
  52714. this._textureAdderPostProcess = undefined;
  52715. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  52716. this._downSamplePostProcesses[i] = undefined;
  52717. }
  52718. this._hdrPostProcess = undefined;
  52719. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52720. };
  52721. /**
  52722. * Creates the HDR post-process and computes the luminance adaptation
  52723. */
  52724. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  52725. var _this = this;
  52726. var hdrLastLuminance = 0.0;
  52727. this._hdrOutputLuminance = -1.0;
  52728. this._hdrCurrentLuminance = 1.0;
  52729. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  52730. this._hdrPostProcess.onApply = function (effect) {
  52731. if (_this._hdrOutputLuminance < 0.0) {
  52732. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  52733. }
  52734. else {
  52735. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  52736. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  52737. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  52738. }
  52739. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  52740. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  52741. }
  52742. else {
  52743. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  52744. }
  52745. }
  52746. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  52747. hdrLastLuminance += scene.getEngine().getDeltaTime();
  52748. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  52749. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  52750. effect.setFloat("exposure", _this.exposure);
  52751. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  52752. _this._needUpdate = false;
  52753. };
  52754. };
  52755. /**
  52756. * Texture Adder post-process
  52757. */
  52758. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  52759. var _this = this;
  52760. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  52761. this._textureAdderPostProcess.onApply = function (effect) {
  52762. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  52763. };
  52764. };
  52765. /**
  52766. * Down sample X4 post-process
  52767. */
  52768. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  52769. var _this = this;
  52770. var downSampleX4Offsets = new Array(32);
  52771. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  52772. this._downSampleX4PostProcess.onApply = function (effect) {
  52773. if (_this._needUpdate) {
  52774. var id = 0;
  52775. for (var i = -2; i < 2; i++) {
  52776. for (var j = -2; j < 2; j++) {
  52777. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  52778. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  52779. id += 2;
  52780. }
  52781. }
  52782. }
  52783. effect.setArray2("dsOffsets", downSampleX4Offsets);
  52784. };
  52785. };
  52786. /**
  52787. * Bright pass post-process
  52788. */
  52789. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  52790. var _this = this;
  52791. var brightOffsets = new Array(8);
  52792. var brightPassCallback = function (effect) {
  52793. if (_this._needUpdate) {
  52794. var sU = (1.0 / _this._brightPassPostProcess.width);
  52795. var sV = (1.0 / _this._brightPassPostProcess.height);
  52796. brightOffsets[0] = -0.5 * sU;
  52797. brightOffsets[1] = 0.5 * sV;
  52798. brightOffsets[2] = 0.5 * sU;
  52799. brightOffsets[3] = 0.5 * sV;
  52800. brightOffsets[4] = -0.5 * sU;
  52801. brightOffsets[5] = -0.5 * sV;
  52802. brightOffsets[6] = 0.5 * sU;
  52803. brightOffsets[7] = -0.5 * sV;
  52804. }
  52805. effect.setArray2("dsOffsets", brightOffsets);
  52806. effect.setFloat("brightThreshold", _this.brightThreshold);
  52807. };
  52808. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  52809. this._brightPassPostProcess.onApply = brightPassCallback;
  52810. };
  52811. /**
  52812. * Luminance generator. Creates the luminance post-process and down sample post-processes
  52813. */
  52814. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  52815. var _this = this;
  52816. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  52817. var luminanceOffsets = new Array(8);
  52818. var downSampleOffsets = new Array(18);
  52819. var halfDestPixelSize;
  52820. this._downSamplePostProcesses = new Array(lumSteps);
  52821. // Utils for luminance
  52822. var luminanceUpdateSourceOffsets = function (width, height) {
  52823. var sU = (1.0 / width);
  52824. var sV = (1.0 / height);
  52825. luminanceOffsets[0] = -0.5 * sU;
  52826. luminanceOffsets[1] = 0.5 * sV;
  52827. luminanceOffsets[2] = 0.5 * sU;
  52828. luminanceOffsets[3] = 0.5 * sV;
  52829. luminanceOffsets[4] = -0.5 * sU;
  52830. luminanceOffsets[5] = -0.5 * sV;
  52831. luminanceOffsets[6] = 0.5 * sU;
  52832. luminanceOffsets[7] = -0.5 * sV;
  52833. };
  52834. var luminanceUpdateDestOffsets = function (width, height) {
  52835. var id = 0;
  52836. for (var x = -1; x < 2; x++) {
  52837. for (var y = -1; y < 2; y++) {
  52838. downSampleOffsets[id] = (x) / width;
  52839. downSampleOffsets[id + 1] = (y) / height;
  52840. id += 2;
  52841. }
  52842. }
  52843. };
  52844. // Luminance callback
  52845. var luminanceCallback = function (effect) {
  52846. if (_this._needUpdate) {
  52847. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  52848. }
  52849. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  52850. effect.setArray2("lumOffsets", luminanceOffsets);
  52851. };
  52852. // Down sample callbacks
  52853. var downSampleCallback = function (indice) {
  52854. var i = indice;
  52855. return function (effect) {
  52856. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  52857. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  52858. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  52859. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  52860. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  52861. effect.setArray2("dsOffsets", downSampleOffsets);
  52862. };
  52863. };
  52864. var downSampleAfterRenderCallback = function (effect) {
  52865. // Unpack result
  52866. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  52867. var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  52868. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  52869. };
  52870. // Create luminance post-process
  52871. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  52872. this._downSamplePostProcesses[lumSteps - 1] = new BABYLON.PostProcess("hdr", "hdr", ["lumOffsets"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE_GENERATOR", BABYLON.Engine.TEXTURETYPE_FLOAT);
  52873. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  52874. // Create down sample post-processes
  52875. for (var i = lumSteps - 2; i >= 0; i--) {
  52876. var length = Math.pow(3, i);
  52877. ratio = { width: length, height: length };
  52878. var defines = "#define DOWN_SAMPLE\n";
  52879. if (i === 0) {
  52880. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  52881. }
  52882. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  52883. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  52884. if (i === 0) {
  52885. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  52886. }
  52887. }
  52888. };
  52889. /**
  52890. * Gaussian blur post-processes. Horizontal and Vertical
  52891. */
  52892. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  52893. var _this = this;
  52894. var blurOffsetsW = new Array(9);
  52895. var blurOffsetsH = new Array(9);
  52896. var blurWeights = new Array(9);
  52897. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  52898. // Utils for gaussian blur
  52899. var calculateBlurOffsets = function (height) {
  52900. var lastOutputDimensions = {
  52901. width: scene.getEngine().getRenderWidth(),
  52902. height: scene.getEngine().getRenderHeight()
  52903. };
  52904. for (var i = 0; i < 9; i++) {
  52905. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  52906. if (height) {
  52907. blurOffsetsH[i] = value;
  52908. }
  52909. else {
  52910. blurOffsetsW[i] = value;
  52911. }
  52912. }
  52913. };
  52914. var calculateWeights = function () {
  52915. var x = 0.0;
  52916. for (var i = 0; i < 9; i++) {
  52917. x = (i - 4.0) / 4.0;
  52918. blurWeights[i] = _this.gaussCoeff * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussStandDev)) * Math.exp((-((x - _this.gaussMean) * (x - _this.gaussMean))) / (2.0 * _this.gaussStandDev * _this.gaussStandDev));
  52919. }
  52920. };
  52921. // Callback
  52922. var gaussianBlurCallback = function (height) {
  52923. return function (effect) {
  52924. if (_this._needUpdate) {
  52925. calculateWeights();
  52926. calculateBlurOffsets(height);
  52927. }
  52928. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  52929. effect.setArray("blurWeights", blurWeights);
  52930. effect.setFloat("multiplier", _this.gaussMultiplier);
  52931. };
  52932. };
  52933. // Create horizontal gaussian blur post-processes
  52934. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  52935. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  52936. // Create vertical gaussian blur post-process
  52937. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  52938. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  52939. };
  52940. // Luminance generator
  52941. HDRRenderingPipeline.LUM_STEPS = 6;
  52942. return HDRRenderingPipeline;
  52943. })(BABYLON.PostProcessRenderPipeline);
  52944. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  52945. })(BABYLON || (BABYLON = {}));
  52946. var BABYLON;
  52947. (function (BABYLON) {
  52948. var FaceAdjacencies = (function () {
  52949. function FaceAdjacencies() {
  52950. this.edges = new Array();
  52951. this.edgesConnectedCount = 0;
  52952. }
  52953. return FaceAdjacencies;
  52954. })();
  52955. var EdgesRenderer = (function () {
  52956. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  52957. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  52958. if (epsilon === void 0) { epsilon = 0.95; }
  52959. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  52960. this.edgesWidthScalerForOrthographic = 1000.0;
  52961. this.edgesWidthScalerForPerspective = 50.0;
  52962. this._linesPositions = new Array();
  52963. this._linesNormals = new Array();
  52964. this._linesIndices = new Array();
  52965. this._buffers = {};
  52966. this._checkVerticesInsteadOfIndices = false;
  52967. this._source = source;
  52968. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  52969. this._epsilon = epsilon;
  52970. this._prepareRessources();
  52971. this._generateEdgesLines();
  52972. }
  52973. EdgesRenderer.prototype._prepareRessources = function () {
  52974. if (this._lineShader) {
  52975. return;
  52976. }
  52977. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  52978. attributes: ["position", "normal"],
  52979. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  52980. });
  52981. this._lineShader.disableDepthWrite = true;
  52982. this._lineShader.backFaceCulling = false;
  52983. };
  52984. EdgesRenderer.prototype.dispose = function () {
  52985. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  52986. if (buffer) {
  52987. buffer.dispose();
  52988. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  52989. }
  52990. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  52991. if (buffer) {
  52992. buffer.dispose();
  52993. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  52994. }
  52995. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  52996. this._lineShader.dispose();
  52997. };
  52998. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  52999. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  53000. return 0;
  53001. }
  53002. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  53003. return 1;
  53004. }
  53005. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  53006. return 2;
  53007. }
  53008. return -1;
  53009. };
  53010. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  53011. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  53012. return 0;
  53013. }
  53014. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  53015. return 1;
  53016. }
  53017. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  53018. return 2;
  53019. }
  53020. return -1;
  53021. };
  53022. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  53023. var needToCreateLine;
  53024. if (edge === undefined) {
  53025. needToCreateLine = true;
  53026. }
  53027. else {
  53028. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  53029. needToCreateLine = dotProduct < this._epsilon;
  53030. }
  53031. if (needToCreateLine) {
  53032. var offset = this._linesPositions.length / 3;
  53033. var normal = p0.subtract(p1);
  53034. normal.normalize();
  53035. // Positions
  53036. this._linesPositions.push(p0.x);
  53037. this._linesPositions.push(p0.y);
  53038. this._linesPositions.push(p0.z);
  53039. this._linesPositions.push(p0.x);
  53040. this._linesPositions.push(p0.y);
  53041. this._linesPositions.push(p0.z);
  53042. this._linesPositions.push(p1.x);
  53043. this._linesPositions.push(p1.y);
  53044. this._linesPositions.push(p1.z);
  53045. this._linesPositions.push(p1.x);
  53046. this._linesPositions.push(p1.y);
  53047. this._linesPositions.push(p1.z);
  53048. // Normals
  53049. this._linesNormals.push(p1.x);
  53050. this._linesNormals.push(p1.y);
  53051. this._linesNormals.push(p1.z);
  53052. this._linesNormals.push(-1);
  53053. this._linesNormals.push(p1.x);
  53054. this._linesNormals.push(p1.y);
  53055. this._linesNormals.push(p1.z);
  53056. this._linesNormals.push(1);
  53057. this._linesNormals.push(p0.x);
  53058. this._linesNormals.push(p0.y);
  53059. this._linesNormals.push(p0.z);
  53060. this._linesNormals.push(-1);
  53061. this._linesNormals.push(p0.x);
  53062. this._linesNormals.push(p0.y);
  53063. this._linesNormals.push(p0.z);
  53064. this._linesNormals.push(1);
  53065. // Indices
  53066. this._linesIndices.push(offset);
  53067. this._linesIndices.push(offset + 1);
  53068. this._linesIndices.push(offset + 2);
  53069. this._linesIndices.push(offset);
  53070. this._linesIndices.push(offset + 2);
  53071. this._linesIndices.push(offset + 3);
  53072. }
  53073. };
  53074. EdgesRenderer.prototype._generateEdgesLines = function () {
  53075. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53076. var indices = this._source.getIndices();
  53077. // First let's find adjacencies
  53078. var adjacencies = new Array();
  53079. var faceNormals = new Array();
  53080. var index;
  53081. var faceAdjacencies;
  53082. // Prepare faces
  53083. for (index = 0; index < indices.length; index += 3) {
  53084. faceAdjacencies = new FaceAdjacencies();
  53085. var p0Index = indices[index];
  53086. var p1Index = indices[index + 1];
  53087. var p2Index = indices[index + 2];
  53088. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  53089. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  53090. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  53091. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  53092. faceNormal.normalize();
  53093. faceNormals.push(faceNormal);
  53094. adjacencies.push(faceAdjacencies);
  53095. }
  53096. // Scan
  53097. for (index = 0; index < adjacencies.length; index++) {
  53098. faceAdjacencies = adjacencies[index];
  53099. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  53100. var otherFaceAdjacencies = adjacencies[otherIndex];
  53101. if (faceAdjacencies.edgesConnectedCount === 3) {
  53102. break;
  53103. }
  53104. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  53105. continue;
  53106. }
  53107. var otherP0 = indices[otherIndex * 3];
  53108. var otherP1 = indices[otherIndex * 3 + 1];
  53109. var otherP2 = indices[otherIndex * 3 + 2];
  53110. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  53111. var otherEdgeIndex;
  53112. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  53113. continue;
  53114. }
  53115. switch (edgeIndex) {
  53116. case 0:
  53117. if (this._checkVerticesInsteadOfIndices) {
  53118. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53119. }
  53120. else {
  53121. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  53122. }
  53123. break;
  53124. case 1:
  53125. if (this._checkVerticesInsteadOfIndices) {
  53126. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53127. }
  53128. else {
  53129. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  53130. }
  53131. break;
  53132. case 2:
  53133. if (this._checkVerticesInsteadOfIndices) {
  53134. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53135. }
  53136. else {
  53137. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  53138. }
  53139. break;
  53140. }
  53141. if (otherEdgeIndex === -1) {
  53142. continue;
  53143. }
  53144. faceAdjacencies.edges[edgeIndex] = otherIndex;
  53145. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  53146. faceAdjacencies.edgesConnectedCount++;
  53147. otherFaceAdjacencies.edgesConnectedCount++;
  53148. if (faceAdjacencies.edgesConnectedCount === 3) {
  53149. break;
  53150. }
  53151. }
  53152. }
  53153. }
  53154. // Create lines
  53155. for (index = 0; index < adjacencies.length; index++) {
  53156. // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
  53157. var current = adjacencies[index];
  53158. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  53159. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  53160. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  53161. }
  53162. // Merge into a single mesh
  53163. var engine = this._source.getScene().getEngine();
  53164. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  53165. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  53166. this._ib = engine.createIndexBuffer(this._linesIndices);
  53167. this._indicesCount = this._linesIndices.length;
  53168. };
  53169. EdgesRenderer.prototype.render = function () {
  53170. if (!this._lineShader.isReady()) {
  53171. return;
  53172. }
  53173. var scene = this._source.getScene();
  53174. var engine = scene.getEngine();
  53175. this._lineShader._preBind();
  53176. // VBOs
  53177. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  53178. scene.resetCachedMaterial();
  53179. this._lineShader.setColor4("color", this._source.edgesColor);
  53180. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  53181. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  53182. }
  53183. else {
  53184. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  53185. }
  53186. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  53187. this._lineShader.bind(this._source.getWorldMatrix());
  53188. // Draw order
  53189. engine.draw(true, 0, this._indicesCount);
  53190. this._lineShader.unbind();
  53191. engine.setDepthWrite(true);
  53192. };
  53193. return EdgesRenderer;
  53194. })();
  53195. BABYLON.EdgesRenderer = EdgesRenderer;
  53196. })(BABYLON || (BABYLON = {}));
  53197. var BABYLON;
  53198. (function (BABYLON) {
  53199. (function (TonemappingOperator) {
  53200. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  53201. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  53202. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  53203. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  53204. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  53205. var TonemappingOperator = BABYLON.TonemappingOperator;
  53206. ;
  53207. var TonemapPostProcess = (function (_super) {
  53208. __extends(TonemapPostProcess, _super);
  53209. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  53210. var _this = this;
  53211. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53212. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53213. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  53214. this._operator = _operator;
  53215. this.exposureAdjustment = exposureAdjustment;
  53216. var defines = "#define ";
  53217. if (this._operator === TonemappingOperator.Hable)
  53218. defines += "HABLE_TONEMAPPING";
  53219. else if (this._operator === TonemappingOperator.Reinhard)
  53220. defines += "REINHARD_TONEMAPPING";
  53221. else if (this._operator === TonemappingOperator.HejiDawson)
  53222. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  53223. else if (this._operator === TonemappingOperator.Photographic)
  53224. defines += "PHOTOGRAPHIC_TONEMAPPING";
  53225. //sadly a second call to create the effect.
  53226. this.updateEffect(defines);
  53227. this.onApply = function (effect) {
  53228. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  53229. };
  53230. }
  53231. return TonemapPostProcess;
  53232. })(BABYLON.PostProcess);
  53233. BABYLON.TonemapPostProcess = TonemapPostProcess;
  53234. })(BABYLON || (BABYLON = {}));
  53235. var BABYLON;
  53236. (function (BABYLON) {
  53237. var ReflectionProbe = (function () {
  53238. function ReflectionProbe(name, size, scene, generateMipMaps) {
  53239. var _this = this;
  53240. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53241. this.name = name;
  53242. this._viewMatrix = BABYLON.Matrix.Identity();
  53243. this._target = BABYLON.Vector3.Zero();
  53244. this._add = BABYLON.Vector3.Zero();
  53245. this.invertYAxis = false;
  53246. this.position = BABYLON.Vector3.Zero();
  53247. this._scene = scene;
  53248. this._scene.reflectionProbes.push(this);
  53249. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  53250. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  53251. switch (faceIndex) {
  53252. case 0:
  53253. _this._add.copyFromFloats(1, 0, 0);
  53254. break;
  53255. case 1:
  53256. _this._add.copyFromFloats(-1, 0, 0);
  53257. break;
  53258. case 2:
  53259. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  53260. break;
  53261. case 3:
  53262. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  53263. break;
  53264. case 4:
  53265. _this._add.copyFromFloats(0, 0, 1);
  53266. break;
  53267. case 5:
  53268. _this._add.copyFromFloats(0, 0, -1);
  53269. break;
  53270. }
  53271. if (_this._attachedMesh) {
  53272. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  53273. }
  53274. _this.position.addToRef(_this._add, _this._target);
  53275. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  53276. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  53277. });
  53278. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  53279. scene.updateTransformMatrix(true);
  53280. });
  53281. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  53282. }
  53283. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  53284. get: function () {
  53285. return this._renderTargetTexture.refreshRate;
  53286. },
  53287. set: function (value) {
  53288. this._renderTargetTexture.refreshRate = value;
  53289. },
  53290. enumerable: true,
  53291. configurable: true
  53292. });
  53293. ReflectionProbe.prototype.getScene = function () {
  53294. return this._scene;
  53295. };
  53296. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  53297. get: function () {
  53298. return this._renderTargetTexture;
  53299. },
  53300. enumerable: true,
  53301. configurable: true
  53302. });
  53303. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  53304. get: function () {
  53305. return this._renderTargetTexture.renderList;
  53306. },
  53307. enumerable: true,
  53308. configurable: true
  53309. });
  53310. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  53311. this._attachedMesh = mesh;
  53312. };
  53313. ReflectionProbe.prototype.dispose = function () {
  53314. var index = this._scene.reflectionProbes.indexOf(this);
  53315. if (index !== -1) {
  53316. // Remove from the scene if found
  53317. this._scene.reflectionProbes.splice(index, 1);
  53318. }
  53319. if (this._renderTargetTexture) {
  53320. this._renderTargetTexture.dispose();
  53321. this._renderTargetTexture = null;
  53322. }
  53323. };
  53324. return ReflectionProbe;
  53325. })();
  53326. BABYLON.ReflectionProbe = ReflectionProbe;
  53327. })(BABYLON || (BABYLON = {}));
  53328. var BABYLON;
  53329. (function (BABYLON) {
  53330. var SolidParticle = (function () {
  53331. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  53332. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  53333. this.position = BABYLON.Vector3.Zero(); // position
  53334. this.rotation = BABYLON.Vector3.Zero(); // rotation
  53335. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  53336. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  53337. this.velocity = BABYLON.Vector3.Zero(); // velocity
  53338. this.alive = true; // alive
  53339. this.isVisible = true; // visibility
  53340. this.idx = particleIndex;
  53341. this._pos = positionIndex;
  53342. this._model = model;
  53343. this.shapeId = shapeId;
  53344. this.idxInShape = idxInShape;
  53345. }
  53346. Object.defineProperty(SolidParticle.prototype, "scale", {
  53347. //legacy support, changed scale to scaling
  53348. get: function () {
  53349. return this.scaling;
  53350. },
  53351. set: function (scale) {
  53352. this.scaling = scale;
  53353. },
  53354. enumerable: true,
  53355. configurable: true
  53356. });
  53357. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53358. //legacy support, changed quaternion to rotationQuaternion
  53359. get: function () {
  53360. return this.rotationQuaternion;
  53361. },
  53362. set: function (q) {
  53363. this.rotationQuaternion = q;
  53364. },
  53365. enumerable: true,
  53366. configurable: true
  53367. });
  53368. return SolidParticle;
  53369. })();
  53370. BABYLON.SolidParticle = SolidParticle;
  53371. var ModelShape = (function () {
  53372. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  53373. this.shapeID = id;
  53374. this._shape = shape;
  53375. this._shapeUV = shapeUV;
  53376. this._positionFunction = posFunction;
  53377. this._vertexFunction = vtxFunction;
  53378. }
  53379. return ModelShape;
  53380. })();
  53381. BABYLON.ModelShape = ModelShape;
  53382. })(BABYLON || (BABYLON = {}));
  53383. var BABYLON;
  53384. (function (BABYLON) {
  53385. /**
  53386. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53387. */
  53388. var SolidParticleSystem = (function () {
  53389. /**
  53390. * Creates a SPS (Solid Particle System) object.
  53391. * `name` (String) is the SPS name, this will be the underlying mesh name.
  53392. * `scene` (Scene) is the scene in which the SPS is added.
  53393. * `updatable` (default true) : if the SPS must be updatable or immutable.
  53394. * `isPickable` (default false) : if the solid particles must be pickable.
  53395. */
  53396. function SolidParticleSystem(name, scene, options) {
  53397. // public members
  53398. /**
  53399. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53400. * Example : var p = SPS.particles[i];
  53401. */
  53402. this.particles = new Array();
  53403. /**
  53404. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53405. */
  53406. this.nbParticles = 0;
  53407. /**
  53408. * If the particles must ever face the camera (default false). Useful for planar particles.
  53409. */
  53410. this.billboard = false;
  53411. /**
  53412. * This a counter ofr your own usage. It's not set by any SPS functions.
  53413. */
  53414. this.counter = 0;
  53415. /**
  53416. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53417. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53418. */
  53419. this.vars = {};
  53420. this._positions = new Array();
  53421. this._indices = new Array();
  53422. this._normals = new Array();
  53423. this._colors = new Array();
  53424. this._uvs = new Array();
  53425. this._index = 0; // indices index
  53426. this._updatable = true;
  53427. this._pickable = false;
  53428. this._isVisibilityBoxLocked = false;
  53429. this._alwaysVisible = false;
  53430. this._shapeCounter = 0;
  53431. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  53432. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53433. this._computeParticleColor = true;
  53434. this._computeParticleTexture = true;
  53435. this._computeParticleRotation = true;
  53436. this._computeParticleVertex = false;
  53437. this._computeBoundingBox = false;
  53438. this._cam_axisZ = BABYLON.Vector3.Zero();
  53439. this._cam_axisY = BABYLON.Vector3.Zero();
  53440. this._cam_axisX = BABYLON.Vector3.Zero();
  53441. this._axisX = BABYLON.Axis.X;
  53442. this._axisY = BABYLON.Axis.Y;
  53443. this._axisZ = BABYLON.Axis.Z;
  53444. this._fakeCamPos = BABYLON.Vector3.Zero();
  53445. this._rotMatrix = new BABYLON.Matrix();
  53446. this._invertMatrix = new BABYLON.Matrix();
  53447. this._rotated = BABYLON.Vector3.Zero();
  53448. this._quaternion = new BABYLON.Quaternion();
  53449. this._vertex = BABYLON.Vector3.Zero();
  53450. this._normal = BABYLON.Vector3.Zero();
  53451. this._yaw = 0.0;
  53452. this._pitch = 0.0;
  53453. this._roll = 0.0;
  53454. this._halfroll = 0.0;
  53455. this._halfpitch = 0.0;
  53456. this._halfyaw = 0.0;
  53457. this._sinRoll = 0.0;
  53458. this._cosRoll = 0.0;
  53459. this._sinPitch = 0.0;
  53460. this._cosPitch = 0.0;
  53461. this._sinYaw = 0.0;
  53462. this._cosYaw = 0.0;
  53463. this._w = 0.0;
  53464. this._minimum = BABYLON.Tmp.Vector3[0];
  53465. this._maximum = BABYLON.Tmp.Vector3[1];
  53466. this.name = name;
  53467. this._scene = scene;
  53468. this._camera = scene.activeCamera;
  53469. this._pickable = options ? options.isPickable : false;
  53470. if (options && options.updatable) {
  53471. this._updatable = options.updatable;
  53472. }
  53473. else {
  53474. this._updatable = true;
  53475. }
  53476. if (this._pickable) {
  53477. this.pickedParticles = [];
  53478. }
  53479. }
  53480. /**
  53481. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53482. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53483. */
  53484. SolidParticleSystem.prototype.buildMesh = function () {
  53485. if (this.nbParticles === 0) {
  53486. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53487. this.addShape(triangle, 1);
  53488. triangle.dispose();
  53489. }
  53490. this._positions32 = new Float32Array(this._positions);
  53491. this._uvs32 = new Float32Array(this._uvs);
  53492. this._colors32 = new Float32Array(this._colors);
  53493. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  53494. this._normals32 = new Float32Array(this._normals);
  53495. this._fixedNormal32 = new Float32Array(this._normals);
  53496. var vertexData = new BABYLON.VertexData();
  53497. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53498. vertexData.indices = this._indices;
  53499. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53500. if (this._uvs32) {
  53501. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53502. ;
  53503. }
  53504. if (this._colors32) {
  53505. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  53506. }
  53507. var mesh = new BABYLON.Mesh(this.name, this._scene);
  53508. vertexData.applyToMesh(mesh, this._updatable);
  53509. this.mesh = mesh;
  53510. this.mesh.isPickable = this._pickable;
  53511. // free memory
  53512. this._positions = null;
  53513. this._normals = null;
  53514. this._uvs = null;
  53515. this._colors = null;
  53516. if (!this._updatable) {
  53517. this.particles.length = 0;
  53518. }
  53519. return mesh;
  53520. };
  53521. /**
  53522. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53523. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53524. * Thus the particles generated from `digest()` have their property `position` set yet.
  53525. * `mesh` ( Mesh ) is the mesh to be digested
  53526. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  53527. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53528. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53529. */
  53530. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53531. var size = (options && options.facetNb) || 1;
  53532. var number = (options && options.number);
  53533. var delta = (options && options.delta) || 0;
  53534. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53535. var meshInd = mesh.getIndices();
  53536. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53537. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53538. var f = 0; // facet counter
  53539. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53540. // compute size from number
  53541. if (number) {
  53542. number = (number > totalFacets) ? totalFacets : number;
  53543. size = Math.round(totalFacets / number);
  53544. delta = 0;
  53545. }
  53546. else {
  53547. size = (size > totalFacets) ? totalFacets : size;
  53548. }
  53549. var facetPos = []; // submesh positions
  53550. var facetInd = []; // submesh indices
  53551. var facetUV = []; // submesh UV
  53552. var facetCol = []; // submesh colors
  53553. var barycenter = BABYLON.Tmp.Vector3[0];
  53554. var rand;
  53555. var sizeO = size;
  53556. while (f < totalFacets) {
  53557. size = sizeO + Math.floor((1 + delta) * Math.random());
  53558. if (f > totalFacets - size) {
  53559. size = totalFacets - f;
  53560. }
  53561. // reset temp arrays
  53562. facetPos.length = 0;
  53563. facetInd.length = 0;
  53564. facetUV.length = 0;
  53565. facetCol.length = 0;
  53566. // iterate over "size" facets
  53567. var fi = 0;
  53568. for (var j = f * 3; j < (f + size) * 3; j++) {
  53569. facetInd.push(fi);
  53570. var i = meshInd[j];
  53571. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53572. if (meshUV) {
  53573. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53574. }
  53575. if (meshCol) {
  53576. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53577. }
  53578. fi++;
  53579. }
  53580. // create a model shape for each single particle
  53581. var idx = this.nbParticles;
  53582. var shape = this._posToShape(facetPos);
  53583. var shapeUV = this._uvsToShapeUV(facetUV);
  53584. // compute the barycenter of the shape
  53585. var v;
  53586. for (v = 0; v < shape.length; v++) {
  53587. barycenter.addInPlace(shape[v]);
  53588. }
  53589. barycenter.scaleInPlace(1 / shape.length);
  53590. // shift the shape from its barycenter to the origin
  53591. for (v = 0; v < shape.length; v++) {
  53592. shape[v].subtractInPlace(barycenter);
  53593. }
  53594. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  53595. // add the particle in the SPS
  53596. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  53597. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  53598. // initialize the particle position
  53599. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53600. this._index += shape.length;
  53601. idx++;
  53602. this.nbParticles++;
  53603. this._shapeCounter++;
  53604. f += size;
  53605. }
  53606. return this;
  53607. };
  53608. //reset copy
  53609. SolidParticleSystem.prototype._resetCopy = function () {
  53610. this._copy.position.x = 0;
  53611. this._copy.position.y = 0;
  53612. this._copy.position.z = 0;
  53613. this._copy.rotation.x = 0;
  53614. this._copy.rotation.y = 0;
  53615. this._copy.rotation.z = 0;
  53616. this._copy.rotationQuaternion = null;
  53617. this._copy.scaling.x = 1;
  53618. this._copy.scaling.y = 1;
  53619. this._copy.scaling.z = 1;
  53620. this._copy.uvs.x = 0;
  53621. this._copy.uvs.y = 0;
  53622. this._copy.uvs.z = 1;
  53623. this._copy.uvs.w = 1;
  53624. this._copy.color = null;
  53625. };
  53626. // _meshBuilder : inserts the shape model in the global SPS mesh
  53627. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  53628. var i;
  53629. var u = 0;
  53630. var c = 0;
  53631. this._resetCopy();
  53632. if (options && options.positionFunction) {
  53633. options.positionFunction(this._copy, idx, idxInShape);
  53634. }
  53635. if (this._copy.rotationQuaternion) {
  53636. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53637. }
  53638. else {
  53639. this._yaw = this._copy.rotation.y;
  53640. this._pitch = this._copy.rotation.x;
  53641. this._roll = this._copy.rotation.z;
  53642. this._quaternionRotationYPR();
  53643. }
  53644. this._quaternionToRotationMatrix();
  53645. for (i = 0; i < shape.length; i++) {
  53646. this._vertex.x = shape[i].x;
  53647. this._vertex.y = shape[i].y;
  53648. this._vertex.z = shape[i].z;
  53649. if (options && options.vertexFunction) {
  53650. options.vertexFunction(this._copy, this._vertex, i);
  53651. }
  53652. this._vertex.x *= this._copy.scaling.x;
  53653. this._vertex.y *= this._copy.scaling.y;
  53654. this._vertex.z *= this._copy.scaling.z;
  53655. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53656. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53657. if (meshUV) {
  53658. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  53659. u += 2;
  53660. }
  53661. if (this._copy.color) {
  53662. this._color = this._copy.color;
  53663. }
  53664. else if (meshCol && meshCol[c]) {
  53665. this._color.r = meshCol[c];
  53666. this._color.g = meshCol[c + 1];
  53667. this._color.b = meshCol[c + 2];
  53668. this._color.a = meshCol[c + 3];
  53669. }
  53670. else {
  53671. this._color.r = 1;
  53672. this._color.g = 1;
  53673. this._color.b = 1;
  53674. this._color.a = 1;
  53675. }
  53676. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53677. c += 4;
  53678. }
  53679. for (i = 0; i < meshInd.length; i++) {
  53680. indices.push(p + meshInd[i]);
  53681. }
  53682. if (this._pickable) {
  53683. var nbfaces = meshInd.length / 3;
  53684. for (i = 0; i < nbfaces; i++) {
  53685. this.pickedParticles.push({ idx: idx, faceId: i });
  53686. }
  53687. }
  53688. };
  53689. // returns a shape array from positions array
  53690. SolidParticleSystem.prototype._posToShape = function (positions) {
  53691. var shape = [];
  53692. for (var i = 0; i < positions.length; i += 3) {
  53693. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  53694. }
  53695. return shape;
  53696. };
  53697. // returns a shapeUV array from a Vector4 uvs
  53698. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  53699. var shapeUV = [];
  53700. if (uvs) {
  53701. for (var i = 0; i < uvs.length; i++)
  53702. shapeUV.push(uvs[i]);
  53703. }
  53704. return shapeUV;
  53705. };
  53706. // adds a new particle object in the particles array
  53707. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  53708. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  53709. };
  53710. /**
  53711. * Adds some particles to the SPS from the model shape. Returns the shape id.
  53712. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  53713. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  53714. * `nb` (positive integer) the number of particles to be created from this model
  53715. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  53716. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  53717. */
  53718. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  53719. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53720. var meshInd = mesh.getIndices();
  53721. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53722. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53723. var shape = this._posToShape(meshPos);
  53724. var shapeUV = this._uvsToShapeUV(meshUV);
  53725. var posfunc = options ? options.positionFunction : null;
  53726. var vtxfunc = options ? options.vertexFunction : null;
  53727. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  53728. // particles
  53729. var idx = this.nbParticles;
  53730. for (var i = 0; i < nb; i++) {
  53731. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  53732. if (this._updatable) {
  53733. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  53734. }
  53735. this._index += shape.length;
  53736. idx++;
  53737. }
  53738. this.nbParticles += nb;
  53739. this._shapeCounter++;
  53740. return this._shapeCounter - 1;
  53741. };
  53742. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  53743. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  53744. this._resetCopy();
  53745. if (particle._model._positionFunction) {
  53746. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  53747. }
  53748. if (this._copy.rotationQuaternion) {
  53749. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53750. }
  53751. else {
  53752. this._yaw = this._copy.rotation.y;
  53753. this._pitch = this._copy.rotation.x;
  53754. this._roll = this._copy.rotation.z;
  53755. this._quaternionRotationYPR();
  53756. }
  53757. this._quaternionToRotationMatrix();
  53758. this._shape = particle._model._shape;
  53759. for (var pt = 0; pt < this._shape.length; pt++) {
  53760. this._vertex.x = this._shape[pt].x;
  53761. this._vertex.y = this._shape[pt].y;
  53762. this._vertex.z = this._shape[pt].z;
  53763. if (particle._model._vertexFunction) {
  53764. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  53765. }
  53766. this._vertex.x *= this._copy.scaling.x;
  53767. this._vertex.y *= this._copy.scaling.y;
  53768. this._vertex.z *= this._copy.scaling.z;
  53769. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53770. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53771. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53772. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53773. }
  53774. particle.position.x = 0;
  53775. particle.position.y = 0;
  53776. particle.position.z = 0;
  53777. particle.rotation.x = 0;
  53778. particle.rotation.y = 0;
  53779. particle.rotation.z = 0;
  53780. particle.rotationQuaternion = null;
  53781. particle.scaling.x = 1;
  53782. particle.scaling.y = 1;
  53783. particle.scaling.z = 1;
  53784. };
  53785. /**
  53786. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53787. */
  53788. SolidParticleSystem.prototype.rebuildMesh = function () {
  53789. for (var p = 0; p < this.particles.length; p++) {
  53790. this._rebuildParticle(this.particles[p]);
  53791. }
  53792. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53793. };
  53794. /**
  53795. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53796. * This method calls `updateParticle()` for each particle of the SPS.
  53797. * For an animated SPS, it is usually called within the render loop.
  53798. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53799. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53800. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53801. */
  53802. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53803. if (start === void 0) { start = 0; }
  53804. if (end === void 0) { end = this.nbParticles - 1; }
  53805. if (update === void 0) { update = true; }
  53806. if (!this._updatable) {
  53807. return;
  53808. }
  53809. // custom beforeUpdate
  53810. this.beforeUpdateParticles(start, end, update);
  53811. this._cam_axisX.x = 1;
  53812. this._cam_axisX.y = 0;
  53813. this._cam_axisX.z = 0;
  53814. this._cam_axisY.x = 0;
  53815. this._cam_axisY.y = 1;
  53816. this._cam_axisY.z = 0;
  53817. this._cam_axisZ.x = 0;
  53818. this._cam_axisZ.y = 0;
  53819. this._cam_axisZ.z = 1;
  53820. // if the particles will always face the camera
  53821. if (this.billboard) {
  53822. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  53823. this._yaw = this.mesh.rotation.y;
  53824. this._pitch = this.mesh.rotation.x;
  53825. this._roll = this.mesh.rotation.z;
  53826. this._quaternionRotationYPR();
  53827. this._quaternionToRotationMatrix();
  53828. this._rotMatrix.invertToRef(this._invertMatrix);
  53829. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  53830. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  53831. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  53832. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  53833. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  53834. this._cam_axisY.normalize();
  53835. this._cam_axisX.normalize();
  53836. this._cam_axisZ.normalize();
  53837. }
  53838. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53839. var idx = 0;
  53840. var index = 0;
  53841. var colidx = 0;
  53842. var colorIndex = 0;
  53843. var uvidx = 0;
  53844. var uvIndex = 0;
  53845. var pt = 0;
  53846. if (this._computeBoundingBox) {
  53847. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53848. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53849. }
  53850. // particle loop
  53851. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  53852. for (var p = start; p <= end; p++) {
  53853. this._particle = this.particles[p];
  53854. this._shape = this._particle._model._shape;
  53855. this._shapeUV = this._particle._model._shapeUV;
  53856. // call to custom user function to update the particle properties
  53857. this.updateParticle(this._particle);
  53858. if (this._particle.isVisible) {
  53859. // particle rotation matrix
  53860. if (this.billboard) {
  53861. this._particle.rotation.x = 0.0;
  53862. this._particle.rotation.y = 0.0;
  53863. }
  53864. if (this._computeParticleRotation) {
  53865. if (this._particle.rotationQuaternion) {
  53866. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53867. }
  53868. else {
  53869. this._yaw = this._particle.rotation.y;
  53870. this._pitch = this._particle.rotation.x;
  53871. this._roll = this._particle.rotation.z;
  53872. this._quaternionRotationYPR();
  53873. }
  53874. this._quaternionToRotationMatrix();
  53875. }
  53876. // particle vertex loop
  53877. for (pt = 0; pt < this._shape.length; pt++) {
  53878. idx = index + pt * 3;
  53879. colidx = colorIndex + pt * 4;
  53880. uvidx = uvIndex + pt * 2;
  53881. this._vertex.x = this._shape[pt].x;
  53882. this._vertex.y = this._shape[pt].y;
  53883. this._vertex.z = this._shape[pt].z;
  53884. if (this._computeParticleVertex) {
  53885. this.updateParticleVertex(this._particle, this._vertex, pt);
  53886. }
  53887. // positions
  53888. this._vertex.x *= this._particle.scaling.x;
  53889. this._vertex.y *= this._particle.scaling.y;
  53890. this._vertex.z *= this._particle.scaling.z;
  53891. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  53892. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  53893. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  53894. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  53895. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53896. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  53897. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  53898. if (this._computeBoundingBox) {
  53899. if (this._positions32[idx] < this._minimum.x) {
  53900. this._minimum.x = this._positions32[idx];
  53901. }
  53902. if (this._positions32[idx] > this._maximum.x) {
  53903. this._maximum.x = this._positions32[idx];
  53904. }
  53905. if (this._positions32[idx + 1] < this._minimum.y) {
  53906. this._minimum.y = this._positions32[idx + 1];
  53907. }
  53908. if (this._positions32[idx + 1] > this._maximum.y) {
  53909. this._maximum.y = this._positions32[idx + 1];
  53910. }
  53911. if (this._positions32[idx + 2] < this._minimum.z) {
  53912. this._minimum.z = this._positions32[idx + 2];
  53913. }
  53914. if (this._positions32[idx + 2] > this._maximum.z) {
  53915. this._maximum.z = this._positions32[idx + 2];
  53916. }
  53917. }
  53918. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  53919. if (!this._computeParticleVertex && !this.billboard) {
  53920. this._normal.x = this._fixedNormal32[idx];
  53921. this._normal.y = this._fixedNormal32[idx + 1];
  53922. this._normal.z = this._fixedNormal32[idx + 2];
  53923. this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  53924. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  53925. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  53926. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  53927. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53928. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  53929. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  53930. }
  53931. if (this._computeParticleColor) {
  53932. this._colors32[colidx] = this._particle.color.r;
  53933. this._colors32[colidx + 1] = this._particle.color.g;
  53934. this._colors32[colidx + 2] = this._particle.color.b;
  53935. this._colors32[colidx + 3] = this._particle.color.a;
  53936. }
  53937. if (this._computeParticleTexture) {
  53938. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53939. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53940. }
  53941. }
  53942. }
  53943. else {
  53944. for (pt = 0; pt < this._shape.length; pt++) {
  53945. idx = index + pt * 3;
  53946. colidx = colorIndex + pt * 4;
  53947. uvidx = uvIndex + pt * 2;
  53948. this._positions32[idx] = this._camera.position.x;
  53949. this._positions32[idx + 1] = this._camera.position.y;
  53950. this._positions32[idx + 2] = this._camera.position.z;
  53951. this._normals32[idx] = 0.0;
  53952. this._normals32[idx + 1] = 0.0;
  53953. this._normals32[idx + 2] = 0.0;
  53954. if (this._computeParticleColor) {
  53955. this._colors32[colidx] = this._particle.color.r;
  53956. this._colors32[colidx + 1] = this._particle.color.g;
  53957. this._colors32[colidx + 2] = this._particle.color.b;
  53958. this._colors32[colidx + 3] = this._particle.color.a;
  53959. }
  53960. if (this._computeParticleTexture) {
  53961. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53962. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53963. }
  53964. }
  53965. }
  53966. // increment indexes for the next particle
  53967. index = idx + 3;
  53968. colorIndex = colidx + 4;
  53969. uvIndex = uvidx + 2;
  53970. }
  53971. // if the VBO must be updated
  53972. if (update) {
  53973. if (this._computeParticleColor) {
  53974. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53975. }
  53976. if (this._computeParticleTexture) {
  53977. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53978. }
  53979. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53980. if (!this.mesh.areNormalsFrozen) {
  53981. if (this._computeParticleVertex || this.billboard) {
  53982. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53983. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  53984. for (var i = 0; i < this._normals32.length; i++) {
  53985. this._fixedNormal32[i] = this._normals32[i];
  53986. }
  53987. }
  53988. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53989. }
  53990. }
  53991. if (this._computeBoundingBox) {
  53992. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53993. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53994. }
  53995. this.afterUpdateParticles(start, end, update);
  53996. };
  53997. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53998. this._halfroll = this._roll * 0.5;
  53999. this._halfpitch = this._pitch * 0.5;
  54000. this._halfyaw = this._yaw * 0.5;
  54001. this._sinRoll = Math.sin(this._halfroll);
  54002. this._cosRoll = Math.cos(this._halfroll);
  54003. this._sinPitch = Math.sin(this._halfpitch);
  54004. this._cosPitch = Math.cos(this._halfpitch);
  54005. this._sinYaw = Math.sin(this._halfyaw);
  54006. this._cosYaw = Math.cos(this._halfyaw);
  54007. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  54008. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  54009. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  54010. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  54011. };
  54012. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54013. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54014. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54015. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54016. this._rotMatrix.m[3] = 0;
  54017. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54018. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54019. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54020. this._rotMatrix.m[7] = 0;
  54021. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54022. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54023. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54024. this._rotMatrix.m[11] = 0;
  54025. this._rotMatrix.m[12] = 0;
  54026. this._rotMatrix.m[13] = 0;
  54027. this._rotMatrix.m[14] = 0;
  54028. this._rotMatrix.m[15] = 1.0;
  54029. };
  54030. /**
  54031. * Disposes the SPS
  54032. */
  54033. SolidParticleSystem.prototype.dispose = function () {
  54034. this.mesh.dispose();
  54035. this.vars = null;
  54036. // drop references to internal big arrays for the GC
  54037. this._positions = null;
  54038. this._indices = null;
  54039. this._normals = null;
  54040. this._uvs = null;
  54041. this._colors = null;
  54042. this._positions32 = null;
  54043. this._normals32 = null;
  54044. this._fixedNormal32 = null;
  54045. this._uvs32 = null;
  54046. this._colors32 = null;
  54047. this.pickedParticles = null;
  54048. };
  54049. /**
  54050. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54051. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54052. */
  54053. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54054. if (!this._isVisibilityBoxLocked) {
  54055. this.mesh.refreshBoundingInfo();
  54056. }
  54057. };
  54058. /**
  54059. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54060. * @param size the size (float) of the visibility box
  54061. * note : this doesn't lock the SPS mesh bounding box.
  54062. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54063. */
  54064. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54065. var vis = size / 2;
  54066. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54067. };
  54068. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54069. // getter and setter
  54070. get: function () {
  54071. return this._alwaysVisible;
  54072. },
  54073. /**
  54074. * Sets the SPS as always visible or not
  54075. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54076. */
  54077. set: function (val) {
  54078. this._alwaysVisible = val;
  54079. this.mesh.alwaysSelectAsActiveMesh = val;
  54080. },
  54081. enumerable: true,
  54082. configurable: true
  54083. });
  54084. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54085. get: function () {
  54086. return this._isVisibilityBoxLocked;
  54087. },
  54088. /**
  54089. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54090. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54091. */
  54092. set: function (val) {
  54093. this._isVisibilityBoxLocked = val;
  54094. this.mesh.getBoundingInfo().isLocked = val;
  54095. },
  54096. enumerable: true,
  54097. configurable: true
  54098. });
  54099. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54100. // getters
  54101. get: function () {
  54102. return this._computeParticleRotation;
  54103. },
  54104. // Optimizer setters
  54105. /**
  54106. * Tells to `setParticles()` to compute the particle rotations or not.
  54107. * Default value : true. The SPS is faster when it's set to false.
  54108. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54109. */
  54110. set: function (val) {
  54111. this._computeParticleRotation = val;
  54112. },
  54113. enumerable: true,
  54114. configurable: true
  54115. });
  54116. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54117. get: function () {
  54118. return this._computeParticleColor;
  54119. },
  54120. /**
  54121. * Tells to `setParticles()` to compute the particle colors or not.
  54122. * Default value : true. The SPS is faster when it's set to false.
  54123. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54124. */
  54125. set: function (val) {
  54126. this._computeParticleColor = val;
  54127. },
  54128. enumerable: true,
  54129. configurable: true
  54130. });
  54131. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54132. get: function () {
  54133. return this._computeParticleTexture;
  54134. },
  54135. /**
  54136. * Tells to `setParticles()` to compute the particle textures or not.
  54137. * Default value : true. The SPS is faster when it's set to false.
  54138. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54139. */
  54140. set: function (val) {
  54141. this._computeParticleTexture = val;
  54142. },
  54143. enumerable: true,
  54144. configurable: true
  54145. });
  54146. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54147. get: function () {
  54148. return this._computeParticleVertex;
  54149. },
  54150. /**
  54151. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54152. * Default value : false. The SPS is faster when it's set to false.
  54153. * Note : the particle custom vertex positions aren't stored values.
  54154. */
  54155. set: function (val) {
  54156. this._computeParticleVertex = val;
  54157. },
  54158. enumerable: true,
  54159. configurable: true
  54160. });
  54161. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54162. get: function () {
  54163. return this._computeBoundingBox;
  54164. },
  54165. /**
  54166. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54167. */
  54168. set: function (val) {
  54169. this._computeBoundingBox = val;
  54170. },
  54171. enumerable: true,
  54172. configurable: true
  54173. });
  54174. // =======================================================================
  54175. // Particle behavior logic
  54176. // these following methods may be overwritten by the user to fit his needs
  54177. /**
  54178. * This function does nothing. It may be overwritten to set all the particle first values.
  54179. * The SPS doesn't call this function, you may have to call it by your own.
  54180. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54181. */
  54182. SolidParticleSystem.prototype.initParticles = function () {
  54183. };
  54184. /**
  54185. * This function does nothing. It may be overwritten to recycle a particle.
  54186. * The SPS doesn't call this function, you may have to call it by your own.
  54187. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54188. */
  54189. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54190. return particle;
  54191. };
  54192. /**
  54193. * Updates a particle : this function should be overwritten by the user.
  54194. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54195. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54196. * ex : just set a particle position or velocity and recycle conditions
  54197. */
  54198. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54199. return particle;
  54200. };
  54201. /**
  54202. * Updates a vertex of a particle : it can be overwritten by the user.
  54203. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54204. * @param particle the current particle
  54205. * @param vertex the current index of the current particle
  54206. * @param pt the index of the current vertex in the particle shape
  54207. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54208. * ex : just set a vertex particle position
  54209. */
  54210. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54211. return vertex;
  54212. };
  54213. /**
  54214. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54215. * This does nothing and may be overwritten by the user.
  54216. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54217. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54218. * @param update the boolean update value actually passed to setParticles()
  54219. */
  54220. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54221. };
  54222. /**
  54223. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54224. * This will be passed three parameters.
  54225. * This does nothing and may be overwritten by the user.
  54226. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54227. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54228. * @param update the boolean update value actually passed to setParticles()
  54229. */
  54230. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54231. };
  54232. return SolidParticleSystem;
  54233. })();
  54234. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54235. })(BABYLON || (BABYLON = {}));
  54236. var BABYLON;
  54237. (function (BABYLON) {
  54238. var Internals;
  54239. (function (Internals) {
  54240. var FileFaceOrientation = (function () {
  54241. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  54242. this.name = name;
  54243. this.worldAxisForNormal = worldAxisForNormal;
  54244. this.worldAxisForFileX = worldAxisForFileX;
  54245. this.worldAxisForFileY = worldAxisForFileY;
  54246. }
  54247. return FileFaceOrientation;
  54248. })();
  54249. ;
  54250. /**
  54251. * Helper class dealing with the extraction of spherical polynomial dataArray
  54252. * from a cube map.
  54253. */
  54254. var CubeMapToSphericalPolynomialTools = (function () {
  54255. function CubeMapToSphericalPolynomialTools() {
  54256. }
  54257. /**
  54258. * Converts a cubemap to the according Spherical Polynomial data.
  54259. * This extracts the first 3 orders only as they are the only one used in the lighting.
  54260. *
  54261. * @param cubeInfo The Cube map to extract the information from.
  54262. * @return The Spherical Polynomial data.
  54263. */
  54264. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  54265. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  54266. var totalSolidAngle = 0.0;
  54267. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  54268. var du = 2.0 / cubeInfo.size;
  54269. var dv = du;
  54270. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  54271. var minUV = du * 0.5 - 1.0;
  54272. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54273. var fileFace = this.FileFaces[faceIndex];
  54274. var dataArray = cubeInfo[fileFace.name];
  54275. var v = minUV;
  54276. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  54277. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  54278. // Because SP is still linear, so summation is fine in that basis.
  54279. for (var y = 0; y < cubeInfo.size; y++) {
  54280. var u = minUV;
  54281. for (var x = 0; x < cubeInfo.size; x++) {
  54282. // World direction (not normalised)
  54283. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  54284. worldDirection.normalize();
  54285. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  54286. if (1) {
  54287. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  54288. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  54289. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  54290. var color = new BABYLON.Color3(r, g, b);
  54291. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  54292. }
  54293. else {
  54294. if (faceIndex == 0) {
  54295. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54296. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54297. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54298. }
  54299. else if (faceIndex == 1) {
  54300. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54301. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54302. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54303. }
  54304. else if (faceIndex == 2) {
  54305. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54306. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54307. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54308. }
  54309. else if (faceIndex == 3) {
  54310. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54311. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54312. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54313. }
  54314. else if (faceIndex == 4) {
  54315. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54316. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54317. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54318. }
  54319. else if (faceIndex == 5) {
  54320. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54321. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54322. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54323. }
  54324. var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
  54325. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  54326. }
  54327. totalSolidAngle += deltaSolidAngle;
  54328. u += du;
  54329. }
  54330. v += dv;
  54331. }
  54332. }
  54333. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  54334. var correction = correctSolidAngle / totalSolidAngle;
  54335. sphericalHarmonics.scale(correction);
  54336. // Additionally scale by pi -- audit needed
  54337. sphericalHarmonics.scale(1.0 / Math.PI);
  54338. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  54339. };
  54340. CubeMapToSphericalPolynomialTools.FileFaces = [
  54341. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  54342. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  54343. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  54344. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  54345. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  54346. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  54347. ];
  54348. return CubeMapToSphericalPolynomialTools;
  54349. })();
  54350. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  54351. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54352. })(BABYLON || (BABYLON = {}));
  54353. var BABYLON;
  54354. (function (BABYLON) {
  54355. var Internals;
  54356. (function (Internals) {
  54357. /**
  54358. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  54359. */
  54360. var PanoramaToCubeMapTools = (function () {
  54361. function PanoramaToCubeMapTools() {
  54362. }
  54363. /**
  54364. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  54365. *
  54366. * @param float32Array The source data.
  54367. * @param inputWidth The width of the input panorama.
  54368. * @param inputhHeight The height of the input panorama.
  54369. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  54370. * @return The cubemap data
  54371. */
  54372. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  54373. if (!float32Array) {
  54374. throw "ConvertPanoramaToCubemap: input cannot be null";
  54375. }
  54376. if (float32Array.length != inputWidth * inputHeight * 3) {
  54377. throw "ConvertPanoramaToCubemap: input size is wrong";
  54378. }
  54379. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  54380. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  54381. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  54382. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  54383. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  54384. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  54385. return {
  54386. front: textureFront,
  54387. back: textureBack,
  54388. left: textureLeft,
  54389. right: textureRight,
  54390. up: textureUp,
  54391. down: textureDown,
  54392. size: size
  54393. };
  54394. };
  54395. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  54396. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  54397. var textureArray = new Float32Array(buffer);
  54398. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  54399. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  54400. var dy = 1 / texSize;
  54401. var fy = 0;
  54402. for (var y = 0; y < texSize; y++) {
  54403. var xv1 = faceData[0];
  54404. var xv2 = faceData[2];
  54405. for (var x = 0; x < texSize; x++) {
  54406. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  54407. v.normalize();
  54408. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  54409. // 3 channels per pixels
  54410. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  54411. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  54412. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  54413. xv1 = xv1.add(rotDX1);
  54414. xv2 = xv2.add(rotDX2);
  54415. }
  54416. fy += dy;
  54417. }
  54418. return textureArray;
  54419. };
  54420. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  54421. var theta = Math.atan2(vDir.z, vDir.x);
  54422. var phi = Math.acos(vDir.y);
  54423. while (theta < -Math.PI)
  54424. theta += 2 * Math.PI;
  54425. while (theta > Math.PI)
  54426. theta -= 2 * Math.PI;
  54427. var dx = theta / Math.PI;
  54428. var dy = phi / Math.PI;
  54429. // recenter.
  54430. dx = dx * 0.5 + 0.5;
  54431. var px = Math.round(dx * inputWidth);
  54432. if (px < 0)
  54433. px = 0;
  54434. else if (px >= inputWidth)
  54435. px = inputWidth - 1;
  54436. var py = Math.round(dy * inputHeight);
  54437. if (py < 0)
  54438. py = 0;
  54439. else if (py >= inputHeight)
  54440. py = inputHeight - 1;
  54441. var inputY = (inputHeight - py - 1);
  54442. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  54443. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  54444. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  54445. return {
  54446. r: r,
  54447. g: g,
  54448. b: b
  54449. };
  54450. };
  54451. PanoramaToCubeMapTools.FACE_FRONT = [
  54452. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  54453. new BABYLON.Vector3(1.0, -1.0, -1.0),
  54454. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  54455. new BABYLON.Vector3(1.0, 1.0, -1.0)
  54456. ];
  54457. PanoramaToCubeMapTools.FACE_BACK = [
  54458. new BABYLON.Vector3(1.0, -1.0, 1.0),
  54459. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  54460. new BABYLON.Vector3(1.0, 1.0, 1.0),
  54461. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  54462. ];
  54463. PanoramaToCubeMapTools.FACE_RIGHT = [
  54464. new BABYLON.Vector3(1.0, -1.0, -1.0),
  54465. new BABYLON.Vector3(1.0, -1.0, 1.0),
  54466. new BABYLON.Vector3(1.0, 1.0, -1.0),
  54467. new BABYLON.Vector3(1.0, 1.0, 1.0)
  54468. ];
  54469. PanoramaToCubeMapTools.FACE_LEFT = [
  54470. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  54471. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  54472. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  54473. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  54474. ];
  54475. PanoramaToCubeMapTools.FACE_DOWN = [
  54476. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  54477. new BABYLON.Vector3(1.0, 1.0, -1.0),
  54478. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  54479. new BABYLON.Vector3(1.0, 1.0, 1.0)
  54480. ];
  54481. PanoramaToCubeMapTools.FACE_UP = [
  54482. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  54483. new BABYLON.Vector3(1.0, -1.0, 1.0),
  54484. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  54485. new BABYLON.Vector3(1.0, -1.0, -1.0)
  54486. ];
  54487. return PanoramaToCubeMapTools;
  54488. })();
  54489. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  54490. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54491. })(BABYLON || (BABYLON = {}));
  54492. var BABYLON;
  54493. (function (BABYLON) {
  54494. var Internals;
  54495. (function (Internals) {
  54496. ;
  54497. /**
  54498. * This groups tools to convert HDR texture to native colors array.
  54499. */
  54500. var HDRTools = (function () {
  54501. function HDRTools() {
  54502. }
  54503. HDRTools.Ldexp = function (mantissa, exponent) {
  54504. if (exponent > 1023) {
  54505. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  54506. }
  54507. if (exponent < -1074) {
  54508. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  54509. }
  54510. return mantissa * Math.pow(2, exponent);
  54511. };
  54512. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  54513. if (exponent > 0) {
  54514. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  54515. float32array[index + 0] = red * exponent;
  54516. float32array[index + 1] = green * exponent;
  54517. float32array[index + 2] = blue * exponent;
  54518. }
  54519. else {
  54520. float32array[index + 0] = 0;
  54521. float32array[index + 1] = 0;
  54522. float32array[index + 2] = 0;
  54523. }
  54524. };
  54525. HDRTools.readStringLine = function (uint8array, startIndex) {
  54526. var line = "";
  54527. var character = "";
  54528. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  54529. character = String.fromCharCode(uint8array[i]);
  54530. if (character == "\n") {
  54531. break;
  54532. }
  54533. line += character;
  54534. }
  54535. return line;
  54536. };
  54537. /**
  54538. * Reads header information from an RGBE texture stored in a native array.
  54539. * More information on this format are available here:
  54540. * https://en.wikipedia.org/wiki/RGBE_image_format
  54541. *
  54542. * @param uint8array The binary file stored in native array.
  54543. * @return The header information.
  54544. */
  54545. HDRTools.RGBE_ReadHeader = function (uint8array) {
  54546. var height = 0;
  54547. var width = 0;
  54548. var line = this.readStringLine(uint8array, 0);
  54549. if (line[0] != '#' || line[1] != '?') {
  54550. throw "Bad HDR Format.";
  54551. }
  54552. var endOfHeader = false;
  54553. var findFormat = false;
  54554. var lineIndex = 0;
  54555. do {
  54556. lineIndex += (line.length + 1);
  54557. line = this.readStringLine(uint8array, lineIndex);
  54558. if (line == "FORMAT=32-bit_rle_rgbe") {
  54559. findFormat = true;
  54560. }
  54561. else if (line.length == 0) {
  54562. endOfHeader = true;
  54563. }
  54564. } while (!endOfHeader);
  54565. if (!findFormat) {
  54566. throw "HDR Bad header format, unsupported FORMAT";
  54567. }
  54568. lineIndex += (line.length + 1);
  54569. line = this.readStringLine(uint8array, lineIndex);
  54570. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  54571. var match = sizeRegexp.exec(line);
  54572. // TODO. Support +Y and -X if needed.
  54573. if (match.length < 3) {
  54574. throw "HDR Bad header format, no size";
  54575. }
  54576. width = parseInt(match[2]);
  54577. height = parseInt(match[1]);
  54578. if (width < 8 || width > 0x7fff) {
  54579. throw "HDR Bad header format, unsupported size";
  54580. }
  54581. lineIndex += (line.length + 1);
  54582. return {
  54583. height: height,
  54584. width: width,
  54585. dataPosition: lineIndex
  54586. };
  54587. };
  54588. /**
  54589. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  54590. * This RGBE texture needs to store the information as a panorama.
  54591. *
  54592. * More information on this format are available here:
  54593. * https://en.wikipedia.org/wiki/RGBE_image_format
  54594. *
  54595. * @param buffer The binary file stored in an array buffer.
  54596. * @param size The expected size of the extracted cubemap.
  54597. * @return The Cube Map information.
  54598. */
  54599. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  54600. var uint8array = new Uint8Array(buffer);
  54601. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  54602. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  54603. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  54604. return cubeMapData;
  54605. };
  54606. /**
  54607. * Returns the pixels data extracted from an RGBE texture.
  54608. * This pixels will be stored left to right up to down in the R G B order in one array.
  54609. *
  54610. * More information on this format are available here:
  54611. * https://en.wikipedia.org/wiki/RGBE_image_format
  54612. *
  54613. * @param uint8array The binary file stored in an array buffer.
  54614. * @param hdrInfo The header information of the file.
  54615. * @return The pixels data in RGB right to left up to down order.
  54616. */
  54617. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  54618. // Keep for multi format supports.
  54619. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  54620. };
  54621. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  54622. var num_scanlines = hdrInfo.height;
  54623. var scanline_width = hdrInfo.width;
  54624. var a, b, c, d, count;
  54625. var dataIndex = hdrInfo.dataPosition;
  54626. var index = 0, endIndex = 0, i = 0;
  54627. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  54628. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  54629. // 3 channels of 4 bytes per pixel in float.
  54630. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  54631. var resultArray = new Float32Array(resultBuffer);
  54632. // read in each successive scanline
  54633. while (num_scanlines > 0) {
  54634. a = uint8array[dataIndex++];
  54635. b = uint8array[dataIndex++];
  54636. c = uint8array[dataIndex++];
  54637. d = uint8array[dataIndex++];
  54638. if (a != 2 || b != 2 || (c & 0x80)) {
  54639. // this file is not run length encoded
  54640. throw "HDR Bad header format, not RLE";
  54641. }
  54642. if (((c << 8) | d) != scanline_width) {
  54643. throw "HDR Bad header format, wrong scan line width";
  54644. }
  54645. index = 0;
  54646. // read each of the four channels for the scanline into the buffer
  54647. for (i = 0; i < 4; i++) {
  54648. endIndex = (i + 1) * scanline_width;
  54649. while (index < endIndex) {
  54650. a = uint8array[dataIndex++];
  54651. b = uint8array[dataIndex++];
  54652. if (a > 128) {
  54653. // a run of the same value
  54654. count = a - 128;
  54655. if ((count == 0) || (count > endIndex - index)) {
  54656. throw "HDR Bad Format, bad scanline data (run)";
  54657. }
  54658. while (count-- > 0) {
  54659. scanLineArray[index++] = b;
  54660. }
  54661. }
  54662. else {
  54663. // a non-run
  54664. count = a;
  54665. if ((count == 0) || (count > endIndex - index)) {
  54666. throw "HDR Bad Format, bad scanline data (non-run)";
  54667. }
  54668. scanLineArray[index++] = b;
  54669. if (--count > 0) {
  54670. for (var j = 0; j < count; j++) {
  54671. scanLineArray[index++] = uint8array[dataIndex++];
  54672. }
  54673. }
  54674. }
  54675. }
  54676. }
  54677. // now convert data from buffer into floats
  54678. for (i = 0; i < scanline_width; i++) {
  54679. a = scanLineArray[i];
  54680. b = scanLineArray[i + scanline_width];
  54681. c = scanLineArray[i + 2 * scanline_width];
  54682. d = scanLineArray[i + 3 * scanline_width];
  54683. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  54684. }
  54685. num_scanlines--;
  54686. }
  54687. return resultArray;
  54688. };
  54689. return HDRTools;
  54690. })();
  54691. Internals.HDRTools = HDRTools;
  54692. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54693. })(BABYLON || (BABYLON = {}));
  54694. //_______________________________________________________________
  54695. // Extracted from CubeMapGen:
  54696. // https://code.google.com/archive/p/cubemapgen/
  54697. //
  54698. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  54699. //_______________________________________________________________
  54700. var BABYLON;
  54701. (function (BABYLON) {
  54702. var Internals;
  54703. (function (Internals) {
  54704. /**
  54705. * The bounding box information used during the conversion process.
  54706. */
  54707. var CMGBoundinBox = (function () {
  54708. function CMGBoundinBox() {
  54709. this.min = new BABYLON.Vector3(0, 0, 0);
  54710. this.max = new BABYLON.Vector3(0, 0, 0);
  54711. this.clear();
  54712. }
  54713. CMGBoundinBox.prototype.clear = function () {
  54714. this.min.x = CMGBoundinBox.MAX;
  54715. this.min.y = CMGBoundinBox.MAX;
  54716. this.min.z = CMGBoundinBox.MAX;
  54717. this.max.x = CMGBoundinBox.MIN;
  54718. this.max.y = CMGBoundinBox.MIN;
  54719. this.max.z = CMGBoundinBox.MIN;
  54720. };
  54721. CMGBoundinBox.prototype.augment = function (x, y, z) {
  54722. this.min.x = Math.min(this.min.x, x);
  54723. this.min.y = Math.min(this.min.y, y);
  54724. this.min.z = Math.min(this.min.z, z);
  54725. this.max.x = Math.max(this.max.x, x);
  54726. this.max.y = Math.max(this.max.y, y);
  54727. this.max.z = Math.max(this.max.z, z);
  54728. };
  54729. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  54730. this.min.x = Math.max(this.min.x, x);
  54731. this.min.y = Math.max(this.min.y, y);
  54732. this.min.z = Math.max(this.min.z, z);
  54733. };
  54734. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  54735. this.max.x = Math.min(this.max.x, x);
  54736. this.max.y = Math.min(this.max.y, y);
  54737. this.max.z = Math.min(this.max.z, z);
  54738. };
  54739. CMGBoundinBox.prototype.empty = function () {
  54740. if ((this.min.x > this.max.y) ||
  54741. (this.min.y > this.max.y) ||
  54742. (this.min.z > this.max.y)) {
  54743. return true;
  54744. }
  54745. else {
  54746. return false;
  54747. }
  54748. };
  54749. CMGBoundinBox.MAX = Number.MAX_VALUE;
  54750. CMGBoundinBox.MIN = Number.MIN_VALUE;
  54751. return CMGBoundinBox;
  54752. })();
  54753. /**
  54754. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  54755. * required by the glossinees of a material.
  54756. *
  54757. * This only supports the cosine drop power as well as Warp fixup generation method.
  54758. *
  54759. * This is using the process from CubeMapGen described here:
  54760. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  54761. */
  54762. var PMREMGenerator = (function () {
  54763. /**
  54764. * Constructor of the generator.
  54765. *
  54766. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  54767. * @param inputSize The size of the cubemap faces
  54768. * @param outputSize The size of the output cubemap faces
  54769. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  54770. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  54771. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  54772. * @param specularPower The max specular level of the desired cubemap
  54773. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  54774. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  54775. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  54776. */
  54777. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  54778. this.input = input;
  54779. this.inputSize = inputSize;
  54780. this.outputSize = outputSize;
  54781. this.maxNumMipLevels = maxNumMipLevels;
  54782. this.numChannels = numChannels;
  54783. this.isFloat = isFloat;
  54784. this.specularPower = specularPower;
  54785. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  54786. this.excludeBase = excludeBase;
  54787. this.fixup = fixup;
  54788. this._outputSurface = [];
  54789. this._numMipLevels = 0;
  54790. }
  54791. /**
  54792. * Launches the filter process and return the result.
  54793. *
  54794. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  54795. */
  54796. PMREMGenerator.prototype.filterCubeMap = function () {
  54797. // Init cubemap processor
  54798. this.init();
  54799. // Filters the cubemap
  54800. this.filterCubeMapMipChain();
  54801. // Returns the filtered mips.
  54802. return this._outputSurface;
  54803. };
  54804. PMREMGenerator.prototype.init = function () {
  54805. var i;
  54806. var j;
  54807. var mipLevelSize;
  54808. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  54809. if (this.maxNumMipLevels == 0) {
  54810. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  54811. }
  54812. //first miplevel size
  54813. mipLevelSize = this.outputSize;
  54814. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  54815. for (j = 0; j < this.maxNumMipLevels; j++) {
  54816. this._outputSurface.length++;
  54817. this._outputSurface[j] = [];
  54818. //Iterate over faces for output images
  54819. for (i = 0; i < 6; i++) {
  54820. this._outputSurface[j].length++;
  54821. // Initializes a new array for the output.
  54822. if (this.isFloat) {
  54823. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  54824. }
  54825. else {
  54826. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  54827. }
  54828. }
  54829. //next mip level is half size
  54830. mipLevelSize >>= 1;
  54831. this._numMipLevels++;
  54832. //terminate if mip chain becomes too small
  54833. if (mipLevelSize == 0) {
  54834. this.maxNumMipLevels = j;
  54835. return;
  54836. }
  54837. }
  54838. };
  54839. //--------------------------------------------------------------------------------------
  54840. //Cube map filtering and mip chain generation.
  54841. // the cube map filtereing is specified using a number of parameters:
  54842. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  54843. // indicates the region of the hemisphere to filter over for each tap.
  54844. //
  54845. // Note that the top mip level is also a filtered version of the original input images
  54846. // as well in order to create mip chains for diffuse environment illumination.
  54847. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  54848. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  54849. //
  54850. // Then the mip angle used to genreate the next level of the mip chain from the first level
  54851. // is a_InitialMipAngle
  54852. //
  54853. // The angle for the subsequent levels of the mip chain are specified by their parents
  54854. // filtering angle and a per-level scale and bias
  54855. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  54856. //
  54857. //--------------------------------------------------------------------------------------
  54858. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  54859. // First, take count of the lighting model to modify SpecularPower
  54860. // var refSpecularPower = (a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN || a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? a_MCO.SpecularPower / GetSpecularPowerFactorToMatchPhong(a_MCO.SpecularPower) : a_MCO.SpecularPower;
  54861. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  54862. //Cone angle start (for generating subsequent mip levels)
  54863. var currentSpecularPower = this.specularPower;
  54864. //Build filter lookup tables based on the source miplevel size
  54865. this.precomputeFilterLookupTables(this.inputSize);
  54866. // Note that we need to filter the first level before generating mipmap
  54867. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  54868. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  54869. // TODO : Write a function to copy and scale the base mipmap in output
  54870. // I am just lazy here and just put a high specular power value, and do some if.
  54871. if (this.excludeBase && (levelIndex == 0)) {
  54872. // If we don't want to process the base mipmap, just put a very high specular power (this allow to handle scale of the texture).
  54873. currentSpecularPower = 100000.0;
  54874. }
  54875. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  54876. var srcCubeImage = this.input;
  54877. var dstCubeImage = this._outputSurface[levelIndex];
  54878. var dstSize = this.outputSize >> levelIndex;
  54879. // Compute required angle.
  54880. var angle = this.getBaseFilterAngle(currentSpecularPower);
  54881. // filter cube surfaces
  54882. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  54883. // fix seams
  54884. if (this.fixup) {
  54885. this.fixupCubeEdges(dstCubeImage, dstSize);
  54886. }
  54887. // Decrease the specular power to generate the mipmap chain
  54888. // TODO : Use another method for Exclude (see first comment at start of the function
  54889. if (this.excludeBase && (levelIndex == 0)) {
  54890. currentSpecularPower = this.specularPower;
  54891. }
  54892. currentSpecularPower *= this.cosinePowerDropPerMip;
  54893. }
  54894. };
  54895. //--------------------------------------------------------------------------------------
  54896. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  54897. // It allow to optimize the texel to access base on the specular power.
  54898. //--------------------------------------------------------------------------------------
  54899. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  54900. // We want to find the alpha such that:
  54901. // cos(alpha)^cosinePower = epsilon
  54902. // That's: acos(epsilon^(1/cosinePower))
  54903. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  54904. var angle = 180.0;
  54905. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  54906. angle *= 180.0 / Math.PI; // Convert to degree
  54907. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  54908. return angle;
  54909. };
  54910. //--------------------------------------------------------------------------------------
  54911. //Builds the following lookup tables prior to filtering:
  54912. // -normalizer cube map
  54913. // -tap weight lookup table
  54914. //
  54915. //--------------------------------------------------------------------------------------
  54916. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  54917. var srcTexelAngle;
  54918. var iCubeFace;
  54919. //clear pre-existing normalizer cube map
  54920. this._normCubeMap = [];
  54921. //Normalized vectors per cubeface and per-texel solid angle
  54922. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  54923. };
  54924. //--------------------------------------------------------------------------------------
  54925. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  54926. //
  54927. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  54928. //
  54929. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  54930. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  54931. // below
  54932. //--------------------------------------------------------------------------------------
  54933. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  54934. var iCubeFace;
  54935. var u;
  54936. var v;
  54937. //iterate over cube faces
  54938. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  54939. //First three channels for norm cube, and last channel for solid angle
  54940. this._normCubeMap.push(new Float32Array(size * size * 4));
  54941. //fast texture walk, build normalizer cube map
  54942. var facesData = this.input[iCubeFace];
  54943. for (v = 0; v < size; v++) {
  54944. for (u = 0; u < size; u++) {
  54945. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  54946. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  54947. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  54948. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  54949. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  54950. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  54951. }
  54952. }
  54953. }
  54954. };
  54955. //--------------------------------------------------------------------------------------
  54956. // Convert cubemap face texel coordinates and face idx to 3D vector
  54957. // note the U and V coords are integer coords and range from 0 to size-1
  54958. // this routine can be used to generate a normalizer cube map
  54959. //--------------------------------------------------------------------------------------
  54960. // SL BEGIN
  54961. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  54962. var nvcU;
  54963. var nvcV;
  54964. var tempVec;
  54965. // Change from original AMD code
  54966. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  54967. // + 0.5f is for texel center addressing
  54968. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  54969. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  54970. // warp fixup
  54971. if (fixup && size > 1) {
  54972. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  54973. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  54974. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  54975. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  54976. }
  54977. // Get current vector
  54978. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  54979. // U contribution
  54980. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  54981. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  54982. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  54983. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  54984. // V contribution and Sum
  54985. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  54986. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  54987. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  54988. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  54989. //add face axis
  54990. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  54991. PMREMGenerator._vectorTemp.x += faceAxis[0];
  54992. PMREMGenerator._vectorTemp.y += faceAxis[1];
  54993. PMREMGenerator._vectorTemp.z += faceAxis[2];
  54994. //normalize vector
  54995. PMREMGenerator._vectorTemp.normalize();
  54996. return PMREMGenerator._vectorTemp;
  54997. };
  54998. //--------------------------------------------------------------------------------------
  54999. // Convert 3D vector to cubemap face texel coordinates and face idx
  55000. // note the U and V coords are integer coords and range from 0 to size-1
  55001. // this routine can be used to generate a normalizer cube map
  55002. //
  55003. // returns face IDX and texel coords
  55004. //--------------------------------------------------------------------------------------
  55005. // SL BEGIN
  55006. /*
  55007. Mapping Texture Coordinates to Cube Map Faces
  55008. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  55009. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  55010. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  55011. map arrangement in Pixar's RenderMan package.
  55012. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  55013. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  55014. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  55015. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  55016. the major axis direction). The target column in the table below explains how the major axis direction
  55017. maps to the 2D image of a particular cube map target.
  55018. major axis
  55019. direction target sc tc ma
  55020. ---------- --------------------------------- --- --- ---
  55021. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  55022. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  55023. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  55024. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  55025. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  55026. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  55027. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  55028. an updated (s,t) is calculated as follows
  55029. s = ( sc/|ma| + 1 ) / 2
  55030. t = ( tc/|ma| + 1 ) / 2
  55031. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  55032. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  55033. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  55034. */
  55035. // Note this method return U and V in range from 0 to size-1
  55036. // SL END
  55037. // Store the information in vector3 for convenience (faceindex, u, v)
  55038. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  55039. var maxCoord;
  55040. var faceIdx;
  55041. //absolute value 3
  55042. var absX = Math.abs(x);
  55043. var absY = Math.abs(y);
  55044. var absZ = Math.abs(z);
  55045. if (absX >= absY && absX >= absZ) {
  55046. maxCoord = absX;
  55047. if (x >= 0) {
  55048. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  55049. }
  55050. else {
  55051. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  55052. }
  55053. }
  55054. else if (absY >= absX && absY >= absZ) {
  55055. maxCoord = absY;
  55056. if (y >= 0) {
  55057. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  55058. }
  55059. else {
  55060. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  55061. }
  55062. }
  55063. else {
  55064. maxCoord = absZ;
  55065. if (z >= 0) {
  55066. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  55067. }
  55068. else {
  55069. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  55070. }
  55071. }
  55072. //divide through by max coord so face vector lies on cube face
  55073. var scale = 1 / maxCoord;
  55074. x *= scale;
  55075. y *= scale;
  55076. z *= scale;
  55077. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55078. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  55079. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55080. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  55081. // Modify original AMD code to return value from 0 to Size - 1
  55082. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  55083. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  55084. PMREMGenerator._vectorTemp.x = faceIdx;
  55085. PMREMGenerator._vectorTemp.y = u;
  55086. PMREMGenerator._vectorTemp.z = v;
  55087. return PMREMGenerator._vectorTemp;
  55088. };
  55089. //--------------------------------------------------------------------------------------
  55090. //Original code from Ignacio CastaÒo
  55091. // This formula is from Manne ÷hrstrˆm's thesis.
  55092. // Take two coordiantes in the range [-1, 1] that define a portion of a
  55093. // cube face and return the area of the projection of that portion on the
  55094. // surface of the sphere.
  55095. //--------------------------------------------------------------------------------------
  55096. PMREMGenerator.prototype.areaElement = function (x, y) {
  55097. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  55098. };
  55099. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  55100. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55101. // (+ 0.5f is for texel center addressing)
  55102. u = (2.0 * (u + 0.5) / size) - 1.0;
  55103. v = (2.0 * (v + 0.5) / size) - 1.0;
  55104. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  55105. var invResolution = 1.0 / size;
  55106. // U and V are the -1..1 texture coordinate on the current face.
  55107. // Get projected area for this texel
  55108. var x0 = u - invResolution;
  55109. var y0 = v - invResolution;
  55110. var x1 = u + invResolution;
  55111. var y1 = v + invResolution;
  55112. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  55113. return solidAngle;
  55114. };
  55115. //--------------------------------------------------------------------------------------
  55116. //The key to the speed of these filtering routines is to quickly define a per-face
  55117. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  55118. // Later these pixels are selectively processed based on their dot products to see if
  55119. // they reside within the filtering cone.
  55120. //
  55121. //This is done by computing the smallest per-texel angle to get a conservative estimate
  55122. // of the number of texels needed to be covered in width and height order to filter the
  55123. // region. the bounding box for the center taps face is defined first, and if the
  55124. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  55125. // defined next
  55126. //--------------------------------------------------------------------------------------
  55127. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  55128. // note that pixels within these regions may be rejected
  55129. // based on the anlge
  55130. var iCubeFace;
  55131. var u;
  55132. var v;
  55133. // bounding box per face to specify region to process
  55134. var filterExtents = [];
  55135. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55136. filterExtents.push(new CMGBoundinBox());
  55137. }
  55138. // min angle a src texel can cover (in degrees)
  55139. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  55140. // angle about center tap to define filter cone
  55141. // filter angle is 1/2 the cone angle
  55142. var filterAngle = filterConeAngle / 2.0;
  55143. //ensure filter angle is larger than a texel
  55144. if (filterAngle < srcTexelAngle) {
  55145. filterAngle = srcTexelAngle;
  55146. }
  55147. //ensure filter cone is always smaller than the hemisphere
  55148. if (filterAngle > 90.0) {
  55149. filterAngle = 90.0;
  55150. }
  55151. // the maximum number of texels in 1D the filter cone angle will cover
  55152. // used to determine bounding box size for filter extents
  55153. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  55154. // ensure conservative region always covers at least one texel
  55155. if (filterSize < 1) {
  55156. filterSize = 1;
  55157. }
  55158. // dotProdThresh threshold based on cone angle to determine whether or not taps
  55159. // reside within the cone angle
  55160. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  55161. // process required faces
  55162. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55163. //iterate over dst cube map face texel
  55164. for (v = 0; v < dstSize; v++) {
  55165. for (u = 0; u < dstSize; u++) {
  55166. //get center tap direction
  55167. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  55168. //clear old per-face filter extents
  55169. this.clearFilterExtents(filterExtents);
  55170. //define per-face filter extents
  55171. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  55172. //perform filtering of src faces using filter extents
  55173. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  55174. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  55175. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  55176. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  55177. }
  55178. }
  55179. }
  55180. };
  55181. //--------------------------------------------------------------------------------------
  55182. //Clear filter extents for the 6 cube map faces
  55183. //--------------------------------------------------------------------------------------
  55184. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  55185. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  55186. filterExtents[iCubeFaces].clear();
  55187. }
  55188. };
  55189. //--------------------------------------------------------------------------------------
  55190. //Define per-face bounding box filter extents
  55191. //
  55192. // These define conservative texel regions in each of the faces the filter can possibly
  55193. // process. When the pixels in the regions are actually processed, the dot product
  55194. // between the tap vector and the center tap vector is used to determine the weight of
  55195. // the tap and whether or not the tap is within the cone.
  55196. //
  55197. //--------------------------------------------------------------------------------------
  55198. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  55199. //neighboring face and bleed over amount, and width of BBOX for
  55200. // left, right, top, and bottom edges of this face
  55201. var bleedOverAmount = [0, 0, 0, 0];
  55202. var bleedOverBBoxMin = [0, 0, 0, 0];
  55203. var bleedOverBBoxMax = [0, 0, 0, 0];
  55204. var neighborFace;
  55205. var neighborEdge;
  55206. var oppositeFaceIdx;
  55207. //get face idx, and u, v info from center tap dir
  55208. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  55209. var faceIdx = result.x;
  55210. var u = result.y;
  55211. var v = result.z;
  55212. //define bbox size within face
  55213. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  55214. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  55215. filterExtents[faceIdx].clampMin(0, 0, 0);
  55216. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  55217. //u and v extent in face corresponding to center tap
  55218. var minU = filterExtents[faceIdx].min.x;
  55219. var minV = filterExtents[faceIdx].min.y;
  55220. var maxU = filterExtents[faceIdx].max.x;
  55221. var maxV = filterExtents[faceIdx].max.y;
  55222. //bleed over amounts for face across u=0 edge (left)
  55223. bleedOverAmount[0] = (bboxSize - u);
  55224. bleedOverBBoxMin[0] = minV;
  55225. bleedOverBBoxMax[0] = maxV;
  55226. //bleed over amounts for face across u=1 edge (right)
  55227. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  55228. bleedOverBBoxMin[1] = minV;
  55229. bleedOverBBoxMax[1] = maxV;
  55230. //bleed over to face across v=0 edge (up)
  55231. bleedOverAmount[2] = (bboxSize - v);
  55232. bleedOverBBoxMin[2] = minU;
  55233. bleedOverBBoxMax[2] = maxU;
  55234. //bleed over to face across v=1 edge (down)
  55235. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  55236. bleedOverBBoxMin[3] = minU;
  55237. bleedOverBBoxMax[3] = maxU;
  55238. //compute bleed over regions in neighboring faces
  55239. for (var i = 0; i < 4; i++) {
  55240. if (bleedOverAmount[i] > 0) {
  55241. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  55242. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  55243. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  55244. // be flipped: the cases are
  55245. // if a left edge mates with a left or bottom edge on the neighbor
  55246. // if a top edge mates with a top or right edge on the neighbor
  55247. // if a right edge mates with a right or top edge on the neighbor
  55248. // if a bottom edge mates with a bottom or left edge on the neighbor
  55249. //Seeing as the edges are enumerated as follows
  55250. // left =0
  55251. // right =1
  55252. // top =2
  55253. // bottom =3
  55254. //
  55255. // so if the edge enums are the same, or the sum of the enums == 3,
  55256. // the bbox needs to be flipped
  55257. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  55258. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  55259. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  55260. }
  55261. //The way the bounding box is extended onto the neighboring face
  55262. // depends on which edge of neighboring face abuts with this one
  55263. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  55264. case PMREMGenerator.CP_EDGE_LEFT:
  55265. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  55266. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55267. break;
  55268. case PMREMGenerator.CP_EDGE_RIGHT:
  55269. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  55270. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55271. break;
  55272. case PMREMGenerator.CP_EDGE_TOP:
  55273. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  55274. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  55275. break;
  55276. case PMREMGenerator.CP_EDGE_BOTTOM:
  55277. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  55278. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  55279. break;
  55280. }
  55281. //clamp filter extents in non-center tap faces to remain within surface
  55282. filterExtents[neighborFace].clampMin(0, 0, 0);
  55283. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  55284. }
  55285. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  55286. // from the center tap face, then process the opposite face entirely for now.
  55287. //Note that the cases in which this happens, what usually happens is that
  55288. // more than one edge bleeds onto the opposite face, and the bounding box
  55289. // encompasses the entire cube map face.
  55290. if (bleedOverAmount[i] > srcSize) {
  55291. //determine opposite face
  55292. switch (faceIdx) {
  55293. case PMREMGenerator.CP_FACE_X_POS:
  55294. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  55295. break;
  55296. case PMREMGenerator.CP_FACE_X_NEG:
  55297. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  55298. break;
  55299. case PMREMGenerator.CP_FACE_Y_POS:
  55300. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  55301. break;
  55302. case PMREMGenerator.CP_FACE_Y_NEG:
  55303. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  55304. break;
  55305. case PMREMGenerator.CP_FACE_Z_POS:
  55306. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  55307. break;
  55308. case PMREMGenerator.CP_FACE_Z_NEG:
  55309. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  55310. break;
  55311. default:
  55312. break;
  55313. }
  55314. //just encompass entire face for now
  55315. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  55316. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  55317. }
  55318. }
  55319. };
  55320. //--------------------------------------------------------------------------------------
  55321. //ProcessFilterExtents
  55322. // Process bounding box in each cube face
  55323. //
  55324. //--------------------------------------------------------------------------------------
  55325. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  55326. //accumulators are 64-bit floats in order to have the precision needed
  55327. // over a summation of a large number of pixels
  55328. var dstAccum = [0, 0, 0, 0];
  55329. var weightAccum = 0;
  55330. var k = 0;
  55331. var nSrcChannels = this.numChannels;
  55332. // norm cube map and srcCubeMap have same face width
  55333. var faceWidth = srcSize;
  55334. //amount to add to pointer to move to next scanline in images
  55335. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  55336. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  55337. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  55338. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  55339. // iterate over cubefaces
  55340. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  55341. //if bbox is non empty
  55342. if (!filterExtents[iFaceIdx].empty()) {
  55343. var uStart = filterExtents[iFaceIdx].min.x;
  55344. var vStart = filterExtents[iFaceIdx].min.y;
  55345. var uEnd = filterExtents[iFaceIdx].max.x;
  55346. var vEnd = filterExtents[iFaceIdx].max.y;
  55347. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  55348. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  55349. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  55350. for (var v = vStart; v <= vEnd; v++) {
  55351. var normCubeRowWalk = 0;
  55352. var srcCubeRowWalk = 0;
  55353. for (var u = uStart; u <= uEnd; u++) {
  55354. //pointer to direction in cube map associated with texel
  55355. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  55356. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  55357. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  55358. //check dot product to see if texel is within cone
  55359. var tapDotProd = texelVectX * centerTapDir.x +
  55360. texelVectY * centerTapDir.y +
  55361. texelVectZ * centerTapDir.z;
  55362. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  55363. //solid angle stored in 4th channel of normalizer/solid angle cube map
  55364. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  55365. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  55366. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  55367. // so just adding one to specularpower do the trick.
  55368. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  55369. //iterate over channels
  55370. for (k = 0; k < nSrcChannels; k++) {
  55371. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  55372. srcCubeRowWalk++;
  55373. }
  55374. weightAccum += weight; //accumulate weight
  55375. }
  55376. else {
  55377. //step across source pixel
  55378. srcCubeRowWalk += nSrcChannels;
  55379. }
  55380. normCubeRowWalk += 4; // 4 channels per norm cube map.
  55381. }
  55382. startIndexNormCubeMap += normCubePitch;
  55383. startIndexSrcCubeMap += srcCubePitch;
  55384. }
  55385. }
  55386. }
  55387. //divide through by weights if weight is non zero
  55388. if (weightAccum != 0.0) {
  55389. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  55390. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  55391. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  55392. if (this.numChannels > 3) {
  55393. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  55394. }
  55395. }
  55396. else {
  55397. // otherwise sample nearest
  55398. // get face idx and u, v texel coordinate in face
  55399. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  55400. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  55401. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  55402. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  55403. if (this.numChannels > 3) {
  55404. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  55405. }
  55406. }
  55407. return PMREMGenerator._vectorTemp;
  55408. };
  55409. //--------------------------------------------------------------------------------------
  55410. // Fixup cube edges
  55411. //
  55412. // average texels on cube map faces across the edges
  55413. // WARP/BENT Method Only.
  55414. //--------------------------------------------------------------------------------------
  55415. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  55416. var k;
  55417. var j;
  55418. var i;
  55419. var iFace;
  55420. var iCorner = 0;
  55421. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  55422. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  55423. // note that if functionality to filter across the three texels for each corner, then
  55424. //indexed by corner and face idx. the array contains the face the start points belongs to.
  55425. var cornerPtr = [
  55426. [[], [], []],
  55427. [[], [], []],
  55428. [[], [], []],
  55429. [[], [], []],
  55430. [[], [], []],
  55431. [[], [], []],
  55432. [[], [], []],
  55433. [[], [], []]
  55434. ];
  55435. //if there is no fixup, or fixup width = 0, do nothing
  55436. if (cubeMapSize < 1) {
  55437. return;
  55438. }
  55439. //special case 1x1 cubemap, average face colors
  55440. if (cubeMapSize == 1) {
  55441. //iterate over channels
  55442. for (k = 0; k < this.numChannels; k++) {
  55443. var accum = 0.0;
  55444. //iterate over faces to accumulate face colors
  55445. for (iFace = 0; iFace < 6; iFace++) {
  55446. accum += cubeMap[iFace][k];
  55447. }
  55448. //compute average over 6 face colors
  55449. accum /= 6.0;
  55450. //iterate over faces to distribute face colors
  55451. for (iFace = 0; iFace < 6; iFace++) {
  55452. cubeMap[iFace][k] = accum;
  55453. }
  55454. }
  55455. return;
  55456. }
  55457. //iterate over faces to collect list of corner texel pointers
  55458. for (iFace = 0; iFace < 6; iFace++) {
  55459. //the 4 corner pointers for this face
  55460. faceCornerStartIndicies[0] = [iFace, 0];
  55461. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  55462. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  55463. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  55464. //iterate over face corners to collect cube corner pointers
  55465. for (iCorner = 0; iCorner < 4; iCorner++) {
  55466. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  55467. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  55468. cornerNumPtrs[corner]++;
  55469. }
  55470. }
  55471. //iterate over corners to average across corner tap values
  55472. for (iCorner = 0; iCorner < 8; iCorner++) {
  55473. for (k = 0; k < this.numChannels; k++) {
  55474. var cornerTapAccum = 0.0;
  55475. //iterate over corner texels and average results
  55476. for (i = 0; i < 3; i++) {
  55477. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  55478. }
  55479. //divide by 3 to compute average of corner tap values
  55480. cornerTapAccum *= (1.0 / 3.0);
  55481. //iterate over corner texels and average results
  55482. for (i = 0; i < 3; i++) {
  55483. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  55484. }
  55485. }
  55486. }
  55487. //iterate over the twelve edges of the cube to average across edges
  55488. for (i = 0; i < 12; i++) {
  55489. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  55490. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  55491. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  55492. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  55493. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  55494. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  55495. var edgeWalk = 0;
  55496. var neighborEdgeWalk = 0;
  55497. //Determine walking pointers based on edge type
  55498. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  55499. switch (edge) {
  55500. case PMREMGenerator.CP_EDGE_LEFT:
  55501. // no change to faceEdgeStartPtr
  55502. edgeWalk = this.numChannels * cubeMapSize;
  55503. break;
  55504. case PMREMGenerator.CP_EDGE_RIGHT:
  55505. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  55506. edgeWalk = this.numChannels * cubeMapSize;
  55507. break;
  55508. case PMREMGenerator.CP_EDGE_TOP:
  55509. // no change to faceEdgeStartPtr
  55510. edgeWalk = this.numChannels;
  55511. break;
  55512. case PMREMGenerator.CP_EDGE_BOTTOM:
  55513. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  55514. edgeWalk = this.numChannels;
  55515. break;
  55516. }
  55517. //For certain types of edge abutments, the neighbor edge walk needs to
  55518. // be flipped: the cases are
  55519. // if a left edge mates with a left or bottom edge on the neighbor
  55520. // if a top edge mates with a top or right edge on the neighbor
  55521. // if a right edge mates with a right or top edge on the neighbor
  55522. // if a bottom edge mates with a bottom or left edge on the neighbor
  55523. //Seeing as the edges are enumerated as follows
  55524. // left =0
  55525. // right =1
  55526. // top =2
  55527. // bottom =3
  55528. //
  55529. //If the edge enums are the same, or the sum of the enums == 3,
  55530. // the neighbor edge walk needs to be flipped
  55531. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  55532. switch (neighborEdge) {
  55533. case PMREMGenerator.CP_EDGE_LEFT:
  55534. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  55535. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  55536. break;
  55537. case PMREMGenerator.CP_EDGE_RIGHT:
  55538. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  55539. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  55540. break;
  55541. case PMREMGenerator.CP_EDGE_TOP:
  55542. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  55543. neighborEdgeWalk = -this.numChannels;
  55544. break;
  55545. case PMREMGenerator.CP_EDGE_BOTTOM:
  55546. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  55547. neighborEdgeWalk = -this.numChannels;
  55548. break;
  55549. }
  55550. }
  55551. else {
  55552. //swapped direction neighbor edge walk
  55553. switch (neighborEdge) {
  55554. case PMREMGenerator.CP_EDGE_LEFT:
  55555. //no change to neighborEdgeStartPtr for this case since it points
  55556. // to the upper left corner already
  55557. neighborEdgeWalk = this.numChannels * cubeMapSize;
  55558. break;
  55559. case PMREMGenerator.CP_EDGE_RIGHT:
  55560. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  55561. neighborEdgeWalk = this.numChannels * cubeMapSize;
  55562. break;
  55563. case PMREMGenerator.CP_EDGE_TOP:
  55564. //no change to neighborEdgeStartPtr for this case since it points
  55565. // to the upper left corner already
  55566. neighborEdgeWalk = this.numChannels;
  55567. break;
  55568. case PMREMGenerator.CP_EDGE_BOTTOM:
  55569. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  55570. neighborEdgeWalk = this.numChannels;
  55571. break;
  55572. }
  55573. }
  55574. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  55575. //nearby neighborhood
  55576. //step ahead one texel on edge
  55577. edgeStartIndex += edgeWalk;
  55578. neighborEdgeStartIndex += neighborEdgeWalk;
  55579. // note that this loop does not process the corner texels, since they have already been
  55580. // averaged across faces across earlier
  55581. for (j = 1; j < (cubeMapSize - 1); j++) {
  55582. //for each set of taps along edge, average them
  55583. // and rewrite the results into the edges
  55584. for (k = 0; k < this.numChannels; k++) {
  55585. var edgeTap = cubeMap[face][edgeStartIndex + k];
  55586. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  55587. //compute average of tap intensity values
  55588. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  55589. //propagate average of taps to edge taps
  55590. cubeMap[face][edgeStartIndex + k] = avgTap;
  55591. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  55592. }
  55593. edgeStartIndex += edgeWalk;
  55594. neighborEdgeStartIndex += neighborEdgeWalk;
  55595. }
  55596. }
  55597. };
  55598. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  55599. PMREMGenerator.CP_UDIR = 0;
  55600. PMREMGenerator.CP_VDIR = 1;
  55601. PMREMGenerator.CP_FACEAXIS = 2;
  55602. //used to index cube faces
  55603. PMREMGenerator.CP_FACE_X_POS = 0;
  55604. PMREMGenerator.CP_FACE_X_NEG = 1;
  55605. PMREMGenerator.CP_FACE_Y_POS = 2;
  55606. PMREMGenerator.CP_FACE_Y_NEG = 3;
  55607. PMREMGenerator.CP_FACE_Z_POS = 4;
  55608. PMREMGenerator.CP_FACE_Z_NEG = 5;
  55609. //used to index image edges
  55610. // NOTE.. the actual number corresponding to the edge is important
  55611. // do not change these, or the code will break
  55612. //
  55613. // CP_EDGE_LEFT is u = 0
  55614. // CP_EDGE_RIGHT is u = width-1
  55615. // CP_EDGE_TOP is v = 0
  55616. // CP_EDGE_BOTTOM is v = height-1
  55617. PMREMGenerator.CP_EDGE_LEFT = 0;
  55618. PMREMGenerator.CP_EDGE_RIGHT = 1;
  55619. PMREMGenerator.CP_EDGE_TOP = 2;
  55620. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  55621. //corners of CUBE map (P or N specifys if it corresponds to the
  55622. // positive or negative direction each of X, Y, and Z
  55623. PMREMGenerator.CP_CORNER_NNN = 0;
  55624. PMREMGenerator.CP_CORNER_NNP = 1;
  55625. PMREMGenerator.CP_CORNER_NPN = 2;
  55626. PMREMGenerator.CP_CORNER_NPP = 3;
  55627. PMREMGenerator.CP_CORNER_PNN = 4;
  55628. PMREMGenerator.CP_CORNER_PNP = 5;
  55629. PMREMGenerator.CP_CORNER_PPN = 6;
  55630. PMREMGenerator.CP_CORNER_PPP = 7;
  55631. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  55632. //3x2 matrices that map cube map indexing vectors in 3d
  55633. // (after face selection and divide through by the
  55634. // _ABSOLUTE VALUE_ of the max coord)
  55635. // into NVC space
  55636. //Note this currently assumes the D3D cube face ordering and orientation
  55637. PMREMGenerator._sgFace2DMapping = [
  55638. //XPOS face
  55639. [[0, 0, -1],
  55640. [0, -1, 0],
  55641. [1, 0, 0]],
  55642. //XNEG face
  55643. [[0, 0, 1],
  55644. [0, -1, 0],
  55645. [-1, 0, 0]],
  55646. //YPOS face
  55647. [[1, 0, 0],
  55648. [0, 0, 1],
  55649. [0, 1, 0]],
  55650. //YNEG face
  55651. [[1, 0, 0],
  55652. [0, 0, -1],
  55653. [0, -1, 0]],
  55654. //ZPOS face
  55655. [[1, 0, 0],
  55656. [0, -1, 0],
  55657. [0, 0, 1]],
  55658. //ZNEG face
  55659. [[-1, 0, 0],
  55660. [0, -1, 0],
  55661. [0, 0, -1]],
  55662. ];
  55663. //------------------------------------------------------------------------------
  55664. // D3D cube map face specification
  55665. // mapping from 3D x,y,z cube map lookup coordinates
  55666. // to 2D within face u,v coordinates
  55667. //
  55668. // --------------------> U direction
  55669. // | (within-face texture space)
  55670. // | _____
  55671. // | | |
  55672. // | | +Y |
  55673. // | _____|_____|_____ _____
  55674. // | | | | | |
  55675. // | | -X | +Z | +X | -Z |
  55676. // | |_____|_____|_____|_____|
  55677. // | | |
  55678. // | | -Y |
  55679. // | |_____|
  55680. // |
  55681. // v V direction
  55682. // (within-face texture space)
  55683. //------------------------------------------------------------------------------
  55684. //Information about neighbors and how texture coorrdinates change across faces
  55685. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  55686. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  55687. //Note this currently assumes the D3D cube face ordering and orientation
  55688. PMREMGenerator._sgCubeNgh = [
  55689. //XPOS face
  55690. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  55691. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  55692. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  55693. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  55694. //XNEG face
  55695. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  55696. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  55697. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  55698. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  55699. //YPOS face
  55700. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  55701. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  55702. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  55703. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  55704. //YNEG face
  55705. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  55706. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55707. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55708. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  55709. //ZPOS face
  55710. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  55711. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  55712. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55713. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  55714. //ZNEG face
  55715. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  55716. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  55717. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  55718. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  55719. ];
  55720. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  55721. // this table is used to average over the edges.
  55722. PMREMGenerator._sgCubeEdgeList = [
  55723. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  55724. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  55725. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  55726. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55727. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  55728. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  55729. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  55730. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  55731. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  55732. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55733. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  55734. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  55735. ];
  55736. //Information about which of the 8 cube corners are correspond to the
  55737. // the 4 corners in each cube face
  55738. // the order is upper left, upper right, lower left, lower right
  55739. PMREMGenerator._sgCubeCornerList = [
  55740. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  55741. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  55742. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  55743. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  55744. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  55745. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  55746. ];
  55747. return PMREMGenerator;
  55748. })();
  55749. Internals.PMREMGenerator = PMREMGenerator;
  55750. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55751. })(BABYLON || (BABYLON = {}));
  55752. var BABYLON;
  55753. (function (BABYLON) {
  55754. /**
  55755. * This represents a texture coming from an HDR input.
  55756. *
  55757. * The only supported format is currently panorama picture stored in RGBE format.
  55758. * Example of such files can be found on HDRLib: http://hdrlib.com/
  55759. */
  55760. var HDRCubeTexture = (function (_super) {
  55761. __extends(HDRCubeTexture, _super);
  55762. /**
  55763. * Instantiates an HDRTexture from the following parameters.
  55764. *
  55765. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  55766. * @param scene The scene the texture will be used in
  55767. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  55768. * @param noMipmap Forces to not generate the mipmap if true
  55769. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  55770. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  55771. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  55772. */
  55773. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  55774. if (noMipmap === void 0) { noMipmap = false; }
  55775. if (generateHarmonics === void 0) { generateHarmonics = true; }
  55776. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  55777. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  55778. _super.call(this, scene);
  55779. this._useInGammaSpace = false;
  55780. this._generateHarmonics = true;
  55781. this._isBABYLONPreprocessed = false;
  55782. /**
  55783. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  55784. */
  55785. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  55786. /**
  55787. * The spherical polynomial data extracted from the texture.
  55788. */
  55789. this.sphericalPolynomial = null;
  55790. /**
  55791. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  55792. * This is usefull at run time to apply the good shader.
  55793. */
  55794. this.isPMREM = false;
  55795. if (!url) {
  55796. return;
  55797. }
  55798. this.name = url;
  55799. this.url = url;
  55800. this.hasAlpha = false;
  55801. this.isCube = true;
  55802. this._textureMatrix = BABYLON.Matrix.Identity();
  55803. if (size) {
  55804. this._isBABYLONPreprocessed = false;
  55805. this._noMipmap = noMipmap;
  55806. this._size = size;
  55807. this._useInGammaSpace = useInGammaSpace;
  55808. this._usePMREMGenerator = usePMREMGenerator &&
  55809. scene.getEngine().getCaps().textureLOD &&
  55810. this.getScene().getEngine().getCaps().textureFloat &&
  55811. !this._useInGammaSpace;
  55812. }
  55813. else {
  55814. this._isBABYLONPreprocessed = true;
  55815. this._noMipmap = false;
  55816. this._useInGammaSpace = false;
  55817. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  55818. this.getScene().getEngine().getCaps().textureFloat &&
  55819. !this._useInGammaSpace;
  55820. }
  55821. this.isPMREM = this._usePMREMGenerator;
  55822. this._texture = this._getFromCache(url, this._noMipmap);
  55823. if (!this._texture) {
  55824. if (!scene.useDelayedTextureLoading) {
  55825. this.loadTexture();
  55826. }
  55827. else {
  55828. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  55829. }
  55830. }
  55831. }
  55832. /**
  55833. * Occurs when the file is a preprocessed .babylon.hdr file.
  55834. */
  55835. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  55836. var _this = this;
  55837. var mipLevels = 0;
  55838. var floatArrayView = null;
  55839. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  55840. var mips = [];
  55841. var startIndex = 30;
  55842. for (var level = 0; level < mipLevels; level++) {
  55843. mips.push([]);
  55844. // Fill each pixel of the mip level.
  55845. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  55846. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  55847. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  55848. mips[level].push(faceData);
  55849. startIndex += faceSize;
  55850. }
  55851. }
  55852. return mips;
  55853. } : null;
  55854. var callback = function (buffer) {
  55855. // Create Native Array Views
  55856. var intArrayView = new Int32Array(buffer);
  55857. floatArrayView = new Float32Array(buffer);
  55858. // Fill header.
  55859. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  55860. _this._size = intArrayView[1]; // CubeMap max mip face size.
  55861. // Update Texture Information.
  55862. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  55863. // Fill polynomial information.
  55864. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  55865. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  55866. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  55867. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  55868. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  55869. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  55870. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  55871. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  55872. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  55873. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  55874. // Fill pixel data.
  55875. mipLevels = intArrayView[29]; // Number of mip levels.
  55876. var startIndex = 30;
  55877. var data = [];
  55878. var faceSize = Math.pow(_this._size, 2) * 3;
  55879. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  55880. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  55881. startIndex += faceSize;
  55882. }
  55883. var results = [];
  55884. var byteArray = null;
  55885. // Push each faces.
  55886. for (var k = 0; k < 6; k++) {
  55887. var dataFace = null;
  55888. // If special cases.
  55889. if (!mipmapGenerator) {
  55890. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  55891. dataFace = data[j];
  55892. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  55893. // 3 channels of 1 bytes per pixel in bytes.
  55894. var byteBuffer = new ArrayBuffer(faceSize);
  55895. byteArray = new Uint8Array(byteBuffer);
  55896. }
  55897. for (var i = 0; i < _this._size * _this._size; i++) {
  55898. // Put in gamma space if requested.
  55899. if (_this._useInGammaSpace) {
  55900. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  55901. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  55902. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  55903. }
  55904. // Convert to int texture for fallback.
  55905. if (byteArray) {
  55906. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  55907. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  55908. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  55909. // May use luminance instead if the result is not accurate.
  55910. var max = Math.max(Math.max(r, g), b);
  55911. if (max > 255) {
  55912. var scale = 255 / max;
  55913. r *= scale;
  55914. g *= scale;
  55915. b *= scale;
  55916. }
  55917. byteArray[(i * 3) + 0] = r;
  55918. byteArray[(i * 3) + 1] = g;
  55919. byteArray[(i * 3) + 2] = b;
  55920. }
  55921. }
  55922. }
  55923. else {
  55924. dataFace = data[k];
  55925. }
  55926. // Fill the array accordingly.
  55927. if (byteArray) {
  55928. results.push(byteArray);
  55929. }
  55930. else {
  55931. results.push(dataFace);
  55932. }
  55933. }
  55934. return results;
  55935. };
  55936. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator);
  55937. };
  55938. /**
  55939. * Occurs when the file is raw .hdr file.
  55940. */
  55941. HDRCubeTexture.prototype.loadHDRTexture = function () {
  55942. var _this = this;
  55943. var callback = function (buffer) {
  55944. // Extract the raw linear data.
  55945. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  55946. // Generate harmonics if needed.
  55947. if (_this._generateHarmonics) {
  55948. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  55949. }
  55950. var results = [];
  55951. var byteArray = null;
  55952. // Push each faces.
  55953. for (var j = 0; j < 6; j++) {
  55954. // Create uintarray fallback.
  55955. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  55956. // 3 channels of 1 bytes per pixel in bytes.
  55957. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  55958. byteArray = new Uint8Array(byteBuffer);
  55959. }
  55960. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  55961. // If special cases.
  55962. if (_this._useInGammaSpace || byteArray) {
  55963. for (var i = 0; i < _this._size * _this._size; i++) {
  55964. // Put in gamma space if requested.
  55965. if (_this._useInGammaSpace) {
  55966. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  55967. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  55968. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  55969. }
  55970. // Convert to int texture for fallback.
  55971. if (byteArray) {
  55972. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  55973. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  55974. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  55975. // May use luminance instead if the result is not accurate.
  55976. var max = Math.max(Math.max(r, g), b);
  55977. if (max > 255) {
  55978. var scale = 255 / max;
  55979. r *= scale;
  55980. g *= scale;
  55981. b *= scale;
  55982. }
  55983. byteArray[(i * 3) + 0] = r;
  55984. byteArray[(i * 3) + 1] = g;
  55985. byteArray[(i * 3) + 2] = b;
  55986. }
  55987. }
  55988. }
  55989. if (byteArray) {
  55990. results.push(byteArray);
  55991. }
  55992. else {
  55993. results.push(dataFace);
  55994. }
  55995. }
  55996. return results;
  55997. };
  55998. var mipmapGenerator = null;
  55999. if (!this._noMipmap &&
  56000. this._usePMREMGenerator) {
  56001. mipmapGenerator = function (data) {
  56002. // Custom setup of the generator matching with the PBR shader values.
  56003. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  56004. return generator.filterCubeMap();
  56005. };
  56006. }
  56007. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator);
  56008. };
  56009. /**
  56010. * Starts the loading process of the texture.
  56011. */
  56012. HDRCubeTexture.prototype.loadTexture = function () {
  56013. if (this._isBABYLONPreprocessed) {
  56014. this.loadBabylonTexture();
  56015. }
  56016. else {
  56017. this.loadHDRTexture();
  56018. }
  56019. };
  56020. HDRCubeTexture.prototype.clone = function () {
  56021. var size = this._isBABYLONPreprocessed ? null : this._size;
  56022. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  56023. // Base texture
  56024. newTexture.level = this.level;
  56025. newTexture.wrapU = this.wrapU;
  56026. newTexture.wrapV = this.wrapV;
  56027. newTexture.coordinatesIndex = this.coordinatesIndex;
  56028. newTexture.coordinatesMode = this.coordinatesMode;
  56029. return newTexture;
  56030. };
  56031. // Methods
  56032. HDRCubeTexture.prototype.delayLoad = function () {
  56033. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56034. return;
  56035. }
  56036. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56037. this._texture = this._getFromCache(this.url, this._noMipmap);
  56038. if (!this._texture) {
  56039. this.loadTexture();
  56040. }
  56041. };
  56042. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  56043. return this._textureMatrix;
  56044. };
  56045. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56046. var texture = null;
  56047. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  56048. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  56049. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  56050. texture.name = parsedTexture.name;
  56051. texture.hasAlpha = parsedTexture.hasAlpha;
  56052. texture.level = parsedTexture.level;
  56053. texture.coordinatesMode = parsedTexture.coordinatesMode;
  56054. }
  56055. return texture;
  56056. };
  56057. HDRCubeTexture.prototype.serialize = function () {
  56058. if (!this.name) {
  56059. return null;
  56060. }
  56061. var serializationObject = {};
  56062. serializationObject.name = this.name;
  56063. serializationObject.hasAlpha = this.hasAlpha;
  56064. serializationObject.isCube = true;
  56065. serializationObject.level = this.level;
  56066. serializationObject.size = this._size;
  56067. serializationObject.coordinatesMode = this.coordinatesMode;
  56068. serializationObject.useInGammaSpace = this._useInGammaSpace;
  56069. serializationObject.generateHarmonics = this._generateHarmonics;
  56070. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  56071. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  56072. return serializationObject;
  56073. };
  56074. /**
  56075. * Saves as a file the data contained in the texture in a binary format.
  56076. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56077. * as the spherical used in the lighting.
  56078. * @param url The HDR file url.
  56079. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56080. * @param onError Method called if any error happens during download.
  56081. * @return The packed binary data.
  56082. */
  56083. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  56084. if (onError === void 0) { onError = null; }
  56085. var callback = function (buffer) {
  56086. var data = new Blob([buffer], { type: 'application/octet-stream' });
  56087. // Returns a URL you can use as a href.
  56088. var objUrl = window.URL.createObjectURL(data);
  56089. // Simulates a link to it and click to dowload.
  56090. var a = document.createElement("a");
  56091. document.body.appendChild(a);
  56092. a.style.display = "none";
  56093. a.href = objUrl;
  56094. a.download = "envmap.babylon.hdr";
  56095. a.click();
  56096. };
  56097. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  56098. };
  56099. /**
  56100. * Serializes the data contained in the texture in a binary format.
  56101. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56102. * as the spherical used in the lighting.
  56103. * @param url The HDR file url.
  56104. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56105. * @param onError Method called if any error happens during download.
  56106. * @return The packed binary data.
  56107. */
  56108. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  56109. if (onError === void 0) { onError = null; }
  56110. // Needs the url tho create the texture.
  56111. if (!url) {
  56112. return null;
  56113. }
  56114. // Check Power of two size.
  56115. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  56116. return null;
  56117. }
  56118. var getDataCallback = function (dataBuffer) {
  56119. // Extract the raw linear data.
  56120. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  56121. // Generate harmonics if needed.
  56122. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  56123. // Generate seamless faces
  56124. var mipGeneratorArray = [];
  56125. // Data are known to be in +X +Y +Z -X -Y -Z
  56126. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  56127. mipGeneratorArray.push(cubeData.right); // +X
  56128. mipGeneratorArray.push(cubeData.left); // -X
  56129. mipGeneratorArray.push(cubeData.up); // +Y
  56130. mipGeneratorArray.push(cubeData.down); // -Y
  56131. mipGeneratorArray.push(cubeData.front); // +Z
  56132. mipGeneratorArray.push(cubeData.back); // -Z
  56133. // Custom setup of the generator matching with the PBR shader values.
  56134. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  56135. var mippedData = generator.filterCubeMap();
  56136. // Compute required byte length.
  56137. var byteLength = 1 * 4; // Raw Data Version int32.
  56138. byteLength += 4; // CubeMap max mip face size int32.
  56139. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  56140. // Add data size.
  56141. byteLength += 4; // Number of mip levels int32.
  56142. for (var level = 0; level < mippedData.length; level++) {
  56143. var mipSize = size >> level;
  56144. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  56145. }
  56146. // Prepare binary structure.
  56147. var buffer = new ArrayBuffer(byteLength);
  56148. var intArrayView = new Int32Array(buffer);
  56149. var floatArrayView = new Float32Array(buffer);
  56150. // Fill header.
  56151. intArrayView[0] = 1; // Version 1.
  56152. intArrayView[1] = size; // CubeMap max mip face size.
  56153. // Fill polynomial information.
  56154. sphericalPolynomial.x.toArray(floatArrayView, 2);
  56155. sphericalPolynomial.y.toArray(floatArrayView, 5);
  56156. sphericalPolynomial.z.toArray(floatArrayView, 8);
  56157. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  56158. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  56159. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  56160. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  56161. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  56162. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  56163. // Fill pixel data.
  56164. intArrayView[29] = mippedData.length; // Number of mip levels.
  56165. var startIndex = 30;
  56166. for (var level = 0; level < mippedData.length; level++) {
  56167. // Fill each pixel of the mip level.
  56168. var faceSize = Math.pow(size >> level, 2) * 3;
  56169. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56170. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  56171. startIndex += faceSize;
  56172. }
  56173. }
  56174. // Callback.
  56175. callback(buffer);
  56176. };
  56177. // Download and process.
  56178. BABYLON.Tools.LoadFile(url, function (data) {
  56179. getDataCallback(data);
  56180. }, null, null, true, onError);
  56181. };
  56182. HDRCubeTexture._facesMapping = [
  56183. "right",
  56184. "up",
  56185. "front",
  56186. "left",
  56187. "down",
  56188. "back"
  56189. ];
  56190. return HDRCubeTexture;
  56191. })(BABYLON.BaseTexture);
  56192. BABYLON.HDRCubeTexture = HDRCubeTexture;
  56193. })(BABYLON || (BABYLON = {}));
  56194. var BABYLON;
  56195. (function (BABYLON) {
  56196. var Debug;
  56197. (function (Debug) {
  56198. /**
  56199. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  56200. */
  56201. var SkeletonViewer = (function () {
  56202. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  56203. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  56204. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  56205. this.skeleton = skeleton;
  56206. this.mesh = mesh;
  56207. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  56208. this.renderingGroupId = renderingGroupId;
  56209. this.color = BABYLON.Color3.White();
  56210. this._debugLines = [];
  56211. this._isEnabled = false;
  56212. this._scene = scene;
  56213. this.update();
  56214. this._renderFunction = this.update.bind(this);
  56215. }
  56216. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  56217. get: function () {
  56218. return this._isEnabled;
  56219. },
  56220. set: function (value) {
  56221. if (this._isEnabled === value) {
  56222. return;
  56223. }
  56224. this._isEnabled = value;
  56225. if (value) {
  56226. this._scene.registerBeforeRender(this._renderFunction);
  56227. }
  56228. else {
  56229. this._scene.unregisterBeforeRender(this._renderFunction);
  56230. }
  56231. },
  56232. enumerable: true,
  56233. configurable: true
  56234. });
  56235. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  56236. if (x === void 0) { x = 0; }
  56237. if (y === void 0) { y = 0; }
  56238. if (z === void 0) { z = 0; }
  56239. var tmat = BABYLON.Tmp.Matrix[0];
  56240. var parentBone = bone.getParent();
  56241. tmat.copyFrom(bone.getLocalMatrix());
  56242. if (x !== 0 || y !== 0 || z !== 0) {
  56243. var tmat2 = BABYLON.Tmp.Matrix[1];
  56244. BABYLON.Matrix.IdentityToRef(tmat2);
  56245. tmat2.m[12] = x;
  56246. tmat2.m[13] = y;
  56247. tmat2.m[14] = z;
  56248. tmat2.multiplyToRef(tmat, tmat);
  56249. }
  56250. if (parentBone) {
  56251. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  56252. }
  56253. tmat.multiplyToRef(meshMat, tmat);
  56254. position.x = tmat.m[12];
  56255. position.y = tmat.m[13];
  56256. position.z = tmat.m[14];
  56257. };
  56258. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  56259. var len = bones.length;
  56260. for (var i = 0; i < len; i++) {
  56261. var bone = bones[i];
  56262. var points = this._debugLines[i];
  56263. if (!points) {
  56264. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56265. this._debugLines[i] = points;
  56266. }
  56267. this._getBonePosition(points[0], bone, meshMat);
  56268. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  56269. }
  56270. };
  56271. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  56272. var len = bones.length;
  56273. var boneNum = 0;
  56274. for (var i = len - 1; i >= 0; i--) {
  56275. var childBone = bones[i];
  56276. var parentBone = childBone.getParent();
  56277. if (!parentBone) {
  56278. continue;
  56279. }
  56280. var points = this._debugLines[boneNum];
  56281. if (!points) {
  56282. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56283. this._debugLines[boneNum] = points;
  56284. }
  56285. this._getBonePosition(points[0], childBone, meshMat);
  56286. this._getBonePosition(points[1], parentBone, meshMat);
  56287. boneNum++;
  56288. }
  56289. };
  56290. SkeletonViewer.prototype.update = function () {
  56291. if (this.autoUpdateBonesMatrices) {
  56292. this._updateBoneMatrix(this.skeleton.bones[0]);
  56293. }
  56294. if (this.skeleton.bones[0].length === undefined) {
  56295. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56296. }
  56297. else {
  56298. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56299. }
  56300. if (!this._debugMesh) {
  56301. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  56302. this._debugMesh.renderingGroupId = this.renderingGroupId;
  56303. }
  56304. else {
  56305. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  56306. }
  56307. this._debugMesh.color = this.color;
  56308. };
  56309. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  56310. if (bone.getParent()) {
  56311. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  56312. }
  56313. var children = bone.children;
  56314. var len = children.length;
  56315. for (var i = 0; i < len; i++) {
  56316. this._updateBoneMatrix(children[i]);
  56317. }
  56318. };
  56319. SkeletonViewer.prototype.dispose = function () {
  56320. if (this._debugMesh) {
  56321. this.isEnabled = false;
  56322. this._debugMesh.dispose();
  56323. this._debugMesh = null;
  56324. }
  56325. };
  56326. return SkeletonViewer;
  56327. })();
  56328. Debug.SkeletonViewer = SkeletonViewer;
  56329. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56330. })(BABYLON || (BABYLON = {}));
  56331. var BABYLON;
  56332. (function (BABYLON) {
  56333. /**
  56334. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  56335. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  56336. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  56337. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  56338. */
  56339. var ColorCurves = (function () {
  56340. function ColorCurves() {
  56341. this._dirty = true;
  56342. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  56343. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  56344. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  56345. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  56346. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  56347. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  56348. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  56349. this._globalHue = 30;
  56350. this._globalDensity = 0;
  56351. this._globalSaturation = 0;
  56352. this._globalExposure = 0;
  56353. this._highlightsHue = 30;
  56354. this._highlightsDensity = 0;
  56355. this._highlightsSaturation = 0;
  56356. this._highlightsExposure = 0;
  56357. this._midtonesHue = 30;
  56358. this._midtonesDensity = 0;
  56359. this._midtonesSaturation = 0;
  56360. this._midtonesExposure = 0;
  56361. this._shadowsHue = 30;
  56362. this._shadowsDensity = 0;
  56363. this._shadowsSaturation = 0;
  56364. this._shadowsExposure = 0;
  56365. }
  56366. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  56367. /**
  56368. * Gets the global Hue value.
  56369. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  56370. */
  56371. get: function () {
  56372. return this._globalHue;
  56373. },
  56374. /**
  56375. * Sets the global Hue value.
  56376. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  56377. */
  56378. set: function (value) {
  56379. this._globalHue = value;
  56380. this._dirty = true;
  56381. },
  56382. enumerable: true,
  56383. configurable: true
  56384. });
  56385. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  56386. /**
  56387. * Gets the global Density value.
  56388. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  56389. * Values less than zero provide a filter of opposite hue.
  56390. */
  56391. get: function () {
  56392. return this._globalDensity;
  56393. },
  56394. /**
  56395. * Sets the global Density value.
  56396. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  56397. * Values less than zero provide a filter of opposite hue.
  56398. */
  56399. set: function (value) {
  56400. this._globalDensity = value;
  56401. this._dirty = true;
  56402. },
  56403. enumerable: true,
  56404. configurable: true
  56405. });
  56406. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  56407. /**
  56408. * Gets the global Saturation value.
  56409. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  56410. */
  56411. get: function () {
  56412. return this._globalSaturation;
  56413. },
  56414. /**
  56415. * Sets the global Saturation value.
  56416. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  56417. */
  56418. set: function (value) {
  56419. this._globalSaturation = value;
  56420. this._dirty = true;
  56421. },
  56422. enumerable: true,
  56423. configurable: true
  56424. });
  56425. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  56426. /**
  56427. * Gets the highlights Hue value.
  56428. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  56429. */
  56430. get: function () {
  56431. return this._highlightsHue;
  56432. },
  56433. /**
  56434. * Sets the highlights Hue value.
  56435. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  56436. */
  56437. set: function (value) {
  56438. this._highlightsHue = value;
  56439. this._dirty = true;
  56440. },
  56441. enumerable: true,
  56442. configurable: true
  56443. });
  56444. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  56445. /**
  56446. * Gets the highlights Density value.
  56447. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  56448. * Values less than zero provide a filter of opposite hue.
  56449. */
  56450. get: function () {
  56451. return this._highlightsDensity;
  56452. },
  56453. /**
  56454. * Sets the highlights Density value.
  56455. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  56456. * Values less than zero provide a filter of opposite hue.
  56457. */
  56458. set: function (value) {
  56459. this._highlightsDensity = value;
  56460. this._dirty = true;
  56461. },
  56462. enumerable: true,
  56463. configurable: true
  56464. });
  56465. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  56466. /**
  56467. * Gets the highlights Saturation value.
  56468. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  56469. */
  56470. get: function () {
  56471. return this._highlightsSaturation;
  56472. },
  56473. /**
  56474. * Sets the highlights Saturation value.
  56475. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  56476. */
  56477. set: function (value) {
  56478. this._highlightsSaturation = value;
  56479. this._dirty = true;
  56480. },
  56481. enumerable: true,
  56482. configurable: true
  56483. });
  56484. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  56485. /**
  56486. * Gets the highlights Exposure value.
  56487. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  56488. */
  56489. get: function () {
  56490. return this._highlightsExposure;
  56491. },
  56492. /**
  56493. * Sets the highlights Exposure value.
  56494. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  56495. */
  56496. set: function (value) {
  56497. this._highlightsExposure = value;
  56498. this._dirty = true;
  56499. },
  56500. enumerable: true,
  56501. configurable: true
  56502. });
  56503. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  56504. /**
  56505. * Gets the midtones Hue value.
  56506. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  56507. */
  56508. get: function () {
  56509. return this._midtonesHue;
  56510. },
  56511. /**
  56512. * Sets the midtones Hue value.
  56513. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  56514. */
  56515. set: function (value) {
  56516. this._midtonesHue = value;
  56517. this._dirty = true;
  56518. },
  56519. enumerable: true,
  56520. configurable: true
  56521. });
  56522. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  56523. /**
  56524. * Gets the midtones Density value.
  56525. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  56526. * Values less than zero provide a filter of opposite hue.
  56527. */
  56528. get: function () {
  56529. return this._midtonesDensity;
  56530. },
  56531. /**
  56532. * Sets the midtones Density value.
  56533. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  56534. * Values less than zero provide a filter of opposite hue.
  56535. */
  56536. set: function (value) {
  56537. this._midtonesDensity = value;
  56538. this._dirty = true;
  56539. },
  56540. enumerable: true,
  56541. configurable: true
  56542. });
  56543. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  56544. /**
  56545. * Gets the midtones Saturation value.
  56546. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  56547. */
  56548. get: function () {
  56549. return this._midtonesSaturation;
  56550. },
  56551. /**
  56552. * Sets the midtones Saturation value.
  56553. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  56554. */
  56555. set: function (value) {
  56556. this._midtonesSaturation = value;
  56557. this._dirty = true;
  56558. },
  56559. enumerable: true,
  56560. configurable: true
  56561. });
  56562. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  56563. /**
  56564. * Gets the midtones Exposure value.
  56565. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  56566. */
  56567. get: function () {
  56568. return this._midtonesExposure;
  56569. },
  56570. /**
  56571. * Sets the midtones Exposure value.
  56572. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  56573. */
  56574. set: function (value) {
  56575. this._midtonesExposure = value;
  56576. this._dirty = true;
  56577. },
  56578. enumerable: true,
  56579. configurable: true
  56580. });
  56581. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  56582. /**
  56583. * Gets the shadows Hue value.
  56584. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  56585. */
  56586. get: function () {
  56587. return this._shadowsHue;
  56588. },
  56589. /**
  56590. * Sets the shadows Hue value.
  56591. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  56592. */
  56593. set: function (value) {
  56594. this._shadowsHue = value;
  56595. this._dirty = true;
  56596. },
  56597. enumerable: true,
  56598. configurable: true
  56599. });
  56600. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  56601. /**
  56602. * Gets the shadows Density value.
  56603. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  56604. * Values less than zero provide a filter of opposite hue.
  56605. */
  56606. get: function () {
  56607. return this._shadowsDensity;
  56608. },
  56609. /**
  56610. * Sets the shadows Density value.
  56611. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  56612. * Values less than zero provide a filter of opposite hue.
  56613. */
  56614. set: function (value) {
  56615. this._shadowsDensity = value;
  56616. this._dirty = true;
  56617. },
  56618. enumerable: true,
  56619. configurable: true
  56620. });
  56621. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  56622. /**
  56623. * Gets the shadows Saturation value.
  56624. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  56625. */
  56626. get: function () {
  56627. return this._shadowsSaturation;
  56628. },
  56629. /**
  56630. * Sets the shadows Saturation value.
  56631. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  56632. */
  56633. set: function (value) {
  56634. this._shadowsSaturation = value;
  56635. this._dirty = true;
  56636. },
  56637. enumerable: true,
  56638. configurable: true
  56639. });
  56640. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  56641. /**
  56642. * Gets the shadows Exposure value.
  56643. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  56644. */
  56645. get: function () {
  56646. return this._shadowsExposure;
  56647. },
  56648. /**
  56649. * Sets the shadows Exposure value.
  56650. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  56651. */
  56652. set: function (value) {
  56653. this._shadowsExposure = value;
  56654. this._dirty = true;
  56655. },
  56656. enumerable: true,
  56657. configurable: true
  56658. });
  56659. /**
  56660. * Binds the color curves to the shader.
  56661. * @param colorCurves The color curve to bind
  56662. * @param effect The effect to bind to
  56663. */
  56664. ColorCurves.Bind = function (colorCurves, effect) {
  56665. if (colorCurves._dirty) {
  56666. colorCurves._dirty = false;
  56667. // Fill in global info.
  56668. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  56669. // Compute highlights info.
  56670. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  56671. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  56672. // Compute midtones info.
  56673. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  56674. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  56675. // Compute shadows info.
  56676. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  56677. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  56678. // Compute deltas (neutral is midtones).
  56679. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  56680. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  56681. }
  56682. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  56683. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  56684. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  56685. };
  56686. /**
  56687. * Prepare the list of uniforms associated with the ColorCurves effects.
  56688. * @param uniformsList The list of uniforms used in the effect
  56689. */
  56690. ColorCurves.PrepareUniforms = function (uniformsList) {
  56691. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  56692. };
  56693. /**
  56694. * Returns color grading data based on a hue, density, saturation and exposure value.
  56695. * @param filterHue The hue of the color filter.
  56696. * @param filterDensity The density of the color filter.
  56697. * @param saturation The saturation.
  56698. * @param exposure The exposure.
  56699. * @param result The result data container.
  56700. */
  56701. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  56702. if (hue == null) {
  56703. return;
  56704. }
  56705. hue = ColorCurves.clamp(hue, 0, 360);
  56706. density = ColorCurves.clamp(density, -100, 100);
  56707. saturation = ColorCurves.clamp(saturation, -100, 100);
  56708. exposure = ColorCurves.clamp(exposure, -100, 100);
  56709. // Remap the slider/config filter density with non-linear mapping and also scale by half
  56710. // so that the maximum filter density is only 50% control. This provides fine control
  56711. // for small values and reasonable range.
  56712. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  56713. density *= 0.5;
  56714. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  56715. if (density < 0) {
  56716. density *= -1;
  56717. hue = (hue + 180) % 360;
  56718. }
  56719. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  56720. result.scaleToRef(2, result);
  56721. result.a = 1 + 0.01 * saturation;
  56722. };
  56723. /**
  56724. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  56725. * @param value The input slider value in range [-100,100].
  56726. * @returns Adjusted value.
  56727. */
  56728. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  56729. value /= 100;
  56730. var x = Math.abs(value);
  56731. x = Math.pow(x, 2);
  56732. if (value < 0) {
  56733. x *= -1;
  56734. }
  56735. x *= 100;
  56736. return x;
  56737. };
  56738. /**
  56739. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  56740. * @param hue The hue (H) input.
  56741. * @param saturation The saturation (S) input.
  56742. * @param brightness The brightness (B) input.
  56743. * @result An RGBA color represented as Vector4.
  56744. */
  56745. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  56746. var h = ColorCurves.clamp(hue, 0, 360);
  56747. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  56748. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  56749. if (s === 0) {
  56750. result.r = v;
  56751. result.g = v;
  56752. result.b = v;
  56753. }
  56754. else {
  56755. // sector 0 to 5
  56756. h /= 60;
  56757. var i = Math.floor(h);
  56758. // fractional part of h
  56759. var f = h - i;
  56760. var p = v * (1 - s);
  56761. var q = v * (1 - s * f);
  56762. var t = v * (1 - s * (1 - f));
  56763. switch (i) {
  56764. case 0:
  56765. result.r = v;
  56766. result.g = t;
  56767. result.b = p;
  56768. break;
  56769. case 1:
  56770. result.r = q;
  56771. result.g = v;
  56772. result.b = p;
  56773. break;
  56774. case 2:
  56775. result.r = p;
  56776. result.g = v;
  56777. result.b = t;
  56778. break;
  56779. case 3:
  56780. result.r = p;
  56781. result.g = q;
  56782. result.b = v;
  56783. break;
  56784. case 4:
  56785. result.r = t;
  56786. result.g = p;
  56787. result.b = v;
  56788. break;
  56789. default:
  56790. result.r = v;
  56791. result.g = p;
  56792. result.b = q;
  56793. break;
  56794. }
  56795. }
  56796. result.a = 1;
  56797. };
  56798. /**
  56799. * Returns a value clamped between min and max
  56800. * @param value The value to clamp
  56801. * @param min The minimum of value
  56802. * @param max The maximum of value
  56803. * @returns The clamped value.
  56804. */
  56805. ColorCurves.clamp = function (value, min, max) {
  56806. return Math.min(Math.max(value, min), max);
  56807. };
  56808. /**
  56809. * Clones the current color curve instance.
  56810. * @return The cloned curves
  56811. */
  56812. ColorCurves.prototype.clone = function () {
  56813. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  56814. };
  56815. /**
  56816. * Serializes the current color curve instance to a json representation.
  56817. * @return a JSON representation
  56818. */
  56819. ColorCurves.prototype.serialize = function () {
  56820. return BABYLON.SerializationHelper.Serialize(this);
  56821. };
  56822. /**
  56823. * Parses the color curve from a json representation.
  56824. * @param source the JSON source to parse
  56825. * @return The parsed curves
  56826. */
  56827. ColorCurves.Parse = function (source) {
  56828. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  56829. };
  56830. __decorate([
  56831. BABYLON.serialize()
  56832. ], ColorCurves.prototype, "_globalHue", void 0);
  56833. __decorate([
  56834. BABYLON.serialize()
  56835. ], ColorCurves.prototype, "_globalDensity", void 0);
  56836. __decorate([
  56837. BABYLON.serialize()
  56838. ], ColorCurves.prototype, "_globalSaturation", void 0);
  56839. __decorate([
  56840. BABYLON.serialize()
  56841. ], ColorCurves.prototype, "_globalExposure", void 0);
  56842. __decorate([
  56843. BABYLON.serialize()
  56844. ], ColorCurves.prototype, "_highlightsHue", void 0);
  56845. __decorate([
  56846. BABYLON.serialize()
  56847. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  56848. __decorate([
  56849. BABYLON.serialize()
  56850. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  56851. __decorate([
  56852. BABYLON.serialize()
  56853. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  56854. __decorate([
  56855. BABYLON.serialize()
  56856. ], ColorCurves.prototype, "_midtonesHue", void 0);
  56857. __decorate([
  56858. BABYLON.serialize()
  56859. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  56860. __decorate([
  56861. BABYLON.serialize()
  56862. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  56863. __decorate([
  56864. BABYLON.serialize()
  56865. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  56866. return ColorCurves;
  56867. })();
  56868. BABYLON.ColorCurves = ColorCurves;
  56869. })(BABYLON || (BABYLON = {}));
  56870. var BABYLON;
  56871. (function (BABYLON) {
  56872. /**
  56873. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  56874. * It can help converting any input color in a desired output one. This can then be used to create effects
  56875. * from sepia, black and white to sixties or futuristic rendering...
  56876. *
  56877. * The only supported format is currently 3dl.
  56878. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  56879. */
  56880. var ColorGradingTexture = (function (_super) {
  56881. __extends(ColorGradingTexture, _super);
  56882. /**
  56883. * Instantiates a ColorGradingTexture from the following parameters.
  56884. *
  56885. * @param url The location of the color gradind data (currently only supporting 3dl)
  56886. * @param scene The scene the texture will be used in
  56887. */
  56888. function ColorGradingTexture(url, scene) {
  56889. _super.call(this, scene);
  56890. if (!url) {
  56891. return;
  56892. }
  56893. this._textureMatrix = BABYLON.Matrix.Identity();
  56894. this.name = url;
  56895. this.url = url;
  56896. this.hasAlpha = false;
  56897. this.isCube = false;
  56898. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56899. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56900. this.anisotropicFilteringLevel = 1;
  56901. this._texture = this._getFromCache(url, true);
  56902. if (!this._texture) {
  56903. if (!scene.useDelayedTextureLoading) {
  56904. this.loadTexture();
  56905. }
  56906. else {
  56907. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56908. }
  56909. }
  56910. }
  56911. /**
  56912. * Returns the texture matrix used in most of the material.
  56913. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  56914. */
  56915. ColorGradingTexture.prototype.getTextureMatrix = function () {
  56916. return this._textureMatrix;
  56917. };
  56918. /**
  56919. * Occurs when the file being loaded is a .3dl LUT file.
  56920. */
  56921. ColorGradingTexture.prototype.load3dlTexture = function () {
  56922. var _this = this;
  56923. var mipLevels = 0;
  56924. var floatArrayView = null;
  56925. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56926. this._texture = texture;
  56927. var callback = function (text) {
  56928. var data;
  56929. var tempData;
  56930. var line;
  56931. var lines = text.split('\n');
  56932. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  56933. var maxColor = 0;
  56934. for (var i = 0; i < lines.length; i++) {
  56935. line = lines[i];
  56936. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  56937. continue;
  56938. if (line.indexOf('#') === 0)
  56939. continue;
  56940. var words = line.split(" ");
  56941. if (size === 0) {
  56942. // Number of space + one
  56943. size = words.length;
  56944. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  56945. tempData = new Float32Array(size * size * size * 4);
  56946. continue;
  56947. }
  56948. if (size != 0) {
  56949. var r = Math.max(parseInt(words[0]), 0);
  56950. var g = Math.max(parseInt(words[1]), 0);
  56951. var b = Math.max(parseInt(words[2]), 0);
  56952. maxColor = Math.max(r, maxColor);
  56953. maxColor = Math.max(g, maxColor);
  56954. maxColor = Math.max(b, maxColor);
  56955. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  56956. tempData[pixelStorageIndex + 0] = r;
  56957. tempData[pixelStorageIndex + 1] = g;
  56958. tempData[pixelStorageIndex + 2] = b;
  56959. tempData[pixelStorageIndex + 3] = 0;
  56960. pixelIndexSlice++;
  56961. if (pixelIndexSlice % size == 0) {
  56962. pixelIndexH++;
  56963. pixelIndexSlice = 0;
  56964. if (pixelIndexH % size == 0) {
  56965. pixelIndexW++;
  56966. pixelIndexH = 0;
  56967. }
  56968. }
  56969. }
  56970. }
  56971. for (var i = 0; i < tempData.length; i++) {
  56972. var value = tempData[i];
  56973. data[i] = (value / maxColor * 255);
  56974. }
  56975. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  56976. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  56977. };
  56978. BABYLON.Tools.LoadFile(this.url, callback);
  56979. return this._texture;
  56980. };
  56981. /**
  56982. * Starts the loading process of the texture.
  56983. */
  56984. ColorGradingTexture.prototype.loadTexture = function () {
  56985. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  56986. this.load3dlTexture();
  56987. }
  56988. };
  56989. /**
  56990. * Clones the color gradind texture.
  56991. */
  56992. ColorGradingTexture.prototype.clone = function () {
  56993. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  56994. // Base texture
  56995. newTexture.level = this.level;
  56996. return newTexture;
  56997. };
  56998. /**
  56999. * Called during delayed load for textures.
  57000. */
  57001. ColorGradingTexture.prototype.delayLoad = function () {
  57002. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57003. return;
  57004. }
  57005. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57006. this._texture = this._getFromCache(this.url, true);
  57007. if (!this._texture) {
  57008. this.loadTexture();
  57009. }
  57010. };
  57011. /**
  57012. * Parses a color grading texture serialized by Babylon.
  57013. * @param parsedTexture The texture information being parsedTexture
  57014. * @param scene The scene to load the texture in
  57015. * @param rootUrl The root url of the data assets to load
  57016. * @return A color gradind texture
  57017. */
  57018. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57019. var texture = null;
  57020. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57021. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  57022. texture.name = parsedTexture.name;
  57023. texture.level = parsedTexture.level;
  57024. }
  57025. return texture;
  57026. };
  57027. /**
  57028. * Serializes the LUT texture to json format.
  57029. */
  57030. ColorGradingTexture.prototype.serialize = function () {
  57031. if (!this.name) {
  57032. return null;
  57033. }
  57034. var serializationObject = {};
  57035. serializationObject.name = this.name;
  57036. serializationObject.level = this.level;
  57037. return serializationObject;
  57038. };
  57039. /**
  57040. * Empty line regex stored for GC.
  57041. */
  57042. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  57043. return ColorGradingTexture;
  57044. })(BABYLON.BaseTexture);
  57045. BABYLON.ColorGradingTexture = ColorGradingTexture;
  57046. })(BABYLON || (BABYLON = {}));
  57047. var BABYLON;
  57048. (function (BABYLON) {
  57049. var PBRMaterialDefines = (function (_super) {
  57050. __extends(PBRMaterialDefines, _super);
  57051. function PBRMaterialDefines() {
  57052. _super.call(this);
  57053. this.ALBEDO = false;
  57054. this.AMBIENT = false;
  57055. this.OPACITY = false;
  57056. this.OPACITYRGB = false;
  57057. this.REFLECTION = false;
  57058. this.EMISSIVE = false;
  57059. this.REFLECTIVITY = false;
  57060. this.BUMP = false;
  57061. this.PARALLAX = false;
  57062. this.PARALLAXOCCLUSION = false;
  57063. this.SPECULAROVERALPHA = false;
  57064. this.CLIPPLANE = false;
  57065. this.ALPHATEST = false;
  57066. this.ALPHAFROMALBEDO = false;
  57067. this.POINTSIZE = false;
  57068. this.FOG = false;
  57069. this.SPECULARTERM = false;
  57070. this.OPACITYFRESNEL = false;
  57071. this.EMISSIVEFRESNEL = false;
  57072. this.FRESNEL = false;
  57073. this.NORMAL = false;
  57074. this.UV1 = false;
  57075. this.UV2 = false;
  57076. this.VERTEXCOLOR = false;
  57077. this.VERTEXALPHA = false;
  57078. this.NUM_BONE_INFLUENCERS = 0;
  57079. this.BonesPerMesh = 0;
  57080. this.INSTANCES = false;
  57081. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  57082. this.MICROSURFACEAUTOMATIC = false;
  57083. this.EMISSIVEASILLUMINATION = false;
  57084. this.LINKEMISSIVEWITHALBEDO = false;
  57085. this.LIGHTMAP = false;
  57086. this.USELIGHTMAPASSHADOWMAP = false;
  57087. this.REFLECTIONMAP_3D = false;
  57088. this.REFLECTIONMAP_SPHERICAL = false;
  57089. this.REFLECTIONMAP_PLANAR = false;
  57090. this.REFLECTIONMAP_CUBIC = false;
  57091. this.REFLECTIONMAP_PROJECTION = false;
  57092. this.REFLECTIONMAP_SKYBOX = false;
  57093. this.REFLECTIONMAP_EXPLICIT = false;
  57094. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  57095. this.INVERTCUBICMAP = false;
  57096. this.LOGARITHMICDEPTH = false;
  57097. this.CAMERATONEMAP = false;
  57098. this.CAMERACONTRAST = false;
  57099. this.CAMERACOLORGRADING = false;
  57100. this.CAMERACOLORCURVES = false;
  57101. this.OVERLOADEDVALUES = false;
  57102. this.OVERLOADEDSHADOWVALUES = false;
  57103. this.USESPHERICALFROMREFLECTIONMAP = false;
  57104. this.REFRACTION = false;
  57105. this.REFRACTIONMAP_3D = false;
  57106. this.LINKREFRACTIONTOTRANSPARENCY = false;
  57107. this.REFRACTIONMAPINLINEARSPACE = false;
  57108. this.LODBASEDMICROSFURACE = false;
  57109. this.USEPHYSICALLIGHTFALLOFF = false;
  57110. this.RADIANCEOVERALPHA = false;
  57111. this.USEPMREMREFLECTION = false;
  57112. this.USEPMREMREFRACTION = false;
  57113. this.OPENGLNORMALMAP = false;
  57114. this.INVERTNORMALMAPX = false;
  57115. this.INVERTNORMALMAPY = false;
  57116. this.rebuild();
  57117. }
  57118. return PBRMaterialDefines;
  57119. })(BABYLON.MaterialDefines);
  57120. /**
  57121. * The Physically based material of BJS.
  57122. *
  57123. * This offers the main features of a standard PBR material.
  57124. * For more information, please refer to the documentation :
  57125. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  57126. */
  57127. var PBRMaterial = (function (_super) {
  57128. __extends(PBRMaterial, _super);
  57129. /**
  57130. * Instantiates a new PBRMaterial instance.
  57131. *
  57132. * @param name The material name
  57133. * @param scene The scene the material will be use in.
  57134. */
  57135. function PBRMaterial(name, scene) {
  57136. var _this = this;
  57137. _super.call(this, name, scene);
  57138. /**
  57139. * Intensity of the direct lights e.g. the four lights available in your scene.
  57140. * This impacts both the direct diffuse and specular highlights.
  57141. */
  57142. this.directIntensity = 1.0;
  57143. /**
  57144. * Intensity of the emissive part of the material.
  57145. * This helps controlling the emissive effect without modifying the emissive color.
  57146. */
  57147. this.emissiveIntensity = 1.0;
  57148. /**
  57149. * Intensity of the environment e.g. how much the environment will light the object
  57150. * either through harmonics for rough material or through the refelction for shiny ones.
  57151. */
  57152. this.environmentIntensity = 1.0;
  57153. /**
  57154. * This is a special control allowing the reduction of the specular highlights coming from the
  57155. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  57156. */
  57157. this.specularIntensity = 1.0;
  57158. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  57159. /**
  57160. * Debug Control allowing disabling the bump map on this material.
  57161. */
  57162. this.disableBumpMap = false;
  57163. /**
  57164. * Debug Control helping enforcing or dropping the darkness of shadows.
  57165. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  57166. */
  57167. this.overloadedShadowIntensity = 1.0;
  57168. /**
  57169. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  57170. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  57171. */
  57172. this.overloadedShadeIntensity = 1.0;
  57173. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  57174. /**
  57175. * The camera exposure used on this material.
  57176. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  57177. * This corresponds to a photographic exposure.
  57178. */
  57179. this.cameraExposure = 1.0;
  57180. /**
  57181. * The camera contrast used on this material.
  57182. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  57183. */
  57184. this.cameraContrast = 1.0;
  57185. /**
  57186. * Color Grading 2D Lookup Texture.
  57187. * This allows special effects like sepia, black and white to sixties rendering style.
  57188. */
  57189. this.cameraColorGradingTexture = null;
  57190. this._cameraColorGradingScaleOffset = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  57191. this._cameraColorGradingInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  57192. /**
  57193. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  57194. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  57195. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  57196. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  57197. */
  57198. this.cameraColorCurves = null;
  57199. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  57200. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  57201. /**
  57202. * Debug Control allowing to overload the ambient color.
  57203. * This as to be use with the overloadedAmbientIntensity parameter.
  57204. */
  57205. this.overloadedAmbient = BABYLON.Color3.White();
  57206. /**
  57207. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  57208. */
  57209. this.overloadedAmbientIntensity = 0.0;
  57210. /**
  57211. * Debug Control allowing to overload the albedo color.
  57212. * This as to be use with the overloadedAlbedoIntensity parameter.
  57213. */
  57214. this.overloadedAlbedo = BABYLON.Color3.White();
  57215. /**
  57216. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  57217. */
  57218. this.overloadedAlbedoIntensity = 0.0;
  57219. /**
  57220. * Debug Control allowing to overload the reflectivity color.
  57221. * This as to be use with the overloadedReflectivityIntensity parameter.
  57222. */
  57223. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  57224. /**
  57225. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  57226. */
  57227. this.overloadedReflectivityIntensity = 0.0;
  57228. /**
  57229. * Debug Control allowing to overload the emissive color.
  57230. * This as to be use with the overloadedEmissiveIntensity parameter.
  57231. */
  57232. this.overloadedEmissive = BABYLON.Color3.White();
  57233. /**
  57234. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  57235. */
  57236. this.overloadedEmissiveIntensity = 0.0;
  57237. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  57238. /**
  57239. * Debug Control allowing to overload the reflection color.
  57240. * This as to be use with the overloadedReflectionIntensity parameter.
  57241. */
  57242. this.overloadedReflection = BABYLON.Color3.White();
  57243. /**
  57244. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  57245. */
  57246. this.overloadedReflectionIntensity = 0.0;
  57247. /**
  57248. * Debug Control allowing to overload the microsurface.
  57249. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  57250. */
  57251. this.overloadedMicroSurface = 0.0;
  57252. /**
  57253. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  57254. */
  57255. this.overloadedMicroSurfaceIntensity = 0.0;
  57256. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  57257. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  57258. /**
  57259. * AKA Diffuse Color in other nomenclature.
  57260. */
  57261. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  57262. /**
  57263. * AKA Specular Color in other nomenclature.
  57264. */
  57265. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  57266. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  57267. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  57268. /**
  57269. * AKA Glossiness in other nomenclature.
  57270. */
  57271. this.microSurface = 0.9;
  57272. /**
  57273. * source material index of refraction (IOR)' / 'destination material IOR.
  57274. */
  57275. this.indexOfRefraction = 0.66;
  57276. /**
  57277. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  57278. */
  57279. this.invertRefractionY = false;
  57280. /**
  57281. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  57282. * Materials half opaque for instance using refraction could benefit from this control.
  57283. */
  57284. this.linkRefractionWithTransparency = false;
  57285. /**
  57286. * The emissive and albedo are linked to never be more than one (Energy conservation).
  57287. */
  57288. this.linkEmissiveWithAlbedo = false;
  57289. this.useLightmapAsShadowmap = false;
  57290. /**
  57291. * In this mode, the emissive informtaion will always be added to the lighting once.
  57292. * A light for instance can be thought as emissive.
  57293. */
  57294. this.useEmissiveAsIllumination = false;
  57295. /**
  57296. * Secifies that the alpha is coming form the albedo channel alpha channel.
  57297. */
  57298. this.useAlphaFromAlbedoTexture = false;
  57299. /**
  57300. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  57301. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  57302. */
  57303. this.useSpecularOverAlpha = true;
  57304. /**
  57305. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  57306. */
  57307. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  57308. /**
  57309. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  57310. * The material will try to infer what glossiness each pixel should be.
  57311. */
  57312. this.useAutoMicroSurfaceFromReflectivityMap = false;
  57313. /**
  57314. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  57315. * the creation of the material.
  57316. */
  57317. this.useScalarInLinearSpace = false;
  57318. /**
  57319. * BJS is using an harcoded light falloff based on a manually sets up range.
  57320. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  57321. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  57322. */
  57323. this.usePhysicalLightFalloff = true;
  57324. /**
  57325. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  57326. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  57327. */
  57328. this.useRadianceOverAlpha = true;
  57329. /**
  57330. * Allows using the bump map in parallax mode.
  57331. */
  57332. this.useParallax = false;
  57333. /**
  57334. * Allows using the bump map in parallax occlusion mode.
  57335. */
  57336. this.useParallaxOcclusion = false;
  57337. /**
  57338. * Controls the scale bias of the parallax mode.
  57339. */
  57340. this.parallaxScaleBias = 0.05;
  57341. /**
  57342. * If sets to true, disables all the lights affecting the material.
  57343. */
  57344. this.disableLighting = false;
  57345. /**
  57346. * Number of Simultaneous lights allowed on the material.
  57347. */
  57348. this.maxSimultaneousLights = 4;
  57349. /**
  57350. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  57351. */
  57352. this.invertNormalMapX = false;
  57353. /**
  57354. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  57355. */
  57356. this.invertNormalMapY = false;
  57357. this._renderTargets = new BABYLON.SmartArray(16);
  57358. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  57359. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  57360. this._tempColor = new BABYLON.Color3();
  57361. this._defines = new PBRMaterialDefines();
  57362. this._cachedDefines = new PBRMaterialDefines();
  57363. this._myScene = null;
  57364. this._myShadowGenerator = null;
  57365. this._cachedDefines.BonesPerMesh = -1;
  57366. this.getRenderTargetTextures = function () {
  57367. _this._renderTargets.reset();
  57368. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  57369. _this._renderTargets.push(_this.reflectionTexture);
  57370. }
  57371. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  57372. _this._renderTargets.push(_this.refractionTexture);
  57373. }
  57374. return _this._renderTargets;
  57375. };
  57376. }
  57377. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  57378. get: function () {
  57379. return this._useLogarithmicDepth;
  57380. },
  57381. set: function (value) {
  57382. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  57383. },
  57384. enumerable: true,
  57385. configurable: true
  57386. });
  57387. PBRMaterial.prototype.needAlphaBlending = function () {
  57388. if (this.linkRefractionWithTransparency) {
  57389. return false;
  57390. }
  57391. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  57392. };
  57393. PBRMaterial.prototype.needAlphaTesting = function () {
  57394. if (this.linkRefractionWithTransparency) {
  57395. return false;
  57396. }
  57397. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  57398. };
  57399. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  57400. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  57401. };
  57402. PBRMaterial.prototype.getAlphaTestTexture = function () {
  57403. return this.albedoTexture;
  57404. };
  57405. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  57406. if (!mesh) {
  57407. return true;
  57408. }
  57409. if (this._defines.INSTANCES !== useInstances) {
  57410. return false;
  57411. }
  57412. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  57413. return true;
  57414. }
  57415. return false;
  57416. };
  57417. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  57418. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  57419. };
  57420. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  57421. if (!useScalarInLinear) {
  57422. color.toLinearSpaceToRef(ref);
  57423. }
  57424. else {
  57425. ref.r = color.r;
  57426. ref.g = color.g;
  57427. ref.b = color.b;
  57428. }
  57429. };
  57430. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  57431. var lightIndex = 0;
  57432. var depthValuesAlreadySet = false;
  57433. for (var index = 0; index < scene.lights.length; index++) {
  57434. var light = scene.lights[index];
  57435. if (!light.isEnabled()) {
  57436. continue;
  57437. }
  57438. if (!light.canAffectMesh(mesh)) {
  57439. continue;
  57440. }
  57441. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  57442. // GAMMA CORRECTION.
  57443. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  57444. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  57445. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  57446. if (defines["SPECULARTERM"]) {
  57447. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  57448. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  57449. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  57450. }
  57451. // Shadows
  57452. if (scene.shadowsEnabled) {
  57453. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  57454. }
  57455. lightIndex++;
  57456. if (lightIndex === maxSimultaneousLights)
  57457. break;
  57458. }
  57459. };
  57460. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  57461. if (this.checkReadyOnlyOnce) {
  57462. if (this._wasPreviouslyReady) {
  57463. return true;
  57464. }
  57465. }
  57466. var scene = this.getScene();
  57467. if (!this.checkReadyOnEveryCall) {
  57468. if (this._renderId === scene.getRenderId()) {
  57469. if (this._checkCache(scene, mesh, useInstances)) {
  57470. return true;
  57471. }
  57472. }
  57473. }
  57474. var engine = scene.getEngine();
  57475. var needNormals = false;
  57476. var needUVs = false;
  57477. this._defines.reset();
  57478. if (scene.texturesEnabled) {
  57479. // Textures
  57480. if (scene.texturesEnabled) {
  57481. if (scene.getEngine().getCaps().textureLOD) {
  57482. this._defines.LODBASEDMICROSFURACE = true;
  57483. }
  57484. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  57485. if (!this.albedoTexture.isReady()) {
  57486. return false;
  57487. }
  57488. else {
  57489. needUVs = true;
  57490. this._defines.ALBEDO = true;
  57491. }
  57492. }
  57493. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  57494. if (!this.ambientTexture.isReady()) {
  57495. return false;
  57496. }
  57497. else {
  57498. needUVs = true;
  57499. this._defines.AMBIENT = true;
  57500. }
  57501. }
  57502. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  57503. if (!this.opacityTexture.isReady()) {
  57504. return false;
  57505. }
  57506. else {
  57507. needUVs = true;
  57508. this._defines.OPACITY = true;
  57509. if (this.opacityTexture.getAlphaFromRGB) {
  57510. this._defines.OPACITYRGB = true;
  57511. }
  57512. }
  57513. }
  57514. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  57515. if (!this.reflectionTexture.isReady()) {
  57516. return false;
  57517. }
  57518. else {
  57519. needNormals = true;
  57520. this._defines.REFLECTION = true;
  57521. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  57522. this._defines.INVERTCUBICMAP = true;
  57523. }
  57524. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  57525. switch (this.reflectionTexture.coordinatesMode) {
  57526. case BABYLON.Texture.CUBIC_MODE:
  57527. case BABYLON.Texture.INVCUBIC_MODE:
  57528. this._defines.REFLECTIONMAP_CUBIC = true;
  57529. break;
  57530. case BABYLON.Texture.EXPLICIT_MODE:
  57531. this._defines.REFLECTIONMAP_EXPLICIT = true;
  57532. break;
  57533. case BABYLON.Texture.PLANAR_MODE:
  57534. this._defines.REFLECTIONMAP_PLANAR = true;
  57535. break;
  57536. case BABYLON.Texture.PROJECTION_MODE:
  57537. this._defines.REFLECTIONMAP_PROJECTION = true;
  57538. break;
  57539. case BABYLON.Texture.SKYBOX_MODE:
  57540. this._defines.REFLECTIONMAP_SKYBOX = true;
  57541. break;
  57542. case BABYLON.Texture.SPHERICAL_MODE:
  57543. this._defines.REFLECTIONMAP_SPHERICAL = true;
  57544. break;
  57545. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  57546. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  57547. break;
  57548. }
  57549. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  57550. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  57551. needNormals = true;
  57552. if (this.reflectionTexture.isPMREM) {
  57553. this._defines.USEPMREMREFLECTION = true;
  57554. }
  57555. }
  57556. }
  57557. }
  57558. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  57559. if (!this.lightmapTexture.isReady()) {
  57560. return false;
  57561. }
  57562. else {
  57563. needUVs = true;
  57564. this._defines.LIGHTMAP = true;
  57565. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  57566. }
  57567. }
  57568. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  57569. if (!this.emissiveTexture.isReady()) {
  57570. return false;
  57571. }
  57572. else {
  57573. needUVs = true;
  57574. this._defines.EMISSIVE = true;
  57575. }
  57576. }
  57577. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  57578. if (!this.reflectivityTexture.isReady()) {
  57579. return false;
  57580. }
  57581. else {
  57582. needUVs = true;
  57583. this._defines.REFLECTIVITY = true;
  57584. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  57585. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  57586. }
  57587. }
  57588. }
  57589. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  57590. if (!this.bumpTexture.isReady()) {
  57591. return false;
  57592. }
  57593. else {
  57594. needUVs = true;
  57595. this._defines.BUMP = true;
  57596. if (this.useParallax) {
  57597. this._defines.PARALLAX = true;
  57598. if (this.useParallaxOcclusion) {
  57599. this._defines.PARALLAXOCCLUSION = true;
  57600. }
  57601. }
  57602. if (this.invertNormalMapX) {
  57603. this._defines.INVERTNORMALMAPX = true;
  57604. }
  57605. if (this.invertNormalMapY) {
  57606. this._defines.INVERTNORMALMAPY = true;
  57607. }
  57608. }
  57609. }
  57610. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  57611. if (!this.refractionTexture.isReady()) {
  57612. return false;
  57613. }
  57614. else {
  57615. needUVs = true;
  57616. this._defines.REFRACTION = true;
  57617. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  57618. if (this.linkRefractionWithTransparency) {
  57619. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  57620. }
  57621. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  57622. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  57623. if (this.refractionTexture.isPMREM) {
  57624. this._defines.USEPMREMREFRACTION = true;
  57625. }
  57626. }
  57627. }
  57628. }
  57629. if (this.cameraColorGradingTexture) {
  57630. if (!this.cameraColorGradingTexture.isReady()) {
  57631. return false;
  57632. }
  57633. else {
  57634. this._defines.CAMERACOLORGRADING = true;
  57635. }
  57636. }
  57637. }
  57638. // Effect
  57639. if (scene.clipPlane) {
  57640. this._defines.CLIPPLANE = true;
  57641. }
  57642. if (engine.getAlphaTesting()) {
  57643. this._defines.ALPHATEST = true;
  57644. }
  57645. if (this._shouldUseAlphaFromAlbedoTexture()) {
  57646. this._defines.ALPHAFROMALBEDO = true;
  57647. }
  57648. if (this.useEmissiveAsIllumination) {
  57649. this._defines.EMISSIVEASILLUMINATION = true;
  57650. }
  57651. if (this.linkEmissiveWithAlbedo) {
  57652. this._defines.LINKEMISSIVEWITHALBEDO = true;
  57653. }
  57654. if (this.useLogarithmicDepth) {
  57655. this._defines.LOGARITHMICDEPTH = true;
  57656. }
  57657. if (this.cameraContrast != 1) {
  57658. this._defines.CAMERACONTRAST = true;
  57659. }
  57660. if (this.cameraExposure != 1) {
  57661. this._defines.CAMERATONEMAP = true;
  57662. }
  57663. if (this.cameraColorCurves) {
  57664. this._defines.CAMERACOLORCURVES = true;
  57665. }
  57666. if (this.overloadedShadeIntensity != 1 ||
  57667. this.overloadedShadowIntensity != 1) {
  57668. this._defines.OVERLOADEDSHADOWVALUES = true;
  57669. }
  57670. if (this.overloadedMicroSurfaceIntensity > 0 ||
  57671. this.overloadedEmissiveIntensity > 0 ||
  57672. this.overloadedReflectivityIntensity > 0 ||
  57673. this.overloadedAlbedoIntensity > 0 ||
  57674. this.overloadedAmbientIntensity > 0 ||
  57675. this.overloadedReflectionIntensity > 0) {
  57676. this._defines.OVERLOADEDVALUES = true;
  57677. }
  57678. // Point size
  57679. if (this.pointsCloud || scene.forcePointsCloud) {
  57680. this._defines.POINTSIZE = true;
  57681. }
  57682. // Fog
  57683. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  57684. this._defines.FOG = true;
  57685. }
  57686. if (scene.lightsEnabled && !this.disableLighting) {
  57687. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  57688. }
  57689. if (BABYLON.StandardMaterial.FresnelEnabled) {
  57690. // Fresnel
  57691. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  57692. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  57693. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  57694. this._defines.OPACITYFRESNEL = true;
  57695. }
  57696. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  57697. this._defines.EMISSIVEFRESNEL = true;
  57698. }
  57699. needNormals = true;
  57700. this._defines.FRESNEL = true;
  57701. }
  57702. }
  57703. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  57704. this._defines.SPECULAROVERALPHA = true;
  57705. }
  57706. if (this.usePhysicalLightFalloff) {
  57707. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  57708. }
  57709. if (this.useRadianceOverAlpha) {
  57710. this._defines.RADIANCEOVERALPHA = true;
  57711. }
  57712. // Attribs
  57713. if (mesh) {
  57714. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  57715. this._defines.NORMAL = true;
  57716. }
  57717. if (needUVs) {
  57718. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57719. this._defines.UV1 = true;
  57720. }
  57721. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57722. this._defines.UV2 = true;
  57723. }
  57724. }
  57725. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  57726. this._defines.VERTEXCOLOR = true;
  57727. if (mesh.hasVertexAlpha) {
  57728. this._defines.VERTEXALPHA = true;
  57729. }
  57730. }
  57731. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57732. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  57733. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  57734. }
  57735. // Instances
  57736. if (useInstances) {
  57737. this._defines.INSTANCES = true;
  57738. }
  57739. }
  57740. // Get correct effect
  57741. if (!this._defines.isEqual(this._cachedDefines)) {
  57742. this._defines.cloneTo(this._cachedDefines);
  57743. scene.resetCachedMaterial();
  57744. // Fallbacks
  57745. var fallbacks = new BABYLON.EffectFallbacks();
  57746. if (this._defines.REFLECTION) {
  57747. fallbacks.addFallback(0, "REFLECTION");
  57748. }
  57749. if (this._defines.REFRACTION) {
  57750. fallbacks.addFallback(0, "REFRACTION");
  57751. }
  57752. if (this._defines.REFLECTIVITY) {
  57753. fallbacks.addFallback(0, "REFLECTIVITY");
  57754. }
  57755. if (this._defines.BUMP) {
  57756. fallbacks.addFallback(0, "BUMP");
  57757. }
  57758. if (this._defines.PARALLAX) {
  57759. fallbacks.addFallback(1, "PARALLAX");
  57760. }
  57761. if (this._defines.PARALLAXOCCLUSION) {
  57762. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  57763. }
  57764. if (this._defines.SPECULAROVERALPHA) {
  57765. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  57766. }
  57767. if (this._defines.FOG) {
  57768. fallbacks.addFallback(1, "FOG");
  57769. }
  57770. if (this._defines.POINTSIZE) {
  57771. fallbacks.addFallback(0, "POINTSIZE");
  57772. }
  57773. if (this._defines.LOGARITHMICDEPTH) {
  57774. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  57775. }
  57776. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  57777. if (this._defines.SPECULARTERM) {
  57778. fallbacks.addFallback(0, "SPECULARTERM");
  57779. }
  57780. if (this._defines.OPACITYFRESNEL) {
  57781. fallbacks.addFallback(1, "OPACITYFRESNEL");
  57782. }
  57783. if (this._defines.EMISSIVEFRESNEL) {
  57784. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  57785. }
  57786. if (this._defines.FRESNEL) {
  57787. fallbacks.addFallback(3, "FRESNEL");
  57788. }
  57789. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  57790. fallbacks.addCPUSkinningFallback(0, mesh);
  57791. }
  57792. //Attributes
  57793. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57794. if (this._defines.NORMAL) {
  57795. attribs.push(BABYLON.VertexBuffer.NormalKind);
  57796. }
  57797. if (this._defines.UV1) {
  57798. attribs.push(BABYLON.VertexBuffer.UVKind);
  57799. }
  57800. if (this._defines.UV2) {
  57801. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57802. }
  57803. if (this._defines.VERTEXCOLOR) {
  57804. attribs.push(BABYLON.VertexBuffer.ColorKind);
  57805. }
  57806. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  57807. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  57808. // Legacy browser patch
  57809. var shaderName = "pbr";
  57810. if (!scene.getEngine().getCaps().standardDerivatives) {
  57811. shaderName = "legacypbr";
  57812. }
  57813. var join = this._defines.toString();
  57814. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  57815. "vFogInfos", "vFogColor", "pointSize",
  57816. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  57817. "mBones",
  57818. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  57819. "depthValues",
  57820. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  57821. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  57822. "logarithmicDepthConstant",
  57823. "vSphericalX", "vSphericalY", "vSphericalZ",
  57824. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  57825. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  57826. "vMicrosurfaceTextureLods",
  57827. "vCameraInfos", "vCameraColorGradingInfos", "vCameraColorGradingScaleOffset"
  57828. ];
  57829. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  57830. "cameraColorGrading2DSampler"];
  57831. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  57832. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  57833. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  57834. }
  57835. if (!this._effect.isReady()) {
  57836. return false;
  57837. }
  57838. this._renderId = scene.getRenderId();
  57839. this._wasPreviouslyReady = true;
  57840. if (mesh) {
  57841. if (!mesh._materialDefines) {
  57842. mesh._materialDefines = new PBRMaterialDefines();
  57843. }
  57844. this._defines.cloneTo(mesh._materialDefines);
  57845. }
  57846. return true;
  57847. };
  57848. PBRMaterial.prototype.unbind = function () {
  57849. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  57850. this._effect.setTexture("reflection2DSampler", null);
  57851. }
  57852. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  57853. this._effect.setTexture("refraction2DSampler", null);
  57854. }
  57855. _super.prototype.unbind.call(this);
  57856. };
  57857. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  57858. this._effect.setMatrix("world", world);
  57859. };
  57860. PBRMaterial.prototype.bind = function (world, mesh) {
  57861. this._myScene = this.getScene();
  57862. // Matrices
  57863. this.bindOnlyWorldMatrix(world);
  57864. // Bones
  57865. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  57866. if (this._myScene.getCachedMaterial() !== this) {
  57867. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  57868. if (BABYLON.StandardMaterial.FresnelEnabled) {
  57869. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  57870. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  57871. }
  57872. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  57873. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  57874. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  57875. }
  57876. }
  57877. // Textures
  57878. if (this._myScene.texturesEnabled) {
  57879. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  57880. this._effect.setTexture("albedoSampler", this.albedoTexture);
  57881. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  57882. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  57883. }
  57884. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  57885. this._effect.setTexture("ambientSampler", this.ambientTexture);
  57886. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  57887. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  57888. }
  57889. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  57890. this._effect.setTexture("opacitySampler", this.opacityTexture);
  57891. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  57892. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  57893. }
  57894. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  57895. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  57896. if (this.reflectionTexture.isCube) {
  57897. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  57898. }
  57899. else {
  57900. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  57901. }
  57902. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  57903. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  57904. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  57905. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  57906. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  57907. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  57908. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  57909. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  57910. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  57911. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  57912. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  57913. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  57914. }
  57915. }
  57916. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  57917. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  57918. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  57919. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  57920. }
  57921. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  57922. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  57923. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  57924. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  57925. }
  57926. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  57927. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  57928. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  57929. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  57930. }
  57931. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  57932. this._effect.setTexture("bumpSampler", this.bumpTexture);
  57933. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  57934. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  57935. }
  57936. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  57937. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  57938. var depth = 1.0;
  57939. if (this.refractionTexture.isCube) {
  57940. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  57941. }
  57942. else {
  57943. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  57944. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  57945. if (this.refractionTexture.depth) {
  57946. depth = this.refractionTexture.depth;
  57947. }
  57948. }
  57949. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  57950. }
  57951. if ((this.reflectionTexture || this.refractionTexture)) {
  57952. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  57953. }
  57954. if (this.cameraColorGradingTexture) {
  57955. this._effect.setTexture("cameraColorGrading2DSampler", this.cameraColorGradingTexture);
  57956. this._cameraColorGradingInfos.x = this.cameraColorGradingTexture.level; // Texture Level
  57957. this._cameraColorGradingInfos.y = this.cameraColorGradingTexture.getSize().height; // Texture Size example with 8
  57958. this._cameraColorGradingInfos.z = this._cameraColorGradingInfos.y - 1.0; // SizeMinusOne 8 - 1
  57959. this._cameraColorGradingInfos.w = 1 / this._cameraColorGradingInfos.y; // Space of 1 slice 1 / 8
  57960. this._effect.setFloat4("vCameraColorGradingInfos", this._cameraColorGradingInfos.x, this._cameraColorGradingInfos.y, this._cameraColorGradingInfos.z, this._cameraColorGradingInfos.w);
  57961. var slicePixelSizeU = this._cameraColorGradingInfos.w / this._cameraColorGradingInfos.y; // Space of 1 pixel in U direction, e.g. 1/64
  57962. var slicePixelSizeV = 1.0 / this._cameraColorGradingInfos.y; // Space of 1 pixel in V direction, e.g. 1/8
  57963. this._cameraColorGradingScaleOffset.x = this._cameraColorGradingInfos.z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
  57964. this._cameraColorGradingScaleOffset.y = this._cameraColorGradingInfos.z /
  57965. this._cameraColorGradingInfos.y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
  57966. this._cameraColorGradingScaleOffset.z = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  57967. this._cameraColorGradingScaleOffset.w = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  57968. this._effect.setFloat4("vCameraColorGradingScaleOffset", this._cameraColorGradingScaleOffset.x, this._cameraColorGradingScaleOffset.y, this._cameraColorGradingScaleOffset.z, this._cameraColorGradingScaleOffset.w);
  57969. }
  57970. }
  57971. // Clip plane
  57972. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  57973. // Point size
  57974. if (this.pointsCloud) {
  57975. this._effect.setFloat("pointSize", this.pointSize);
  57976. }
  57977. // Colors
  57978. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  57979. // GAMMA CORRECTION.
  57980. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  57981. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  57982. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  57983. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  57984. // GAMMA CORRECTION.
  57985. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  57986. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  57987. // GAMMA CORRECTION.
  57988. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  57989. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  57990. }
  57991. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  57992. // GAMMA CORRECTION.
  57993. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  57994. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  57995. // Lights
  57996. if (this._myScene.lightsEnabled && !this.disableLighting) {
  57997. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  57998. }
  57999. // View
  58000. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  58001. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  58002. }
  58003. // Fog
  58004. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  58005. this._lightingInfos.x = this.directIntensity;
  58006. this._lightingInfos.y = this.emissiveIntensity;
  58007. this._lightingInfos.z = this.environmentIntensity;
  58008. this._lightingInfos.w = this.specularIntensity;
  58009. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  58010. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  58011. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  58012. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  58013. this._cameraInfos.x = this.cameraExposure;
  58014. this._cameraInfos.y = this.cameraContrast;
  58015. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  58016. if (this.cameraColorCurves) {
  58017. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  58018. }
  58019. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  58020. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  58021. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  58022. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  58023. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  58024. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  58025. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  58026. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  58027. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  58028. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  58029. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  58030. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  58031. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  58032. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  58033. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  58034. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  58035. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  58036. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  58037. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  58038. // Log. depth
  58039. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  58040. }
  58041. _super.prototype.bind.call(this, world, mesh);
  58042. this._myScene = null;
  58043. };
  58044. PBRMaterial.prototype.getAnimatables = function () {
  58045. var results = [];
  58046. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  58047. results.push(this.albedoTexture);
  58048. }
  58049. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  58050. results.push(this.ambientTexture);
  58051. }
  58052. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  58053. results.push(this.opacityTexture);
  58054. }
  58055. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  58056. results.push(this.reflectionTexture);
  58057. }
  58058. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  58059. results.push(this.emissiveTexture);
  58060. }
  58061. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  58062. results.push(this.reflectivityTexture);
  58063. }
  58064. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  58065. results.push(this.bumpTexture);
  58066. }
  58067. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  58068. results.push(this.lightmapTexture);
  58069. }
  58070. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  58071. results.push(this.refractionTexture);
  58072. }
  58073. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  58074. results.push(this.cameraColorGradingTexture);
  58075. }
  58076. return results;
  58077. };
  58078. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58079. if (forceDisposeTextures) {
  58080. if (this.albedoTexture) {
  58081. this.albedoTexture.dispose();
  58082. }
  58083. if (this.ambientTexture) {
  58084. this.ambientTexture.dispose();
  58085. }
  58086. if (this.opacityTexture) {
  58087. this.opacityTexture.dispose();
  58088. }
  58089. if (this.reflectionTexture) {
  58090. this.reflectionTexture.dispose();
  58091. }
  58092. if (this.emissiveTexture) {
  58093. this.emissiveTexture.dispose();
  58094. }
  58095. if (this.reflectivityTexture) {
  58096. this.reflectivityTexture.dispose();
  58097. }
  58098. if (this.bumpTexture) {
  58099. this.bumpTexture.dispose();
  58100. }
  58101. if (this.lightmapTexture) {
  58102. this.lightmapTexture.dispose();
  58103. }
  58104. if (this.refractionTexture) {
  58105. this.refractionTexture.dispose();
  58106. }
  58107. if (this.cameraColorGradingTexture) {
  58108. this.cameraColorGradingTexture.dispose();
  58109. }
  58110. }
  58111. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58112. };
  58113. PBRMaterial.prototype.clone = function (name) {
  58114. var _this = this;
  58115. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  58116. };
  58117. PBRMaterial.prototype.serialize = function () {
  58118. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58119. serializationObject.customType = "BABYLON.PBRMaterial";
  58120. return serializationObject;
  58121. };
  58122. // Statics
  58123. PBRMaterial.Parse = function (source, scene, rootUrl) {
  58124. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  58125. };
  58126. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  58127. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  58128. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  58129. PBRMaterial._scaledReflection = new BABYLON.Color3();
  58130. __decorate([
  58131. BABYLON.serialize()
  58132. ], PBRMaterial.prototype, "directIntensity", void 0);
  58133. __decorate([
  58134. BABYLON.serialize()
  58135. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  58136. __decorate([
  58137. BABYLON.serialize()
  58138. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  58139. __decorate([
  58140. BABYLON.serialize()
  58141. ], PBRMaterial.prototype, "specularIntensity", void 0);
  58142. __decorate([
  58143. BABYLON.serialize()
  58144. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  58145. __decorate([
  58146. BABYLON.serialize()
  58147. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  58148. __decorate([
  58149. BABYLON.serialize()
  58150. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  58151. __decorate([
  58152. BABYLON.serialize()
  58153. ], PBRMaterial.prototype, "cameraExposure", void 0);
  58154. __decorate([
  58155. BABYLON.serialize()
  58156. ], PBRMaterial.prototype, "cameraContrast", void 0);
  58157. __decorate([
  58158. BABYLON.serializeAsTexture()
  58159. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  58160. __decorate([
  58161. BABYLON.serializeAsColorCurves()
  58162. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  58163. __decorate([
  58164. BABYLON.serializeAsColor3()
  58165. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  58166. __decorate([
  58167. BABYLON.serialize()
  58168. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  58169. __decorate([
  58170. BABYLON.serializeAsColor3()
  58171. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  58172. __decorate([
  58173. BABYLON.serialize()
  58174. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  58175. __decorate([
  58176. BABYLON.serializeAsColor3()
  58177. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  58178. __decorate([
  58179. BABYLON.serialize()
  58180. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  58181. __decorate([
  58182. BABYLON.serializeAsColor3()
  58183. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  58184. __decorate([
  58185. BABYLON.serialize()
  58186. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  58187. __decorate([
  58188. BABYLON.serializeAsColor3()
  58189. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  58190. __decorate([
  58191. BABYLON.serialize()
  58192. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  58193. __decorate([
  58194. BABYLON.serialize()
  58195. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  58196. __decorate([
  58197. BABYLON.serialize()
  58198. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  58199. __decorate([
  58200. BABYLON.serializeAsTexture()
  58201. ], PBRMaterial.prototype, "albedoTexture", void 0);
  58202. __decorate([
  58203. BABYLON.serializeAsTexture()
  58204. ], PBRMaterial.prototype, "ambientTexture", void 0);
  58205. __decorate([
  58206. BABYLON.serializeAsTexture()
  58207. ], PBRMaterial.prototype, "opacityTexture", void 0);
  58208. __decorate([
  58209. BABYLON.serializeAsTexture()
  58210. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  58211. __decorate([
  58212. BABYLON.serializeAsTexture()
  58213. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  58214. __decorate([
  58215. BABYLON.serializeAsTexture()
  58216. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  58217. __decorate([
  58218. BABYLON.serializeAsTexture()
  58219. ], PBRMaterial.prototype, "bumpTexture", void 0);
  58220. __decorate([
  58221. BABYLON.serializeAsTexture()
  58222. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  58223. __decorate([
  58224. BABYLON.serializeAsTexture()
  58225. ], PBRMaterial.prototype, "refractionTexture", void 0);
  58226. __decorate([
  58227. BABYLON.serializeAsColor3("ambient")
  58228. ], PBRMaterial.prototype, "ambientColor", void 0);
  58229. __decorate([
  58230. BABYLON.serializeAsColor3("albedo")
  58231. ], PBRMaterial.prototype, "albedoColor", void 0);
  58232. __decorate([
  58233. BABYLON.serializeAsColor3("reflectivity")
  58234. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  58235. __decorate([
  58236. BABYLON.serializeAsColor3("reflection")
  58237. ], PBRMaterial.prototype, "reflectionColor", void 0);
  58238. __decorate([
  58239. BABYLON.serializeAsColor3("emissive")
  58240. ], PBRMaterial.prototype, "emissiveColor", void 0);
  58241. __decorate([
  58242. BABYLON.serialize()
  58243. ], PBRMaterial.prototype, "microSurface", void 0);
  58244. __decorate([
  58245. BABYLON.serialize()
  58246. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  58247. __decorate([
  58248. BABYLON.serialize()
  58249. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  58250. __decorate([
  58251. BABYLON.serializeAsFresnelParameters()
  58252. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  58253. __decorate([
  58254. BABYLON.serializeAsFresnelParameters()
  58255. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  58256. __decorate([
  58257. BABYLON.serialize()
  58258. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  58259. __decorate([
  58260. BABYLON.serialize()
  58261. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  58262. __decorate([
  58263. BABYLON.serialize()
  58264. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  58265. __decorate([
  58266. BABYLON.serialize()
  58267. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  58268. __decorate([
  58269. BABYLON.serialize()
  58270. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  58271. __decorate([
  58272. BABYLON.serialize()
  58273. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  58274. __decorate([
  58275. BABYLON.serialize()
  58276. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  58277. __decorate([
  58278. BABYLON.serialize()
  58279. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  58280. __decorate([
  58281. BABYLON.serialize()
  58282. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  58283. __decorate([
  58284. BABYLON.serialize()
  58285. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  58286. __decorate([
  58287. BABYLON.serialize()
  58288. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  58289. __decorate([
  58290. BABYLON.serialize()
  58291. ], PBRMaterial.prototype, "useParallax", void 0);
  58292. __decorate([
  58293. BABYLON.serialize()
  58294. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  58295. __decorate([
  58296. BABYLON.serialize()
  58297. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  58298. __decorate([
  58299. BABYLON.serialize()
  58300. ], PBRMaterial.prototype, "disableLighting", void 0);
  58301. __decorate([
  58302. BABYLON.serialize()
  58303. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  58304. __decorate([
  58305. BABYLON.serialize()
  58306. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  58307. __decorate([
  58308. BABYLON.serialize()
  58309. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  58310. __decorate([
  58311. BABYLON.serialize()
  58312. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  58313. return PBRMaterial;
  58314. })(BABYLON.Material);
  58315. BABYLON.PBRMaterial = PBRMaterial;
  58316. })(BABYLON || (BABYLON = {}));
  58317. var BABYLON;
  58318. (function (BABYLON) {
  58319. var DebugLayer = (function () {
  58320. function DebugLayer(scene) {
  58321. var _this = this;
  58322. this._transformationMatrix = BABYLON.Matrix.Identity();
  58323. this._enabled = false;
  58324. this._labelsEnabled = false;
  58325. this._displayStatistics = true;
  58326. this._displayTree = false;
  58327. this._displayLogs = false;
  58328. this._skeletonViewers = new Array();
  58329. this._identityMatrix = BABYLON.Matrix.Identity();
  58330. this.axisRatio = 0.02;
  58331. this.accentColor = "orange";
  58332. this._scene = scene;
  58333. this._syncPositions = function () {
  58334. var engine = _this._scene.getEngine();
  58335. var canvasRect = engine.getRenderingCanvasClientRect();
  58336. if (_this._showUI) {
  58337. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  58338. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  58339. _this._statsDiv.style.width = "400px";
  58340. _this._statsDiv.style.height = "auto";
  58341. _this._statsSubsetDiv.style.maxHeight = "240px";
  58342. _this._optionsDiv.style.left = "0px";
  58343. _this._optionsDiv.style.top = "10px";
  58344. _this._optionsDiv.style.width = "200px";
  58345. _this._optionsDiv.style.height = "auto";
  58346. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  58347. _this._logDiv.style.left = "0px";
  58348. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  58349. _this._logDiv.style.width = "600px";
  58350. _this._logDiv.style.height = "160px";
  58351. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  58352. _this._treeDiv.style.top = "10px";
  58353. _this._treeDiv.style.width = "300px";
  58354. _this._treeDiv.style.height = "auto";
  58355. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  58356. }
  58357. _this._globalDiv.style.left = canvasRect.left + "px";
  58358. _this._globalDiv.style.top = canvasRect.top + "px";
  58359. _this._drawingCanvas.style.left = "0px";
  58360. _this._drawingCanvas.style.top = "0px";
  58361. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  58362. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  58363. var devicePixelRatio = window.devicePixelRatio || 1;
  58364. var context = _this._drawingContext;
  58365. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  58366. context.mozBackingStorePixelRatio ||
  58367. context.msBackingStorePixelRatio ||
  58368. context.oBackingStorePixelRatio ||
  58369. context.backingStorePixelRatio || 1;
  58370. _this._ratio = devicePixelRatio / backingStoreRatio;
  58371. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  58372. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  58373. };
  58374. this._onCanvasClick = function (evt) {
  58375. _this._clickPosition = {
  58376. x: evt.clientX * _this._ratio,
  58377. y: evt.clientY * _this._ratio
  58378. };
  58379. };
  58380. this._syncUI = function () {
  58381. if (_this._showUI) {
  58382. if (_this._displayStatistics) {
  58383. _this._displayStats();
  58384. _this._statsDiv.style.display = "";
  58385. }
  58386. else {
  58387. _this._statsDiv.style.display = "none";
  58388. }
  58389. if (_this._displayLogs) {
  58390. _this._logDiv.style.display = "";
  58391. }
  58392. else {
  58393. _this._logDiv.style.display = "none";
  58394. }
  58395. if (_this._displayTree) {
  58396. _this._treeDiv.style.display = "";
  58397. if (_this._needToRefreshMeshesTree) {
  58398. _this._needToRefreshMeshesTree = false;
  58399. _this._refreshMeshesTreeContent();
  58400. }
  58401. }
  58402. else {
  58403. _this._treeDiv.style.display = "none";
  58404. }
  58405. }
  58406. };
  58407. this._syncData = function () {
  58408. if (_this._labelsEnabled || !_this._showUI) {
  58409. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  58410. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  58411. var engine = _this._scene.getEngine();
  58412. var viewport = _this._camera.viewport;
  58413. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  58414. // Meshes
  58415. var meshes = _this._camera.getActiveMeshes();
  58416. var index;
  58417. var projectedPosition;
  58418. for (index = 0; index < meshes.length; index++) {
  58419. var mesh = meshes.data[index];
  58420. var position = mesh.getBoundingInfo().boundingSphere.center;
  58421. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  58422. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  58423. _this._renderAxis(projectedPosition, mesh, globalViewport);
  58424. }
  58425. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  58426. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  58427. }
  58428. }
  58429. // Cameras
  58430. var cameras = _this._scene.cameras;
  58431. for (index = 0; index < cameras.length; index++) {
  58432. var camera = cameras[index];
  58433. if (camera === _this._camera) {
  58434. continue;
  58435. }
  58436. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  58437. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  58438. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  58439. _this._camera.detachControl(engine.getRenderingCanvas());
  58440. _this._camera = camera;
  58441. _this._camera.attachControl(engine.getRenderingCanvas());
  58442. }, function () { return "purple"; });
  58443. }
  58444. }
  58445. // Lights
  58446. var lights = _this._scene.lights;
  58447. for (index = 0; index < lights.length; index++) {
  58448. var light = lights[index];
  58449. if (light.position) {
  58450. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  58451. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  58452. _this._renderLabel(light.name, projectedPosition, -20, function () {
  58453. light.setEnabled(!light.isEnabled());
  58454. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  58455. }
  58456. }
  58457. }
  58458. }
  58459. _this._clickPosition = undefined;
  58460. };
  58461. }
  58462. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  58463. while (this._treeSubsetDiv.hasChildNodes()) {
  58464. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  58465. }
  58466. // Add meshes
  58467. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  58468. sortedArray.sort(function (a, b) {
  58469. if (a.name === b.name) {
  58470. return 0;
  58471. }
  58472. return (a.name > b.name) ? 1 : -1;
  58473. });
  58474. for (var index = 0; index < sortedArray.length; index++) {
  58475. var mesh = sortedArray[index];
  58476. if (!mesh.isEnabled()) {
  58477. continue;
  58478. }
  58479. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  58480. m.isVisible = element.checked;
  58481. }, mesh);
  58482. }
  58483. };
  58484. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  58485. this._drawingContext.beginPath();
  58486. this._drawingContext.moveTo(zero.x, zero.y);
  58487. this._drawingContext.lineTo(unit.x, unit.y);
  58488. this._drawingContext.strokeStyle = color;
  58489. this._drawingContext.lineWidth = 4;
  58490. this._drawingContext.stroke();
  58491. this._drawingContext.font = "normal 14px Segoe UI";
  58492. this._drawingContext.fillStyle = color;
  58493. this._drawingContext.fillText(label, unitText.x, unitText.y);
  58494. };
  58495. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  58496. var position = mesh.getBoundingInfo().boundingSphere.center;
  58497. var worldMatrix = mesh.getWorldMatrix();
  58498. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  58499. var unit = (unprojectedVector.subtract(position)).length();
  58500. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  58501. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  58502. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  58503. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  58504. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  58505. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  58506. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  58507. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  58508. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  58509. };
  58510. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  58511. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  58512. this._drawingContext.font = "normal 12px Segoe UI";
  58513. var textMetrics = this._drawingContext.measureText(text);
  58514. var centerX = projectedPosition.x - textMetrics.width / 2;
  58515. var centerY = projectedPosition.y;
  58516. var clientRect = this._drawingCanvas.getBoundingClientRect();
  58517. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  58518. onClick();
  58519. }
  58520. this._drawingContext.beginPath();
  58521. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  58522. this._drawingContext.fillStyle = getFillStyle();
  58523. this._drawingContext.globalAlpha = 0.5;
  58524. this._drawingContext.fill();
  58525. this._drawingContext.globalAlpha = 1.0;
  58526. this._drawingContext.strokeStyle = '#FFFFFF';
  58527. this._drawingContext.lineWidth = 1;
  58528. this._drawingContext.stroke();
  58529. this._drawingContext.fillStyle = "#FFFFFF";
  58530. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  58531. this._drawingContext.beginPath();
  58532. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  58533. this._drawingContext.fill();
  58534. }
  58535. };
  58536. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  58537. if (!this._clickPosition) {
  58538. return false;
  58539. }
  58540. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  58541. return false;
  58542. }
  58543. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  58544. return false;
  58545. }
  58546. return true;
  58547. };
  58548. DebugLayer.prototype.isVisible = function () {
  58549. return this._enabled;
  58550. };
  58551. DebugLayer.prototype.hide = function () {
  58552. if (!this._enabled) {
  58553. return;
  58554. }
  58555. this._enabled = false;
  58556. var engine = this._scene.getEngine();
  58557. this._scene.unregisterBeforeRender(this._syncData);
  58558. this._scene.unregisterAfterRender(this._syncUI);
  58559. this._rootElement.removeChild(this._globalDiv);
  58560. this._scene.forceShowBoundingBoxes = false;
  58561. this._scene.forceWireframe = false;
  58562. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  58563. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  58564. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  58565. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  58566. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  58567. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  58568. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  58569. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  58570. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  58571. this._scene.shadowsEnabled = true;
  58572. this._scene.particlesEnabled = true;
  58573. this._scene.postProcessesEnabled = true;
  58574. this._scene.collisionsEnabled = true;
  58575. this._scene.lightsEnabled = true;
  58576. this._scene.texturesEnabled = true;
  58577. this._scene.lensFlaresEnabled = true;
  58578. this._scene.proceduralTexturesEnabled = true;
  58579. this._scene.renderTargetsEnabled = true;
  58580. this._scene.probesEnabled = true;
  58581. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  58582. this._clearSkeletonViewers();
  58583. };
  58584. DebugLayer.prototype._clearSkeletonViewers = function () {
  58585. for (var index = 0; index < this._skeletonViewers.length; index++) {
  58586. this._skeletonViewers[index].dispose();
  58587. }
  58588. this._skeletonViewers = [];
  58589. };
  58590. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  58591. if (showUI === void 0) { showUI = true; }
  58592. if (camera === void 0) { camera = null; }
  58593. if (rootElement === void 0) { rootElement = null; }
  58594. if (this._enabled) {
  58595. return;
  58596. }
  58597. this._enabled = true;
  58598. if (camera) {
  58599. this._camera = camera;
  58600. }
  58601. else {
  58602. this._camera = this._scene.activeCamera;
  58603. }
  58604. this._showUI = showUI;
  58605. var engine = this._scene.getEngine();
  58606. this._globalDiv = document.createElement("div");
  58607. this._rootElement = rootElement || document.body;
  58608. this._rootElement.appendChild(this._globalDiv);
  58609. this._generateDOMelements();
  58610. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  58611. this._syncPositions();
  58612. this._scene.registerBeforeRender(this._syncData);
  58613. this._scene.registerAfterRender(this._syncUI);
  58614. };
  58615. DebugLayer.prototype._clearLabels = function () {
  58616. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  58617. for (var index = 0; index < this._scene.meshes.length; index++) {
  58618. var mesh = this._scene.meshes[index];
  58619. mesh.renderOverlay = false;
  58620. }
  58621. };
  58622. DebugLayer.prototype._generateheader = function (root, text) {
  58623. var header = document.createElement("div");
  58624. header.innerHTML = text + "&nbsp;";
  58625. header.style.textAlign = "right";
  58626. header.style.width = "100%";
  58627. header.style.color = "white";
  58628. header.style.backgroundColor = "Black";
  58629. header.style.padding = "5px 5px 4px 0px";
  58630. header.style.marginLeft = "-5px";
  58631. header.style.fontWeight = "bold";
  58632. root.appendChild(header);
  58633. };
  58634. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  58635. var label = document.createElement("label");
  58636. label.style.display = "inline";
  58637. label.innerHTML = title;
  58638. label.style.color = color;
  58639. root.appendChild(label);
  58640. root.appendChild(document.createElement("br"));
  58641. };
  58642. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  58643. if (tag === void 0) { tag = null; }
  58644. var label = document.createElement("label");
  58645. label.style.display = "inline";
  58646. var boundingBoxesCheckbox = document.createElement("input");
  58647. boundingBoxesCheckbox.type = "checkbox";
  58648. boundingBoxesCheckbox.checked = initialState;
  58649. boundingBoxesCheckbox.style.display = "inline";
  58650. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  58651. boundingBoxesCheckbox.style.verticalAlign = "sub";
  58652. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  58653. task(evt.target, tag);
  58654. });
  58655. label.appendChild(boundingBoxesCheckbox);
  58656. var container = document.createElement("span");
  58657. var leftPart = document.createElement("span");
  58658. var rightPart = document.createElement("span");
  58659. rightPart.style.cssFloat = "right";
  58660. leftPart.innerHTML = leftTitle;
  58661. rightPart.innerHTML = rightTitle;
  58662. rightPart.style.fontSize = "12px";
  58663. rightPart.style.maxWidth = "200px";
  58664. container.appendChild(leftPart);
  58665. container.appendChild(rightPart);
  58666. label.appendChild(container);
  58667. root.appendChild(label);
  58668. root.appendChild(document.createElement("br"));
  58669. };
  58670. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  58671. if (tag === void 0) { tag = null; }
  58672. var label = document.createElement("label");
  58673. label.style.display = "inline";
  58674. var checkBox = document.createElement("input");
  58675. checkBox.type = "checkbox";
  58676. checkBox.checked = initialState;
  58677. checkBox.style.display = "inline";
  58678. checkBox.style.margin = "0px 5px 0px 0px";
  58679. checkBox.style.verticalAlign = "sub";
  58680. checkBox.addEventListener("change", function (evt) {
  58681. task(evt.target, tag);
  58682. });
  58683. label.appendChild(checkBox);
  58684. label.appendChild(document.createTextNode(title));
  58685. root.appendChild(label);
  58686. root.appendChild(document.createElement("br"));
  58687. };
  58688. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  58689. if (tag === void 0) { tag = null; }
  58690. var button = document.createElement("button");
  58691. button.innerHTML = title;
  58692. button.style.height = "24px";
  58693. button.style.width = "150px";
  58694. button.style.marginBottom = "5px";
  58695. button.style.color = "#444444";
  58696. button.style.border = "1px solid white";
  58697. button.className = "debugLayerButton";
  58698. button.addEventListener("click", function (evt) {
  58699. task(evt.target, tag);
  58700. });
  58701. root.appendChild(button);
  58702. root.appendChild(document.createElement("br"));
  58703. };
  58704. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  58705. if (tag === void 0) { tag = null; }
  58706. var label = document.createElement("label");
  58707. label.style.display = "inline";
  58708. var boundingBoxesRadio = document.createElement("input");
  58709. boundingBoxesRadio.type = "radio";
  58710. boundingBoxesRadio.name = name;
  58711. boundingBoxesRadio.checked = initialState;
  58712. boundingBoxesRadio.style.display = "inline";
  58713. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  58714. boundingBoxesRadio.style.verticalAlign = "sub";
  58715. boundingBoxesRadio.addEventListener("change", function (evt) {
  58716. task(evt.target, tag);
  58717. });
  58718. label.appendChild(boundingBoxesRadio);
  58719. label.appendChild(document.createTextNode(title));
  58720. root.appendChild(label);
  58721. root.appendChild(document.createElement("br"));
  58722. };
  58723. DebugLayer.prototype._generateDOMelements = function () {
  58724. var _this = this;
  58725. this._globalDiv.id = "DebugLayer";
  58726. this._globalDiv.style.position = "absolute";
  58727. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  58728. this._globalDiv.style.fontSize = "14px";
  58729. this._globalDiv.style.color = "white";
  58730. // Drawing canvas
  58731. this._drawingCanvas = document.createElement("canvas");
  58732. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  58733. this._drawingCanvas.style.position = "absolute";
  58734. this._drawingCanvas.style.pointerEvents = "none";
  58735. this._drawingCanvas.style.backgroundColor = "transparent";
  58736. this._drawingContext = this._drawingCanvas.getContext("2d");
  58737. this._globalDiv.appendChild(this._drawingCanvas);
  58738. if (this._showUI) {
  58739. var background = "rgba(128, 128, 128, 0.4)";
  58740. var border = "rgb(180, 180, 180) solid 1px";
  58741. // Stats
  58742. this._statsDiv = document.createElement("div");
  58743. this._statsDiv.id = "DebugLayerStats";
  58744. this._statsDiv.style.border = border;
  58745. this._statsDiv.style.position = "absolute";
  58746. this._statsDiv.style.background = background;
  58747. this._statsDiv.style.padding = "0px 0px 0px 5px";
  58748. this._generateheader(this._statsDiv, "STATISTICS");
  58749. this._statsSubsetDiv = document.createElement("div");
  58750. this._statsSubsetDiv.style.paddingTop = "5px";
  58751. this._statsSubsetDiv.style.paddingBottom = "5px";
  58752. this._statsSubsetDiv.style.overflowY = "auto";
  58753. this._statsDiv.appendChild(this._statsSubsetDiv);
  58754. // Tree
  58755. this._treeDiv = document.createElement("div");
  58756. this._treeDiv.id = "DebugLayerTree";
  58757. this._treeDiv.style.border = border;
  58758. this._treeDiv.style.position = "absolute";
  58759. this._treeDiv.style.background = background;
  58760. this._treeDiv.style.padding = "0px 0px 0px 5px";
  58761. this._treeDiv.style.display = "none";
  58762. this._generateheader(this._treeDiv, "MESHES TREE");
  58763. this._treeSubsetDiv = document.createElement("div");
  58764. this._treeSubsetDiv.style.paddingTop = "5px";
  58765. this._treeSubsetDiv.style.paddingRight = "5px";
  58766. this._treeSubsetDiv.style.overflowY = "auto";
  58767. this._treeSubsetDiv.style.maxHeight = "300px";
  58768. this._treeDiv.appendChild(this._treeSubsetDiv);
  58769. this._needToRefreshMeshesTree = true;
  58770. // Logs
  58771. this._logDiv = document.createElement("div");
  58772. this._logDiv.style.border = border;
  58773. this._logDiv.id = "DebugLayerLogs";
  58774. this._logDiv.style.position = "absolute";
  58775. this._logDiv.style.background = background;
  58776. this._logDiv.style.padding = "0px 0px 0px 5px";
  58777. this._logDiv.style.display = "none";
  58778. this._generateheader(this._logDiv, "LOGS");
  58779. this._logSubsetDiv = document.createElement("div");
  58780. this._logSubsetDiv.style.height = "127px";
  58781. this._logSubsetDiv.style.paddingTop = "5px";
  58782. this._logSubsetDiv.style.overflowY = "auto";
  58783. this._logSubsetDiv.style.fontSize = "12px";
  58784. this._logSubsetDiv.style.fontFamily = "consolas";
  58785. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  58786. this._logDiv.appendChild(this._logSubsetDiv);
  58787. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  58788. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  58789. };
  58790. // Options
  58791. this._optionsDiv = document.createElement("div");
  58792. this._optionsDiv.id = "DebugLayerOptions";
  58793. this._optionsDiv.style.border = border;
  58794. this._optionsDiv.style.position = "absolute";
  58795. this._optionsDiv.style.background = background;
  58796. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  58797. this._optionsDiv.style.overflowY = "auto";
  58798. this._generateheader(this._optionsDiv, "OPTIONS");
  58799. this._optionsSubsetDiv = document.createElement("div");
  58800. this._optionsSubsetDiv.style.paddingTop = "5px";
  58801. this._optionsSubsetDiv.style.paddingBottom = "5px";
  58802. this._optionsSubsetDiv.style.overflowY = "auto";
  58803. this._optionsSubsetDiv.style.maxHeight = "200px";
  58804. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  58805. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  58806. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  58807. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  58808. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  58809. _this._displayTree = element.checked;
  58810. _this._needToRefreshMeshesTree = true;
  58811. });
  58812. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  58813. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  58814. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  58815. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  58816. _this._labelsEnabled = element.checked;
  58817. if (!_this._labelsEnabled) {
  58818. _this._clearLabels();
  58819. }
  58820. });
  58821. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  58822. if (element.checked) {
  58823. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  58824. }
  58825. else {
  58826. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  58827. }
  58828. });
  58829. ;
  58830. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  58831. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  58832. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  58833. if (element.checked) {
  58834. _this._scene.forceWireframe = false;
  58835. _this._scene.forcePointsCloud = false;
  58836. }
  58837. });
  58838. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  58839. if (element.checked) {
  58840. _this._scene.forceWireframe = true;
  58841. _this._scene.forcePointsCloud = false;
  58842. }
  58843. });
  58844. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  58845. if (element.checked) {
  58846. _this._scene.forceWireframe = false;
  58847. _this._scene.forcePointsCloud = true;
  58848. }
  58849. });
  58850. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  58851. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  58852. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  58853. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  58854. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  58855. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  58856. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  58857. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  58858. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  58859. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  58860. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  58861. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  58862. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  58863. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  58864. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  58865. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  58866. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  58867. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  58868. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  58869. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  58870. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  58871. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  58872. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  58873. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  58874. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  58875. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  58876. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  58877. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  58878. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  58879. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  58880. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  58881. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  58882. if (element.checked) {
  58883. _this._scene.headphone = true;
  58884. }
  58885. });
  58886. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  58887. if (element.checked) {
  58888. _this._scene.headphone = false;
  58889. }
  58890. });
  58891. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  58892. _this._scene.audioEnabled = !element.checked;
  58893. });
  58894. }
  58895. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  58896. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  58897. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  58898. if (!element.checked) {
  58899. _this._clearSkeletonViewers();
  58900. return;
  58901. }
  58902. for (var index = 0; index < _this._scene.meshes.length; index++) {
  58903. var mesh = _this._scene.meshes[index];
  58904. if (mesh.skeleton) {
  58905. var found = false;
  58906. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  58907. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  58908. found = true;
  58909. break;
  58910. }
  58911. }
  58912. if (found) {
  58913. continue;
  58914. }
  58915. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  58916. viewer.isEnabled = true;
  58917. _this._skeletonViewers.push(viewer);
  58918. }
  58919. }
  58920. });
  58921. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  58922. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  58923. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  58924. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  58925. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  58926. if (_this._camera) {
  58927. console.log(_this._camera);
  58928. }
  58929. else {
  58930. console.warn("No camera defined, or debug layer created before camera creation!");
  58931. }
  58932. });
  58933. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  58934. this._globalDiv.appendChild(this._statsDiv);
  58935. this._globalDiv.appendChild(this._logDiv);
  58936. this._globalDiv.appendChild(this._optionsDiv);
  58937. this._globalDiv.appendChild(this._treeDiv);
  58938. }
  58939. };
  58940. DebugLayer.prototype._displayStats = function () {
  58941. var scene = this._scene;
  58942. var engine = scene.getEngine();
  58943. var glInfo = engine.getGlInfo();
  58944. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  58945. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  58946. + "<b>Count</b><br>"
  58947. + "Total meshes: " + scene.meshes.length + "<br>"
  58948. + "Total lights: " + scene.lights.length + "<br>"
  58949. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  58950. + "Total materials: " + scene.materials.length + "<br>"
  58951. + "Total textures: " + scene.textures.length + "<br>"
  58952. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  58953. + "Active indices: " + scene.getActiveIndices() + "<br>"
  58954. + "Active bones: " + scene.getActiveBones() + "<br>"
  58955. + "Active particles: " + scene.getActiveParticles() + "<br>"
  58956. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  58957. + "<b>Duration</b><br>"
  58958. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  58959. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  58960. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  58961. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  58962. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  58963. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  58964. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  58965. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  58966. + "</div>"
  58967. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  58968. + "<b>Extensions</b><br>"
  58969. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  58970. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  58971. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  58972. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  58973. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  58974. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  58975. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  58976. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  58977. + "</div><br>"
  58978. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  58979. + "<b>Caps.</b><br>"
  58980. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  58981. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  58982. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  58983. + "<b>Info</b><br>"
  58984. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  58985. + glInfo.version + "<br>"
  58986. + "</div><br>"
  58987. + glInfo.renderer + "<br>";
  58988. if (this.customStatsFunction) {
  58989. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  58990. }
  58991. };
  58992. return DebugLayer;
  58993. })();
  58994. BABYLON.DebugLayer = DebugLayer;
  58995. })(BABYLON || (BABYLON = {}));
  58996. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","ellipse2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","ellipse2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat ms=properties.z;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<ms) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=ms;\n}\nfloat angle=TWOPI*segi/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat ms=properties.z;\nfloat angle=TWOPI*(index-1.0)/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\n}\n#endif\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#ifdef CAMERACOLORGRADING\nuniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;\n#endif\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor,cameraColorGrading2DSampler,vCameraColorGradingInfos,vCameraColorGradingScaleOffset);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","lines2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","lines2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute vec2 position;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec2 boundingMin;\natt vec2 boundingMax;\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvec4 pos;\npos.xy=position.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","rect2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","rect2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n\n#define rsub0 17.0\n#define rsub1 33.0\n#define rsub2 49.0\n#define rsub3 65.0\n#define rsub 64.0\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (properties.z == 0.0) {\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<4.0) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=4.0;\n}\nif (segi == 0.0) {\npos2=vec2(1.0,1.0);\n} \nelse if (segi == 1.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (segi == 2.0) {\npos2=vec2(0.0,0.0);\n} \nelse {\npos2=vec2(0.0,1.0);\n}\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse if (index == 1.0) {\npos2=vec2(1.0,1.0);\n}\nelse if (index == 2.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (index == 3.0) {\npos2=vec2(0.0,0.0);\n}\nelse {\npos2=vec2(0.0,1.0);\n}\n#endif\n}\nelse\n{\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<rsub) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=rsub;\n}\n\nif (segi<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (segi<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (segi<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\n\nif (index<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (index<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (index<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\n}\n#endif\n}\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=pack(depth);\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","sprite2dPixelShader":"varying vec2 vUV;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (color.a == 0.05) {\ndiscard;\n}\ngl_FragColor=color;\n}","sprite2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\n\natt vec3 properties;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\n\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nvec2 off=vec2(0.0,0.0);\nfloat frame=properties.x;\nfloat invertY=properties.y;\nfloat alignToPixel=properties.z;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x+(frame*sizeUV.x)+off.x,topLeftUV.y-off.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x+(frame*sizeUV.x)+off.x,(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),topLeftUV.y-off.y);\n}\nif (invertY == 1.0) {\nvUV.y=1.0-vUV.y;\n}\nvec4 pos;\nif (alignToPixel == 1.0)\n{\npos.xy=floor(pos2.xy*sizeUV*textureSize);\n} else {\npos.xy=pos2.xy*sizeUV*textureSize;\n}\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n} ","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","text2dPixelShader":"varying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (color.a<0.05)\ndiscard;\ngl_FragColor=color*vColor;\n}","text2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\natt vec4 color;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y);\n}\n\nelse if (index == 2.0) {\npos2=vec2(1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y);\n}\n\nelse if (index == 3.0) {\npos2=vec2(1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\n}\n\nvUV=(floor(vUV*textureSize)+vec2(0.0,0.0))/textureSize;\nvColor=color;\nvec4 pos;\npos.xy=floor(pos2.xy*sizeUV*textureSize); \npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  58997. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  58998. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:!(o.z-i>e.z)},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return r>=-n&&n>=r},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.getClassName=function(){return\"Color3\"},n.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,s=t.g+(i.g-t.g)*r,e=t.b+(i.b-t.b)*r;return new n(o,s,e)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),s=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,s)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.getClassName=function(){return\"Vector2\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n(-this.x,-this.y)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<i.y?i.y:s,new n(o,s)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r;return new n(o,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=n.Zero();return n.TransformToRef(t,i,r),r},n.TransformToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];n.x=r,n.y=o},n.PointInTriangle=function(t,i,n,r){var o=.5*(-n.y*r.x+i.y*(-n.x+r.x)+i.x*(n.y-r.y)+n.x*r.y),s=0>o?-1:1,e=(i.y*r.x-i.x*r.y+(r.y-i.y)*t.x+(i.x-r.x)*t.y)*s,h=(i.x*n.y-i.y*n.x+(i.y-n.y)*t.x+(n.x-i.x)*t.y)*s;return e>0&&h>0&&2*o*s>e+h},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n.DistanceOfPointFromSegment=function(t,i,r){var o=n.DistanceSquared(i,r);if(0===o)return n.Distance(t,i);var s=r.subtract(i),e=Math.max(0,Math.min(1,n.Dot(t.subtract(i),s)/o)),h=i.add(s.multiplyByFloats(e,e));return n.Distance(t,h)},n}();t.Vector2=o;var s=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.getClassName=function(){return\"Vector3\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},n.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var s=n.Dot(t,r)-o,e=n.Dot(i,r)-o,h=s/(s-e);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*s+(2*t.z-5*i.z+4*r.z-o.z)*e+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<i.y?i.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<i.z?i.z:e,new n(o,s,e)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r,e=t.z+(i.z-t.z)*r;return new n(o,s,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,n.copyFrom(M.Vector3[0])},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var s=o.width,e=o.height,h=o.x,a=o.y,m=u.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+a,0,1),y=i.multiply(r).multiply(m);return n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,s,e){var h=s.multiply(e);h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),u=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},n.Unproject=function(t,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new n(t.x/r*2-1,-(t.y/o*2-1),t.z),m=n.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return i.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,s,e){var h=r.normalize(),a=s.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],T=0,R=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),n.CrossToRef(h,R,g),g.normalize(),n.Dot(a,g)<0&&(v=1),T=n.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,n.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var _=M.Vector3[2],b=M.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=l,_.y=x,_.z=z,_.normalize(),n.CrossToRef(_,R,b),b.normalize(),n.CrossToRef(a,_,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,_),T=Math.min(1,Math.max(-1,T)),c=Math.acos(T)*v,n.Dot(b,m)<0&&(c=Math.PI+c,d++),v=-1,n.CrossToRef(u,R,g),g.normalize(),n.Dot(g,m)<0&&(v=1),T=n.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),e.x=c,e.y=y,e.z=f},n}();t.Vector3=s;var e=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},n.prototype.getClassName=function(){return\"Vector4\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z,-this.w)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},n.prototype.toVector3=function(){return new s(this.x,this.y,this.z)},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=e;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return t?this.width===t.width&&this.height===t.height:!1},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var n=new t(this.width+i.width,this.height+i.height);return n},t.prototype.substract=function(i){var n=new t(this.width-i.width,this.height-i.height);return n},t.Lerp=function(i,n,r){var o=i.width+(n.width-i.width)*r,s=i.height+(n.height-i.height)*r;return new t(o,s)},t}();t.Size=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t(-this.x,-this.y,-this.z,this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=s.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,y=e*e,c=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14]},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,b=-(s*v-e*g+h*T),F=1/(i*R+n*_+r*M+o*b),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,C=s*x-a*p,Z=s*l-h*p,S=s*f-e*p,I=h*c-a*y,q=e*c-a*m,H=e*y-h*m,N=s*c-a*u,V=s*y-h*u,D=s*m-e*u;return t.m[0]=R*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=b*F,t.m[1]=-(n*z-r*w+o*v)*F,t.m[5]=(i*z-r*d+o*g)*F,t.m[9]=-(i*w-n*d+o*T)*F,t.m[13]=(i*v-n*g+r*T)*F,t.m[2]=(n*A-r*L+o*P)*F,t.m[6]=-(i*A-r*C+o*Z)*F,t.m[10]=(i*L-n*C+o*S)*F,t.m[14]=-(i*P-n*Z+r*S)*F,t.m[3]=-(n*I-r*q+o*H)*F,t.m[7]=(i*I-r*N+o*V)*F,t.m[11]=-(i*q-n*N+o*D)*F,t.m[15]=(i*H-n*V+r*D)*F,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new s(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],b=t.m[7],F=t.m[8],A=t.m[9],L=t.m[10],P=t.m[11],C=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*R+s*F+e*C,i[n+1]=r*d+o*_+s*A+e*Z,i[n+2]=r*g+o*M+s*L+e*S,i[n+3]=r*T+o*b+s*P+e*I,i[n+4]=h*v+a*R+u*F+m*C,i[n+5]=h*d+a*_+u*A+m*Z,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*T+a*b+u*P+m*I,i[n+8]=y*v+c*R+p*F+f*C,\ni[n+9]=y*d+c*_+p*A+f*Z,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*T+c*b+p*P+f*I,i[n+12]=l*v+x*R+z*F+w*C,i[n+13]=l*d+x*_+z*A+w*Z,i[n+14]=l*g+x*M+z*L+w*S,i[n+15]=l*T+x*b+z*P+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.getClassName=function(){return\"Matrix\"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;16>i;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=t.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,r),!0},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.prototype.getRow=function(t){if(0>t||t>3)return null;var i=4*t;return new e(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(0>t||t>3)return this;var n=4*t;return this.m[n+0]=i.x,this.m[n+1]=i.y,this.m[n+2]=i.z,this.m[n+3]=i.w,this},t.FromValues=function(i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),s=t.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){for(var o=t.Zero(),s=0;16>s;s++)o.m[s]=i.m[s]*(1-r)+n.m[s]*r;return o},t.DecomposeLerp=function(i,n,r){var o=new s(0,0,0),e=new a,h=new s(0,0,0);i.decompose(o,e,h);var u=new s(0,0,0),m=new a,y=new s(0,0,0);n.decompose(u,m,y);var c=s.Lerp(o,u,r),p=a.Slerp(e,m,r),f=s.Lerp(h,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),s.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),s.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-s.Dot(this._xAxis,i),h=-s.Dot(this._yAxis,i),a=-s.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var s=t.Zero();return t.OrthoLHToRef(i,n,r,o,s),s},t.OrthoLHToRef=function(i,n,r,o,s){var e=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},t.OrthoOffCenterLH=function(i,n,r,o,s,e){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,s,e,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},t.PerspectiveLH=function(i,n,r,o){var s=t.Zero();return s.m[0]=2*r/i,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},t.PerspectiveFovLH=function(i,n,r,o){var s=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,s),s},t.PerspectiveFovLHToRef=function(t,i,n,r,o,s){void 0===s&&(s=!0);var e=1/Math.tan(.5*t);s?o.m[0]=e/i:o.m[0]=e,o.m[1]=o.m[2]=o.m[3]=0,s?o.m[5]=e:o.m[5]=e*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-r/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.GetFinalMatrix=function(i,n,r,o,s,e){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=s.Zero(),t._yAxis=s.Zero(),t._zAxis=s.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new s(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],a=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=s.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return s.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return s.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var p=(t.Space,function(){function t(){}return t.X=new s(1,0,0),t.Y=new s(0,1,0),t.Z=new s(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var l=t.Orientation,x=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=x;var z=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=x.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=x.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=x.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?l.CW:l.CCW,this.angle=x.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,s){if(void 0===s&&(s=36),closed)return this;var e=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new z(e,h,a),m=u.angle.radians()/s;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;s>c;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(0>t||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var s=(r+1)%this._points.length,e=this._points[r],h=this._points[s],a=h.subtract(e),u=a.length()+n;if(i>=n&&u>=i){var m=a.normalize(),y=i-n;return new o(e.x+m.x*y,e.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=w;var v=function(){function n(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=s.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,e,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=o.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=s.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=s.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var e;if(void 0===o||null===o){var h;i.WithinEpsilon(r.y,1,t.Epsilon)?i.WithinEpsilon(r.x,1,t.Epsilon)?i.WithinEpsilon(r.z,1,t.Epsilon)||(h=new s(0,0,1)):h=new s(1,0,0):h=new s(0,-1,0),e=s.Cross(r,h)}else e=s.Cross(r,o),s.CrossToRef(e,r,e);return e.normalize(),e},n}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var e=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)e.push(new s(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,o,e){e=e>3?e:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;e>=u;u++)h.push(new s(a(u/e,i.x,n.x,r.x,o.x),a(u/e,i.y,n.y,r.y,o.y),a(u/e,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(s.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=s.Zero(),this.L1_1=s.Zero(),this.L10=s.Zero(),this.L11=s.Zero(),this.L2_2=s.Zero(),this.L2_1=s.Zero(),this.L20=s.Zero(),this.L21=s.Zero(),this.L22=s.Zero()}return t.prototype.addLight=function(t,i,n){var r=new s(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var T=function(){function t(){this.x=s.Zero(),this.y=s.Zero(),this.z=s.Zero(),this.xx=s.Zero(),this.yy=s.Zero(),this.zz=s.Zero(),this.xy=s.Zero(),this.yz=s.Zero(),this.zx=s.Zero()}return t.prototype.addAmbient=function(t){var i=new s(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=T;var R=function(){function t(t,i){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero()],t.Vector4=[e.Zero(),e.Zero(),e.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  58999. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  59000. module.exports = BABYLON;
  59001. };